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-2017, PostgreSQL Global Development Group
30 * Portions Copyright (c) 1994, Regents of the University of California
34 * src/backend/executor/execMain.c
36 *-------------------------------------------------------------------------
40 #include "access/htup_details.h"
41 #include "access/sysattr.h"
42 #include "access/transam.h"
43 #include "access/xact.h"
44 #include "catalog/namespace.h"
45 #include "catalog/partition.h"
46 #include "catalog/pg_publication.h"
47 #include "commands/matview.h"
48 #include "commands/trigger.h"
49 #include "executor/execdebug.h"
50 #include "foreign/fdwapi.h"
51 #include "mb/pg_wchar.h"
52 #include "miscadmin.h"
53 #include "optimizer/clauses.h"
54 #include "parser/parsetree.h"
55 #include "rewrite/rewriteManip.h"
56 #include "storage/bufmgr.h"
57 #include "storage/lmgr.h"
58 #include "tcop/utility.h"
59 #include "utils/acl.h"
60 #include "utils/lsyscache.h"
61 #include "utils/memutils.h"
62 #include "utils/rls.h"
63 #include "utils/ruleutils.h"
64 #include "utils/snapmgr.h"
65 #include "utils/tqual.h"
68 /* Hooks for plugins to get control in ExecutorStart/Run/Finish/End */
69 ExecutorStart_hook_type ExecutorStart_hook = NULL;
70 ExecutorRun_hook_type ExecutorRun_hook = NULL;
71 ExecutorFinish_hook_type ExecutorFinish_hook = NULL;
72 ExecutorEnd_hook_type ExecutorEnd_hook = NULL;
74 /* Hook for plugin to get control in ExecCheckRTPerms() */
75 ExecutorCheckPerms_hook_type ExecutorCheckPerms_hook = NULL;
77 /* decls for local routines only used within this module */
78 static void InitPlan(QueryDesc *queryDesc, int eflags);
79 static void CheckValidRowMarkRel(Relation rel, RowMarkType markType);
80 static void ExecPostprocessPlan(EState *estate);
81 static void ExecEndPlan(PlanState *planstate, EState *estate);
82 static void ExecutePlan(EState *estate, PlanState *planstate,
83 bool use_parallel_mode,
87 ScanDirection direction,
90 static bool ExecCheckRTEPerms(RangeTblEntry *rte);
91 static bool ExecCheckRTEPermsModified(Oid relOid, Oid userid,
92 Bitmapset *modifiedCols,
93 AclMode requiredPerms);
94 static void ExecCheckXactReadOnly(PlannedStmt *plannedstmt);
95 static char *ExecBuildSlotValueDescription(Oid reloid,
98 Bitmapset *modifiedCols,
100 static char *ExecBuildSlotPartitionKeyDescription(Relation rel,
104 static void EvalPlanQualStart(EPQState *epqstate, EState *parentestate,
108 * Note that GetUpdatedColumns() also exists in commands/trigger.c. There does
109 * not appear to be any good header to put it into, given the structures that
110 * it uses, so we let them be duplicated. Be sure to update both if one needs
111 * to be changed, however.
113 #define GetInsertedColumns(relinfo, estate) \
114 (rt_fetch((relinfo)->ri_RangeTableIndex, (estate)->es_range_table)->insertedCols)
115 #define GetUpdatedColumns(relinfo, estate) \
116 (rt_fetch((relinfo)->ri_RangeTableIndex, (estate)->es_range_table)->updatedCols)
118 /* end of local decls */
121 /* ----------------------------------------------------------------
124 * This routine must be called at the beginning of any execution of any
127 * Takes a QueryDesc previously created by CreateQueryDesc (which is separate
128 * only because some places use QueryDescs for utility commands). The tupDesc
129 * field of the QueryDesc is filled in to describe the tuples that will be
130 * returned, and the internal fields (estate and planstate) are set up.
132 * eflags contains flag bits as described in executor.h.
134 * NB: the CurrentMemoryContext when this is called will become the parent
135 * of the per-query context used for this Executor invocation.
137 * We provide a function hook variable that lets loadable plugins
138 * get control when ExecutorStart is called. Such a plugin would
139 * normally call standard_ExecutorStart().
141 * ----------------------------------------------------------------
144 ExecutorStart(QueryDesc *queryDesc, int eflags)
146 if (ExecutorStart_hook)
147 (*ExecutorStart_hook) (queryDesc, eflags);
149 standard_ExecutorStart(queryDesc, eflags);
153 standard_ExecutorStart(QueryDesc *queryDesc, int eflags)
156 MemoryContext oldcontext;
158 /* sanity checks: queryDesc must not be started already */
159 Assert(queryDesc != NULL);
160 Assert(queryDesc->estate == NULL);
163 * If the transaction is read-only, we need to check if any writes are
164 * planned to non-temporary tables. EXPLAIN is considered read-only.
166 * Don't allow writes in parallel mode. Supporting UPDATE and DELETE
167 * would require (a) storing the combocid hash in shared memory, rather
168 * than synchronizing it just once at the start of parallelism, and (b) an
169 * alternative to heap_update()'s reliance on xmax for mutual exclusion.
170 * INSERT may have no such troubles, but we forbid it to simplify the
173 * We have lower-level defenses in CommandCounterIncrement and elsewhere
174 * against performing unsafe operations in parallel mode, but this gives a
175 * more user-friendly error message.
177 if ((XactReadOnly || IsInParallelMode()) &&
178 !(eflags & EXEC_FLAG_EXPLAIN_ONLY))
179 ExecCheckXactReadOnly(queryDesc->plannedstmt);
182 * Build EState, switch into per-query memory context for startup.
184 estate = CreateExecutorState();
185 queryDesc->estate = estate;
187 oldcontext = MemoryContextSwitchTo(estate->es_query_cxt);
190 * Fill in external parameters, if any, from queryDesc; and allocate
191 * workspace for internal parameters
193 estate->es_param_list_info = queryDesc->params;
195 if (queryDesc->plannedstmt->nParamExec > 0)
196 estate->es_param_exec_vals = (ParamExecData *)
197 palloc0(queryDesc->plannedstmt->nParamExec * sizeof(ParamExecData));
199 estate->es_sourceText = queryDesc->sourceText;
202 * If non-read-only query, set the command ID to mark output tuples with
204 switch (queryDesc->operation)
209 * SELECT FOR [KEY] UPDATE/SHARE and modifying CTEs need to mark
212 if (queryDesc->plannedstmt->rowMarks != NIL ||
213 queryDesc->plannedstmt->hasModifyingCTE)
214 estate->es_output_cid = GetCurrentCommandId(true);
217 * A SELECT without modifying CTEs can't possibly queue triggers,
218 * so force skip-triggers mode. This is just a marginal efficiency
219 * hack, since AfterTriggerBeginQuery/AfterTriggerEndQuery aren't
220 * all that expensive, but we might as well do it.
222 if (!queryDesc->plannedstmt->hasModifyingCTE)
223 eflags |= EXEC_FLAG_SKIP_TRIGGERS;
229 estate->es_output_cid = GetCurrentCommandId(true);
233 elog(ERROR, "unrecognized operation code: %d",
234 (int) queryDesc->operation);
239 * Copy other important information into the EState
241 estate->es_snapshot = RegisterSnapshot(queryDesc->snapshot);
242 estate->es_crosscheck_snapshot = RegisterSnapshot(queryDesc->crosscheck_snapshot);
243 estate->es_top_eflags = eflags;
244 estate->es_instrument = queryDesc->instrument_options;
247 * Initialize the plan state tree
249 InitPlan(queryDesc, eflags);
252 * Set up an AFTER-trigger statement context, unless told not to, or
253 * unless it's EXPLAIN-only mode (when ExecutorFinish won't be called).
255 if (!(eflags & (EXEC_FLAG_SKIP_TRIGGERS | EXEC_FLAG_EXPLAIN_ONLY)))
256 AfterTriggerBeginQuery();
258 MemoryContextSwitchTo(oldcontext);
261 /* ----------------------------------------------------------------
264 * This is the main routine of the executor module. It accepts
265 * the query descriptor from the traffic cop and executes the
268 * ExecutorStart must have been called already.
270 * If direction is NoMovementScanDirection then nothing is done
271 * except to start up/shut down the destination. Otherwise,
272 * we retrieve up to 'count' tuples in the specified direction.
274 * Note: count = 0 is interpreted as no portal limit, i.e., run to
275 * completion. Also note that the count limit is only applied to
276 * retrieved tuples, not for instance to those inserted/updated/deleted
277 * by a ModifyTable plan node.
279 * There is no return value, but output tuples (if any) are sent to
280 * the destination receiver specified in the QueryDesc; and the number
281 * of tuples processed at the top level can be found in
282 * estate->es_processed.
284 * We provide a function hook variable that lets loadable plugins
285 * get control when ExecutorRun is called. Such a plugin would
286 * normally call standard_ExecutorRun().
288 * ----------------------------------------------------------------
291 ExecutorRun(QueryDesc *queryDesc,
292 ScanDirection direction, uint64 count,
295 if (ExecutorRun_hook)
296 (*ExecutorRun_hook) (queryDesc, direction, count, execute_once);
298 standard_ExecutorRun(queryDesc, direction, count, execute_once);
302 standard_ExecutorRun(QueryDesc *queryDesc,
303 ScanDirection direction, uint64 count, bool execute_once)
309 MemoryContext oldcontext;
312 Assert(queryDesc != NULL);
314 estate = queryDesc->estate;
316 Assert(estate != NULL);
317 Assert(!(estate->es_top_eflags & EXEC_FLAG_EXPLAIN_ONLY));
320 * Switch into per-query memory context
322 oldcontext = MemoryContextSwitchTo(estate->es_query_cxt);
324 /* Allow instrumentation of Executor overall runtime */
325 if (queryDesc->totaltime)
326 InstrStartNode(queryDesc->totaltime);
329 * extract information from the query descriptor and the query feature.
331 operation = queryDesc->operation;
332 dest = queryDesc->dest;
335 * startup tuple receiver, if we will be emitting tuples
337 estate->es_processed = 0;
338 estate->es_lastoid = InvalidOid;
340 sendTuples = (operation == CMD_SELECT ||
341 queryDesc->plannedstmt->hasReturning);
344 (*dest->rStartup) (dest, operation, queryDesc->tupDesc);
349 if (!ScanDirectionIsNoMovement(direction))
351 if (execute_once && queryDesc->already_executed)
352 elog(ERROR, "can't re-execute query flagged for single execution");
353 queryDesc->already_executed = true;
356 queryDesc->planstate,
357 queryDesc->plannedstmt->parallelModeNeeded,
367 * shutdown tuple receiver, if we started it
370 (*dest->rShutdown) (dest);
372 if (queryDesc->totaltime)
373 InstrStopNode(queryDesc->totaltime, estate->es_processed);
375 MemoryContextSwitchTo(oldcontext);
378 /* ----------------------------------------------------------------
381 * This routine must be called after the last ExecutorRun call.
382 * It performs cleanup such as firing AFTER triggers. It is
383 * separate from ExecutorEnd because EXPLAIN ANALYZE needs to
384 * include these actions in the total runtime.
386 * We provide a function hook variable that lets loadable plugins
387 * get control when ExecutorFinish is called. Such a plugin would
388 * normally call standard_ExecutorFinish().
390 * ----------------------------------------------------------------
393 ExecutorFinish(QueryDesc *queryDesc)
395 if (ExecutorFinish_hook)
396 (*ExecutorFinish_hook) (queryDesc);
398 standard_ExecutorFinish(queryDesc);
402 standard_ExecutorFinish(QueryDesc *queryDesc)
405 MemoryContext oldcontext;
408 Assert(queryDesc != NULL);
410 estate = queryDesc->estate;
412 Assert(estate != NULL);
413 Assert(!(estate->es_top_eflags & EXEC_FLAG_EXPLAIN_ONLY));
415 /* This should be run once and only once per Executor instance */
416 Assert(!estate->es_finished);
418 /* Switch into per-query memory context */
419 oldcontext = MemoryContextSwitchTo(estate->es_query_cxt);
421 /* Allow instrumentation of Executor overall runtime */
422 if (queryDesc->totaltime)
423 InstrStartNode(queryDesc->totaltime);
425 /* Run ModifyTable nodes to completion */
426 ExecPostprocessPlan(estate);
428 /* Execute queued AFTER triggers, unless told not to */
429 if (!(estate->es_top_eflags & EXEC_FLAG_SKIP_TRIGGERS))
430 AfterTriggerEndQuery(estate);
432 if (queryDesc->totaltime)
433 InstrStopNode(queryDesc->totaltime, 0);
435 MemoryContextSwitchTo(oldcontext);
437 estate->es_finished = true;
440 /* ----------------------------------------------------------------
443 * This routine must be called at the end of execution of any
446 * We provide a function hook variable that lets loadable plugins
447 * get control when ExecutorEnd is called. Such a plugin would
448 * normally call standard_ExecutorEnd().
450 * ----------------------------------------------------------------
453 ExecutorEnd(QueryDesc *queryDesc)
455 if (ExecutorEnd_hook)
456 (*ExecutorEnd_hook) (queryDesc);
458 standard_ExecutorEnd(queryDesc);
462 standard_ExecutorEnd(QueryDesc *queryDesc)
465 MemoryContext oldcontext;
468 Assert(queryDesc != NULL);
470 estate = queryDesc->estate;
472 Assert(estate != NULL);
475 * Check that ExecutorFinish was called, unless in EXPLAIN-only mode. This
476 * Assert is needed because ExecutorFinish is new as of 9.1, and callers
477 * might forget to call it.
479 Assert(estate->es_finished ||
480 (estate->es_top_eflags & EXEC_FLAG_EXPLAIN_ONLY));
483 * Switch into per-query memory context to run ExecEndPlan
485 oldcontext = MemoryContextSwitchTo(estate->es_query_cxt);
487 ExecEndPlan(queryDesc->planstate, estate);
489 /* do away with our snapshots */
490 UnregisterSnapshot(estate->es_snapshot);
491 UnregisterSnapshot(estate->es_crosscheck_snapshot);
494 * Must switch out of context before destroying it
496 MemoryContextSwitchTo(oldcontext);
499 * Release EState and per-query memory context. This should release
500 * everything the executor has allocated.
502 FreeExecutorState(estate);
504 /* Reset queryDesc fields that no longer point to anything */
505 queryDesc->tupDesc = NULL;
506 queryDesc->estate = NULL;
507 queryDesc->planstate = NULL;
508 queryDesc->totaltime = NULL;
511 /* ----------------------------------------------------------------
514 * This routine may be called on an open queryDesc to rewind it
516 * ----------------------------------------------------------------
519 ExecutorRewind(QueryDesc *queryDesc)
522 MemoryContext oldcontext;
525 Assert(queryDesc != NULL);
527 estate = queryDesc->estate;
529 Assert(estate != NULL);
531 /* It's probably not sensible to rescan updating queries */
532 Assert(queryDesc->operation == CMD_SELECT);
535 * Switch into per-query memory context
537 oldcontext = MemoryContextSwitchTo(estate->es_query_cxt);
542 ExecReScan(queryDesc->planstate);
544 MemoryContextSwitchTo(oldcontext);
550 * Check access permissions for all relations listed in a range table.
552 * Returns true if permissions are adequate. Otherwise, throws an appropriate
553 * error if ereport_on_violation is true, or simply returns false otherwise.
555 * Note that this does NOT address row level security policies (aka: RLS). If
556 * rows will be returned to the user as a result of this permission check
557 * passing, then RLS also needs to be consulted (and check_enable_rls()).
559 * See rewrite/rowsecurity.c.
562 ExecCheckRTPerms(List *rangeTable, bool ereport_on_violation)
567 foreach(l, rangeTable)
569 RangeTblEntry *rte = (RangeTblEntry *) lfirst(l);
571 result = ExecCheckRTEPerms(rte);
574 Assert(rte->rtekind == RTE_RELATION);
575 if (ereport_on_violation)
576 aclcheck_error(ACLCHECK_NO_PRIV, ACL_KIND_CLASS,
577 get_rel_name(rte->relid));
582 if (ExecutorCheckPerms_hook)
583 result = (*ExecutorCheckPerms_hook) (rangeTable,
584 ereport_on_violation);
590 * Check access permissions for a single RTE.
593 ExecCheckRTEPerms(RangeTblEntry *rte)
595 AclMode requiredPerms;
597 AclMode remainingPerms;
602 * Only plain-relation RTEs need to be checked here. Function RTEs are
603 * checked when the function is prepared for execution. Join, subquery,
604 * and special RTEs need no checks.
606 if (rte->rtekind != RTE_RELATION)
610 * No work if requiredPerms is empty.
612 requiredPerms = rte->requiredPerms;
613 if (requiredPerms == 0)
619 * userid to check as: current user unless we have a setuid indication.
621 * Note: GetUserId() is presently fast enough that there's no harm in
622 * calling it separately for each RTE. If that stops being true, we could
623 * call it once in ExecCheckRTPerms and pass the userid down from there.
624 * But for now, no need for the extra clutter.
626 userid = rte->checkAsUser ? rte->checkAsUser : GetUserId();
629 * We must have *all* the requiredPerms bits, but some of the bits can be
630 * satisfied from column-level rather than relation-level permissions.
631 * First, remove any bits that are satisfied by relation permissions.
633 relPerms = pg_class_aclmask(relOid, userid, requiredPerms, ACLMASK_ALL);
634 remainingPerms = requiredPerms & ~relPerms;
635 if (remainingPerms != 0)
640 * If we lack any permissions that exist only as relation permissions,
641 * we can fail straight away.
643 if (remainingPerms & ~(ACL_SELECT | ACL_INSERT | ACL_UPDATE))
647 * Check to see if we have the needed privileges at column level.
649 * Note: failures just report a table-level error; it would be nicer
650 * to report a column-level error if we have some but not all of the
653 if (remainingPerms & ACL_SELECT)
656 * When the query doesn't explicitly reference any columns (for
657 * example, SELECT COUNT(*) FROM table), allow the query if we
658 * have SELECT on any column of the rel, as per SQL spec.
660 if (bms_is_empty(rte->selectedCols))
662 if (pg_attribute_aclcheck_all(relOid, userid, ACL_SELECT,
663 ACLMASK_ANY) != ACLCHECK_OK)
667 while ((col = bms_next_member(rte->selectedCols, col)) >= 0)
669 /* bit #s are offset by FirstLowInvalidHeapAttributeNumber */
670 AttrNumber attno = col + FirstLowInvalidHeapAttributeNumber;
672 if (attno == InvalidAttrNumber)
674 /* Whole-row reference, must have priv on all cols */
675 if (pg_attribute_aclcheck_all(relOid, userid, ACL_SELECT,
676 ACLMASK_ALL) != ACLCHECK_OK)
681 if (pg_attribute_aclcheck(relOid, attno, userid,
682 ACL_SELECT) != ACLCHECK_OK)
689 * Basically the same for the mod columns, for both INSERT and UPDATE
690 * privilege as specified by remainingPerms.
692 if (remainingPerms & ACL_INSERT && !ExecCheckRTEPermsModified(relOid,
698 if (remainingPerms & ACL_UPDATE && !ExecCheckRTEPermsModified(relOid,
708 * ExecCheckRTEPermsModified
709 * Check INSERT or UPDATE access permissions for a single RTE (these
710 * are processed uniformly).
713 ExecCheckRTEPermsModified(Oid relOid, Oid userid, Bitmapset *modifiedCols,
714 AclMode requiredPerms)
719 * When the query doesn't explicitly update any columns, allow the query
720 * if we have permission on any column of the rel. This is to handle
721 * SELECT FOR UPDATE as well as possible corner cases in UPDATE.
723 if (bms_is_empty(modifiedCols))
725 if (pg_attribute_aclcheck_all(relOid, userid, requiredPerms,
726 ACLMASK_ANY) != ACLCHECK_OK)
730 while ((col = bms_next_member(modifiedCols, col)) >= 0)
732 /* bit #s are offset by FirstLowInvalidHeapAttributeNumber */
733 AttrNumber attno = col + FirstLowInvalidHeapAttributeNumber;
735 if (attno == InvalidAttrNumber)
737 /* whole-row reference can't happen here */
738 elog(ERROR, "whole-row update is not implemented");
742 if (pg_attribute_aclcheck(relOid, attno, userid,
743 requiredPerms) != ACLCHECK_OK)
751 * Check that the query does not imply any writes to non-temp tables;
752 * unless we're in parallel mode, in which case don't even allow writes
755 * Note: in a Hot Standby slave this would need to reject writes to temp
756 * tables just as we do in parallel mode; but an HS slave can't have created
757 * any temp tables in the first place, so no need to check that.
760 ExecCheckXactReadOnly(PlannedStmt *plannedstmt)
765 * Fail if write permissions are requested in parallel mode for table
766 * (temp or non-temp), otherwise fail for any non-temp table.
768 foreach(l, plannedstmt->rtable)
770 RangeTblEntry *rte = (RangeTblEntry *) lfirst(l);
772 if (rte->rtekind != RTE_RELATION)
775 if ((rte->requiredPerms & (~ACL_SELECT)) == 0)
778 if (isTempNamespace(get_rel_namespace(rte->relid)))
781 PreventCommandIfReadOnly(CreateCommandTag((Node *) plannedstmt));
784 if (plannedstmt->commandType != CMD_SELECT || plannedstmt->hasModifyingCTE)
785 PreventCommandIfParallelMode(CreateCommandTag((Node *) plannedstmt));
789 /* ----------------------------------------------------------------
792 * Initializes the query plan: open files, allocate storage
793 * and start up the rule manager
794 * ----------------------------------------------------------------
797 InitPlan(QueryDesc *queryDesc, int eflags)
799 CmdType operation = queryDesc->operation;
800 PlannedStmt *plannedstmt = queryDesc->plannedstmt;
801 Plan *plan = plannedstmt->planTree;
802 List *rangeTable = plannedstmt->rtable;
803 EState *estate = queryDesc->estate;
804 PlanState *planstate;
810 * Do permissions checks
812 ExecCheckRTPerms(rangeTable, true);
815 * initialize the node's execution state
817 estate->es_range_table = rangeTable;
818 estate->es_plannedstmt = plannedstmt;
821 * initialize result relation stuff, and open/lock the result rels.
823 * We must do this before initializing the plan tree, else we might try to
824 * do a lock upgrade if a result rel is also a source rel.
826 if (plannedstmt->resultRelations)
828 List *resultRelations = plannedstmt->resultRelations;
829 int numResultRelations = list_length(resultRelations);
830 ResultRelInfo *resultRelInfos;
831 ResultRelInfo *resultRelInfo;
833 resultRelInfos = (ResultRelInfo *)
834 palloc(numResultRelations * sizeof(ResultRelInfo));
835 resultRelInfo = resultRelInfos;
836 foreach(l, resultRelations)
838 Index resultRelationIndex = lfirst_int(l);
839 Oid resultRelationOid;
840 Relation resultRelation;
842 resultRelationOid = getrelid(resultRelationIndex, rangeTable);
843 resultRelation = heap_open(resultRelationOid, RowExclusiveLock);
845 InitResultRelInfo(resultRelInfo,
849 estate->es_instrument);
852 estate->es_result_relations = resultRelInfos;
853 estate->es_num_result_relations = numResultRelations;
854 /* es_result_relation_info is NULL except when within ModifyTable */
855 estate->es_result_relation_info = NULL;
858 * In the partitioned result relation case, lock the non-leaf result
859 * relations too. We don't however need ResultRelInfos for them.
861 if (plannedstmt->nonleafResultRelations)
863 foreach(l, plannedstmt->nonleafResultRelations)
865 Index resultRelationIndex = lfirst_int(l);
866 Oid resultRelationOid;
868 resultRelationOid = getrelid(resultRelationIndex, rangeTable);
869 LockRelationOid(resultRelationOid, RowExclusiveLock);
876 * if no result relation, then set state appropriately
878 estate->es_result_relations = NULL;
879 estate->es_num_result_relations = 0;
880 estate->es_result_relation_info = NULL;
884 * Similarly, we have to lock relations selected FOR [KEY] UPDATE/SHARE
885 * before we initialize the plan tree, else we'd be risking lock upgrades.
886 * While we are at it, build the ExecRowMark list. Any partitioned child
887 * tables are ignored here (because isParent=true) and will be locked by
888 * the first Append or MergeAppend node that references them. (Note that
889 * the RowMarks corresponding to partitioned child tables are present in
890 * the same list as the rest, i.e., plannedstmt->rowMarks.)
892 estate->es_rowMarks = NIL;
893 foreach(l, plannedstmt->rowMarks)
895 PlanRowMark *rc = (PlanRowMark *) lfirst(l);
900 /* ignore "parent" rowmarks; they are irrelevant at runtime */
904 /* get relation's OID (will produce InvalidOid if subquery) */
905 relid = getrelid(rc->rti, rangeTable);
908 * If you change the conditions under which rel locks are acquired
909 * here, be sure to adjust ExecOpenScanRelation to match.
911 switch (rc->markType)
913 case ROW_MARK_EXCLUSIVE:
914 case ROW_MARK_NOKEYEXCLUSIVE:
916 case ROW_MARK_KEYSHARE:
917 relation = heap_open(relid, RowShareLock);
919 case ROW_MARK_REFERENCE:
920 relation = heap_open(relid, AccessShareLock);
923 /* no physical table access is required */
927 elog(ERROR, "unrecognized markType: %d", rc->markType);
928 relation = NULL; /* keep compiler quiet */
932 /* Check that relation is a legal target for marking */
934 CheckValidRowMarkRel(relation, rc->markType);
936 erm = (ExecRowMark *) palloc(sizeof(ExecRowMark));
937 erm->relation = relation;
940 erm->prti = rc->prti;
941 erm->rowmarkId = rc->rowmarkId;
942 erm->markType = rc->markType;
943 erm->strength = rc->strength;
944 erm->waitPolicy = rc->waitPolicy;
945 erm->ermActive = false;
946 ItemPointerSetInvalid(&(erm->curCtid));
947 erm->ermExtra = NULL;
948 estate->es_rowMarks = lappend(estate->es_rowMarks, erm);
952 * Initialize the executor's tuple table to empty.
954 estate->es_tupleTable = NIL;
955 estate->es_trig_tuple_slot = NULL;
956 estate->es_trig_oldtup_slot = NULL;
957 estate->es_trig_newtup_slot = NULL;
959 /* mark EvalPlanQual not active */
960 estate->es_epqTuple = NULL;
961 estate->es_epqTupleSet = NULL;
962 estate->es_epqScanDone = NULL;
965 * Initialize private state information for each SubPlan. We must do this
966 * before running ExecInitNode on the main query tree, since
967 * ExecInitSubPlan expects to be able to find these entries.
969 Assert(estate->es_subplanstates == NIL);
970 i = 1; /* subplan indices count from 1 */
971 foreach(l, plannedstmt->subplans)
973 Plan *subplan = (Plan *) lfirst(l);
974 PlanState *subplanstate;
978 * A subplan will never need to do BACKWARD scan nor MARK/RESTORE. If
979 * it is a parameterless subplan (not initplan), we suggest that it be
980 * prepared to handle REWIND efficiently; otherwise there is no need.
983 & (EXEC_FLAG_EXPLAIN_ONLY | EXEC_FLAG_WITH_NO_DATA);
984 if (bms_is_member(i, plannedstmt->rewindPlanIDs))
985 sp_eflags |= EXEC_FLAG_REWIND;
987 subplanstate = ExecInitNode(subplan, estate, sp_eflags);
989 estate->es_subplanstates = lappend(estate->es_subplanstates,
996 * Initialize the private state information for all the nodes in the query
997 * tree. This opens files, allocates storage and leaves us ready to start
1000 planstate = ExecInitNode(plan, estate, eflags);
1003 * Get the tuple descriptor describing the type of tuples to return.
1005 tupType = ExecGetResultType(planstate);
1008 * Initialize the junk filter if needed. SELECT queries need a filter if
1009 * there are any junk attrs in the top-level tlist.
1011 if (operation == CMD_SELECT)
1013 bool junk_filter_needed = false;
1016 foreach(tlist, plan->targetlist)
1018 TargetEntry *tle = (TargetEntry *) lfirst(tlist);
1022 junk_filter_needed = true;
1027 if (junk_filter_needed)
1031 j = ExecInitJunkFilter(planstate->plan->targetlist,
1033 ExecInitExtraTupleSlot(estate));
1034 estate->es_junkFilter = j;
1036 /* Want to return the cleaned tuple type */
1037 tupType = j->jf_cleanTupType;
1041 queryDesc->tupDesc = tupType;
1042 queryDesc->planstate = planstate;
1046 * Check that a proposed result relation is a legal target for the operation
1048 * Generally the parser and/or planner should have noticed any such mistake
1049 * already, but let's make sure.
1051 * Note: when changing this function, you probably also need to look at
1052 * CheckValidRowMarkRel.
1055 CheckValidResultRel(Relation resultRel, CmdType operation)
1057 TriggerDesc *trigDesc = resultRel->trigdesc;
1058 FdwRoutine *fdwroutine;
1060 switch (resultRel->rd_rel->relkind)
1062 case RELKIND_RELATION:
1063 case RELKIND_PARTITIONED_TABLE:
1064 CheckCmdReplicaIdentity(resultRel, operation);
1066 case RELKIND_SEQUENCE:
1068 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1069 errmsg("cannot change sequence \"%s\"",
1070 RelationGetRelationName(resultRel))));
1072 case RELKIND_TOASTVALUE:
1074 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1075 errmsg("cannot change TOAST relation \"%s\"",
1076 RelationGetRelationName(resultRel))));
1081 * Okay only if there's a suitable INSTEAD OF trigger. Messages
1082 * here should match rewriteHandler.c's rewriteTargetView, except
1083 * that we omit errdetail because we haven't got the information
1084 * handy (and given that we really shouldn't get here anyway, it's
1085 * not worth great exertion to get).
1090 if (!trigDesc || !trigDesc->trig_insert_instead_row)
1092 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
1093 errmsg("cannot insert into view \"%s\"",
1094 RelationGetRelationName(resultRel)),
1095 errhint("To enable inserting into the view, provide an INSTEAD OF INSERT trigger or an unconditional ON INSERT DO INSTEAD rule.")));
1098 if (!trigDesc || !trigDesc->trig_update_instead_row)
1100 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
1101 errmsg("cannot update view \"%s\"",
1102 RelationGetRelationName(resultRel)),
1103 errhint("To enable updating the view, provide an INSTEAD OF UPDATE trigger or an unconditional ON UPDATE DO INSTEAD rule.")));
1106 if (!trigDesc || !trigDesc->trig_delete_instead_row)
1108 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
1109 errmsg("cannot delete from view \"%s\"",
1110 RelationGetRelationName(resultRel)),
1111 errhint("To enable deleting from the view, provide an INSTEAD OF DELETE trigger or an unconditional ON DELETE DO INSTEAD rule.")));
1114 elog(ERROR, "unrecognized CmdType: %d", (int) operation);
1118 case RELKIND_MATVIEW:
1119 if (!MatViewIncrementalMaintenanceIsEnabled())
1121 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1122 errmsg("cannot change materialized view \"%s\"",
1123 RelationGetRelationName(resultRel))));
1125 case RELKIND_FOREIGN_TABLE:
1126 /* Okay only if the FDW supports it */
1127 fdwroutine = GetFdwRoutineForRelation(resultRel, false);
1131 if (fdwroutine->ExecForeignInsert == NULL)
1133 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1134 errmsg("cannot insert into foreign table \"%s\"",
1135 RelationGetRelationName(resultRel))));
1136 if (fdwroutine->IsForeignRelUpdatable != NULL &&
1137 (fdwroutine->IsForeignRelUpdatable(resultRel) & (1 << CMD_INSERT)) == 0)
1139 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
1140 errmsg("foreign table \"%s\" does not allow inserts",
1141 RelationGetRelationName(resultRel))));
1144 if (fdwroutine->ExecForeignUpdate == NULL)
1146 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1147 errmsg("cannot update foreign table \"%s\"",
1148 RelationGetRelationName(resultRel))));
1149 if (fdwroutine->IsForeignRelUpdatable != NULL &&
1150 (fdwroutine->IsForeignRelUpdatable(resultRel) & (1 << CMD_UPDATE)) == 0)
1152 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
1153 errmsg("foreign table \"%s\" does not allow updates",
1154 RelationGetRelationName(resultRel))));
1157 if (fdwroutine->ExecForeignDelete == NULL)
1159 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1160 errmsg("cannot delete from foreign table \"%s\"",
1161 RelationGetRelationName(resultRel))));
1162 if (fdwroutine->IsForeignRelUpdatable != NULL &&
1163 (fdwroutine->IsForeignRelUpdatable(resultRel) & (1 << CMD_DELETE)) == 0)
1165 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
1166 errmsg("foreign table \"%s\" does not allow deletes",
1167 RelationGetRelationName(resultRel))));
1170 elog(ERROR, "unrecognized CmdType: %d", (int) operation);
1176 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1177 errmsg("cannot change relation \"%s\"",
1178 RelationGetRelationName(resultRel))));
1184 * Check that a proposed rowmark target relation is a legal target
1186 * In most cases parser and/or planner should have noticed this already, but
1187 * they don't cover all cases.
1190 CheckValidRowMarkRel(Relation rel, RowMarkType markType)
1192 FdwRoutine *fdwroutine;
1194 switch (rel->rd_rel->relkind)
1196 case RELKIND_RELATION:
1197 case RELKIND_PARTITIONED_TABLE:
1200 case RELKIND_SEQUENCE:
1201 /* Must disallow this because we don't vacuum sequences */
1203 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1204 errmsg("cannot lock rows in sequence \"%s\"",
1205 RelationGetRelationName(rel))));
1207 case RELKIND_TOASTVALUE:
1208 /* We could allow this, but there seems no good reason to */
1210 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1211 errmsg("cannot lock rows in TOAST relation \"%s\"",
1212 RelationGetRelationName(rel))));
1215 /* Should not get here; planner should have expanded the view */
1217 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1218 errmsg("cannot lock rows in view \"%s\"",
1219 RelationGetRelationName(rel))));
1221 case RELKIND_MATVIEW:
1222 /* Allow referencing a matview, but not actual locking clauses */
1223 if (markType != ROW_MARK_REFERENCE)
1225 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1226 errmsg("cannot lock rows in materialized view \"%s\"",
1227 RelationGetRelationName(rel))));
1229 case RELKIND_FOREIGN_TABLE:
1230 /* Okay only if the FDW supports it */
1231 fdwroutine = GetFdwRoutineForRelation(rel, false);
1232 if (fdwroutine->RefetchForeignRow == NULL)
1234 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1235 errmsg("cannot lock rows in foreign table \"%s\"",
1236 RelationGetRelationName(rel))));
1240 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1241 errmsg("cannot lock rows in relation \"%s\"",
1242 RelationGetRelationName(rel))));
1248 * Initialize ResultRelInfo data for one result relation
1250 * Caution: before Postgres 9.1, this function included the relkind checking
1251 * that's now in CheckValidResultRel, and it also did ExecOpenIndices if
1252 * appropriate. Be sure callers cover those needs.
1255 InitResultRelInfo(ResultRelInfo *resultRelInfo,
1256 Relation resultRelationDesc,
1257 Index resultRelationIndex,
1258 Relation partition_root,
1259 int instrument_options)
1261 List *partition_check = NIL;
1263 MemSet(resultRelInfo, 0, sizeof(ResultRelInfo));
1264 resultRelInfo->type = T_ResultRelInfo;
1265 resultRelInfo->ri_RangeTableIndex = resultRelationIndex;
1266 resultRelInfo->ri_RelationDesc = resultRelationDesc;
1267 resultRelInfo->ri_NumIndices = 0;
1268 resultRelInfo->ri_IndexRelationDescs = NULL;
1269 resultRelInfo->ri_IndexRelationInfo = NULL;
1270 /* make a copy so as not to depend on relcache info not changing... */
1271 resultRelInfo->ri_TrigDesc = CopyTriggerDesc(resultRelationDesc->trigdesc);
1272 if (resultRelInfo->ri_TrigDesc)
1274 int n = resultRelInfo->ri_TrigDesc->numtriggers;
1276 resultRelInfo->ri_TrigFunctions = (FmgrInfo *)
1277 palloc0(n * sizeof(FmgrInfo));
1278 resultRelInfo->ri_TrigWhenExprs = (ExprState **)
1279 palloc0(n * sizeof(ExprState *));
1280 if (instrument_options)
1281 resultRelInfo->ri_TrigInstrument = InstrAlloc(n, instrument_options);
1285 resultRelInfo->ri_TrigFunctions = NULL;
1286 resultRelInfo->ri_TrigWhenExprs = NULL;
1287 resultRelInfo->ri_TrigInstrument = NULL;
1289 if (resultRelationDesc->rd_rel->relkind == RELKIND_FOREIGN_TABLE)
1290 resultRelInfo->ri_FdwRoutine = GetFdwRoutineForRelation(resultRelationDesc, true);
1292 resultRelInfo->ri_FdwRoutine = NULL;
1293 resultRelInfo->ri_FdwState = NULL;
1294 resultRelInfo->ri_usesFdwDirectModify = false;
1295 resultRelInfo->ri_ConstraintExprs = NULL;
1296 resultRelInfo->ri_junkFilter = NULL;
1297 resultRelInfo->ri_projectReturning = NULL;
1300 * If partition_root has been specified, that means we are building the
1301 * ResultRelationInfo for one of its leaf partitions. In that case, we
1302 * need *not* initialize the leaf partition's constraint, but rather the
1303 * the partition_root's (if any). We must do that explicitly like this,
1304 * because implicit partition constraints are not inherited like user-
1305 * defined constraints and would fail to be enforced by ExecConstraints()
1306 * after a tuple is routed to a leaf partition.
1311 * Root table itself may or may not be a partition; partition_check
1312 * would be NIL in the latter case.
1314 partition_check = RelationGetPartitionQual(partition_root);
1317 * This is not our own partition constraint, but rather an ancestor's.
1318 * So any Vars in it bear the ancestor's attribute numbers. We must
1319 * switch them to our own. (dummy varno = 1)
1321 if (partition_check != NIL)
1322 partition_check = map_partition_varattnos(partition_check, 1,
1327 partition_check = RelationGetPartitionQual(resultRelationDesc);
1329 resultRelInfo->ri_PartitionCheck = partition_check;
1330 resultRelInfo->ri_PartitionRoot = partition_root;
1334 * ExecGetTriggerResultRel
1336 * Get a ResultRelInfo for a trigger target relation. Most of the time,
1337 * triggers are fired on one of the result relations of the query, and so
1338 * we can just return a member of the es_result_relations array. (Note: in
1339 * self-join situations there might be multiple members with the same OID;
1340 * if so it doesn't matter which one we pick.) However, it is sometimes
1341 * necessary to fire triggers on other relations; this happens mainly when an
1342 * RI update trigger queues additional triggers on other relations, which will
1343 * be processed in the context of the outer query. For efficiency's sake,
1344 * we want to have a ResultRelInfo for those triggers too; that can avoid
1345 * repeated re-opening of the relation. (It also provides a way for EXPLAIN
1346 * ANALYZE to report the runtimes of such triggers.) So we make additional
1347 * ResultRelInfo's as needed, and save them in es_trig_target_relations.
1350 ExecGetTriggerResultRel(EState *estate, Oid relid)
1352 ResultRelInfo *rInfo;
1356 MemoryContext oldcontext;
1358 /* First, search through the query result relations */
1359 rInfo = estate->es_result_relations;
1360 nr = estate->es_num_result_relations;
1363 if (RelationGetRelid(rInfo->ri_RelationDesc) == relid)
1368 /* Nope, but maybe we already made an extra ResultRelInfo for it */
1369 foreach(l, estate->es_trig_target_relations)
1371 rInfo = (ResultRelInfo *) lfirst(l);
1372 if (RelationGetRelid(rInfo->ri_RelationDesc) == relid)
1375 /* Nope, so we need a new one */
1378 * Open the target relation's relcache entry. We assume that an
1379 * appropriate lock is still held by the backend from whenever the trigger
1380 * event got queued, so we need take no new lock here. Also, we need not
1381 * recheck the relkind, so no need for CheckValidResultRel.
1383 rel = heap_open(relid, NoLock);
1386 * Make the new entry in the right context.
1388 oldcontext = MemoryContextSwitchTo(estate->es_query_cxt);
1389 rInfo = makeNode(ResultRelInfo);
1390 InitResultRelInfo(rInfo,
1392 0, /* dummy rangetable index */
1394 estate->es_instrument);
1395 estate->es_trig_target_relations =
1396 lappend(estate->es_trig_target_relations, rInfo);
1397 MemoryContextSwitchTo(oldcontext);
1400 * Currently, we don't need any index information in ResultRelInfos used
1401 * only for triggers, so no need to call ExecOpenIndices.
1408 * ExecContextForcesOids
1410 * This is pretty grotty: when doing INSERT, UPDATE, or CREATE TABLE AS,
1411 * we need to ensure that result tuples have space for an OID iff they are
1412 * going to be stored into a relation that has OIDs. In other contexts
1413 * we are free to choose whether to leave space for OIDs in result tuples
1414 * (we generally don't want to, but we do if a physical-tlist optimization
1415 * is possible). This routine checks the plan context and returns TRUE if the
1416 * choice is forced, FALSE if the choice is not forced. In the TRUE case,
1417 * *hasoids is set to the required value.
1419 * One reason this is ugly is that all plan nodes in the plan tree will emit
1420 * tuples with space for an OID, though we really only need the topmost node
1421 * to do so. However, node types like Sort don't project new tuples but just
1422 * return their inputs, and in those cases the requirement propagates down
1423 * to the input node. Eventually we might make this code smart enough to
1424 * recognize how far down the requirement really goes, but for now we just
1425 * make all plan nodes do the same thing if the top level forces the choice.
1427 * We assume that if we are generating tuples for INSERT or UPDATE,
1428 * estate->es_result_relation_info is already set up to describe the target
1429 * relation. Note that in an UPDATE that spans an inheritance tree, some of
1430 * the target relations may have OIDs and some not. We have to make the
1431 * decisions on a per-relation basis as we initialize each of the subplans of
1432 * the ModifyTable node, so ModifyTable has to set es_result_relation_info
1433 * while initializing each subplan.
1435 * CREATE TABLE AS is even uglier, because we don't have the target relation's
1436 * descriptor available when this code runs; we have to look aside at the
1437 * flags passed to ExecutorStart().
1440 ExecContextForcesOids(PlanState *planstate, bool *hasoids)
1442 ResultRelInfo *ri = planstate->state->es_result_relation_info;
1446 Relation rel = ri->ri_RelationDesc;
1450 *hasoids = rel->rd_rel->relhasoids;
1455 if (planstate->state->es_top_eflags & EXEC_FLAG_WITH_OIDS)
1460 if (planstate->state->es_top_eflags & EXEC_FLAG_WITHOUT_OIDS)
1469 /* ----------------------------------------------------------------
1470 * ExecPostprocessPlan
1472 * Give plan nodes a final chance to execute before shutdown
1473 * ----------------------------------------------------------------
1476 ExecPostprocessPlan(EState *estate)
1481 * Make sure nodes run forward.
1483 estate->es_direction = ForwardScanDirection;
1486 * Run any secondary ModifyTable nodes to completion, in case the main
1487 * query did not fetch all rows from them. (We do this to ensure that
1488 * such nodes have predictable results.)
1490 foreach(lc, estate->es_auxmodifytables)
1492 PlanState *ps = (PlanState *) lfirst(lc);
1496 TupleTableSlot *slot;
1498 /* Reset the per-output-tuple exprcontext each time */
1499 ResetPerTupleExprContext(estate);
1501 slot = ExecProcNode(ps);
1503 if (TupIsNull(slot))
1509 /* ----------------------------------------------------------------
1512 * Cleans up the query plan -- closes files and frees up storage
1514 * NOTE: we are no longer very worried about freeing storage per se
1515 * in this code; FreeExecutorState should be guaranteed to release all
1516 * memory that needs to be released. What we are worried about doing
1517 * is closing relations and dropping buffer pins. Thus, for example,
1518 * tuple tables must be cleared or dropped to ensure pins are released.
1519 * ----------------------------------------------------------------
1522 ExecEndPlan(PlanState *planstate, EState *estate)
1524 ResultRelInfo *resultRelInfo;
1529 * shut down the node-type-specific query processing
1531 ExecEndNode(planstate);
1536 foreach(l, estate->es_subplanstates)
1538 PlanState *subplanstate = (PlanState *) lfirst(l);
1540 ExecEndNode(subplanstate);
1544 * destroy the executor's tuple table. Actually we only care about
1545 * releasing buffer pins and tupdesc refcounts; there's no need to pfree
1546 * the TupleTableSlots, since the containing memory context is about to go
1549 ExecResetTupleTable(estate->es_tupleTable, false);
1552 * close the result relation(s) if any, but hold locks until xact commit.
1554 resultRelInfo = estate->es_result_relations;
1555 for (i = estate->es_num_result_relations; i > 0; i--)
1557 /* Close indices and then the relation itself */
1558 ExecCloseIndices(resultRelInfo);
1559 heap_close(resultRelInfo->ri_RelationDesc, NoLock);
1564 * likewise close any trigger target relations
1566 foreach(l, estate->es_trig_target_relations)
1568 resultRelInfo = (ResultRelInfo *) lfirst(l);
1569 /* Close indices and then the relation itself */
1570 ExecCloseIndices(resultRelInfo);
1571 heap_close(resultRelInfo->ri_RelationDesc, NoLock);
1575 * close any relations selected FOR [KEY] UPDATE/SHARE, again keeping
1578 foreach(l, estate->es_rowMarks)
1580 ExecRowMark *erm = (ExecRowMark *) lfirst(l);
1583 heap_close(erm->relation, NoLock);
1587 /* ----------------------------------------------------------------
1590 * Processes the query plan until we have retrieved 'numberTuples' tuples,
1591 * moving in the specified direction.
1593 * Runs to completion if numberTuples is 0
1595 * Note: the ctid attribute is a 'junk' attribute that is removed before the
1597 * ----------------------------------------------------------------
1600 ExecutePlan(EState *estate,
1601 PlanState *planstate,
1602 bool use_parallel_mode,
1605 uint64 numberTuples,
1606 ScanDirection direction,
1610 TupleTableSlot *slot;
1611 uint64 current_tuple_count;
1614 * initialize local variables
1616 current_tuple_count = 0;
1619 * Set the direction.
1621 estate->es_direction = direction;
1624 * If the plan might potentially be executed multiple times, we must force
1625 * it to run without parallelism, because we might exit early. Also
1626 * disable parallelism when writing into a relation, because no database
1627 * changes are allowed in parallel mode.
1629 if (!execute_once || dest->mydest == DestIntoRel)
1630 use_parallel_mode = false;
1632 if (use_parallel_mode)
1633 EnterParallelMode();
1636 * Loop until we've processed the proper number of tuples from the plan.
1640 /* Reset the per-output-tuple exprcontext */
1641 ResetPerTupleExprContext(estate);
1644 * Execute the plan and obtain a tuple
1646 slot = ExecProcNode(planstate);
1649 * if the tuple is null, then we assume there is nothing more to
1650 * process so we just end the loop...
1652 if (TupIsNull(slot))
1654 /* Allow nodes to release or shut down resources. */
1655 (void) ExecShutdownNode(planstate);
1660 * If we have a junk filter, then project a new tuple with the junk
1663 * Store this new "clean" tuple in the junkfilter's resultSlot.
1664 * (Formerly, we stored it back over the "dirty" tuple, which is WRONG
1665 * because that tuple slot has the wrong descriptor.)
1667 if (estate->es_junkFilter != NULL)
1668 slot = ExecFilterJunk(estate->es_junkFilter, slot);
1671 * If we are supposed to send the tuple somewhere, do so. (In
1672 * practice, this is probably always the case at this point.)
1677 * If we are not able to send the tuple, we assume the destination
1678 * has closed and no more tuples can be sent. If that's the case,
1681 if (!((*dest->receiveSlot) (slot, dest)))
1686 * Count tuples processed, if this is a SELECT. (For other operation
1687 * types, the ModifyTable plan node must count the appropriate
1690 if (operation == CMD_SELECT)
1691 (estate->es_processed)++;
1694 * check our tuple count.. if we've processed the proper number then
1695 * quit, else loop again and process more tuples. Zero numberTuples
1698 current_tuple_count++;
1699 if (numberTuples && numberTuples == current_tuple_count)
1701 /* Allow nodes to release or shut down resources. */
1702 (void) ExecShutdownNode(planstate);
1707 if (use_parallel_mode)
1713 * ExecRelCheck --- check that tuple meets constraints for result relation
1715 * Returns NULL if OK, else name of failed check constraint
1718 ExecRelCheck(ResultRelInfo *resultRelInfo,
1719 TupleTableSlot *slot, EState *estate)
1721 Relation rel = resultRelInfo->ri_RelationDesc;
1722 int ncheck = rel->rd_att->constr->num_check;
1723 ConstrCheck *check = rel->rd_att->constr->check;
1724 ExprContext *econtext;
1725 MemoryContext oldContext;
1729 * If first time through for this result relation, build expression
1730 * nodetrees for rel's constraint expressions. Keep them in the per-query
1731 * memory context so they'll survive throughout the query.
1733 if (resultRelInfo->ri_ConstraintExprs == NULL)
1735 oldContext = MemoryContextSwitchTo(estate->es_query_cxt);
1736 resultRelInfo->ri_ConstraintExprs =
1737 (ExprState **) palloc(ncheck * sizeof(ExprState *));
1738 for (i = 0; i < ncheck; i++)
1742 checkconstr = stringToNode(check[i].ccbin);
1743 resultRelInfo->ri_ConstraintExprs[i] =
1744 ExecPrepareExpr(checkconstr, estate);
1746 MemoryContextSwitchTo(oldContext);
1750 * We will use the EState's per-tuple context for evaluating constraint
1751 * expressions (creating it if it's not already there).
1753 econtext = GetPerTupleExprContext(estate);
1755 /* Arrange for econtext's scan tuple to be the tuple under test */
1756 econtext->ecxt_scantuple = slot;
1758 /* And evaluate the constraints */
1759 for (i = 0; i < ncheck; i++)
1761 ExprState *checkconstr = resultRelInfo->ri_ConstraintExprs[i];
1764 * NOTE: SQL specifies that a NULL result from a constraint expression
1765 * is not to be treated as a failure. Therefore, use ExecCheck not
1768 if (!ExecCheck(checkconstr, econtext))
1769 return check[i].ccname;
1772 /* NULL result means no error */
1777 * ExecPartitionCheck --- check that tuple meets the partition constraint.
1779 * Note: This is called *iff* resultRelInfo is the main target table.
1782 ExecPartitionCheck(ResultRelInfo *resultRelInfo, TupleTableSlot *slot,
1785 ExprContext *econtext;
1788 * If first time through, build expression state tree for the partition
1789 * check expression. Keep it in the per-query memory context so they'll
1790 * survive throughout the query.
1792 if (resultRelInfo->ri_PartitionCheckExpr == NULL)
1794 List *qual = resultRelInfo->ri_PartitionCheck;
1796 resultRelInfo->ri_PartitionCheckExpr = ExecPrepareCheck(qual, estate);
1800 * We will use the EState's per-tuple context for evaluating constraint
1801 * expressions (creating it if it's not already there).
1803 econtext = GetPerTupleExprContext(estate);
1805 /* Arrange for econtext's scan tuple to be the tuple under test */
1806 econtext->ecxt_scantuple = slot;
1809 * As in case of the catalogued constraints, we treat a NULL result as
1810 * success here, not a failure.
1812 return ExecCheck(resultRelInfo->ri_PartitionCheckExpr, econtext);
1816 * ExecConstraints - check constraints of the tuple in 'slot'
1818 * This checks the traditional NOT NULL and check constraints, as well as
1819 * the partition constraint, if any.
1821 * Note: 'slot' contains the tuple to check the constraints of, which may
1822 * have been converted from the original input tuple after tuple routing,
1823 * while 'orig_slot' contains the original tuple to be shown in the message,
1824 * if an error occurs.
1827 ExecConstraints(ResultRelInfo *resultRelInfo,
1828 TupleTableSlot *slot, TupleTableSlot *orig_slot,
1831 Relation rel = resultRelInfo->ri_RelationDesc;
1832 TupleDesc tupdesc = RelationGetDescr(rel);
1833 TupleConstr *constr = tupdesc->constr;
1834 Bitmapset *modifiedCols;
1835 Bitmapset *insertedCols;
1836 Bitmapset *updatedCols;
1838 Assert(constr || resultRelInfo->ri_PartitionCheck);
1840 if (constr && constr->has_not_null)
1842 int natts = tupdesc->natts;
1845 for (attrChk = 1; attrChk <= natts; attrChk++)
1847 if (tupdesc->attrs[attrChk - 1]->attnotnull &&
1848 slot_attisnull(slot, attrChk))
1851 Relation orig_rel = rel;
1852 TupleDesc orig_tupdesc = tupdesc;
1855 * choose the correct relation to build val_desc from the
1856 * tuple contained in orig_slot
1858 if (resultRelInfo->ri_PartitionRoot)
1860 rel = resultRelInfo->ri_PartitionRoot;
1861 tupdesc = RelationGetDescr(rel);
1864 insertedCols = GetInsertedColumns(resultRelInfo, estate);
1865 updatedCols = GetUpdatedColumns(resultRelInfo, estate);
1866 modifiedCols = bms_union(insertedCols, updatedCols);
1867 val_desc = ExecBuildSlotValueDescription(RelationGetRelid(rel),
1874 (errcode(ERRCODE_NOT_NULL_VIOLATION),
1875 errmsg("null value in column \"%s\" violates not-null constraint",
1876 NameStr(orig_tupdesc->attrs[attrChk - 1]->attname)),
1877 val_desc ? errdetail("Failing row contains %s.", val_desc) : 0,
1878 errtablecol(orig_rel, attrChk)));
1883 if (constr && constr->num_check > 0)
1887 if ((failed = ExecRelCheck(resultRelInfo, slot, estate)) != NULL)
1890 Relation orig_rel = rel;
1892 /* See the comment above. */
1893 if (resultRelInfo->ri_PartitionRoot)
1895 rel = resultRelInfo->ri_PartitionRoot;
1896 tupdesc = RelationGetDescr(rel);
1899 insertedCols = GetInsertedColumns(resultRelInfo, estate);
1900 updatedCols = GetUpdatedColumns(resultRelInfo, estate);
1901 modifiedCols = bms_union(insertedCols, updatedCols);
1902 val_desc = ExecBuildSlotValueDescription(RelationGetRelid(rel),
1908 (errcode(ERRCODE_CHECK_VIOLATION),
1909 errmsg("new row for relation \"%s\" violates check constraint \"%s\"",
1910 RelationGetRelationName(orig_rel), failed),
1911 val_desc ? errdetail("Failing row contains %s.", val_desc) : 0,
1912 errtableconstraint(orig_rel, failed)));
1916 if (resultRelInfo->ri_PartitionCheck &&
1917 !ExecPartitionCheck(resultRelInfo, slot, estate))
1920 Relation orig_rel = rel;
1922 /* See the comment above. */
1923 if (resultRelInfo->ri_PartitionRoot)
1925 rel = resultRelInfo->ri_PartitionRoot;
1926 tupdesc = RelationGetDescr(rel);
1929 insertedCols = GetInsertedColumns(resultRelInfo, estate);
1930 updatedCols = GetUpdatedColumns(resultRelInfo, estate);
1931 modifiedCols = bms_union(insertedCols, updatedCols);
1932 val_desc = ExecBuildSlotValueDescription(RelationGetRelid(rel),
1938 (errcode(ERRCODE_CHECK_VIOLATION),
1939 errmsg("new row for relation \"%s\" violates partition constraint",
1940 RelationGetRelationName(orig_rel)),
1941 val_desc ? errdetail("Failing row contains %s.", val_desc) : 0));
1946 * ExecWithCheckOptions -- check that tuple satisfies any WITH CHECK OPTIONs
1947 * of the specified kind.
1949 * Note that this needs to be called multiple times to ensure that all kinds of
1950 * WITH CHECK OPTIONs are handled (both those from views which have the WITH
1951 * CHECK OPTION set and from row level security policies). See ExecInsert()
1955 ExecWithCheckOptions(WCOKind kind, ResultRelInfo *resultRelInfo,
1956 TupleTableSlot *slot, EState *estate)
1958 Relation rel = resultRelInfo->ri_RelationDesc;
1959 TupleDesc tupdesc = RelationGetDescr(rel);
1960 ExprContext *econtext;
1965 * We will use the EState's per-tuple context for evaluating constraint
1966 * expressions (creating it if it's not already there).
1968 econtext = GetPerTupleExprContext(estate);
1970 /* Arrange for econtext's scan tuple to be the tuple under test */
1971 econtext->ecxt_scantuple = slot;
1973 /* Check each of the constraints */
1974 forboth(l1, resultRelInfo->ri_WithCheckOptions,
1975 l2, resultRelInfo->ri_WithCheckOptionExprs)
1977 WithCheckOption *wco = (WithCheckOption *) lfirst(l1);
1978 ExprState *wcoExpr = (ExprState *) lfirst(l2);
1981 * Skip any WCOs which are not the kind we are looking for at this
1984 if (wco->kind != kind)
1988 * WITH CHECK OPTION checks are intended to ensure that the new tuple
1989 * is visible (in the case of a view) or that it passes the
1990 * 'with-check' policy (in the case of row security). If the qual
1991 * evaluates to NULL or FALSE, then the new tuple won't be included in
1992 * the view or doesn't pass the 'with-check' policy for the table.
1994 if (!ExecQual(wcoExpr, econtext))
1997 Bitmapset *modifiedCols;
1998 Bitmapset *insertedCols;
1999 Bitmapset *updatedCols;
2004 * For WITH CHECK OPTIONs coming from views, we might be
2005 * able to provide the details on the row, depending on
2006 * the permissions on the relation (that is, if the user
2007 * could view it directly anyway). For RLS violations, we
2008 * don't include the data since we don't know if the user
2009 * should be able to view the tuple as as that depends on
2012 case WCO_VIEW_CHECK:
2013 insertedCols = GetInsertedColumns(resultRelInfo, estate);
2014 updatedCols = GetUpdatedColumns(resultRelInfo, estate);
2015 modifiedCols = bms_union(insertedCols, updatedCols);
2016 val_desc = ExecBuildSlotValueDescription(RelationGetRelid(rel),
2023 (errcode(ERRCODE_WITH_CHECK_OPTION_VIOLATION),
2024 errmsg("new row violates check option for view \"%s\"",
2026 val_desc ? errdetail("Failing row contains %s.",
2029 case WCO_RLS_INSERT_CHECK:
2030 case WCO_RLS_UPDATE_CHECK:
2031 if (wco->polname != NULL)
2033 (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
2034 errmsg("new row violates row-level security policy \"%s\" for table \"%s\"",
2035 wco->polname, wco->relname)));
2038 (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
2039 errmsg("new row violates row-level security policy for table \"%s\"",
2042 case WCO_RLS_CONFLICT_CHECK:
2043 if (wco->polname != NULL)
2045 (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
2046 errmsg("new row violates row-level security policy \"%s\" (USING expression) for table \"%s\"",
2047 wco->polname, wco->relname)));
2050 (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
2051 errmsg("new row violates row-level security policy (USING expression) for table \"%s\"",
2055 elog(ERROR, "unrecognized WCO kind: %u", wco->kind);
2063 * ExecBuildSlotValueDescription -- construct a string representing a tuple
2065 * This is intentionally very similar to BuildIndexValueDescription, but
2066 * unlike that function, we truncate long field values (to at most maxfieldlen
2067 * bytes). That seems necessary here since heap field values could be very
2068 * long, whereas index entries typically aren't so wide.
2070 * Also, unlike the case with index entries, we need to be prepared to ignore
2071 * dropped columns. We used to use the slot's tuple descriptor to decode the
2072 * data, but the slot's descriptor doesn't identify dropped columns, so we
2073 * now need to be passed the relation's descriptor.
2075 * Note that, like BuildIndexValueDescription, if the user does not have
2076 * permission to view any of the columns involved, a NULL is returned. Unlike
2077 * BuildIndexValueDescription, if the user has access to view a subset of the
2078 * column involved, that subset will be returned with a key identifying which
2082 ExecBuildSlotValueDescription(Oid reloid,
2083 TupleTableSlot *slot,
2085 Bitmapset *modifiedCols,
2089 StringInfoData collist;
2090 bool write_comma = false;
2091 bool write_comma_collist = false;
2093 AclResult aclresult;
2094 bool table_perm = false;
2095 bool any_perm = false;
2098 * Check if RLS is enabled and should be active for the relation; if so,
2099 * then don't return anything. Otherwise, go through normal permission
2102 if (check_enable_rls(reloid, InvalidOid, true) == RLS_ENABLED)
2105 initStringInfo(&buf);
2107 appendStringInfoChar(&buf, '(');
2110 * Check if the user has permissions to see the row. Table-level SELECT
2111 * allows access to all columns. If the user does not have table-level
2112 * SELECT then we check each column and include those the user has SELECT
2113 * rights on. Additionally, we always include columns the user provided
2116 aclresult = pg_class_aclcheck(reloid, GetUserId(), ACL_SELECT);
2117 if (aclresult != ACLCHECK_OK)
2119 /* Set up the buffer for the column list */
2120 initStringInfo(&collist);
2121 appendStringInfoChar(&collist, '(');
2124 table_perm = any_perm = true;
2126 /* Make sure the tuple is fully deconstructed */
2127 slot_getallattrs(slot);
2129 for (i = 0; i < tupdesc->natts; i++)
2131 bool column_perm = false;
2135 /* ignore dropped columns */
2136 if (tupdesc->attrs[i]->attisdropped)
2142 * No table-level SELECT, so need to make sure they either have
2143 * SELECT rights on the column or that they have provided the data
2144 * for the column. If not, omit this column from the error
2147 aclresult = pg_attribute_aclcheck(reloid, tupdesc->attrs[i]->attnum,
2148 GetUserId(), ACL_SELECT);
2149 if (bms_is_member(tupdesc->attrs[i]->attnum - FirstLowInvalidHeapAttributeNumber,
2150 modifiedCols) || aclresult == ACLCHECK_OK)
2152 column_perm = any_perm = true;
2154 if (write_comma_collist)
2155 appendStringInfoString(&collist, ", ");
2157 write_comma_collist = true;
2159 appendStringInfoString(&collist, NameStr(tupdesc->attrs[i]->attname));
2163 if (table_perm || column_perm)
2165 if (slot->tts_isnull[i])
2172 getTypeOutputInfo(tupdesc->attrs[i]->atttypid,
2173 &foutoid, &typisvarlena);
2174 val = OidOutputFunctionCall(foutoid, slot->tts_values[i]);
2178 appendStringInfoString(&buf, ", ");
2182 /* truncate if needed */
2183 vallen = strlen(val);
2184 if (vallen <= maxfieldlen)
2185 appendStringInfoString(&buf, val);
2188 vallen = pg_mbcliplen(val, vallen, maxfieldlen);
2189 appendBinaryStringInfo(&buf, val, vallen);
2190 appendStringInfoString(&buf, "...");
2195 /* If we end up with zero columns being returned, then return NULL. */
2199 appendStringInfoChar(&buf, ')');
2203 appendStringInfoString(&collist, ") = ");
2204 appendStringInfoString(&collist, buf.data);
2206 return collist.data;
2214 * ExecUpdateLockMode -- find the appropriate UPDATE tuple lock mode for a
2215 * given ResultRelInfo
2218 ExecUpdateLockMode(EState *estate, ResultRelInfo *relinfo)
2221 Bitmapset *updatedCols;
2224 * Compute lock mode to use. If columns that are part of the key have not
2225 * been modified, then we can use a weaker lock, allowing for better
2228 updatedCols = GetUpdatedColumns(relinfo, estate);
2229 keyCols = RelationGetIndexAttrBitmap(relinfo->ri_RelationDesc,
2230 INDEX_ATTR_BITMAP_KEY);
2232 if (bms_overlap(keyCols, updatedCols))
2233 return LockTupleExclusive;
2235 return LockTupleNoKeyExclusive;
2239 * ExecFindRowMark -- find the ExecRowMark struct for given rangetable index
2241 * If no such struct, either return NULL or throw error depending on missing_ok
2244 ExecFindRowMark(EState *estate, Index rti, bool missing_ok)
2248 foreach(lc, estate->es_rowMarks)
2250 ExecRowMark *erm = (ExecRowMark *) lfirst(lc);
2252 if (erm->rti == rti)
2256 elog(ERROR, "failed to find ExecRowMark for rangetable index %u", rti);
2261 * ExecBuildAuxRowMark -- create an ExecAuxRowMark struct
2263 * Inputs are the underlying ExecRowMark struct and the targetlist of the
2264 * input plan node (not planstate node!). We need the latter to find out
2265 * the column numbers of the resjunk columns.
2268 ExecBuildAuxRowMark(ExecRowMark *erm, List *targetlist)
2270 ExecAuxRowMark *aerm = (ExecAuxRowMark *) palloc0(sizeof(ExecAuxRowMark));
2273 aerm->rowmark = erm;
2275 /* Look up the resjunk columns associated with this rowmark */
2276 if (erm->markType != ROW_MARK_COPY)
2278 /* need ctid for all methods other than COPY */
2279 snprintf(resname, sizeof(resname), "ctid%u", erm->rowmarkId);
2280 aerm->ctidAttNo = ExecFindJunkAttributeInTlist(targetlist,
2282 if (!AttributeNumberIsValid(aerm->ctidAttNo))
2283 elog(ERROR, "could not find junk %s column", resname);
2287 /* need wholerow if COPY */
2288 snprintf(resname, sizeof(resname), "wholerow%u", erm->rowmarkId);
2289 aerm->wholeAttNo = ExecFindJunkAttributeInTlist(targetlist,
2291 if (!AttributeNumberIsValid(aerm->wholeAttNo))
2292 elog(ERROR, "could not find junk %s column", resname);
2295 /* if child rel, need tableoid */
2296 if (erm->rti != erm->prti)
2298 snprintf(resname, sizeof(resname), "tableoid%u", erm->rowmarkId);
2299 aerm->toidAttNo = ExecFindJunkAttributeInTlist(targetlist,
2301 if (!AttributeNumberIsValid(aerm->toidAttNo))
2302 elog(ERROR, "could not find junk %s column", resname);
2310 * EvalPlanQual logic --- recheck modified tuple(s) to see if we want to
2311 * process the updated version under READ COMMITTED rules.
2313 * See backend/executor/README for some info about how this works.
2318 * Check a modified tuple to see if we want to process its updated version
2319 * under READ COMMITTED rules.
2321 * estate - outer executor state data
2322 * epqstate - state for EvalPlanQual rechecking
2323 * relation - table containing tuple
2324 * rti - rangetable index of table containing tuple
2325 * lockmode - requested tuple lock mode
2326 * *tid - t_ctid from the outdated tuple (ie, next updated version)
2327 * priorXmax - t_xmax from the outdated tuple
2329 * *tid is also an output parameter: it's modified to hold the TID of the
2330 * latest version of the tuple (note this may be changed even on failure)
2332 * Returns a slot containing the new candidate update/delete tuple, or
2333 * NULL if we determine we shouldn't process the row.
2335 * Note: properly, lockmode should be declared as enum LockTupleMode,
2336 * but we use "int" to avoid having to include heapam.h in executor.h.
2339 EvalPlanQual(EState *estate, EPQState *epqstate,
2340 Relation relation, Index rti, int lockmode,
2341 ItemPointer tid, TransactionId priorXmax)
2343 TupleTableSlot *slot;
2344 HeapTuple copyTuple;
2349 * Get and lock the updated version of the row; if fail, return NULL.
2351 copyTuple = EvalPlanQualFetch(estate, relation, lockmode, LockWaitBlock,
2354 if (copyTuple == NULL)
2358 * For UPDATE/DELETE we have to return tid of actual row we're executing
2361 *tid = copyTuple->t_self;
2364 * Need to run a recheck subquery. Initialize or reinitialize EPQ state.
2366 EvalPlanQualBegin(epqstate, estate);
2369 * Free old test tuple, if any, and store new tuple where relation's scan
2372 EvalPlanQualSetTuple(epqstate, rti, copyTuple);
2375 * Fetch any non-locked source rows
2377 EvalPlanQualFetchRowMarks(epqstate);
2380 * Run the EPQ query. We assume it will return at most one tuple.
2382 slot = EvalPlanQualNext(epqstate);
2385 * If we got a tuple, force the slot to materialize the tuple so that it
2386 * is not dependent on any local state in the EPQ query (in particular,
2387 * it's highly likely that the slot contains references to any pass-by-ref
2388 * datums that may be present in copyTuple). As with the next step, this
2389 * is to guard against early re-use of the EPQ query.
2391 if (!TupIsNull(slot))
2392 (void) ExecMaterializeSlot(slot);
2395 * Clear out the test tuple. This is needed in case the EPQ query is
2396 * re-used to test a tuple for a different relation. (Not clear that can
2397 * really happen, but let's be safe.)
2399 EvalPlanQualSetTuple(epqstate, rti, NULL);
2405 * Fetch a copy of the newest version of an outdated tuple
2407 * estate - executor state data
2408 * relation - table containing tuple
2409 * lockmode - requested tuple lock mode
2410 * wait_policy - requested lock wait policy
2411 * *tid - t_ctid from the outdated tuple (ie, next updated version)
2412 * priorXmax - t_xmax from the outdated tuple
2414 * Returns a palloc'd copy of the newest tuple version, or NULL if we find
2415 * that there is no newest version (ie, the row was deleted not updated).
2416 * We also return NULL if the tuple is locked and the wait policy is to skip
2419 * If successful, we have locked the newest tuple version, so caller does not
2420 * need to worry about it changing anymore.
2422 * Note: properly, lockmode should be declared as enum LockTupleMode,
2423 * but we use "int" to avoid having to include heapam.h in executor.h.
2426 EvalPlanQualFetch(EState *estate, Relation relation, int lockmode,
2427 LockWaitPolicy wait_policy,
2428 ItemPointer tid, TransactionId priorXmax)
2430 HeapTuple copyTuple = NULL;
2431 HeapTupleData tuple;
2432 SnapshotData SnapshotDirty;
2435 * fetch target tuple
2437 * Loop here to deal with updated or busy tuples
2439 InitDirtySnapshot(SnapshotDirty);
2440 tuple.t_self = *tid;
2445 if (heap_fetch(relation, &SnapshotDirty, &tuple, &buffer, true, NULL))
2448 HeapUpdateFailureData hufd;
2451 * If xmin isn't what we're expecting, the slot must have been
2452 * recycled and reused for an unrelated tuple. This implies that
2453 * the latest version of the row was deleted, so we need do
2454 * nothing. (Should be safe to examine xmin without getting
2455 * buffer's content lock. We assume reading a TransactionId to be
2456 * atomic, and Xmin never changes in an existing tuple, except to
2457 * invalid or frozen, and neither of those can match priorXmax.)
2459 if (!TransactionIdEquals(HeapTupleHeaderGetXmin(tuple.t_data),
2462 ReleaseBuffer(buffer);
2466 /* otherwise xmin should not be dirty... */
2467 if (TransactionIdIsValid(SnapshotDirty.xmin))
2468 elog(ERROR, "t_xmin is uncommitted in tuple to be updated");
2471 * If tuple is being updated by other transaction then we have to
2472 * wait for its commit/abort, or die trying.
2474 if (TransactionIdIsValid(SnapshotDirty.xmax))
2476 ReleaseBuffer(buffer);
2477 switch (wait_policy)
2480 XactLockTableWait(SnapshotDirty.xmax,
2481 relation, &tuple.t_self,
2485 if (!ConditionalXactLockTableWait(SnapshotDirty.xmax))
2486 return NULL; /* skip instead of waiting */
2489 if (!ConditionalXactLockTableWait(SnapshotDirty.xmax))
2491 (errcode(ERRCODE_LOCK_NOT_AVAILABLE),
2492 errmsg("could not obtain lock on row in relation \"%s\"",
2493 RelationGetRelationName(relation))));
2496 continue; /* loop back to repeat heap_fetch */
2500 * If tuple was inserted by our own transaction, we have to check
2501 * cmin against es_output_cid: cmin >= current CID means our
2502 * command cannot see the tuple, so we should ignore it. Otherwise
2503 * heap_lock_tuple() will throw an error, and so would any later
2504 * attempt to update or delete the tuple. (We need not check cmax
2505 * because HeapTupleSatisfiesDirty will consider a tuple deleted
2506 * by our transaction dead, regardless of cmax.) We just checked
2507 * that priorXmax == xmin, so we can test that variable instead of
2508 * doing HeapTupleHeaderGetXmin again.
2510 if (TransactionIdIsCurrentTransactionId(priorXmax) &&
2511 HeapTupleHeaderGetCmin(tuple.t_data) >= estate->es_output_cid)
2513 ReleaseBuffer(buffer);
2518 * This is a live tuple, so now try to lock it.
2520 test = heap_lock_tuple(relation, &tuple,
2521 estate->es_output_cid,
2522 lockmode, wait_policy,
2523 false, &buffer, &hufd);
2524 /* We now have two pins on the buffer, get rid of one */
2525 ReleaseBuffer(buffer);
2529 case HeapTupleSelfUpdated:
2532 * The target tuple was already updated or deleted by the
2533 * current command, or by a later command in the current
2534 * transaction. We *must* ignore the tuple in the former
2535 * case, so as to avoid the "Halloween problem" of
2536 * repeated update attempts. In the latter case it might
2537 * be sensible to fetch the updated tuple instead, but
2538 * doing so would require changing heap_update and
2539 * heap_delete to not complain about updating "invisible"
2540 * tuples, which seems pretty scary (heap_lock_tuple will
2541 * not complain, but few callers expect
2542 * HeapTupleInvisible, and we're not one of them). So for
2543 * now, treat the tuple as deleted and do not process.
2545 ReleaseBuffer(buffer);
2548 case HeapTupleMayBeUpdated:
2549 /* successfully locked */
2552 case HeapTupleUpdated:
2553 ReleaseBuffer(buffer);
2554 if (IsolationUsesXactSnapshot())
2556 (errcode(ERRCODE_T_R_SERIALIZATION_FAILURE),
2557 errmsg("could not serialize access due to concurrent update")));
2559 /* Should not encounter speculative tuple on recheck */
2560 Assert(!HeapTupleHeaderIsSpeculative(tuple.t_data));
2561 if (!ItemPointerEquals(&hufd.ctid, &tuple.t_self))
2563 /* it was updated, so look at the updated version */
2564 tuple.t_self = hufd.ctid;
2565 /* updated row should have xmin matching this xmax */
2566 priorXmax = hufd.xmax;
2569 /* tuple was deleted, so give up */
2572 case HeapTupleWouldBlock:
2573 ReleaseBuffer(buffer);
2576 case HeapTupleInvisible:
2577 elog(ERROR, "attempted to lock invisible tuple");
2580 ReleaseBuffer(buffer);
2581 elog(ERROR, "unrecognized heap_lock_tuple status: %u",
2583 return NULL; /* keep compiler quiet */
2587 * We got tuple - now copy it for use by recheck query.
2589 copyTuple = heap_copytuple(&tuple);
2590 ReleaseBuffer(buffer);
2595 * If the referenced slot was actually empty, the latest version of
2596 * the row must have been deleted, so we need do nothing.
2598 if (tuple.t_data == NULL)
2600 ReleaseBuffer(buffer);
2605 * As above, if xmin isn't what we're expecting, do nothing.
2607 if (!TransactionIdEquals(HeapTupleHeaderGetXmin(tuple.t_data),
2610 ReleaseBuffer(buffer);
2615 * If we get here, the tuple was found but failed SnapshotDirty.
2616 * Assuming the xmin is either a committed xact or our own xact (as it
2617 * certainly should be if we're trying to modify the tuple), this must
2618 * mean that the row was updated or deleted by either a committed xact
2619 * or our own xact. If it was deleted, we can ignore it; if it was
2620 * updated then chain up to the next version and repeat the whole
2623 * As above, it should be safe to examine xmax and t_ctid without the
2624 * buffer content lock, because they can't be changing.
2626 if (ItemPointerEquals(&tuple.t_self, &tuple.t_data->t_ctid))
2628 /* deleted, so forget about it */
2629 ReleaseBuffer(buffer);
2633 /* updated, so look at the updated row */
2634 tuple.t_self = tuple.t_data->t_ctid;
2635 /* updated row should have xmin matching this xmax */
2636 priorXmax = HeapTupleHeaderGetUpdateXid(tuple.t_data);
2637 ReleaseBuffer(buffer);
2638 /* loop back to fetch next in chain */
2642 * Return the copied tuple
2648 * EvalPlanQualInit -- initialize during creation of a plan state node
2649 * that might need to invoke EPQ processing.
2651 * Note: subplan/auxrowmarks can be NULL/NIL if they will be set later
2652 * with EvalPlanQualSetPlan.
2655 EvalPlanQualInit(EPQState *epqstate, EState *estate,
2656 Plan *subplan, List *auxrowmarks, int epqParam)
2658 /* Mark the EPQ state inactive */
2659 epqstate->estate = NULL;
2660 epqstate->planstate = NULL;
2661 epqstate->origslot = NULL;
2662 /* ... and remember data that EvalPlanQualBegin will need */
2663 epqstate->plan = subplan;
2664 epqstate->arowMarks = auxrowmarks;
2665 epqstate->epqParam = epqParam;
2669 * EvalPlanQualSetPlan -- set or change subplan of an EPQState.
2671 * We need this so that ModifyTable can deal with multiple subplans.
2674 EvalPlanQualSetPlan(EPQState *epqstate, Plan *subplan, List *auxrowmarks)
2676 /* If we have a live EPQ query, shut it down */
2677 EvalPlanQualEnd(epqstate);
2678 /* And set/change the plan pointer */
2679 epqstate->plan = subplan;
2680 /* The rowmarks depend on the plan, too */
2681 epqstate->arowMarks = auxrowmarks;
2685 * Install one test tuple into EPQ state, or clear test tuple if tuple == NULL
2687 * NB: passed tuple must be palloc'd; it may get freed later
2690 EvalPlanQualSetTuple(EPQState *epqstate, Index rti, HeapTuple tuple)
2692 EState *estate = epqstate->estate;
2697 * free old test tuple, if any, and store new tuple where relation's scan
2700 if (estate->es_epqTuple[rti - 1] != NULL)
2701 heap_freetuple(estate->es_epqTuple[rti - 1]);
2702 estate->es_epqTuple[rti - 1] = tuple;
2703 estate->es_epqTupleSet[rti - 1] = true;
2707 * Fetch back the current test tuple (if any) for the specified RTI
2710 EvalPlanQualGetTuple(EPQState *epqstate, Index rti)
2712 EState *estate = epqstate->estate;
2716 return estate->es_epqTuple[rti - 1];
2720 * Fetch the current row values for any non-locked relations that need
2721 * to be scanned by an EvalPlanQual operation. origslot must have been set
2722 * to contain the current result row (top-level row) that we need to recheck.
2725 EvalPlanQualFetchRowMarks(EPQState *epqstate)
2729 Assert(epqstate->origslot != NULL);
2731 foreach(l, epqstate->arowMarks)
2733 ExecAuxRowMark *aerm = (ExecAuxRowMark *) lfirst(l);
2734 ExecRowMark *erm = aerm->rowmark;
2737 HeapTupleData tuple;
2739 if (RowMarkRequiresRowShareLock(erm->markType))
2740 elog(ERROR, "EvalPlanQual doesn't support locking rowmarks");
2742 /* clear any leftover test tuple for this rel */
2743 EvalPlanQualSetTuple(epqstate, erm->rti, NULL);
2745 /* if child rel, must check whether it produced this row */
2746 if (erm->rti != erm->prti)
2750 datum = ExecGetJunkAttribute(epqstate->origslot,
2753 /* non-locked rels could be on the inside of outer joins */
2756 tableoid = DatumGetObjectId(datum);
2758 Assert(OidIsValid(erm->relid));
2759 if (tableoid != erm->relid)
2761 /* this child is inactive right now */
2766 if (erm->markType == ROW_MARK_REFERENCE)
2768 HeapTuple copyTuple;
2770 Assert(erm->relation != NULL);
2772 /* fetch the tuple's ctid */
2773 datum = ExecGetJunkAttribute(epqstate->origslot,
2776 /* non-locked rels could be on the inside of outer joins */
2780 /* fetch requests on foreign tables must be passed to their FDW */
2781 if (erm->relation->rd_rel->relkind == RELKIND_FOREIGN_TABLE)
2783 FdwRoutine *fdwroutine;
2784 bool updated = false;
2786 fdwroutine = GetFdwRoutineForRelation(erm->relation, false);
2787 /* this should have been checked already, but let's be safe */
2788 if (fdwroutine->RefetchForeignRow == NULL)
2790 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2791 errmsg("cannot lock rows in foreign table \"%s\"",
2792 RelationGetRelationName(erm->relation))));
2793 copyTuple = fdwroutine->RefetchForeignRow(epqstate->estate,
2797 if (copyTuple == NULL)
2798 elog(ERROR, "failed to fetch tuple for EvalPlanQual recheck");
2801 * Ideally we'd insist on updated == false here, but that
2802 * assumes that FDWs can track that exactly, which they might
2803 * not be able to. So just ignore the flag.
2808 /* ordinary table, fetch the tuple */
2811 tuple.t_self = *((ItemPointer) DatumGetPointer(datum));
2812 if (!heap_fetch(erm->relation, SnapshotAny, &tuple, &buffer,
2814 elog(ERROR, "failed to fetch tuple for EvalPlanQual recheck");
2816 /* successful, copy tuple */
2817 copyTuple = heap_copytuple(&tuple);
2818 ReleaseBuffer(buffer);
2822 EvalPlanQualSetTuple(epqstate, erm->rti, copyTuple);
2828 Assert(erm->markType == ROW_MARK_COPY);
2830 /* fetch the whole-row Var for the relation */
2831 datum = ExecGetJunkAttribute(epqstate->origslot,
2834 /* non-locked rels could be on the inside of outer joins */
2837 td = DatumGetHeapTupleHeader(datum);
2839 /* build a temporary HeapTuple control structure */
2840 tuple.t_len = HeapTupleHeaderGetDatumLength(td);
2842 /* relation might be a foreign table, if so provide tableoid */
2843 tuple.t_tableOid = erm->relid;
2844 /* also copy t_ctid in case there's valid data there */
2845 tuple.t_self = td->t_ctid;
2847 /* copy and store tuple */
2848 EvalPlanQualSetTuple(epqstate, erm->rti,
2849 heap_copytuple(&tuple));
2855 * Fetch the next row (if any) from EvalPlanQual testing
2857 * (In practice, there should never be more than one row...)
2860 EvalPlanQualNext(EPQState *epqstate)
2862 MemoryContext oldcontext;
2863 TupleTableSlot *slot;
2865 oldcontext = MemoryContextSwitchTo(epqstate->estate->es_query_cxt);
2866 slot = ExecProcNode(epqstate->planstate);
2867 MemoryContextSwitchTo(oldcontext);
2873 * Initialize or reset an EvalPlanQual state tree
2876 EvalPlanQualBegin(EPQState *epqstate, EState *parentestate)
2878 EState *estate = epqstate->estate;
2882 /* First time through, so create a child EState */
2883 EvalPlanQualStart(epqstate, parentestate, epqstate->plan);
2888 * We already have a suitable child EPQ tree, so just reset it.
2890 int rtsize = list_length(parentestate->es_range_table);
2891 PlanState *planstate = epqstate->planstate;
2893 MemSet(estate->es_epqScanDone, 0, rtsize * sizeof(bool));
2895 /* Recopy current values of parent parameters */
2896 if (parentestate->es_plannedstmt->nParamExec > 0)
2898 int i = parentestate->es_plannedstmt->nParamExec;
2902 /* copy value if any, but not execPlan link */
2903 estate->es_param_exec_vals[i].value =
2904 parentestate->es_param_exec_vals[i].value;
2905 estate->es_param_exec_vals[i].isnull =
2906 parentestate->es_param_exec_vals[i].isnull;
2911 * Mark child plan tree as needing rescan at all scan nodes. The
2912 * first ExecProcNode will take care of actually doing the rescan.
2914 planstate->chgParam = bms_add_member(planstate->chgParam,
2915 epqstate->epqParam);
2920 * Start execution of an EvalPlanQual plan tree.
2922 * This is a cut-down version of ExecutorStart(): we copy some state from
2923 * the top-level estate rather than initializing it fresh.
2926 EvalPlanQualStart(EPQState *epqstate, EState *parentestate, Plan *planTree)
2930 MemoryContext oldcontext;
2933 rtsize = list_length(parentestate->es_range_table);
2935 epqstate->estate = estate = CreateExecutorState();
2937 oldcontext = MemoryContextSwitchTo(estate->es_query_cxt);
2940 * Child EPQ EStates share the parent's copy of unchanging state such as
2941 * the snapshot, rangetable, result-rel info, and external Param info.
2942 * They need their own copies of local state, including a tuple table,
2943 * es_param_exec_vals, etc.
2945 * The ResultRelInfo array management is trickier than it looks. We
2946 * create a fresh array for the child but copy all the content from the
2947 * parent. This is because it's okay for the child to share any
2948 * per-relation state the parent has already created --- but if the child
2949 * sets up any ResultRelInfo fields, such as its own junkfilter, that
2950 * state must *not* propagate back to the parent. (For one thing, the
2951 * pointed-to data is in a memory context that won't last long enough.)
2953 estate->es_direction = ForwardScanDirection;
2954 estate->es_snapshot = parentestate->es_snapshot;
2955 estate->es_crosscheck_snapshot = parentestate->es_crosscheck_snapshot;
2956 estate->es_range_table = parentestate->es_range_table;
2957 estate->es_plannedstmt = parentestate->es_plannedstmt;
2958 estate->es_junkFilter = parentestate->es_junkFilter;
2959 estate->es_output_cid = parentestate->es_output_cid;
2960 if (parentestate->es_num_result_relations > 0)
2962 int numResultRelations = parentestate->es_num_result_relations;
2963 ResultRelInfo *resultRelInfos;
2965 resultRelInfos = (ResultRelInfo *)
2966 palloc(numResultRelations * sizeof(ResultRelInfo));
2967 memcpy(resultRelInfos, parentestate->es_result_relations,
2968 numResultRelations * sizeof(ResultRelInfo));
2969 estate->es_result_relations = resultRelInfos;
2970 estate->es_num_result_relations = numResultRelations;
2972 /* es_result_relation_info must NOT be copied */
2973 /* es_trig_target_relations must NOT be copied */
2974 estate->es_rowMarks = parentestate->es_rowMarks;
2975 estate->es_top_eflags = parentestate->es_top_eflags;
2976 estate->es_instrument = parentestate->es_instrument;
2977 /* es_auxmodifytables must NOT be copied */
2980 * The external param list is simply shared from parent. The internal
2981 * param workspace has to be local state, but we copy the initial values
2982 * from the parent, so as to have access to any param values that were
2983 * already set from other parts of the parent's plan tree.
2985 estate->es_param_list_info = parentestate->es_param_list_info;
2986 if (parentestate->es_plannedstmt->nParamExec > 0)
2988 int i = parentestate->es_plannedstmt->nParamExec;
2990 estate->es_param_exec_vals = (ParamExecData *)
2991 palloc0(i * sizeof(ParamExecData));
2994 /* copy value if any, but not execPlan link */
2995 estate->es_param_exec_vals[i].value =
2996 parentestate->es_param_exec_vals[i].value;
2997 estate->es_param_exec_vals[i].isnull =
2998 parentestate->es_param_exec_vals[i].isnull;
3003 * Each EState must have its own es_epqScanDone state, but if we have
3004 * nested EPQ checks they should share es_epqTuple arrays. This allows
3005 * sub-rechecks to inherit the values being examined by an outer recheck.
3007 estate->es_epqScanDone = (bool *) palloc0(rtsize * sizeof(bool));
3008 if (parentestate->es_epqTuple != NULL)
3010 estate->es_epqTuple = parentestate->es_epqTuple;
3011 estate->es_epqTupleSet = parentestate->es_epqTupleSet;
3015 estate->es_epqTuple = (HeapTuple *)
3016 palloc0(rtsize * sizeof(HeapTuple));
3017 estate->es_epqTupleSet = (bool *)
3018 palloc0(rtsize * sizeof(bool));
3022 * Each estate also has its own tuple table.
3024 estate->es_tupleTable = NIL;
3027 * Initialize private state information for each SubPlan. We must do this
3028 * before running ExecInitNode on the main query tree, since
3029 * ExecInitSubPlan expects to be able to find these entries. Some of the
3030 * SubPlans might not be used in the part of the plan tree we intend to
3031 * run, but since it's not easy to tell which, we just initialize them
3034 Assert(estate->es_subplanstates == NIL);
3035 foreach(l, parentestate->es_plannedstmt->subplans)
3037 Plan *subplan = (Plan *) lfirst(l);
3038 PlanState *subplanstate;
3040 subplanstate = ExecInitNode(subplan, estate, 0);
3041 estate->es_subplanstates = lappend(estate->es_subplanstates,
3046 * Initialize the private state information for all the nodes in the part
3047 * of the plan tree we need to run. This opens files, allocates storage
3048 * and leaves us ready to start processing tuples.
3050 epqstate->planstate = ExecInitNode(planTree, estate, 0);
3052 MemoryContextSwitchTo(oldcontext);
3056 * EvalPlanQualEnd -- shut down at termination of parent plan state node,
3057 * or if we are done with the current EPQ child.
3059 * This is a cut-down version of ExecutorEnd(); basically we want to do most
3060 * of the normal cleanup, but *not* close result relations (which we are
3061 * just sharing from the outer query). We do, however, have to close any
3062 * trigger target relations that got opened, since those are not shared.
3063 * (There probably shouldn't be any of the latter, but just in case...)
3066 EvalPlanQualEnd(EPQState *epqstate)
3068 EState *estate = epqstate->estate;
3069 MemoryContext oldcontext;
3073 return; /* idle, so nothing to do */
3075 oldcontext = MemoryContextSwitchTo(estate->es_query_cxt);
3077 ExecEndNode(epqstate->planstate);
3079 foreach(l, estate->es_subplanstates)
3081 PlanState *subplanstate = (PlanState *) lfirst(l);
3083 ExecEndNode(subplanstate);
3086 /* throw away the per-estate tuple table */
3087 ExecResetTupleTable(estate->es_tupleTable, false);
3089 /* close any trigger target relations attached to this EState */
3090 foreach(l, estate->es_trig_target_relations)
3092 ResultRelInfo *resultRelInfo = (ResultRelInfo *) lfirst(l);
3094 /* Close indices and then the relation itself */
3095 ExecCloseIndices(resultRelInfo);
3096 heap_close(resultRelInfo->ri_RelationDesc, NoLock);
3099 MemoryContextSwitchTo(oldcontext);
3101 FreeExecutorState(estate);
3103 /* Mark EPQState idle */
3104 epqstate->estate = NULL;
3105 epqstate->planstate = NULL;
3106 epqstate->origslot = NULL;
3110 * ExecSetupPartitionTupleRouting - set up information needed during
3111 * tuple routing for partitioned tables
3114 * 'pd' receives an array of PartitionDispatch objects with one entry for
3115 * every partitioned table in the partition tree
3116 * 'partitions' receives an array of ResultRelInfo objects with one entry for
3117 * every leaf partition in the partition tree
3118 * 'tup_conv_maps' receives an array of TupleConversionMap objects with one
3119 * entry for every leaf partition (required to convert input tuple based
3120 * on the root table's rowtype to a leaf partition's rowtype after tuple
3122 * 'partition_tuple_slot' receives a standalone TupleTableSlot to be used
3123 * to manipulate any given leaf partition's rowtype after that partition
3124 * is chosen by tuple-routing.
3125 * 'num_parted' receives the number of partitioned tables in the partition
3126 * tree (= the number of entries in the 'pd' output array)
3127 * 'num_partitions' receives the number of leaf partitions in the partition
3128 * tree (= the number of entries in the 'partitions' and 'tup_conv_maps'
3131 * Note that all the relations in the partition tree are locked using the
3132 * RowExclusiveLock mode upon return from this function.
3135 ExecSetupPartitionTupleRouting(Relation rel,
3136 PartitionDispatch **pd,
3137 ResultRelInfo **partitions,
3138 TupleConversionMap ***tup_conv_maps,
3139 TupleTableSlot **partition_tuple_slot,
3140 int *num_parted, int *num_partitions)
3142 TupleDesc tupDesc = RelationGetDescr(rel);
3146 ResultRelInfo *leaf_part_rri;
3148 /* Get the tuple-routing information and lock partitions */
3149 *pd = RelationGetPartitionDispatchInfo(rel, RowExclusiveLock, num_parted,
3151 *num_partitions = list_length(leaf_parts);
3152 *partitions = (ResultRelInfo *) palloc(*num_partitions *
3153 sizeof(ResultRelInfo));
3154 *tup_conv_maps = (TupleConversionMap **) palloc0(*num_partitions *
3155 sizeof(TupleConversionMap *));
3158 * Initialize an empty slot that will be used to manipulate tuples of any
3159 * given partition's rowtype. It is attached to the caller-specified node
3160 * (such as ModifyTableState) and released when the node finishes
3163 *partition_tuple_slot = MakeTupleTableSlot();
3165 leaf_part_rri = *partitions;
3167 foreach(cell, leaf_parts)
3170 TupleDesc part_tupdesc;
3173 * We locked all the partitions above including the leaf partitions.
3174 * Note that each of the relations in *partitions are eventually
3175 * closed by the caller.
3177 partrel = heap_open(lfirst_oid(cell), NoLock);
3178 part_tupdesc = RelationGetDescr(partrel);
3181 * Verify result relation is a valid target for the current operation.
3183 CheckValidResultRel(partrel, CMD_INSERT);
3186 * Save a tuple conversion map to convert a tuple routed to this
3187 * partition from the parent's type to the partition's.
3189 (*tup_conv_maps)[i] = convert_tuples_by_name(tupDesc, part_tupdesc,
3190 gettext_noop("could not convert row type"));
3192 InitResultRelInfo(leaf_part_rri,
3199 * Open partition indices (remember we do not support ON CONFLICT in
3200 * case of partitioned tables, so we do not need support information
3201 * for speculative insertion)
3203 if (leaf_part_rri->ri_RelationDesc->rd_rel->relhasindex &&
3204 leaf_part_rri->ri_IndexRelationDescs == NULL)
3205 ExecOpenIndices(leaf_part_rri, false);
3213 * ExecFindPartition -- Find a leaf partition in the partition tree rooted
3214 * at parent, for the heap tuple contained in *slot
3216 * estate must be non-NULL; we'll need it to compute any expressions in the
3219 * If no leaf partition is found, this routine errors out with the appropriate
3220 * error message, else it returns the leaf partition sequence number returned
3221 * by get_partition_for_tuple() unchanged.
3224 ExecFindPartition(ResultRelInfo *resultRelInfo, PartitionDispatch *pd,
3225 TupleTableSlot *slot, EState *estate)
3228 PartitionDispatchData *failed_at;
3229 TupleTableSlot *failed_slot;
3231 result = get_partition_for_tuple(pd, slot, estate,
3232 &failed_at, &failed_slot);
3235 Relation failed_rel;
3236 Datum key_values[PARTITION_MAX_KEYS];
3237 bool key_isnull[PARTITION_MAX_KEYS];
3239 ExprContext *ecxt = GetPerTupleExprContext(estate);
3241 failed_rel = failed_at->reldesc;
3242 ecxt->ecxt_scantuple = failed_slot;
3243 FormPartitionKeyDatum(failed_at, failed_slot, estate,
3244 key_values, key_isnull);
3245 val_desc = ExecBuildSlotPartitionKeyDescription(failed_rel,
3249 Assert(OidIsValid(RelationGetRelid(failed_rel)));
3251 (errcode(ERRCODE_CHECK_VIOLATION),
3252 errmsg("no partition of relation \"%s\" found for row",
3253 RelationGetRelationName(failed_rel)),
3254 val_desc ? errdetail("Partition key of the failing row contains %s.", val_desc) : 0));
3261 * BuildSlotPartitionKeyDescription
3263 * This works very much like BuildIndexValueDescription() and is currently
3264 * used for building error messages when ExecFindPartition() fails to find
3265 * partition for a row.
3268 ExecBuildSlotPartitionKeyDescription(Relation rel,
3274 PartitionKey key = RelationGetPartitionKey(rel);
3275 int partnatts = get_partition_natts(key);
3277 Oid relid = RelationGetRelid(rel);
3278 AclResult aclresult;
3280 if (check_enable_rls(relid, InvalidOid, true) == RLS_ENABLED)
3283 /* If the user has table-level access, just go build the description. */
3284 aclresult = pg_class_aclcheck(relid, GetUserId(), ACL_SELECT);
3285 if (aclresult != ACLCHECK_OK)
3288 * Step through the columns of the partition key and make sure the
3289 * user has SELECT rights on all of them.
3291 for (i = 0; i < partnatts; i++)
3293 AttrNumber attnum = get_partition_col_attnum(key, i);
3296 * If this partition key column is an expression, we return no
3297 * detail rather than try to figure out what column(s) the
3298 * expression includes and if the user has SELECT rights on them.
3300 if (attnum == InvalidAttrNumber ||
3301 pg_attribute_aclcheck(relid, attnum, GetUserId(),
3302 ACL_SELECT) != ACLCHECK_OK)
3307 initStringInfo(&buf);
3308 appendStringInfo(&buf, "(%s) = (",
3309 pg_get_partkeydef_columns(relid, true));
3311 for (i = 0; i < partnatts; i++)
3323 getTypeOutputInfo(get_partition_col_typid(key, i),
3324 &foutoid, &typisvarlena);
3325 val = OidOutputFunctionCall(foutoid, values[i]);
3329 appendStringInfoString(&buf, ", ");
3331 /* truncate if needed */
3332 vallen = strlen(val);
3333 if (vallen <= maxfieldlen)
3334 appendStringInfoString(&buf, val);
3337 vallen = pg_mbcliplen(val, vallen, maxfieldlen);
3338 appendBinaryStringInfo(&buf, val, vallen);
3339 appendStringInfoString(&buf, "...");
3343 appendStringInfoChar(&buf, ')');