PostgreSQL Source Code git master
Loading...
Searching...
No Matches
execMain.c File Reference
#include "postgres.h"
#include "access/sysattr.h"
#include "access/table.h"
#include "access/tableam.h"
#include "access/tupconvert.h"
#include "access/xact.h"
#include "catalog/namespace.h"
#include "catalog/partition.h"
#include "commands/matview.h"
#include "commands/trigger.h"
#include "executor/executor.h"
#include "executor/execPartition.h"
#include "executor/instrument.h"
#include "executor/nodeSubplan.h"
#include "foreign/fdwapi.h"
#include "mb/pg_wchar.h"
#include "miscadmin.h"
#include "nodes/queryjumble.h"
#include "parser/parse_relation.h"
#include "pgstat.h"
#include "rewrite/rewriteHandler.h"
#include "tcop/utility.h"
#include "utils/acl.h"
#include "utils/backend_status.h"
#include "utils/lsyscache.h"
#include "utils/partcache.h"
#include "utils/rls.h"
#include "utils/snapmgr.h"
Include dependency graph for execMain.c:

Go to the source code of this file.

Functions

static void InitPlan (QueryDesc *queryDesc, int eflags)
 
static void CheckValidRowMarkRel (Relation rel, RowMarkType markType)
 
static void ExecPostprocessPlan (EState *estate)
 
static void ExecEndPlan (PlanState *planstate, EState *estate)
 
static void ExecutePlan (QueryDesc *queryDesc, CmdType operation, bool sendTuples, uint64 numberTuples, ScanDirection direction, DestReceiver *dest)
 
static bool ExecCheckPermissionsModified (Oid relOid, Oid userid, Bitmapset *modifiedCols, AclMode requiredPerms)
 
static void ExecCheckXactReadOnly (PlannedStmt *plannedstmt)
 
static void EvalPlanQualStart (EPQState *epqstate, Plan *planTree)
 
static void ReportNotNullViolationError (ResultRelInfo *resultRelInfo, TupleTableSlot *slot, EState *estate, int attnum)
 
void ExecutorStart (QueryDesc *queryDesc, int eflags)
 
void standard_ExecutorStart (QueryDesc *queryDesc, int eflags)
 
void ExecutorRun (QueryDesc *queryDesc, ScanDirection direction, uint64 count)
 
void standard_ExecutorRun (QueryDesc *queryDesc, ScanDirection direction, uint64 count)
 
void ExecutorFinish (QueryDesc *queryDesc)
 
void standard_ExecutorFinish (QueryDesc *queryDesc)
 
void ExecutorEnd (QueryDesc *queryDesc)
 
void standard_ExecutorEnd (QueryDesc *queryDesc)
 
void ExecutorRewind (QueryDesc *queryDesc)
 
bool ExecCheckPermissions (List *rangeTable, List *rteperminfos, bool ereport_on_violation)
 
bool ExecCheckOneRelPerms (RTEPermissionInfo *perminfo)
 
void CheckValidResultRel (ResultRelInfo *resultRelInfo, CmdType operation, OnConflictAction onConflictAction, List *mergeActions)
 
void InitResultRelInfo (ResultRelInfo *resultRelInfo, Relation resultRelationDesc, Index resultRelationIndex, ResultRelInfo *partition_root_rri, int instrument_options)
 
ResultRelInfoExecGetTriggerResultRel (EState *estate, Oid relid, ResultRelInfo *rootRelInfo)
 
ListExecGetAncestorResultRels (EState *estate, ResultRelInfo *resultRelInfo)
 
void ExecCloseResultRelations (EState *estate)
 
void ExecCloseRangeTableRelations (EState *estate)
 
static const charExecRelCheck (ResultRelInfo *resultRelInfo, TupleTableSlot *slot, EState *estate)
 
bool ExecPartitionCheck (ResultRelInfo *resultRelInfo, TupleTableSlot *slot, EState *estate, bool emitError)
 
void ExecPartitionCheckEmitError (ResultRelInfo *resultRelInfo, TupleTableSlot *slot, EState *estate)
 
void ExecConstraints (ResultRelInfo *resultRelInfo, TupleTableSlot *slot, EState *estate)
 
AttrNumber ExecRelGenVirtualNotNull (ResultRelInfo *resultRelInfo, TupleTableSlot *slot, EState *estate, List *notnull_virtual_attrs)
 
void ExecWithCheckOptions (WCOKind kind, ResultRelInfo *resultRelInfo, TupleTableSlot *slot, EState *estate)
 
charExecBuildSlotValueDescription (Oid reloid, TupleTableSlot *slot, TupleDesc tupdesc, Bitmapset *modifiedCols, int maxfieldlen)
 
LockTupleMode ExecUpdateLockMode (EState *estate, ResultRelInfo *relinfo)
 
ExecRowMarkExecFindRowMark (EState *estate, Index rti, bool missing_ok)
 
ExecAuxRowMarkExecBuildAuxRowMark (ExecRowMark *erm, List *targetlist)
 
TupleTableSlotEvalPlanQual (EPQState *epqstate, Relation relation, Index rti, TupleTableSlot *inputslot)
 
void EvalPlanQualInit (EPQState *epqstate, EState *parentestate, Plan *subplan, List *auxrowmarks, int epqParam, List *resultRelations)
 
void EvalPlanQualSetPlan (EPQState *epqstate, Plan *subplan, List *auxrowmarks)
 
TupleTableSlotEvalPlanQualSlot (EPQState *epqstate, Relation relation, Index rti)
 
bool EvalPlanQualFetchRowMark (EPQState *epqstate, Index rti, TupleTableSlot *slot)
 
TupleTableSlotEvalPlanQualNext (EPQState *epqstate)
 
void EvalPlanQualBegin (EPQState *epqstate)
 
void EvalPlanQualEnd (EPQState *epqstate)
 

Variables

ExecutorStart_hook_type ExecutorStart_hook = NULL
 
ExecutorRun_hook_type ExecutorRun_hook = NULL
 
ExecutorFinish_hook_type ExecutorFinish_hook = NULL
 
ExecutorEnd_hook_type ExecutorEnd_hook = NULL
 
ExecutorCheckPerms_hook_type ExecutorCheckPerms_hook = NULL
 

Function Documentation

◆ CheckValidResultRel()

void CheckValidResultRel ( ResultRelInfo resultRelInfo,
CmdType  operation,
OnConflictAction  onConflictAction,
List mergeActions 
)

Definition at line 1056 of file execMain.c.

1058{
1059 Relation resultRel = resultRelInfo->ri_RelationDesc;
1060 FdwRoutine *fdwroutine;
1061
1062 /* Expect a fully-formed ResultRelInfo from InitResultRelInfo(). */
1063 Assert(resultRelInfo->ri_needLockTagTuple ==
1064 IsInplaceUpdateRelation(resultRel));
1065
1066 switch (resultRel->rd_rel->relkind)
1067 {
1068 case RELKIND_RELATION:
1070
1071 /*
1072 * For MERGE, check that the target relation supports each action.
1073 * For other operations, just check the operation itself.
1074 */
1075 if (operation == CMD_MERGE)
1077 CheckCmdReplicaIdentity(resultRel, action->commandType);
1078 else
1079 CheckCmdReplicaIdentity(resultRel, operation);
1080
1081 /*
1082 * For INSERT ON CONFLICT DO UPDATE, additionally check that the
1083 * target relation supports UPDATE.
1084 */
1085 if (onConflictAction == ONCONFLICT_UPDATE)
1087 break;
1088 case RELKIND_SEQUENCE:
1089 ereport(ERROR,
1091 errmsg("cannot change sequence \"%s\"",
1092 RelationGetRelationName(resultRel))));
1093 break;
1094 case RELKIND_TOASTVALUE:
1095 ereport(ERROR,
1097 errmsg("cannot change TOAST relation \"%s\"",
1098 RelationGetRelationName(resultRel))));
1099 break;
1100 case RELKIND_VIEW:
1101
1102 /*
1103 * Okay only if there's a suitable INSTEAD OF trigger. Otherwise,
1104 * complain, but omit errdetail because we haven't got the
1105 * information handy (and given that it really shouldn't happen,
1106 * it's not worth great exertion to get).
1107 */
1108 if (!view_has_instead_trigger(resultRel, operation, mergeActions))
1109 error_view_not_updatable(resultRel, operation, mergeActions,
1110 NULL);
1111 break;
1112 case RELKIND_MATVIEW:
1114 ereport(ERROR,
1116 errmsg("cannot change materialized view \"%s\"",
1117 RelationGetRelationName(resultRel))));
1118 break;
1120 /* Okay only if the FDW supports it */
1121 fdwroutine = resultRelInfo->ri_FdwRoutine;
1122 switch (operation)
1123 {
1124 case CMD_INSERT:
1125 if (fdwroutine->ExecForeignInsert == NULL)
1126 ereport(ERROR,
1128 errmsg("cannot insert into foreign table \"%s\"",
1129 RelationGetRelationName(resultRel))));
1130 if (fdwroutine->IsForeignRelUpdatable != NULL &&
1131 (fdwroutine->IsForeignRelUpdatable(resultRel) & (1 << CMD_INSERT)) == 0)
1132 ereport(ERROR,
1134 errmsg("foreign table \"%s\" does not allow inserts",
1135 RelationGetRelationName(resultRel))));
1136 break;
1137 case CMD_UPDATE:
1138 if (fdwroutine->ExecForeignUpdate == NULL)
1139 ereport(ERROR,
1141 errmsg("cannot update foreign table \"%s\"",
1142 RelationGetRelationName(resultRel))));
1143 if (fdwroutine->IsForeignRelUpdatable != NULL &&
1144 (fdwroutine->IsForeignRelUpdatable(resultRel) & (1 << CMD_UPDATE)) == 0)
1145 ereport(ERROR,
1147 errmsg("foreign table \"%s\" does not allow updates",
1148 RelationGetRelationName(resultRel))));
1149 break;
1150 case CMD_DELETE:
1151 if (fdwroutine->ExecForeignDelete == NULL)
1152 ereport(ERROR,
1154 errmsg("cannot delete from foreign table \"%s\"",
1155 RelationGetRelationName(resultRel))));
1156 if (fdwroutine->IsForeignRelUpdatable != NULL &&
1157 (fdwroutine->IsForeignRelUpdatable(resultRel) & (1 << CMD_DELETE)) == 0)
1158 ereport(ERROR,
1160 errmsg("foreign table \"%s\" does not allow deletes",
1161 RelationGetRelationName(resultRel))));
1162 break;
1163 default:
1164 elog(ERROR, "unrecognized CmdType: %d", (int) operation);
1165 break;
1166 }
1167 break;
1168 case RELKIND_PROPGRAPH:
1169 ereport(ERROR,
1171 errmsg("cannot change property graph \"%s\"",
1172 RelationGetRelationName(resultRel))));
1173 break;
1174 default:
1175 ereport(ERROR,
1177 errmsg("cannot change relation \"%s\"",
1178 RelationGetRelationName(resultRel))));
1179 break;
1180 }
1181}
#define Assert(condition)
Definition c.h:945
bool IsInplaceUpdateRelation(Relation relation)
Definition catalog.c:183
int errcode(int sqlerrcode)
Definition elog.c:874
#define ERROR
Definition elog.h:39
#define elog(elevel,...)
Definition elog.h:226
#define ereport(elevel,...)
Definition elog.h:150
void CheckCmdReplicaIdentity(Relation rel, CmdType cmd)
bool MatViewIncrementalMaintenanceIsEnabled(void)
Definition matview.c:952
@ ONCONFLICT_UPDATE
Definition nodes.h:430
@ CMD_MERGE
Definition nodes.h:279
@ CMD_INSERT
Definition nodes.h:277
@ CMD_DELETE
Definition nodes.h:278
@ CMD_UPDATE
Definition nodes.h:276
static char * errmsg
#define foreach_node(type, var, lst)
Definition pg_list.h:496
static int fb(int x)
#define RelationGetRelationName(relation)
Definition rel.h:548
bool view_has_instead_trigger(Relation view, CmdType event, List *mergeActionList)
void error_view_not_updatable(Relation view, CmdType command, List *mergeActionList, const char *detail)
ExecForeignInsert_function ExecForeignInsert
Definition fdwapi.h:232
ExecForeignUpdate_function ExecForeignUpdate
Definition fdwapi.h:235
ExecForeignDelete_function ExecForeignDelete
Definition fdwapi.h:236
IsForeignRelUpdatable_function IsForeignRelUpdatable
Definition fdwapi.h:240
Form_pg_class rd_rel
Definition rel.h:111
bool ri_needLockTagTuple
Definition execnodes.h:524
Relation ri_RelationDesc
Definition execnodes.h:492
struct FdwRoutine * ri_FdwRoutine
Definition execnodes.h:545

References Assert, CheckCmdReplicaIdentity(), CMD_DELETE, CMD_INSERT, CMD_MERGE, CMD_UPDATE, elog, ereport, errcode(), errmsg, ERROR, error_view_not_updatable(), FdwRoutine::ExecForeignDelete, FdwRoutine::ExecForeignInsert, FdwRoutine::ExecForeignUpdate, fb(), foreach_node, FdwRoutine::IsForeignRelUpdatable, IsInplaceUpdateRelation(), MatViewIncrementalMaintenanceIsEnabled(), ONCONFLICT_UPDATE, RelationData::rd_rel, RelationGetRelationName, ResultRelInfo::ri_FdwRoutine, ResultRelInfo::ri_needLockTagTuple, ResultRelInfo::ri_RelationDesc, and view_has_instead_trigger().

Referenced by CopyFrom(), ExecFindPartition(), ExecInitModifyTable(), and ExecInitPartitionInfo().

◆ CheckValidRowMarkRel()

static void CheckValidRowMarkRel ( Relation  rel,
RowMarkType  markType 
)
static

Definition at line 1190 of file execMain.c.

1191{
1192 FdwRoutine *fdwroutine;
1193
1194 switch (rel->rd_rel->relkind)
1195 {
1196 case RELKIND_RELATION:
1198 /* OK */
1199 break;
1200 case RELKIND_SEQUENCE:
1201 /* Must disallow this because we don't vacuum sequences */
1202 ereport(ERROR,
1204 errmsg("cannot lock rows in sequence \"%s\"",
1206 break;
1207 case RELKIND_TOASTVALUE:
1208 /* We could allow this, but there seems no good reason to */
1209 ereport(ERROR,
1211 errmsg("cannot lock rows in TOAST relation \"%s\"",
1213 break;
1214 case RELKIND_VIEW:
1215 /* Should not get here; planner should have expanded the view */
1216 ereport(ERROR,
1218 errmsg("cannot lock rows in view \"%s\"",
1220 break;
1221 case RELKIND_MATVIEW:
1222 /* Allow referencing a matview, but not actual locking clauses */
1223 if (markType != ROW_MARK_REFERENCE)
1224 ereport(ERROR,
1226 errmsg("cannot lock rows in materialized view \"%s\"",
1228 break;
1230 /* Okay only if the FDW supports it */
1231 fdwroutine = GetFdwRoutineForRelation(rel, false);
1232 if (fdwroutine->RefetchForeignRow == NULL)
1233 ereport(ERROR,
1235 errmsg("cannot lock rows in foreign table \"%s\"",
1237 break;
1238 case RELKIND_PROPGRAPH:
1239 /* Should not get here; rewriter should have expanded the graph */
1240 ereport(ERROR,
1242 errmsg_internal("cannot lock rows in property graph \"%s\"",
1244 break;
1245 default:
1246 ereport(ERROR,
1248 errmsg("cannot lock rows in relation \"%s\"",
1250 break;
1251 }
1252}
int int errmsg_internal(const char *fmt,...) pg_attribute_printf(1
FdwRoutine * GetFdwRoutineForRelation(Relation relation, bool makecopy)
Definition foreign.c:531
@ ROW_MARK_REFERENCE
Definition plannodes.h:1557
RefetchForeignRow_function RefetchForeignRow
Definition fdwapi.h:248

References ereport, errcode(), errmsg, errmsg_internal(), ERROR, fb(), GetFdwRoutineForRelation(), RelationData::rd_rel, FdwRoutine::RefetchForeignRow, RelationGetRelationName, and ROW_MARK_REFERENCE.

Referenced by InitPlan().

◆ EvalPlanQual()

TupleTableSlot * EvalPlanQual ( EPQState epqstate,
Relation  relation,
Index  rti,
TupleTableSlot inputslot 
)

Definition at line 2668 of file execMain.c.

2670{
2671 TupleTableSlot *slot;
2673
2674 Assert(rti > 0);
2675
2676 /*
2677 * Need to run a recheck subquery. Initialize or reinitialize EPQ state.
2678 */
2679 EvalPlanQualBegin(epqstate);
2680
2681 /*
2682 * Callers will often use the EvalPlanQualSlot to store the tuple to avoid
2683 * an unnecessary copy.
2684 */
2685 testslot = EvalPlanQualSlot(epqstate, relation, rti);
2686 if (testslot != inputslot)
2687 ExecCopySlot(testslot, inputslot);
2688
2689 /*
2690 * Mark that an EPQ tuple is available for this relation. (If there is
2691 * more than one result relation, the others remain marked as having no
2692 * tuple available.)
2693 */
2694 epqstate->relsubs_done[rti - 1] = false;
2695 epqstate->relsubs_blocked[rti - 1] = false;
2696
2697 /*
2698 * Run the EPQ query. We assume it will return at most one tuple.
2699 */
2700 slot = EvalPlanQualNext(epqstate);
2701
2702 /*
2703 * If we got a tuple, force the slot to materialize the tuple so that it
2704 * is not dependent on any local state in the EPQ query (in particular,
2705 * it's highly likely that the slot contains references to any pass-by-ref
2706 * datums that may be present in copyTuple). As with the next step, this
2707 * is to guard against early re-use of the EPQ query.
2708 */
2709 if (!TupIsNull(slot))
2710 ExecMaterializeSlot(slot);
2711
2712 /*
2713 * Clear out the test tuple, and mark that no tuple is available here.
2714 * This is needed in case the EPQ state is re-used to test a tuple for a
2715 * different target relation.
2716 */
2718 epqstate->relsubs_blocked[rti - 1] = true;
2719
2720 return slot;
2721}
TupleTableSlot * EvalPlanQualSlot(EPQState *epqstate, Relation relation, Index rti)
Definition execMain.c:2795
void EvalPlanQualBegin(EPQState *epqstate)
Definition execMain.c:2950
TupleTableSlot * EvalPlanQualNext(EPQState *epqstate)
Definition execMain.c:2934
bool * relsubs_blocked
Definition execnodes.h:1368
bool * relsubs_done
Definition execnodes.h:1359
static TupleTableSlot * ExecClearTuple(TupleTableSlot *slot)
Definition tuptable.h:476
#define TupIsNull(slot)
Definition tuptable.h:325
static TupleTableSlot * ExecCopySlot(TupleTableSlot *dstslot, TupleTableSlot *srcslot)
Definition tuptable.h:543
static void ExecMaterializeSlot(TupleTableSlot *slot)
Definition tuptable.h:494

References Assert, EvalPlanQualBegin(), EvalPlanQualNext(), EvalPlanQualSlot(), ExecClearTuple(), ExecCopySlot(), ExecMaterializeSlot(), fb(), EPQState::relsubs_blocked, EPQState::relsubs_done, and TupIsNull.

Referenced by ExecDelete(), ExecMergeMatched(), ExecUpdate(), and GetTupleForTrigger().

◆ EvalPlanQualBegin()

void EvalPlanQualBegin ( EPQState epqstate)

Definition at line 2950 of file execMain.c.

2951{
2952 EState *parentestate = epqstate->parentestate;
2953 EState *recheckestate = epqstate->recheckestate;
2954
2955 if (recheckestate == NULL)
2956 {
2957 /* First time through, so create a child EState */
2958 EvalPlanQualStart(epqstate, epqstate->plan);
2959 }
2960 else
2961 {
2962 /*
2963 * We already have a suitable child EPQ tree, so just reset it.
2964 */
2965 Index rtsize = parentestate->es_range_table_size;
2967
2968 /*
2969 * Reset the relsubs_done[] flags to equal relsubs_blocked[], so that
2970 * the EPQ run will never attempt to fetch tuples from blocked target
2971 * relations.
2972 */
2973 memcpy(epqstate->relsubs_done, epqstate->relsubs_blocked,
2974 rtsize * sizeof(bool));
2975
2976 /* Recopy current values of parent parameters */
2977 if (parentestate->es_plannedstmt->paramExecTypes != NIL)
2978 {
2979 int i;
2980
2981 /*
2982 * Force evaluation of any InitPlan outputs that could be needed
2983 * by the subplan, just in case they got reset since
2984 * EvalPlanQualStart (see comments therein).
2985 */
2986 ExecSetParamPlanMulti(rcplanstate->plan->extParam,
2987 GetPerTupleExprContext(parentestate));
2988
2989 i = list_length(parentestate->es_plannedstmt->paramExecTypes);
2990
2991 while (--i >= 0)
2992 {
2993 /* copy value if any, but not execPlan link */
2994 recheckestate->es_param_exec_vals[i].value =
2995 parentestate->es_param_exec_vals[i].value;
2996 recheckestate->es_param_exec_vals[i].isnull =
2997 parentestate->es_param_exec_vals[i].isnull;
2998 }
2999 }
3000
3001 /*
3002 * Mark child plan tree as needing rescan at all scan nodes. The
3003 * first ExecProcNode will take care of actually doing the rescan.
3004 */
3005 rcplanstate->chgParam = bms_add_member(rcplanstate->chgParam,
3006 epqstate->epqParam);
3007 }
3008}
Bitmapset * bms_add_member(Bitmapset *a, int x)
Definition bitmapset.c:799
unsigned int Index
Definition c.h:700
static void EvalPlanQualStart(EPQState *epqstate, Plan *planTree)
Definition execMain.c:3017
#define GetPerTupleExprContext(estate)
Definition executor.h:660
int i
Definition isn.c:77
void ExecSetParamPlanMulti(const Bitmapset *params, ExprContext *econtext)
static int list_length(const List *l)
Definition pg_list.h:152
#define NIL
Definition pg_list.h:68
Plan * plan
Definition execnodes.h:1331
int epqParam
Definition execnodes.h:1314
EState * parentestate
Definition execnodes.h:1313
EState * recheckestate
Definition execnodes.h:1345
PlanState * recheckplanstate
Definition execnodes.h:1370
PlannedStmt * es_plannedstmt
Definition execnodes.h:681
ParamExecData * es_param_exec_vals
Definition execnodes.h:717
Index es_range_table_size
Definition execnodes.h:675
bool isnull
Definition params.h:149
Datum value
Definition params.h:148
List * paramExecTypes
Definition plannodes.h:148

References bms_add_member(), EPQState::epqParam, EState::es_param_exec_vals, EState::es_plannedstmt, EState::es_range_table_size, EvalPlanQualStart(), ExecSetParamPlanMulti(), fb(), GetPerTupleExprContext, i, ParamExecData::isnull, list_length(), NIL, PlannedStmt::paramExecTypes, EPQState::parentestate, EPQState::plan, EPQState::recheckestate, EPQState::recheckplanstate, EPQState::relsubs_blocked, EPQState::relsubs_done, and ParamExecData::value.

Referenced by EvalPlanQual(), ExecDelete(), and ExecLockRows().

◆ EvalPlanQualEnd()

void EvalPlanQualEnd ( EPQState epqstate)

Definition at line 3198 of file execMain.c.

3199{
3200 EState *estate = epqstate->recheckestate;
3201 Index rtsize;
3202 MemoryContext oldcontext;
3203 ListCell *l;
3204
3206
3207 /*
3208 * We may have a tuple table, even if EPQ wasn't started, because we allow
3209 * use of EvalPlanQualSlot() without calling EvalPlanQualBegin().
3210 */
3211 if (epqstate->tuple_table != NIL)
3212 {
3213 memset(epqstate->relsubs_slot, 0,
3214 rtsize * sizeof(TupleTableSlot *));
3215 ExecResetTupleTable(epqstate->tuple_table, true);
3216 epqstate->tuple_table = NIL;
3217 }
3218
3219 /* EPQ wasn't started, nothing further to do */
3220 if (estate == NULL)
3221 return;
3222
3223 oldcontext = MemoryContextSwitchTo(estate->es_query_cxt);
3224
3225 ExecEndNode(epqstate->recheckplanstate);
3226
3227 foreach(l, estate->es_subplanstates)
3228 {
3230
3232 }
3233
3234 /* throw away the per-estate tuple table, some node may have used it */
3235 ExecResetTupleTable(estate->es_tupleTable, false);
3236
3237 /* Close any result and trigger target relations attached to this EState */
3239
3240 MemoryContextSwitchTo(oldcontext);
3241
3242 /*
3243 * NULLify the partition directory before freeing the executor state.
3244 * Since EvalPlanQualStart() just borrowed the parent EState's directory,
3245 * we'd better leave it up to the parent to delete it.
3246 */
3247 estate->es_partition_directory = NULL;
3248
3249 FreeExecutorState(estate);
3250
3251 /* Mark EPQState idle */
3252 epqstate->origslot = NULL;
3253 epqstate->recheckestate = NULL;
3254 epqstate->recheckplanstate = NULL;
3255 epqstate->relsubs_rowmark = NULL;
3256 epqstate->relsubs_done = NULL;
3257 epqstate->relsubs_blocked = NULL;
3258}
void ExecCloseResultRelations(EState *estate)
Definition execMain.c:1594
void ExecEndNode(PlanState *node)
void ExecResetTupleTable(List *tupleTable, bool shouldFree)
void FreeExecutorState(EState *estate)
Definition execUtils.c:197
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition palloc.h:124
#define lfirst(lc)
Definition pg_list.h:172
ExecAuxRowMark ** relsubs_rowmark
Definition execnodes.h:1352
TupleTableSlot * origslot
Definition execnodes.h:1340
TupleTableSlot ** relsubs_slot
Definition execnodes.h:1324
List * tuple_table
Definition execnodes.h:1323
MemoryContext es_query_cxt
Definition execnodes.h:722
List * es_tupleTable
Definition execnodes.h:724
PartitionDirectory es_partition_directory
Definition execnodes.h:704
List * es_subplanstates
Definition execnodes.h:737

References EState::es_partition_directory, EState::es_query_cxt, EState::es_range_table_size, EState::es_subplanstates, EState::es_tupleTable, ExecCloseResultRelations(), ExecEndNode(), ExecResetTupleTable(), fb(), FreeExecutorState(), lfirst, MemoryContextSwitchTo(), NIL, EPQState::origslot, EPQState::parentestate, EPQState::recheckestate, EPQState::recheckplanstate, EPQState::relsubs_blocked, EPQState::relsubs_done, EPQState::relsubs_rowmark, EPQState::relsubs_slot, and EPQState::tuple_table.

Referenced by apply_handle_delete_internal(), apply_handle_tuple_routing(), apply_handle_update_internal(), EvalPlanQualSetPlan(), ExecEndLockRows(), ExecEndModifyTable(), and ExecLockRows().

◆ EvalPlanQualFetchRowMark()

bool EvalPlanQualFetchRowMark ( EPQState epqstate,
Index  rti,
TupleTableSlot slot 
)

Definition at line 2823 of file execMain.c.

2824{
2825 ExecAuxRowMark *earm = epqstate->relsubs_rowmark[rti - 1];
2827 Datum datum;
2828 bool isNull;
2829
2830 Assert(earm != NULL);
2831 Assert(epqstate->origslot != NULL);
2832
2833 erm = earm->rowmark;
2834
2835 if (RowMarkRequiresRowShareLock(erm->markType))
2836 elog(ERROR, "EvalPlanQual doesn't support locking rowmarks");
2837
2838 /* if child rel, must check whether it produced this row */
2839 if (erm->rti != erm->prti)
2840 {
2841 Oid tableoid;
2842
2843 datum = ExecGetJunkAttribute(epqstate->origslot,
2844 earm->toidAttNo,
2845 &isNull);
2846 /* non-locked rels could be on the inside of outer joins */
2847 if (isNull)
2848 return false;
2849
2850 tableoid = DatumGetObjectId(datum);
2851
2852 Assert(OidIsValid(erm->relid));
2853 if (tableoid != erm->relid)
2854 {
2855 /* this child is inactive right now */
2856 return false;
2857 }
2858 }
2859
2860 if (erm->markType == ROW_MARK_REFERENCE)
2861 {
2862 Assert(erm->relation != NULL);
2863
2864 /* fetch the tuple's ctid */
2865 datum = ExecGetJunkAttribute(epqstate->origslot,
2866 earm->ctidAttNo,
2867 &isNull);
2868 /* non-locked rels could be on the inside of outer joins */
2869 if (isNull)
2870 return false;
2871
2872 /* fetch requests on foreign tables must be passed to their FDW */
2873 if (erm->relation->rd_rel->relkind == RELKIND_FOREIGN_TABLE)
2874 {
2875 FdwRoutine *fdwroutine;
2876 bool updated = false;
2877
2878 fdwroutine = GetFdwRoutineForRelation(erm->relation, false);
2879 /* this should have been checked already, but let's be safe */
2880 if (fdwroutine->RefetchForeignRow == NULL)
2881 ereport(ERROR,
2883 errmsg("cannot lock rows in foreign table \"%s\"",
2884 RelationGetRelationName(erm->relation))));
2885
2886 fdwroutine->RefetchForeignRow(epqstate->recheckestate,
2887 erm,
2888 datum,
2889 slot,
2890 &updated);
2891 if (TupIsNull(slot))
2892 elog(ERROR, "failed to fetch tuple for EvalPlanQual recheck");
2893
2894 /*
2895 * Ideally we'd insist on updated == false here, but that assumes
2896 * that FDWs can track that exactly, which they might not be able
2897 * to. So just ignore the flag.
2898 */
2899 return true;
2900 }
2901 else
2902 {
2903 /* ordinary table, fetch the tuple */
2904 if (!table_tuple_fetch_row_version(erm->relation,
2906 SnapshotAny, slot))
2907 elog(ERROR, "failed to fetch tuple for EvalPlanQual recheck");
2908 return true;
2909 }
2910 }
2911 else
2912 {
2913 Assert(erm->markType == ROW_MARK_COPY);
2914
2915 /* fetch the whole-row Var for the relation */
2916 datum = ExecGetJunkAttribute(epqstate->origslot,
2917 earm->wholeAttNo,
2918 &isNull);
2919 /* non-locked rels could be on the inside of outer joins */
2920 if (isNull)
2921 return false;
2922
2923 ExecStoreHeapTupleDatum(datum, slot);
2924 return true;
2925 }
2926}
#define OidIsValid(objectId)
Definition c.h:860
void ExecStoreHeapTupleDatum(Datum data, TupleTableSlot *slot)
static Datum ExecGetJunkAttribute(TupleTableSlot *slot, AttrNumber attno, bool *isNull)
Definition executor.h:226
#define RowMarkRequiresRowShareLock(marktype)
Definition plannodes.h:1561
@ ROW_MARK_COPY
Definition plannodes.h:1558
static Oid DatumGetObjectId(Datum X)
Definition postgres.h:242
uint64_t Datum
Definition postgres.h:70
static Pointer DatumGetPointer(Datum X)
Definition postgres.h:332
unsigned int Oid
#define SnapshotAny
Definition snapmgr.h:33
static bool table_tuple_fetch_row_version(Relation rel, ItemPointer tid, Snapshot snapshot, TupleTableSlot *slot)
Definition tableam.h:1274

References Assert, DatumGetObjectId(), DatumGetPointer(), elog, ereport, errcode(), errmsg, ERROR, ExecGetJunkAttribute(), ExecStoreHeapTupleDatum(), fb(), GetFdwRoutineForRelation(), OidIsValid, EPQState::origslot, EPQState::recheckestate, FdwRoutine::RefetchForeignRow, RelationGetRelationName, EPQState::relsubs_rowmark, ROW_MARK_COPY, ROW_MARK_REFERENCE, RowMarkRequiresRowShareLock, SnapshotAny, table_tuple_fetch_row_version(), and TupIsNull.

Referenced by ExecScanFetch().

◆ EvalPlanQualInit()

void EvalPlanQualInit ( EPQState epqstate,
EState parentestate,
Plan subplan,
List auxrowmarks,
int  epqParam,
List resultRelations 
)

Definition at line 2737 of file execMain.c.

2740{
2741 Index rtsize = parentestate->es_range_table_size;
2742
2743 /* initialize data not changing over EPQState's lifetime */
2744 epqstate->parentestate = parentestate;
2745 epqstate->epqParam = epqParam;
2746 epqstate->resultRelations = resultRelations;
2747
2748 /*
2749 * Allocate space to reference a slot for each potential rti - do so now
2750 * rather than in EvalPlanQualBegin(), as done for other dynamically
2751 * allocated resources, so EvalPlanQualSlot() can be used to hold tuples
2752 * that *may* need EPQ later, without forcing the overhead of
2753 * EvalPlanQualBegin().
2754 */
2755 epqstate->tuple_table = NIL;
2757
2758 /* ... and remember data that EvalPlanQualBegin will need */
2759 epqstate->plan = subplan;
2760 epqstate->arowMarks = auxrowmarks;
2761
2762 /* ... and mark the EPQ state inactive */
2763 epqstate->origslot = NULL;
2764 epqstate->recheckestate = NULL;
2765 epqstate->recheckplanstate = NULL;
2766 epqstate->relsubs_rowmark = NULL;
2767 epqstate->relsubs_done = NULL;
2768 epqstate->relsubs_blocked = NULL;
2769}
#define palloc0_array(type, count)
Definition fe_memutils.h:77
List * resultRelations
Definition execnodes.h:1315
List * arowMarks
Definition execnodes.h:1332

References EPQState::arowMarks, EPQState::epqParam, EState::es_range_table_size, fb(), NIL, EPQState::origslot, palloc0_array, EPQState::parentestate, EPQState::plan, EPQState::recheckestate, EPQState::recheckplanstate, EPQState::relsubs_blocked, EPQState::relsubs_done, EPQState::relsubs_rowmark, EPQState::relsubs_slot, EPQState::resultRelations, and EPQState::tuple_table.

Referenced by apply_handle_delete_internal(), apply_handle_tuple_routing(), apply_handle_update_internal(), ExecInitLockRows(), and ExecInitModifyTable().

◆ EvalPlanQualNext()

TupleTableSlot * EvalPlanQualNext ( EPQState epqstate)

Definition at line 2934 of file execMain.c.

2935{
2936 MemoryContext oldcontext;
2937 TupleTableSlot *slot;
2938
2939 oldcontext = MemoryContextSwitchTo(epqstate->recheckestate->es_query_cxt);
2940 slot = ExecProcNode(epqstate->recheckplanstate);
2941 MemoryContextSwitchTo(oldcontext);
2942
2943 return slot;
2944}
static TupleTableSlot * ExecProcNode(PlanState *node)
Definition executor.h:315

References EState::es_query_cxt, ExecProcNode(), MemoryContextSwitchTo(), EPQState::recheckestate, and EPQState::recheckplanstate.

Referenced by EvalPlanQual(), and ExecLockRows().

◆ EvalPlanQualSetPlan()

void EvalPlanQualSetPlan ( EPQState epqstate,
Plan subplan,
List auxrowmarks 
)

Definition at line 2778 of file execMain.c.

2779{
2780 /* If we have a live EPQ query, shut it down */
2781 EvalPlanQualEnd(epqstate);
2782 /* And set/change the plan pointer */
2783 epqstate->plan = subplan;
2784 /* The rowmarks depend on the plan, too */
2785 epqstate->arowMarks = auxrowmarks;
2786}
void EvalPlanQualEnd(EPQState *epqstate)
Definition execMain.c:3198

References EPQState::arowMarks, EvalPlanQualEnd(), fb(), and EPQState::plan.

Referenced by ExecInitModifyTable().

◆ EvalPlanQualSlot()

TupleTableSlot * EvalPlanQualSlot ( EPQState epqstate,
Relation  relation,
Index  rti 
)

Definition at line 2795 of file execMain.c.

2797{
2798 TupleTableSlot **slot;
2799
2800 Assert(relation);
2801 Assert(rti > 0 && rti <= epqstate->parentestate->es_range_table_size);
2802 slot = &epqstate->relsubs_slot[rti - 1];
2803
2804 if (*slot == NULL)
2805 {
2806 MemoryContext oldcontext;
2807
2808 oldcontext = MemoryContextSwitchTo(epqstate->parentestate->es_query_cxt);
2809 *slot = table_slot_create(relation, &epqstate->tuple_table);
2810 MemoryContextSwitchTo(oldcontext);
2811 }
2812
2813 return *slot;
2814}
TupleTableSlot * table_slot_create(Relation relation, List **reglist)
Definition tableam.c:92

References Assert, EState::es_query_cxt, fb(), MemoryContextSwitchTo(), EPQState::parentestate, EPQState::relsubs_slot, table_slot_create(), and EPQState::tuple_table.

Referenced by EvalPlanQual(), ExecDelete(), ExecLockRows(), ExecMergeMatched(), and ExecUpdate().

◆ EvalPlanQualStart()

static void EvalPlanQualStart ( EPQState epqstate,
Plan planTree 
)
static

Definition at line 3017 of file execMain.c.

3018{
3019 EState *parentestate = epqstate->parentestate;
3020 Index rtsize = parentestate->es_range_table_size;
3022 MemoryContext oldcontext;
3023 ListCell *l;
3024
3026
3027 oldcontext = MemoryContextSwitchTo(rcestate->es_query_cxt);
3028
3029 /* signal that this is an EState for executing EPQ */
3030 rcestate->es_epq_active = epqstate;
3031
3032 /*
3033 * Child EPQ EStates share the parent's copy of unchanging state such as
3034 * the snapshot, rangetable, and external Param info. They need their own
3035 * copies of local state, including a tuple table, es_param_exec_vals,
3036 * result-rel info, etc.
3037 */
3038 rcestate->es_direction = ForwardScanDirection;
3039 rcestate->es_snapshot = parentestate->es_snapshot;
3040 rcestate->es_crosscheck_snapshot = parentestate->es_crosscheck_snapshot;
3041 rcestate->es_range_table = parentestate->es_range_table;
3042 rcestate->es_range_table_size = parentestate->es_range_table_size;
3043 rcestate->es_relations = parentestate->es_relations;
3044 rcestate->es_rowmarks = parentestate->es_rowmarks;
3045 rcestate->es_rteperminfos = parentestate->es_rteperminfos;
3046 rcestate->es_plannedstmt = parentestate->es_plannedstmt;
3047 rcestate->es_junkFilter = parentestate->es_junkFilter;
3048 rcestate->es_output_cid = parentestate->es_output_cid;
3049 rcestate->es_queryEnv = parentestate->es_queryEnv;
3050
3051 /*
3052 * ResultRelInfos needed by subplans are initialized from scratch when the
3053 * subplans themselves are initialized.
3054 */
3055 rcestate->es_result_relations = NULL;
3056 /* es_trig_target_relations must NOT be copied */
3057 rcestate->es_top_eflags = parentestate->es_top_eflags;
3058 rcestate->es_instrument = parentestate->es_instrument;
3059 /* es_auxmodifytables must NOT be copied */
3060
3061 /*
3062 * The external param list is simply shared from parent. The internal
3063 * param workspace has to be local state, but we copy the initial values
3064 * from the parent, so as to have access to any param values that were
3065 * already set from other parts of the parent's plan tree.
3066 */
3067 rcestate->es_param_list_info = parentestate->es_param_list_info;
3068 if (parentestate->es_plannedstmt->paramExecTypes != NIL)
3069 {
3070 int i;
3071
3072 /*
3073 * Force evaluation of any InitPlan outputs that could be needed by
3074 * the subplan. (With more complexity, maybe we could postpone this
3075 * till the subplan actually demands them, but it doesn't seem worth
3076 * the trouble; this is a corner case already, since usually the
3077 * InitPlans would have been evaluated before reaching EvalPlanQual.)
3078 *
3079 * This will not touch output params of InitPlans that occur somewhere
3080 * within the subplan tree, only those that are attached to the
3081 * ModifyTable node or above it and are referenced within the subplan.
3082 * That's OK though, because the planner would only attach such
3083 * InitPlans to a lower-level SubqueryScan node, and EPQ execution
3084 * will not descend into a SubqueryScan.
3085 *
3086 * The EState's per-output-tuple econtext is sufficiently short-lived
3087 * for this, since it should get reset before there is any chance of
3088 * doing EvalPlanQual again.
3089 */
3091 GetPerTupleExprContext(parentestate));
3092
3093 /* now make the internal param workspace ... */
3094 i = list_length(parentestate->es_plannedstmt->paramExecTypes);
3095 rcestate->es_param_exec_vals = palloc0_array(ParamExecData, i);
3096 /* ... and copy down all values, whether really needed or not */
3097 while (--i >= 0)
3098 {
3099 /* copy value if any, but not execPlan link */
3100 rcestate->es_param_exec_vals[i].value =
3101 parentestate->es_param_exec_vals[i].value;
3102 rcestate->es_param_exec_vals[i].isnull =
3103 parentestate->es_param_exec_vals[i].isnull;
3104 }
3105 }
3106
3107 /*
3108 * Copy es_unpruned_relids so that pruned relations are ignored by
3109 * ExecInitLockRows() and ExecInitModifyTable() when initializing the plan
3110 * trees below.
3111 */
3112 rcestate->es_unpruned_relids = parentestate->es_unpruned_relids;
3113
3114 /*
3115 * Also make the PartitionPruneInfo and the results of pruning available.
3116 * These need to match exactly so that we initialize all the same Append
3117 * and MergeAppend subplans as the parent did.
3118 */
3119 rcestate->es_part_prune_infos = parentestate->es_part_prune_infos;
3120 rcestate->es_part_prune_states = parentestate->es_part_prune_states;
3121 rcestate->es_part_prune_results = parentestate->es_part_prune_results;
3122
3123 /* We'll also borrow the es_partition_directory from the parent state */
3124 rcestate->es_partition_directory = parentestate->es_partition_directory;
3125
3126 /*
3127 * Initialize private state information for each SubPlan. We must do this
3128 * before running ExecInitNode on the main query tree, since
3129 * ExecInitSubPlan expects to be able to find these entries. Some of the
3130 * SubPlans might not be used in the part of the plan tree we intend to
3131 * run, but since it's not easy to tell which, we just initialize them
3132 * all.
3133 */
3134 Assert(rcestate->es_subplanstates == NIL);
3135 foreach(l, parentestate->es_plannedstmt->subplans)
3136 {
3137 Plan *subplan = (Plan *) lfirst(l);
3139
3140 subplanstate = ExecInitNode(subplan, rcestate, 0);
3141 rcestate->es_subplanstates = lappend(rcestate->es_subplanstates,
3142 subplanstate);
3143 }
3144
3145 /*
3146 * Build an RTI indexed array of rowmarks, so that
3147 * EvalPlanQualFetchRowMark() can efficiently access the to be fetched
3148 * rowmark.
3149 */
3151 foreach(l, epqstate->arowMarks)
3152 {
3154
3155 epqstate->relsubs_rowmark[earm->rowmark->rti - 1] = earm;
3156 }
3157
3158 /*
3159 * Initialize per-relation EPQ tuple states. Result relations, if any,
3160 * get marked as blocked; others as not-fetched.
3161 */
3162 epqstate->relsubs_done = palloc_array(bool, rtsize);
3163 epqstate->relsubs_blocked = palloc0_array(bool, rtsize);
3164
3165 foreach(l, epqstate->resultRelations)
3166 {
3167 int rtindex = lfirst_int(l);
3168
3169 Assert(rtindex > 0 && rtindex <= rtsize);
3170 epqstate->relsubs_blocked[rtindex - 1] = true;
3171 }
3172
3173 memcpy(epqstate->relsubs_done, epqstate->relsubs_blocked,
3174 rtsize * sizeof(bool));
3175
3176 /*
3177 * Initialize the private state information for all the nodes in the part
3178 * of the plan tree we need to run. This opens files, allocates storage
3179 * and leaves us ready to start processing tuples.
3180 */
3181 epqstate->recheckplanstate = ExecInitNode(planTree, rcestate, 0);
3182
3183 MemoryContextSwitchTo(oldcontext);
3184}
PlanState * ExecInitNode(Plan *node, EState *estate, int eflags)
EState * CreateExecutorState(void)
Definition execUtils.c:90
#define palloc_array(type, count)
Definition fe_memutils.h:76
List * lappend(List *list, void *datum)
Definition list.c:339
#define lfirst_int(lc)
Definition pg_list.h:173
@ ForwardScanDirection
Definition sdir.h:28
List * es_part_prune_infos
Definition execnodes.h:682
int es_top_eflags
Definition execnodes.h:731
int es_instrument
Definition execnodes.h:732
QueryEnvironment * es_queryEnv
Definition execnodes.h:719
List * es_range_table
Definition execnodes.h:674
List * es_rteperminfos
Definition execnodes.h:680
Bitmapset * es_unpruned_relids
Definition execnodes.h:685
List * es_part_prune_states
Definition execnodes.h:683
ParamListInfo es_param_list_info
Definition execnodes.h:716
ExecRowMark ** es_rowmarks
Definition execnodes.h:678
Relation * es_relations
Definition execnodes.h:676
CommandId es_output_cid
Definition execnodes.h:694
Snapshot es_snapshot
Definition execnodes.h:672
JunkFilter * es_junkFilter
Definition execnodes.h:691
List * es_part_prune_results
Definition execnodes.h:684
Snapshot es_crosscheck_snapshot
Definition execnodes.h:673
Bitmapset * extParam
Definition plannodes.h:253
List * subplans
Definition plannodes.h:130

References EPQState::arowMarks, Assert, CreateExecutorState(), EState::es_crosscheck_snapshot, EState::es_instrument, EState::es_junkFilter, EState::es_output_cid, EState::es_param_exec_vals, EState::es_param_list_info, EState::es_part_prune_infos, EState::es_part_prune_results, EState::es_part_prune_states, EState::es_partition_directory, EState::es_plannedstmt, EState::es_queryEnv, EState::es_range_table, EState::es_range_table_size, EState::es_relations, EState::es_rowmarks, EState::es_rteperminfos, EState::es_snapshot, EState::es_top_eflags, EState::es_unpruned_relids, ExecInitNode(), ExecSetParamPlanMulti(), Plan::extParam, fb(), ForwardScanDirection, GetPerTupleExprContext, i, ParamExecData::isnull, lappend(), lfirst, lfirst_int, list_length(), MemoryContextSwitchTo(), NIL, palloc0_array, palloc_array, PlannedStmt::paramExecTypes, EPQState::parentestate, EPQState::recheckestate, EPQState::recheckplanstate, EPQState::relsubs_blocked, EPQState::relsubs_done, EPQState::relsubs_rowmark, EPQState::resultRelations, PlannedStmt::subplans, and ParamExecData::value.

Referenced by EvalPlanQualBegin().

◆ ExecBuildAuxRowMark()

ExecAuxRowMark * ExecBuildAuxRowMark ( ExecRowMark erm,
List targetlist 
)

Definition at line 2598 of file execMain.c.

2599{
2601 char resname[32];
2602
2603 aerm->rowmark = erm;
2604
2605 /* Look up the resjunk columns associated with this rowmark */
2606 if (erm->markType != ROW_MARK_COPY)
2607 {
2608 /* need ctid for all methods other than COPY */
2609 snprintf(resname, sizeof(resname), "ctid%u", erm->rowmarkId);
2610 aerm->ctidAttNo = ExecFindJunkAttributeInTlist(targetlist,
2611 resname);
2612 if (!AttributeNumberIsValid(aerm->ctidAttNo))
2613 elog(ERROR, "could not find junk %s column", resname);
2614 }
2615 else
2616 {
2617 /* need wholerow if COPY */
2618 snprintf(resname, sizeof(resname), "wholerow%u", erm->rowmarkId);
2619 aerm->wholeAttNo = ExecFindJunkAttributeInTlist(targetlist,
2620 resname);
2621 if (!AttributeNumberIsValid(aerm->wholeAttNo))
2622 elog(ERROR, "could not find junk %s column", resname);
2623 }
2624
2625 /* if child rel, need tableoid */
2626 if (erm->rti != erm->prti)
2627 {
2628 snprintf(resname, sizeof(resname), "tableoid%u", erm->rowmarkId);
2629 aerm->toidAttNo = ExecFindJunkAttributeInTlist(targetlist,
2630 resname);
2631 if (!AttributeNumberIsValid(aerm->toidAttNo))
2632 elog(ERROR, "could not find junk %s column", resname);
2633 }
2634
2635 return aerm;
2636}
#define AttributeNumberIsValid(attributeNumber)
Definition attnum.h:34
AttrNumber ExecFindJunkAttributeInTlist(List *targetlist, const char *attrName)
Definition execJunk.c:222
#define palloc0_object(type)
Definition fe_memutils.h:75
#define snprintf
Definition port.h:260

References AttributeNumberIsValid, elog, ERROR, ExecFindJunkAttributeInTlist(), fb(), palloc0_object, ROW_MARK_COPY, and snprintf.

Referenced by ExecInitLockRows(), and ExecInitModifyTable().

◆ ExecBuildSlotValueDescription()

char * ExecBuildSlotValueDescription ( Oid  reloid,
TupleTableSlot slot,
TupleDesc  tupdesc,
Bitmapset modifiedCols,
int  maxfieldlen 
)

Definition at line 2410 of file execMain.c.

2415{
2418 bool write_comma = false;
2419 bool write_comma_collist = false;
2420 int i;
2422 bool table_perm = false;
2423 bool any_perm = false;
2424
2425 /*
2426 * Check if RLS is enabled and should be active for the relation; if so,
2427 * then don't return anything. Otherwise, go through normal permission
2428 * checks.
2429 */
2430 if (check_enable_rls(reloid, InvalidOid, true) == RLS_ENABLED)
2431 return NULL;
2432
2434
2436
2437 /*
2438 * Check if the user has permissions to see the row. Table-level SELECT
2439 * allows access to all columns. If the user does not have table-level
2440 * SELECT then we check each column and include those the user has SELECT
2441 * rights on. Additionally, we always include columns the user provided
2442 * data for.
2443 */
2445 if (aclresult != ACLCHECK_OK)
2446 {
2447 /* Set up the buffer for the column list */
2450 }
2451 else
2452 table_perm = any_perm = true;
2453
2454 /* Make sure the tuple is fully deconstructed */
2455 slot_getallattrs(slot);
2456
2457 for (i = 0; i < tupdesc->natts; i++)
2458 {
2459 bool column_perm = false;
2460 char *val;
2461 int vallen;
2463
2464 /* ignore dropped columns */
2465 if (att->attisdropped)
2466 continue;
2467
2468 if (!table_perm)
2469 {
2470 /*
2471 * No table-level SELECT, so need to make sure they either have
2472 * SELECT rights on the column or that they have provided the data
2473 * for the column. If not, omit this column from the error
2474 * message.
2475 */
2476 aclresult = pg_attribute_aclcheck(reloid, att->attnum,
2480 {
2481 column_perm = any_perm = true;
2482
2485 else
2486 write_comma_collist = true;
2487
2489 }
2490 }
2491
2492 if (table_perm || column_perm)
2493 {
2494 if (att->attgenerated == ATTRIBUTE_GENERATED_VIRTUAL)
2495 val = "virtual";
2496 else if (slot->tts_isnull[i])
2497 val = "null";
2498 else
2499 {
2500 Oid foutoid;
2501 bool typisvarlena;
2502
2503 getTypeOutputInfo(att->atttypid,
2504 &foutoid, &typisvarlena);
2506 }
2507
2508 if (write_comma)
2510 else
2511 write_comma = true;
2512
2513 /* truncate if needed */
2514 vallen = strlen(val);
2515 if (vallen <= maxfieldlen)
2516 appendBinaryStringInfo(&buf, val, vallen);
2517 else
2518 {
2519 vallen = pg_mbcliplen(val, vallen, maxfieldlen);
2520 appendBinaryStringInfo(&buf, val, vallen);
2521 appendStringInfoString(&buf, "...");
2522 }
2523 }
2524 }
2525
2526 /* If we end up with zero columns being returned, then return NULL. */
2527 if (!any_perm)
2528 return NULL;
2529
2531
2532 if (!table_perm)
2533 {
2536
2537 return collist.data;
2538 }
2539
2540 return buf.data;
2541}
AclResult
Definition acl.h:183
@ ACLCHECK_OK
Definition acl.h:184
AclResult pg_attribute_aclcheck(Oid table_oid, AttrNumber attnum, Oid roleid, AclMode mode)
Definition aclchk.c:3911
AclResult pg_class_aclcheck(Oid table_oid, Oid roleid, AclMode mode)
Definition aclchk.c:4082
bool bms_is_member(int x, const Bitmapset *a)
Definition bitmapset.c:510
#define NameStr(name)
Definition c.h:837
char * OidOutputFunctionCall(Oid functionId, Datum val)
Definition fmgr.c:1764
long val
Definition informix.c:689
void getTypeOutputInfo(Oid type, Oid *typOutput, bool *typIsVarlena)
Definition lsyscache.c:3129
int pg_mbcliplen(const char *mbstr, int len, int limit)
Definition mbutils.c:1211
Oid GetUserId(void)
Definition miscinit.c:470
#define ACL_SELECT
Definition parsenodes.h:77
FormData_pg_attribute * Form_pg_attribute
static char buf[DEFAULT_XLOG_SEG_SIZE]
#define InvalidOid
int check_enable_rls(Oid relid, Oid checkAsUser, bool noError)
Definition rls.c:52
@ RLS_ENABLED
Definition rls.h:45
void appendBinaryStringInfo(StringInfo str, const void *data, int datalen)
Definition stringinfo.c:281
void appendStringInfoString(StringInfo str, const char *s)
Definition stringinfo.c:230
void appendStringInfoChar(StringInfo str, char ch)
Definition stringinfo.c:242
void initStringInfo(StringInfo str)
Definition stringinfo.c:97
bool * tts_isnull
Definition tuptable.h:133
Datum * tts_values
Definition tuptable.h:131
#define FirstLowInvalidHeapAttributeNumber
Definition sysattr.h:27
static FormData_pg_attribute * TupleDescAttr(TupleDesc tupdesc, int i)
Definition tupdesc.h:178
static void slot_getallattrs(TupleTableSlot *slot)
Definition tuptable.h:390

References ACL_SELECT, ACLCHECK_OK, appendBinaryStringInfo(), appendStringInfoChar(), appendStringInfoString(), bms_is_member(), buf, check_enable_rls(), fb(), FirstLowInvalidHeapAttributeNumber, getTypeOutputInfo(), GetUserId(), i, initStringInfo(), InvalidOid, NameStr, TupleDescData::natts, OidOutputFunctionCall(), pg_attribute_aclcheck(), pg_class_aclcheck(), pg_mbcliplen(), RLS_ENABLED, slot_getallattrs(), TupleTableSlot::tts_isnull, TupleTableSlot::tts_values, TupleDescAttr(), and val.

Referenced by ExecConstraints(), ExecPartitionCheckEmitError(), ExecWithCheckOptions(), get_tuple_desc(), and ReportNotNullViolationError().

◆ ExecCheckOneRelPerms()

bool ExecCheckOneRelPerms ( RTEPermissionInfo perminfo)

Definition at line 648 of file execMain.c.

649{
650 AclMode requiredPerms;
653 Oid userid;
654 Oid relOid = perminfo->relid;
655
656 requiredPerms = perminfo->requiredPerms;
657 Assert(requiredPerms != 0);
658
659 /*
660 * userid to check as: current user unless we have a setuid indication.
661 *
662 * Note: GetUserId() is presently fast enough that there's no harm in
663 * calling it separately for each relation. If that stops being true, we
664 * could call it once in ExecCheckPermissions and pass the userid down
665 * from there. But for now, no need for the extra clutter.
666 */
667 userid = OidIsValid(perminfo->checkAsUser) ?
668 perminfo->checkAsUser : GetUserId();
669
670 /*
671 * We must have *all* the requiredPerms bits, but some of the bits can be
672 * satisfied from column-level rather than relation-level permissions.
673 * First, remove any bits that are satisfied by relation permissions.
674 */
675 relPerms = pg_class_aclmask(relOid, userid, requiredPerms, ACLMASK_ALL);
676 remainingPerms = requiredPerms & ~relPerms;
677 if (remainingPerms != 0)
678 {
679 int col = -1;
680
681 /*
682 * If we lack any permissions that exist only as relation permissions,
683 * we can fail straight away.
684 */
686 return false;
687
688 /*
689 * Check to see if we have the needed privileges at column level.
690 *
691 * Note: failures just report a table-level error; it would be nicer
692 * to report a column-level error if we have some but not all of the
693 * column privileges.
694 */
696 {
697 /*
698 * When the query doesn't explicitly reference any columns (for
699 * example, SELECT COUNT(*) FROM table), allow the query if we
700 * have SELECT on any column of the rel, as per SQL spec.
701 */
702 if (bms_is_empty(perminfo->selectedCols))
703 {
704 if (pg_attribute_aclcheck_all(relOid, userid, ACL_SELECT,
706 return false;
707 }
708
709 while ((col = bms_next_member(perminfo->selectedCols, col)) >= 0)
710 {
711 /* bit #s are offset by FirstLowInvalidHeapAttributeNumber */
713
714 if (attno == InvalidAttrNumber)
715 {
716 /* Whole-row reference, must have priv on all cols */
717 if (pg_attribute_aclcheck_all(relOid, userid, ACL_SELECT,
719 return false;
720 }
721 else
722 {
723 if (pg_attribute_aclcheck(relOid, attno, userid,
725 return false;
726 }
727 }
728 }
729
730 /*
731 * Basically the same for the mod columns, for both INSERT and UPDATE
732 * privilege as specified by remainingPerms.
733 */
736 userid,
737 perminfo->insertedCols,
738 ACL_INSERT))
739 return false;
740
743 userid,
744 perminfo->updatedCols,
745 ACL_UPDATE))
746 return false;
747 }
748 return true;
749}
@ ACLMASK_ANY
Definition acl.h:178
@ ACLMASK_ALL
Definition acl.h:177
AclResult pg_attribute_aclcheck_all(Oid table_oid, Oid roleid, AclMode mode, AclMaskHow how)
Definition aclchk.c:3953
AclMode pg_class_aclmask(Oid table_oid, Oid roleid, AclMode mask, AclMaskHow how)
Definition aclchk.c:3297
int16 AttrNumber
Definition attnum.h:21
#define InvalidAttrNumber
Definition attnum.h:23
int bms_next_member(const Bitmapset *a, int prevbit)
Definition bitmapset.c:1290
#define bms_is_empty(a)
Definition bitmapset.h:118
static bool ExecCheckPermissionsModified(Oid relOid, Oid userid, Bitmapset *modifiedCols, AclMode requiredPerms)
Definition execMain.c:757
uint64 AclMode
Definition parsenodes.h:74
#define ACL_INSERT
Definition parsenodes.h:76
#define ACL_UPDATE
Definition parsenodes.h:78

References ACL_INSERT, ACL_SELECT, ACL_UPDATE, ACLCHECK_OK, ACLMASK_ALL, ACLMASK_ANY, Assert, bms_is_empty, bms_next_member(), ExecCheckPermissionsModified(), fb(), FirstLowInvalidHeapAttributeNumber, GetUserId(), InvalidAttrNumber, OidIsValid, pg_attribute_aclcheck(), pg_attribute_aclcheck_all(), and pg_class_aclmask().

Referenced by ExecCheckPermissions(), and subquery_planner().

◆ ExecCheckPermissions()

bool ExecCheckPermissions ( List rangeTable,
List rteperminfos,
bool  ereport_on_violation 
)

Definition at line 584 of file execMain.c.

586{
587 ListCell *l;
588 bool result = true;
589
590#ifdef USE_ASSERT_CHECKING
592
593 /* Check that rteperminfos is consistent with rangeTable */
594 foreach(l, rangeTable)
595 {
597
598 if (rte->perminfoindex != 0)
599 {
600 /* Sanity checks */
601
602 /*
603 * Only relation RTEs and subquery RTEs that were once relation
604 * RTEs (views, property graphs) have their perminfoindex set.
605 */
606 Assert(rte->rtekind == RTE_RELATION ||
607 (rte->rtekind == RTE_SUBQUERY &&
608 (rte->relkind == RELKIND_VIEW || rte->relkind == RELKIND_PROPGRAPH)));
609
610 (void) getRTEPermissionInfo(rteperminfos, rte);
611 /* Many-to-one mapping not allowed */
612 Assert(!bms_is_member(rte->perminfoindex, indexset));
613 indexset = bms_add_member(indexset, rte->perminfoindex);
614 }
615 }
616
617 /* All rteperminfos are referenced */
618 Assert(bms_num_members(indexset) == list_length(rteperminfos));
619#endif
620
621 foreach(l, rteperminfos)
622 {
624
625 Assert(OidIsValid(perminfo->relid));
627 if (!result)
628 {
629 if (ereport_on_violation)
632 get_rel_name(perminfo->relid));
633 return false;
634 }
635 }
636
638 result = (*ExecutorCheckPerms_hook) (rangeTable, rteperminfos,
639 ereport_on_violation);
640 return result;
641}
@ ACLCHECK_NO_PRIV
Definition acl.h:185
void aclcheck_error(AclResult aclerr, ObjectType objtype, const char *objectname)
Definition aclchk.c:2672
int bms_num_members(const Bitmapset *a)
Definition bitmapset.c:744
ExecutorCheckPerms_hook_type ExecutorCheckPerms_hook
Definition execMain.c:76
bool ExecCheckOneRelPerms(RTEPermissionInfo *perminfo)
Definition execMain.c:648
char * get_rel_name(Oid relid)
Definition lsyscache.c:2148
char get_rel_relkind(Oid relid)
Definition lsyscache.c:2223
ObjectType get_relkind_objtype(char relkind)
RTEPermissionInfo * getRTEPermissionInfo(List *rteperminfos, RangeTblEntry *rte)
@ RTE_SUBQUERY
@ RTE_RELATION
#define lfirst_node(type, lc)
Definition pg_list.h:176

References aclcheck_error(), ACLCHECK_NO_PRIV, Assert, bms_add_member(), bms_is_member(), bms_num_members(), ExecCheckOneRelPerms(), ExecutorCheckPerms_hook, fb(), get_rel_name(), get_rel_relkind(), get_relkind_objtype(), getRTEPermissionInfo(), lfirst_node, list_length(), OidIsValid, RTE_RELATION, and RTE_SUBQUERY.

Referenced by DoCopy(), InitPlan(), and RI_Initial_Check().

◆ ExecCheckPermissionsModified()

static bool ExecCheckPermissionsModified ( Oid  relOid,
Oid  userid,
Bitmapset modifiedCols,
AclMode  requiredPerms 
)
static

Definition at line 757 of file execMain.c.

759{
760 int col = -1;
761
762 /*
763 * When the query doesn't explicitly update any columns, allow the query
764 * if we have permission on any column of the rel. This is to handle
765 * SELECT FOR UPDATE as well as possible corner cases in UPDATE.
766 */
768 {
769 if (pg_attribute_aclcheck_all(relOid, userid, requiredPerms,
771 return false;
772 }
773
774 while ((col = bms_next_member(modifiedCols, col)) >= 0)
775 {
776 /* bit #s are offset by FirstLowInvalidHeapAttributeNumber */
778
779 if (attno == InvalidAttrNumber)
780 {
781 /* whole-row reference can't happen here */
782 elog(ERROR, "whole-row update is not implemented");
783 }
784 else
785 {
786 if (pg_attribute_aclcheck(relOid, attno, userid,
787 requiredPerms) != ACLCHECK_OK)
788 return false;
789 }
790 }
791 return true;
792}

References ACLCHECK_OK, ACLMASK_ANY, bms_is_empty, bms_next_member(), elog, ERROR, fb(), FirstLowInvalidHeapAttributeNumber, InvalidAttrNumber, pg_attribute_aclcheck(), and pg_attribute_aclcheck_all().

Referenced by ExecCheckOneRelPerms().

◆ ExecCheckXactReadOnly()

static void ExecCheckXactReadOnly ( PlannedStmt plannedstmt)
static

Definition at line 804 of file execMain.c.

805{
806 ListCell *l;
807
808 /*
809 * Fail if write permissions are requested in parallel mode for table
810 * (temp or non-temp), otherwise fail for any non-temp table.
811 */
812 foreach(l, plannedstmt->permInfos)
813 {
815
816 if ((perminfo->requiredPerms & (~ACL_SELECT)) == 0)
817 continue;
818
820 continue;
821
823 }
824
825 if (plannedstmt->commandType != CMD_SELECT || plannedstmt->hasModifyingCTE)
827}
Oid get_rel_namespace(Oid relid)
Definition lsyscache.c:2172
bool isTempNamespace(Oid namespaceId)
Definition namespace.c:3721
@ CMD_SELECT
Definition nodes.h:275
Definition nodes.h:135
bool hasModifyingCTE
Definition plannodes.h:81
List * permInfos
Definition plannodes.h:118
CmdType commandType
Definition plannodes.h:66
void PreventCommandIfReadOnly(const char *cmdname)
Definition utility.c:409
void PreventCommandIfParallelMode(const char *cmdname)
Definition utility.c:427
static const char * CreateCommandName(Node *parsetree)
Definition utility.h:103

References ACL_SELECT, CMD_SELECT, PlannedStmt::commandType, CreateCommandName(), fb(), get_rel_namespace(), PlannedStmt::hasModifyingCTE, isTempNamespace(), lfirst_node, PlannedStmt::permInfos, PreventCommandIfParallelMode(), and PreventCommandIfReadOnly().

Referenced by standard_ExecutorStart().

◆ ExecCloseRangeTableRelations()

void ExecCloseRangeTableRelations ( EState estate)

Definition at line 1654 of file execMain.c.

1655{
1656 int i;
1657
1658 for (i = 0; i < estate->es_range_table_size; i++)
1659 {
1660 if (estate->es_relations[i])
1661 table_close(estate->es_relations[i], NoLock);
1662 }
1663}
#define NoLock
Definition lockdefs.h:34
void table_close(Relation relation, LOCKMODE lockmode)
Definition table.c:126

References EState::es_range_table_size, EState::es_relations, i, NoLock, and table_close().

Referenced by CopyFrom(), and ExecEndPlan().

◆ ExecCloseResultRelations()

void ExecCloseResultRelations ( EState estate)

Definition at line 1594 of file execMain.c.

1595{
1596 ListCell *l;
1597
1598 /*
1599 * close indexes of result relation(s) if any. (Rels themselves are
1600 * closed in ExecCloseRangeTableRelations())
1601 *
1602 * In addition, close the stub RTs that may be in each resultrel's
1603 * ri_ancestorResultRels.
1604 */
1605 foreach(l, estate->es_opened_result_relations)
1606 {
1607 ResultRelInfo *resultRelInfo = lfirst(l);
1608 ListCell *lc;
1609
1610 ExecCloseIndices(resultRelInfo);
1611 foreach(lc, resultRelInfo->ri_ancestorResultRels)
1612 {
1614
1615 /*
1616 * Ancestors with RTI > 0 (should only be the root ancestor) are
1617 * closed by ExecCloseRangeTableRelations.
1618 */
1619 if (rInfo->ri_RangeTableIndex > 0)
1620 continue;
1621
1622 table_close(rInfo->ri_RelationDesc, NoLock);
1623 }
1624 }
1625
1626 /* Close any relations that have been opened by ExecGetTriggerResultRel(). */
1627 foreach(l, estate->es_trig_target_relations)
1628 {
1629 ResultRelInfo *resultRelInfo = (ResultRelInfo *) lfirst(l);
1630
1631 /*
1632 * Assert this is a "dummy" ResultRelInfo, see above. Otherwise we
1633 * might be issuing a duplicate close against a Relation opened by
1634 * ExecGetRangeTableRelation.
1635 */
1636 Assert(resultRelInfo->ri_RangeTableIndex == 0);
1637
1638 /*
1639 * Since ExecGetTriggerResultRel doesn't call ExecOpenIndices for
1640 * these rels, we needn't call ExecCloseIndices either.
1641 */
1642 Assert(resultRelInfo->ri_NumIndices == 0);
1643
1644 table_close(resultRelInfo->ri_RelationDesc, NoLock);
1645 }
1646}
void ExecCloseIndices(ResultRelInfo *resultRelInfo)
List * es_trig_target_relations
Definition execnodes.h:713
List * es_opened_result_relations
Definition execnodes.h:700
Index ri_RangeTableIndex
Definition execnodes.h:489
List * ri_ancestorResultRels
Definition execnodes.h:640

References Assert, EState::es_opened_result_relations, EState::es_trig_target_relations, ExecCloseIndices(), fb(), lfirst, NoLock, ResultRelInfo::ri_ancestorResultRels, ResultRelInfo::ri_NumIndices, ResultRelInfo::ri_RangeTableIndex, ResultRelInfo::ri_RelationDesc, and table_close().

Referenced by afterTriggerInvokeEvents(), CopyFrom(), EvalPlanQualEnd(), and ExecEndPlan().

◆ ExecConstraints()

void ExecConstraints ( ResultRelInfo resultRelInfo,
TupleTableSlot slot,
EState estate 
)

Definition at line 1999 of file execMain.c.

2001{
2002 Relation rel = resultRelInfo->ri_RelationDesc;
2003 TupleDesc tupdesc = RelationGetDescr(rel);
2004 TupleConstr *constr = tupdesc->constr;
2007
2008 Assert(constr); /* we should not be called otherwise */
2009
2010 /*
2011 * Verify not-null constraints.
2012 *
2013 * Not-null constraints on virtual generated columns are collected and
2014 * checked separately below.
2015 */
2016 if (constr->has_not_null)
2017 {
2018 for (AttrNumber attnum = 1; attnum <= tupdesc->natts; attnum++)
2019 {
2020 Form_pg_attribute att = TupleDescAttr(tupdesc, attnum - 1);
2021
2022 if (att->attnotnull && att->attgenerated == ATTRIBUTE_GENERATED_VIRTUAL)
2024 else if (att->attnotnull && slot_attisnull(slot, attnum))
2025 ReportNotNullViolationError(resultRelInfo, slot, estate, attnum);
2026 }
2027 }
2028
2029 /*
2030 * Verify not-null constraints on virtual generated column, if any.
2031 */
2033 {
2035
2036 attnum = ExecRelGenVirtualNotNull(resultRelInfo, slot, estate,
2039 ReportNotNullViolationError(resultRelInfo, slot, estate, attnum);
2040 }
2041
2042 /*
2043 * Verify check constraints.
2044 */
2045 if (rel->rd_rel->relchecks > 0)
2046 {
2047 const char *failed;
2048
2049 if ((failed = ExecRelCheck(resultRelInfo, slot, estate)) != NULL)
2050 {
2051 char *val_desc;
2052 Relation orig_rel = rel;
2053
2054 /*
2055 * If the tuple has been routed, it's been converted to the
2056 * partition's rowtype, which might differ from the root table's.
2057 * We must convert it back to the root table's rowtype so that
2058 * val_desc shown error message matches the input tuple.
2059 */
2060 if (resultRelInfo->ri_RootResultRelInfo)
2061 {
2062 ResultRelInfo *rootrel = resultRelInfo->ri_RootResultRelInfo;
2064 AttrMap *map;
2065
2066 tupdesc = RelationGetDescr(rootrel->ri_RelationDesc);
2067 /* a reverse map */
2069 tupdesc,
2070 false);
2071
2072 /*
2073 * Partition-specific slot's tupdesc can't be changed, so
2074 * allocate a new one.
2075 */
2076 if (map != NULL)
2077 slot = execute_attr_map_slot(map, slot,
2078 MakeTupleTableSlot(tupdesc, &TTSOpsVirtual, 0));
2080 ExecGetUpdatedCols(rootrel, estate));
2081 rel = rootrel->ri_RelationDesc;
2082 }
2083 else
2084 modifiedCols = bms_union(ExecGetInsertedCols(resultRelInfo, estate),
2085 ExecGetUpdatedCols(resultRelInfo, estate));
2087 slot,
2088 tupdesc,
2090 64);
2091 ereport(ERROR,
2093 errmsg("new row for relation \"%s\" violates check constraint \"%s\"",
2095 val_desc ? errdetail("Failing row contains %s.", val_desc) : 0,
2096 errtableconstraint(orig_rel, failed)));
2097 }
2098 }
2099}
AttrMap * build_attrmap_by_name_if_req(TupleDesc indesc, TupleDesc outdesc, bool missing_ok)
Definition attmap.c:261
Bitmapset * bms_union(const Bitmapset *a, const Bitmapset *b)
Definition bitmapset.c:251
int errdetail(const char *fmt,...) pg_attribute_printf(1
static void ReportNotNullViolationError(ResultRelInfo *resultRelInfo, TupleTableSlot *slot, EState *estate, int attnum)
Definition execMain.c:2178
char * ExecBuildSlotValueDescription(Oid reloid, TupleTableSlot *slot, TupleDesc tupdesc, Bitmapset *modifiedCols, int maxfieldlen)
Definition execMain.c:2410
AttrNumber ExecRelGenVirtualNotNull(ResultRelInfo *resultRelInfo, TupleTableSlot *slot, EState *estate, List *notnull_virtual_attrs)
Definition execMain.c:2113
static const char * ExecRelCheck(ResultRelInfo *resultRelInfo, TupleTableSlot *slot, EState *estate)
Definition execMain.c:1797
const TupleTableSlotOps TTSOpsVirtual
Definition execTuples.c:84
TupleTableSlot * MakeTupleTableSlot(TupleDesc tupleDesc, const TupleTableSlotOps *tts_ops, uint16 flags)
Bitmapset * ExecGetInsertedCols(ResultRelInfo *relinfo, EState *estate)
Definition execUtils.c:1366
Bitmapset * ExecGetUpdatedCols(ResultRelInfo *relinfo, EState *estate)
Definition execUtils.c:1387
List * lappend_int(List *list, int datum)
Definition list.c:357
int16 attnum
#define RelationGetRelid(relation)
Definition rel.h:514
#define RelationGetDescr(relation)
Definition rel.h:540
int errtableconstraint(Relation rel, const char *conname)
Definition relcache.c:6116
Definition pg_list.h:54
struct ResultRelInfo * ri_RootResultRelInfo
Definition execnodes.h:630
bool has_not_null
Definition tupdesc.h:45
TupleConstr * constr
Definition tupdesc.h:159
TupleTableSlot * execute_attr_map_slot(AttrMap *attrMap, TupleTableSlot *in_slot, TupleTableSlot *out_slot)
Definition tupconvert.c:193
static bool slot_attisnull(TupleTableSlot *slot, int attnum)
Definition tuptable.h:403

References Assert, attnum, bms_union(), build_attrmap_by_name_if_req(), TupleDescData::constr, ereport, errcode(), errdetail(), errmsg, ERROR, errtableconstraint(), ExecBuildSlotValueDescription(), ExecGetInsertedCols(), ExecGetUpdatedCols(), ExecRelCheck(), ExecRelGenVirtualNotNull(), execute_attr_map_slot(), fb(), TupleConstr::has_not_null, InvalidAttrNumber, lappend_int(), MakeTupleTableSlot(), TupleDescData::natts, NIL, RelationData::rd_rel, RelationGetDescr, RelationGetRelationName, RelationGetRelid, ReportNotNullViolationError(), ResultRelInfo::ri_RelationDesc, ResultRelInfo::ri_RootResultRelInfo, slot_attisnull(), TTSOpsVirtual, and TupleDescAttr().

Referenced by CopyFrom(), ExecInsert(), ExecSimpleRelationInsert(), ExecSimpleRelationUpdate(), and ExecUpdateAct().

◆ ExecEndPlan()

static void ExecEndPlan ( PlanState planstate,
EState estate 
)
static

Definition at line 1555 of file execMain.c.

1556{
1557 ListCell *l;
1558
1559 /*
1560 * shut down the node-type-specific query processing
1561 */
1562 ExecEndNode(planstate);
1563
1564 /*
1565 * for subplans too
1566 */
1567 foreach(l, estate->es_subplanstates)
1568 {
1570
1572 }
1573
1574 /*
1575 * destroy the executor's tuple table. Actually we only care about
1576 * releasing buffer pins and tupdesc refcounts; there's no need to pfree
1577 * the TupleTableSlots, since the containing memory context is about to go
1578 * away anyway.
1579 */
1580 ExecResetTupleTable(estate->es_tupleTable, false);
1581
1582 /*
1583 * Close any Relations that have been opened for range table entries or
1584 * result relations.
1585 */
1588}
void ExecCloseRangeTableRelations(EState *estate)
Definition execMain.c:1654

References EState::es_subplanstates, EState::es_tupleTable, ExecCloseRangeTableRelations(), ExecCloseResultRelations(), ExecEndNode(), ExecResetTupleTable(), fb(), and lfirst.

Referenced by standard_ExecutorEnd().

◆ ExecFindRowMark()

ExecRowMark * ExecFindRowMark ( EState estate,
Index  rti,
bool  missing_ok 
)

Definition at line 2575 of file execMain.c.

2576{
2577 if (rti > 0 && rti <= estate->es_range_table_size &&
2578 estate->es_rowmarks != NULL)
2579 {
2580 ExecRowMark *erm = estate->es_rowmarks[rti - 1];
2581
2582 if (erm)
2583 return erm;
2584 }
2585 if (!missing_ok)
2586 elog(ERROR, "failed to find ExecRowMark for rangetable index %u", rti);
2587 return NULL;
2588}

References elog, ERROR, EState::es_rowmarks, and fb().

Referenced by ExecInitLockRows(), and ExecInitModifyTable().

◆ ExecGetAncestorResultRels()

List * ExecGetAncestorResultRels ( EState estate,
ResultRelInfo resultRelInfo 
)

Definition at line 1449 of file execMain.c.

1450{
1452 Relation partRel = resultRelInfo->ri_RelationDesc;
1454
1455 if (!partRel->rd_rel->relispartition)
1456 elog(ERROR, "cannot find ancestors of a non-partition result relation");
1458 rootRelOid = RelationGetRelid(rootRelInfo->ri_RelationDesc);
1459 if (resultRelInfo->ri_ancestorResultRels == NIL)
1460 {
1461 ListCell *lc;
1464
1465 foreach(lc, oids)
1466 {
1470
1471 /*
1472 * Ignore the root ancestor here, and use ri_RootResultRelInfo
1473 * (below) for it instead. Also, we stop climbing up the
1474 * hierarchy when we find the table that was mentioned in the
1475 * query.
1476 */
1477 if (ancOid == rootRelOid)
1478 break;
1479
1480 /*
1481 * All ancestors up to the root target relation must have been
1482 * locked by the planner or AcquireExecutorLocks().
1483 */
1486
1487 /* dummy rangetable index */
1489 estate->es_instrument);
1491 }
1493 resultRelInfo->ri_ancestorResultRels = ancResultRels;
1494 }
1495
1496 /* We must have found some ancestor */
1497 Assert(resultRelInfo->ri_ancestorResultRels != NIL);
1498
1499 return resultRelInfo->ri_ancestorResultRels;
1500}
void InitResultRelInfo(ResultRelInfo *resultRelInfo, Relation resultRelationDesc, Index resultRelationIndex, ResultRelInfo *partition_root_rri, int instrument_options)
Definition execMain.c:1262
#define makeNode(_type_)
Definition nodes.h:161
List * get_partition_ancestors(Oid relid)
Definition partition.c:134
#define lfirst_oid(lc)
Definition pg_list.h:174
Relation table_open(Oid relationId, LOCKMODE lockmode)
Definition table.c:40

References Assert, elog, ERROR, EState::es_instrument, fb(), get_partition_ancestors(), InitResultRelInfo(), lappend(), lfirst_oid, makeNode, NIL, NoLock, RelationData::rd_rel, RelationGetRelid, ResultRelInfo::ri_ancestorResultRels, ResultRelInfo::ri_RelationDesc, ResultRelInfo::ri_RootResultRelInfo, and table_open().

Referenced by ExecCrossPartitionUpdateForeignKey().

◆ ExecGetTriggerResultRel()

ResultRelInfo * ExecGetTriggerResultRel ( EState estate,
Oid  relid,
ResultRelInfo rootRelInfo 
)

Definition at line 1362 of file execMain.c.

1364{
1366 ListCell *l;
1367 Relation rel;
1368 MemoryContext oldcontext;
1369
1370 /*
1371 * Before creating a new ResultRelInfo, check if we've already made and
1372 * cached one for this relation. We must ensure that the given
1373 * 'rootRelInfo' matches the one stored in the cached ResultRelInfo as
1374 * trigger handling for partitions can result in mixed requirements for
1375 * what ri_RootResultRelInfo is set to.
1376 */
1377
1378 /* Search through the query result relations */
1379 foreach(l, estate->es_opened_result_relations)
1380 {
1381 rInfo = lfirst(l);
1382 if (RelationGetRelid(rInfo->ri_RelationDesc) == relid &&
1383 rInfo->ri_RootResultRelInfo == rootRelInfo)
1384 return rInfo;
1385 }
1386
1387 /*
1388 * Search through the result relations that were created during tuple
1389 * routing, if any.
1390 */
1391 foreach(l, estate->es_tuple_routing_result_relations)
1392 {
1393 rInfo = (ResultRelInfo *) lfirst(l);
1394 if (RelationGetRelid(rInfo->ri_RelationDesc) == relid &&
1395 rInfo->ri_RootResultRelInfo == rootRelInfo)
1396 return rInfo;
1397 }
1398
1399 /* Nope, but maybe we already made an extra ResultRelInfo for it */
1400 foreach(l, estate->es_trig_target_relations)
1401 {
1402 rInfo = (ResultRelInfo *) lfirst(l);
1403 if (RelationGetRelid(rInfo->ri_RelationDesc) == relid &&
1404 rInfo->ri_RootResultRelInfo == rootRelInfo)
1405 return rInfo;
1406 }
1407 /* Nope, so we need a new one */
1408
1409 /*
1410 * Open the target relation's relcache entry. We assume that an
1411 * appropriate lock is still held by the backend from whenever the trigger
1412 * event got queued, so we need take no new lock here. Also, we need not
1413 * recheck the relkind, so no need for CheckValidResultRel.
1414 */
1415 rel = table_open(relid, NoLock);
1416
1417 /*
1418 * Make the new entry in the right context.
1419 */
1420 oldcontext = MemoryContextSwitchTo(estate->es_query_cxt);
1423 rel,
1424 0, /* dummy rangetable index */
1426 estate->es_instrument);
1427 estate->es_trig_target_relations =
1429 MemoryContextSwitchTo(oldcontext);
1430
1431 /*
1432 * Currently, we don't need any index information in ResultRelInfos used
1433 * only for triggers, so no need to call ExecOpenIndices.
1434 */
1435
1436 return rInfo;
1437}
List * es_tuple_routing_result_relations
Definition execnodes.h:710

References EState::es_instrument, EState::es_opened_result_relations, EState::es_query_cxt, EState::es_trig_target_relations, EState::es_tuple_routing_result_relations, fb(), InitResultRelInfo(), lappend(), lfirst, makeNode, MemoryContextSwitchTo(), NoLock, RelationGetRelid, and table_open().

Referenced by afterTriggerInvokeEvents().

◆ ExecPartitionCheck()

bool ExecPartitionCheck ( ResultRelInfo resultRelInfo,
TupleTableSlot slot,
EState estate,
bool  emitError 
)

Definition at line 1875 of file execMain.c.

1877{
1878 ExprContext *econtext;
1879 bool success;
1880
1881 /*
1882 * If first time through, build expression state tree for the partition
1883 * check expression. (In the corner case where the partition check
1884 * expression is empty, ie there's a default partition and nothing else,
1885 * we'll be fooled into executing this code each time through. But it's
1886 * pretty darn cheap in that case, so we don't worry about it.)
1887 */
1888 if (resultRelInfo->ri_PartitionCheckExpr == NULL)
1889 {
1890 /*
1891 * Ensure that the qual tree and prepared expression are in the
1892 * query-lifespan context.
1893 */
1895 List *qual = RelationGetPartitionQual(resultRelInfo->ri_RelationDesc);
1896
1897 resultRelInfo->ri_PartitionCheckExpr = ExecPrepareCheck(qual, estate);
1899 }
1900
1901 /*
1902 * We will use the EState's per-tuple context for evaluating constraint
1903 * expressions (creating it if it's not already there).
1904 */
1905 econtext = GetPerTupleExprContext(estate);
1906
1907 /* Arrange for econtext's scan tuple to be the tuple under test */
1908 econtext->ecxt_scantuple = slot;
1909
1910 /*
1911 * As in case of the cataloged constraints, we treat a NULL result as
1912 * success here, not a failure.
1913 */
1914 success = ExecCheck(resultRelInfo->ri_PartitionCheckExpr, econtext);
1915
1916 /* if asked to emit error, don't actually return on failure */
1917 if (!success && emitError)
1918 ExecPartitionCheckEmitError(resultRelInfo, slot, estate);
1919
1920 return success;
1921}
bool ExecCheck(ExprState *state, ExprContext *econtext)
Definition execExpr.c:905
ExprState * ExecPrepareCheck(List *qual, EState *estate)
Definition execExpr.c:849
void ExecPartitionCheckEmitError(ResultRelInfo *resultRelInfo, TupleTableSlot *slot, EState *estate)
Definition execMain.c:1928
static bool success
Definition initdb.c:188
List * RelationGetPartitionQual(Relation rel)
Definition partcache.c:277
TupleTableSlot * ecxt_scantuple
Definition execnodes.h:284
ExprState * ri_PartitionCheckExpr
Definition execnodes.h:604

References ExprContext::ecxt_scantuple, EState::es_query_cxt, ExecCheck(), ExecPartitionCheckEmitError(), ExecPrepareCheck(), fb(), GetPerTupleExprContext, MemoryContextSwitchTo(), RelationGetPartitionQual(), ResultRelInfo::ri_PartitionCheckExpr, ResultRelInfo::ri_RelationDesc, and success.

Referenced by apply_handle_tuple_routing(), CopyFrom(), ExecBRInsertTriggers(), ExecFindPartition(), ExecInsert(), ExecSimpleRelationInsert(), ExecSimpleRelationUpdate(), and ExecUpdateAct().

◆ ExecPartitionCheckEmitError()

void ExecPartitionCheckEmitError ( ResultRelInfo resultRelInfo,
TupleTableSlot slot,
EState estate 
)

Definition at line 1928 of file execMain.c.

1931{
1933 TupleDesc tupdesc;
1934 char *val_desc;
1936
1937 /*
1938 * If the tuple has been routed, it's been converted to the partition's
1939 * rowtype, which might differ from the root table's. We must convert it
1940 * back to the root table's rowtype so that val_desc in the error message
1941 * matches the input tuple.
1942 */
1943 if (resultRelInfo->ri_RootResultRelInfo)
1944 {
1945 ResultRelInfo *rootrel = resultRelInfo->ri_RootResultRelInfo;
1947 AttrMap *map;
1948
1949 root_relid = RelationGetRelid(rootrel->ri_RelationDesc);
1950 tupdesc = RelationGetDescr(rootrel->ri_RelationDesc);
1951
1953 /* a reverse map */
1954 map = build_attrmap_by_name_if_req(old_tupdesc, tupdesc, false);
1955
1956 /*
1957 * Partition-specific slot's tupdesc can't be changed, so allocate a
1958 * new one.
1959 */
1960 if (map != NULL)
1961 slot = execute_attr_map_slot(map, slot,
1962 MakeTupleTableSlot(tupdesc, &TTSOpsVirtual, 0));
1964 ExecGetUpdatedCols(rootrel, estate));
1965 }
1966 else
1967 {
1969 tupdesc = RelationGetDescr(resultRelInfo->ri_RelationDesc);
1970 modifiedCols = bms_union(ExecGetInsertedCols(resultRelInfo, estate),
1971 ExecGetUpdatedCols(resultRelInfo, estate));
1972 }
1973
1975 slot,
1976 tupdesc,
1978 64);
1979 ereport(ERROR,
1981 errmsg("new row for relation \"%s\" violates partition constraint",
1983 val_desc ? errdetail("Failing row contains %s.", val_desc) : 0,
1984 errtable(resultRelInfo->ri_RelationDesc)));
1985}
int errtable(Relation rel)
Definition relcache.c:6062

References bms_union(), build_attrmap_by_name_if_req(), ereport, errcode(), errdetail(), errmsg, ERROR, errtable(), ExecBuildSlotValueDescription(), ExecGetInsertedCols(), ExecGetUpdatedCols(), execute_attr_map_slot(), fb(), MakeTupleTableSlot(), RelationGetDescr, RelationGetRelationName, RelationGetRelid, ResultRelInfo::ri_RelationDesc, ResultRelInfo::ri_RootResultRelInfo, and TTSOpsVirtual.

Referenced by ExecCrossPartitionUpdate(), and ExecPartitionCheck().

◆ ExecPostprocessPlan()

static void ExecPostprocessPlan ( EState estate)
static

Definition at line 1509 of file execMain.c.

1510{
1511 ListCell *lc;
1512
1513 /*
1514 * Make sure nodes run forward.
1515 */
1517
1518 /*
1519 * Run any secondary ModifyTable nodes to completion, in case the main
1520 * query did not fetch all rows from them. (We do this to ensure that
1521 * such nodes have predictable results.)
1522 */
1523 foreach(lc, estate->es_auxmodifytables)
1524 {
1525 PlanState *ps = (PlanState *) lfirst(lc);
1526
1527 for (;;)
1528 {
1529 TupleTableSlot *slot;
1530
1531 /* Reset the per-output-tuple exprcontext each time */
1533
1534 slot = ExecProcNode(ps);
1535
1536 if (TupIsNull(slot))
1537 break;
1538 }
1539 }
1540}
#define ResetPerTupleExprContext(estate)
Definition executor.h:669
struct parser_state ps
ScanDirection es_direction
Definition execnodes.h:671
List * es_auxmodifytables
Definition execnodes.h:739

References EState::es_auxmodifytables, EState::es_direction, ExecProcNode(), fb(), ForwardScanDirection, lfirst, ps, ResetPerTupleExprContext, and TupIsNull.

Referenced by standard_ExecutorFinish().

◆ ExecRelCheck()

static const char * ExecRelCheck ( ResultRelInfo resultRelInfo,
TupleTableSlot slot,
EState estate 
)
static

Definition at line 1797 of file execMain.c.

1799{
1800 Relation rel = resultRelInfo->ri_RelationDesc;
1801 int ncheck = rel->rd_att->constr->num_check;
1802 ConstrCheck *check = rel->rd_att->constr->check;
1803 ExprContext *econtext;
1805
1806 /*
1807 * CheckNNConstraintFetch let this pass with only a warning, but now we
1808 * should fail rather than possibly failing to enforce an important
1809 * constraint.
1810 */
1811 if (ncheck != rel->rd_rel->relchecks)
1812 elog(ERROR, "%d pg_constraint record(s) missing for relation \"%s\"",
1813 rel->rd_rel->relchecks - ncheck, RelationGetRelationName(rel));
1814
1815 /*
1816 * If first time through for this result relation, build expression
1817 * nodetrees for rel's constraint expressions. Keep them in the per-query
1818 * memory context so they'll survive throughout the query.
1819 */
1820 if (resultRelInfo->ri_CheckConstraintExprs == NULL)
1821 {
1823 resultRelInfo->ri_CheckConstraintExprs = palloc0_array(ExprState *, ncheck);
1824 for (int i = 0; i < ncheck; i++)
1825 {
1827
1828 /* Skip not enforced constraint */
1829 if (!check[i].ccenforced)
1830 continue;
1831
1832 checkconstr = stringToNode(check[i].ccbin);
1834 resultRelInfo->ri_CheckConstraintExprs[i] =
1836 }
1838 }
1839
1840 /*
1841 * We will use the EState's per-tuple context for evaluating constraint
1842 * expressions (creating it if it's not already there).
1843 */
1844 econtext = GetPerTupleExprContext(estate);
1845
1846 /* Arrange for econtext's scan tuple to be the tuple under test */
1847 econtext->ecxt_scantuple = slot;
1848
1849 /* And evaluate the constraints */
1850 for (int i = 0; i < ncheck; i++)
1851 {
1853
1854 /*
1855 * NOTE: SQL specifies that a NULL result from a constraint expression
1856 * is not to be treated as a failure. Therefore, use ExecCheck not
1857 * ExecQual.
1858 */
1859 if (checkconstr && !ExecCheck(checkconstr, econtext))
1860 return check[i].ccname;
1861 }
1862
1863 /* NULL result means no error */
1864 return NULL;
1865}
ExprState * ExecPrepareExpr(Expr *node, EState *estate)
Definition execExpr.c:786
void * stringToNode(const char *str)
Definition read.c:90
Node * expand_generated_columns_in_expr(Node *node, Relation rel, int rt_index)
char * ccname
Definition tupdesc.h:30
TupleDesc rd_att
Definition rel.h:112
ExprState ** ri_CheckConstraintExprs
Definition execnodes.h:567
ConstrCheck * check
Definition tupdesc.h:41
uint16 num_check
Definition tupdesc.h:44

References ConstrCheck::ccname, TupleConstr::check, TupleDescData::constr, ExprContext::ecxt_scantuple, elog, ERROR, EState::es_query_cxt, ExecCheck(), ExecPrepareExpr(), expand_generated_columns_in_expr(), fb(), GetPerTupleExprContext, i, MemoryContextSwitchTo(), TupleConstr::num_check, palloc0_array, RelationData::rd_att, RelationData::rd_rel, RelationGetRelationName, ResultRelInfo::ri_CheckConstraintExprs, ResultRelInfo::ri_RelationDesc, and stringToNode().

Referenced by ExecConstraints().

◆ ExecRelGenVirtualNotNull()

AttrNumber ExecRelGenVirtualNotNull ( ResultRelInfo resultRelInfo,
TupleTableSlot slot,
EState estate,
List notnull_virtual_attrs 
)

Definition at line 2113 of file execMain.c.

2115{
2116 Relation rel = resultRelInfo->ri_RelationDesc;
2117 ExprContext *econtext;
2119
2120 /*
2121 * We implement this by building a NullTest node for each virtual
2122 * generated column, which we cache in resultRelInfo, and running those
2123 * through ExecCheck().
2124 */
2125 if (resultRelInfo->ri_GenVirtualNotNullConstraintExprs == NULL)
2126 {
2130
2132 {
2135
2136 /* "generated_expression IS NOT NULL" check. */
2139 nnulltest->nulltesttype = IS_NOT_NULL;
2140 nnulltest->argisrow = false;
2141 nnulltest->location = -1;
2142
2143 resultRelInfo->ri_GenVirtualNotNullConstraintExprs[i] =
2144 ExecPrepareExpr((Expr *) nnulltest, estate);
2145 }
2147 }
2148
2149 /*
2150 * We will use the EState's per-tuple context for evaluating virtual
2151 * generated column not null constraint expressions (creating it if it's
2152 * not already there).
2153 */
2154 econtext = GetPerTupleExprContext(estate);
2155
2156 /* Arrange for econtext's scan tuple to be the tuple under test */
2157 econtext->ecxt_scantuple = slot;
2158
2159 /* And evaluate the check constraints for virtual generated column */
2161 {
2163 ExprState *exprstate = resultRelInfo->ri_GenVirtualNotNullConstraintExprs[i];
2164
2165 Assert(exprstate != NULL);
2166 if (!ExecCheck(exprstate, econtext))
2167 return attnum;
2168 }
2169
2170 /* InvalidAttrNumber result means no error */
2171 return InvalidAttrNumber;
2172}
#define foreach_current_index(var_or_cell)
Definition pg_list.h:403
#define foreach_int(var, lst)
Definition pg_list.h:470
@ IS_NOT_NULL
Definition primnodes.h:1979
Node * build_generation_expression(Relation rel, int attrno)
ExprState ** ri_GenVirtualNotNullConstraintExprs
Definition execnodes.h:573

References Assert, attnum, build_generation_expression(), ExprContext::ecxt_scantuple, EState::es_query_cxt, ExecCheck(), ExecPrepareExpr(), fb(), foreach_current_index, foreach_int, GetPerTupleExprContext, i, InvalidAttrNumber, IS_NOT_NULL, list_length(), makeNode, MemoryContextSwitchTo(), palloc0_array, ResultRelInfo::ri_GenVirtualNotNullConstraintExprs, and ResultRelInfo::ri_RelationDesc.

Referenced by ATRewriteTable(), and ExecConstraints().

◆ ExecUpdateLockMode()

LockTupleMode ExecUpdateLockMode ( EState estate,
ResultRelInfo relinfo 
)

Definition at line 2549 of file execMain.c.

2550{
2552 Bitmapset *updatedCols;
2553
2554 /*
2555 * Compute lock mode to use. If columns that are part of the key have not
2556 * been modified, then we can use a weaker lock, allowing for better
2557 * concurrency.
2558 */
2559 updatedCols = ExecGetAllUpdatedCols(relinfo, estate);
2560 keyCols = RelationGetIndexAttrBitmap(relinfo->ri_RelationDesc,
2562
2563 if (bms_overlap(keyCols, updatedCols))
2564 return LockTupleExclusive;
2565
2567}
bool bms_overlap(const Bitmapset *a, const Bitmapset *b)
Definition bitmapset.c:575
Bitmapset * ExecGetAllUpdatedCols(ResultRelInfo *relinfo, EState *estate)
Definition execUtils.c:1423
@ LockTupleExclusive
Definition lockoptions.h:59
@ LockTupleNoKeyExclusive
Definition lockoptions.h:57
Bitmapset * RelationGetIndexAttrBitmap(Relation relation, IndexAttrBitmapKind attrKind)
Definition relcache.c:5293
@ INDEX_ATTR_BITMAP_KEY
Definition relcache.h:69

References bms_overlap(), ExecGetAllUpdatedCols(), fb(), INDEX_ATTR_BITMAP_KEY, LockTupleExclusive, LockTupleNoKeyExclusive, and RelationGetIndexAttrBitmap().

Referenced by ExecBRUpdateTriggers(), ExecMergeMatched(), and ExecOnConflictUpdate().

◆ ExecutePlan()

static void ExecutePlan ( QueryDesc queryDesc,
CmdType  operation,
bool  sendTuples,
uint64  numberTuples,
ScanDirection  direction,
DestReceiver dest 
)
static

Definition at line 1675 of file execMain.c.

1681{
1682 EState *estate = queryDesc->estate;
1683 PlanState *planstate = queryDesc->planstate;
1684 bool use_parallel_mode;
1685 TupleTableSlot *slot;
1687
1688 /*
1689 * initialize local variables
1690 */
1692
1693 /*
1694 * Set the direction.
1695 */
1696 estate->es_direction = direction;
1697
1698 /*
1699 * Set up parallel mode if appropriate.
1700 *
1701 * Parallel mode only supports complete execution of a plan. If we've
1702 * already partially executed it, or if the caller asks us to exit early,
1703 * we must force the plan to run without parallelism.
1704 */
1705 if (queryDesc->already_executed || numberTuples != 0)
1706 use_parallel_mode = false;
1707 else
1709 queryDesc->already_executed = true;
1710
1714
1715 /*
1716 * Loop until we've processed the proper number of tuples from the plan.
1717 */
1718 for (;;)
1719 {
1720 /* Reset the per-output-tuple exprcontext */
1722
1723 /*
1724 * Execute the plan and obtain a tuple
1725 */
1726 slot = ExecProcNode(planstate);
1727
1728 /*
1729 * if the tuple is null, then we assume there is nothing more to
1730 * process so we just end the loop...
1731 */
1732 if (TupIsNull(slot))
1733 break;
1734
1735 /*
1736 * If we have a junk filter, then project a new tuple with the junk
1737 * removed.
1738 *
1739 * Store this new "clean" tuple in the junkfilter's resultSlot.
1740 * (Formerly, we stored it back over the "dirty" tuple, which is WRONG
1741 * because that tuple slot has the wrong descriptor.)
1742 */
1743 if (estate->es_junkFilter != NULL)
1744 slot = ExecFilterJunk(estate->es_junkFilter, slot);
1745
1746 /*
1747 * If we are supposed to send the tuple somewhere, do so. (In
1748 * practice, this is probably always the case at this point.)
1749 */
1750 if (sendTuples)
1751 {
1752 /*
1753 * If we are not able to send the tuple, we assume the destination
1754 * has closed and no more tuples can be sent. If that's the case,
1755 * end the loop.
1756 */
1757 if (!dest->receiveSlot(slot, dest))
1758 break;
1759 }
1760
1761 /*
1762 * Count tuples processed, if this is a SELECT. (For other operation
1763 * types, the ModifyTable plan node must count the appropriate
1764 * events.)
1765 */
1766 if (operation == CMD_SELECT)
1767 (estate->es_processed)++;
1768
1769 /*
1770 * check our tuple count.. if we've processed the proper number then
1771 * quit, else loop again and process more tuples. Zero numberTuples
1772 * means no limit.
1773 */
1776 break;
1777 }
1778
1779 /*
1780 * If we know we won't need to back up, we can release resources at this
1781 * point.
1782 */
1783 if (!(estate->es_top_eflags & EXEC_FLAG_BACKWARD))
1784 ExecShutdownNode(planstate);
1785
1788}
uint64_t uint64
Definition c.h:619
TupleTableSlot * ExecFilterJunk(JunkFilter *junkfilter, TupleTableSlot *slot)
Definition execJunk.c:247
void ExecShutdownNode(PlanState *node)
#define EXEC_FLAG_BACKWARD
Definition executor.h:70
uint64 es_processed
Definition execnodes.h:726
bool es_use_parallel_mode
Definition execnodes.h:756
bool parallelModeNeeded
Definition plannodes.h:93
EState * estate
Definition execdesc.h:48
bool already_executed
Definition execdesc.h:52
PlannedStmt * plannedstmt
Definition execdesc.h:37
PlanState * planstate
Definition execdesc.h:49
void ExitParallelMode(void)
Definition xact.c:1066
void EnterParallelMode(void)
Definition xact.c:1053

References QueryDesc::already_executed, CMD_SELECT, EnterParallelMode(), EState::es_direction, EState::es_junkFilter, EState::es_processed, EState::es_top_eflags, EState::es_use_parallel_mode, QueryDesc::estate, EXEC_FLAG_BACKWARD, ExecFilterJunk(), ExecProcNode(), ExecShutdownNode(), ExitParallelMode(), fb(), PlannedStmt::parallelModeNeeded, QueryDesc::plannedstmt, QueryDesc::planstate, ResetPerTupleExprContext, and TupIsNull.

Referenced by standard_ExecutorRun().

◆ ExecutorEnd()

void ExecutorEnd ( QueryDesc queryDesc)

Definition at line 468 of file execMain.c.

469{
471 (*ExecutorEnd_hook) (queryDesc);
472 else
473 standard_ExecutorEnd(queryDesc);
474}
ExecutorEnd_hook_type ExecutorEnd_hook
Definition execMain.c:73
void standard_ExecutorEnd(QueryDesc *queryDesc)
Definition execMain.c:477

References ExecutorEnd_hook, and standard_ExecutorEnd().

Referenced by _SPI_pquery(), EndCopyTo(), ExecCreateTableAs(), execute_sql_string(), ExplainOnePlan(), ParallelQueryMain(), PersistHoldablePortal(), PortalCleanup(), postquel_end(), ProcessQuery(), and refresh_matview_datafill().

◆ ExecutorFinish()

void ExecutorFinish ( QueryDesc queryDesc)

Definition at line 408 of file execMain.c.

409{
411 (*ExecutorFinish_hook) (queryDesc);
412 else
413 standard_ExecutorFinish(queryDesc);
414}
ExecutorFinish_hook_type ExecutorFinish_hook
Definition execMain.c:72
void standard_ExecutorFinish(QueryDesc *queryDesc)
Definition execMain.c:417

References ExecutorFinish_hook, and standard_ExecutorFinish().

Referenced by _SPI_pquery(), EndCopyTo(), ExecCreateTableAs(), execute_sql_string(), ExplainOnePlan(), ParallelQueryMain(), PersistHoldablePortal(), PortalCleanup(), postquel_end(), ProcessQuery(), and refresh_matview_datafill().

◆ ExecutorRewind()

void ExecutorRewind ( QueryDesc queryDesc)

Definition at line 538 of file execMain.c.

539{
540 EState *estate;
541 MemoryContext oldcontext;
542
543 /* sanity checks */
544 Assert(queryDesc != NULL);
545
546 estate = queryDesc->estate;
547
548 Assert(estate != NULL);
549
550 /* It's probably not sensible to rescan updating queries */
551 Assert(queryDesc->operation == CMD_SELECT);
552
553 /*
554 * Switch into per-query memory context
555 */
556 oldcontext = MemoryContextSwitchTo(estate->es_query_cxt);
557
558 /*
559 * rescan plan
560 */
561 ExecReScan(queryDesc->planstate);
562
563 MemoryContextSwitchTo(oldcontext);
564}
void ExecReScan(PlanState *node)
Definition execAmi.c:78
CmdType operation
Definition execdesc.h:36

References Assert, CMD_SELECT, EState::es_query_cxt, QueryDesc::estate, ExecReScan(), fb(), MemoryContextSwitchTo(), QueryDesc::operation, and QueryDesc::planstate.

Referenced by DoPortalRewind(), and PersistHoldablePortal().

◆ ExecutorRun()

void ExecutorRun ( QueryDesc queryDesc,
ScanDirection  direction,
uint64  count 
)

Definition at line 299 of file execMain.c.

301{
303 (*ExecutorRun_hook) (queryDesc, direction, count);
304 else
305 standard_ExecutorRun(queryDesc, direction, count);
306}
ExecutorRun_hook_type ExecutorRun_hook
Definition execMain.c:71
void standard_ExecutorRun(QueryDesc *queryDesc, ScanDirection direction, uint64 count)
Definition execMain.c:309

References ExecutorRun_hook, and standard_ExecutorRun().

Referenced by _SPI_pquery(), DoCopyTo(), ExecCreateTableAs(), execute_sql_string(), ExplainOnePlan(), ParallelQueryMain(), PersistHoldablePortal(), PortalRunSelect(), postquel_getnext(), ProcessQuery(), and refresh_matview_datafill().

◆ ExecutorStart()

void ExecutorStart ( QueryDesc queryDesc,
int  eflags 
)

Definition at line 124 of file execMain.c.

125{
126 /*
127 * In some cases (e.g. an EXECUTE statement or an execute message with the
128 * extended query protocol) the query_id won't be reported, so do it now.
129 *
130 * Note that it's harmless to report the query_id multiple times, as the
131 * call will be ignored if the top level query_id has already been
132 * reported.
133 */
134 pgstat_report_query_id(queryDesc->plannedstmt->queryId, false);
135
137 (*ExecutorStart_hook) (queryDesc, eflags);
138 else
139 standard_ExecutorStart(queryDesc, eflags);
140}
void pgstat_report_query_id(int64 query_id, bool force)
ExecutorStart_hook_type ExecutorStart_hook
Definition execMain.c:70
void standard_ExecutorStart(QueryDesc *queryDesc, int eflags)
Definition execMain.c:143
int64 queryId
Definition plannodes.h:69

References ExecutorStart_hook, pgstat_report_query_id(), QueryDesc::plannedstmt, PlannedStmt::queryId, and standard_ExecutorStart().

Referenced by _SPI_pquery(), BeginCopyTo(), ExecCreateTableAs(), execute_sql_string(), ExplainOnePlan(), ParallelQueryMain(), PortalStart(), postquel_start(), ProcessQuery(), and refresh_matview_datafill().

◆ ExecWithCheckOptions()

void ExecWithCheckOptions ( WCOKind  kind,
ResultRelInfo resultRelInfo,
TupleTableSlot slot,
EState estate 
)

Definition at line 2247 of file execMain.c.

2249{
2250 Relation rel = resultRelInfo->ri_RelationDesc;
2251 TupleDesc tupdesc = RelationGetDescr(rel);
2252 ExprContext *econtext;
2253 ListCell *l1,
2254 *l2;
2255
2256 /*
2257 * We will use the EState's per-tuple context for evaluating constraint
2258 * expressions (creating it if it's not already there).
2259 */
2260 econtext = GetPerTupleExprContext(estate);
2261
2262 /* Arrange for econtext's scan tuple to be the tuple under test */
2263 econtext->ecxt_scantuple = slot;
2264
2265 /* Check each of the constraints */
2266 forboth(l1, resultRelInfo->ri_WithCheckOptions,
2267 l2, resultRelInfo->ri_WithCheckOptionExprs)
2268 {
2270 ExprState *wcoExpr = (ExprState *) lfirst(l2);
2271
2272 /*
2273 * Skip any WCOs which are not the kind we are looking for at this
2274 * time.
2275 */
2276 if (wco->kind != kind)
2277 continue;
2278
2279 /*
2280 * WITH CHECK OPTION checks are intended to ensure that the new tuple
2281 * is visible (in the case of a view) or that it passes the
2282 * 'with-check' policy (in the case of row security). If the qual
2283 * evaluates to NULL or FALSE, then the new tuple won't be included in
2284 * the view or doesn't pass the 'with-check' policy for the table.
2285 */
2286 if (!ExecQual(wcoExpr, econtext))
2287 {
2288 char *val_desc;
2290
2291 switch (wco->kind)
2292 {
2293 /*
2294 * For WITH CHECK OPTIONs coming from views, we might be
2295 * able to provide the details on the row, depending on
2296 * the permissions on the relation (that is, if the user
2297 * could view it directly anyway). For RLS violations, we
2298 * don't include the data since we don't know if the user
2299 * should be able to view the tuple as that depends on the
2300 * USING policy.
2301 */
2302 case WCO_VIEW_CHECK:
2303 /* See the comment in ExecConstraints(). */
2304 if (resultRelInfo->ri_RootResultRelInfo)
2305 {
2306 ResultRelInfo *rootrel = resultRelInfo->ri_RootResultRelInfo;
2308 AttrMap *map;
2309
2310 tupdesc = RelationGetDescr(rootrel->ri_RelationDesc);
2311 /* a reverse map */
2313 tupdesc,
2314 false);
2315
2316 /*
2317 * Partition-specific slot's tupdesc can't be changed,
2318 * so allocate a new one.
2319 */
2320 if (map != NULL)
2321 slot = execute_attr_map_slot(map, slot,
2322 MakeTupleTableSlot(tupdesc, &TTSOpsVirtual, 0));
2323
2325 ExecGetUpdatedCols(rootrel, estate));
2326 rel = rootrel->ri_RelationDesc;
2327 }
2328 else
2329 modifiedCols = bms_union(ExecGetInsertedCols(resultRelInfo, estate),
2330 ExecGetUpdatedCols(resultRelInfo, estate));
2332 slot,
2333 tupdesc,
2335 64);
2336
2337 ereport(ERROR,
2339 errmsg("new row violates check option for view \"%s\"",
2340 wco->relname),
2341 val_desc ? errdetail("Failing row contains %s.",
2342 val_desc) : 0));
2343 break;
2346 if (wco->polname != NULL)
2347 ereport(ERROR,
2349 errmsg("new row violates row-level security policy \"%s\" for table \"%s\"",
2350 wco->polname, wco->relname)));
2351 else
2352 ereport(ERROR,
2354 errmsg("new row violates row-level security policy for table \"%s\"",
2355 wco->relname)));
2356 break;
2359 if (wco->polname != NULL)
2360 ereport(ERROR,
2362 errmsg("target row violates row-level security policy \"%s\" (USING expression) for table \"%s\"",
2363 wco->polname, wco->relname)));
2364 else
2365 ereport(ERROR,
2367 errmsg("target row violates row-level security policy (USING expression) for table \"%s\"",
2368 wco->relname)));
2369 break;
2371 if (wco->polname != NULL)
2372 ereport(ERROR,
2374 errmsg("new row violates row-level security policy \"%s\" (USING expression) for table \"%s\"",
2375 wco->polname, wco->relname)));
2376 else
2377 ereport(ERROR,
2379 errmsg("new row violates row-level security policy (USING expression) for table \"%s\"",
2380 wco->relname)));
2381 break;
2382 default:
2383 elog(ERROR, "unrecognized WCO kind: %u", wco->kind);
2384 break;
2385 }
2386 }
2387 }
2388}
static bool ExecQual(ExprState *state, ExprContext *econtext)
Definition executor.h:522
@ WCO_RLS_MERGE_UPDATE_CHECK
@ WCO_RLS_CONFLICT_CHECK
@ WCO_RLS_INSERT_CHECK
@ WCO_VIEW_CHECK
@ WCO_RLS_UPDATE_CHECK
@ WCO_RLS_MERGE_DELETE_CHECK
#define forboth(cell1, list1, cell2, list2)
Definition pg_list.h:518
List * ri_WithCheckOptions
Definition execnodes.h:561
List * ri_WithCheckOptionExprs
Definition execnodes.h:564

References bms_union(), build_attrmap_by_name_if_req(), ExprContext::ecxt_scantuple, elog, ereport, errcode(), errdetail(), errmsg, ERROR, ExecBuildSlotValueDescription(), ExecGetInsertedCols(), ExecGetUpdatedCols(), ExecQual(), execute_attr_map_slot(), fb(), forboth, GetPerTupleExprContext, lfirst, MakeTupleTableSlot(), RelationGetDescr, RelationGetRelid, ResultRelInfo::ri_RelationDesc, ResultRelInfo::ri_RootResultRelInfo, ResultRelInfo::ri_WithCheckOptionExprs, ResultRelInfo::ri_WithCheckOptions, TTSOpsVirtual, WCO_RLS_CONFLICT_CHECK, WCO_RLS_INSERT_CHECK, WCO_RLS_MERGE_DELETE_CHECK, WCO_RLS_MERGE_UPDATE_CHECK, WCO_RLS_UPDATE_CHECK, and WCO_VIEW_CHECK.

Referenced by ExecBatchInsert(), ExecInsert(), ExecMergeMatched(), ExecOnConflictSelect(), ExecOnConflictUpdate(), ExecUpdateAct(), and ExecUpdateEpilogue().

◆ InitPlan()

static void InitPlan ( QueryDesc queryDesc,
int  eflags 
)
static

Definition at line 838 of file execMain.c.

839{
840 CmdType operation = queryDesc->operation;
841 PlannedStmt *plannedstmt = queryDesc->plannedstmt;
842 Plan *plan = plannedstmt->planTree;
843 List *rangeTable = plannedstmt->rtable;
844 EState *estate = queryDesc->estate;
845 PlanState *planstate;
847 ListCell *l;
848 int i;
849
850 /*
851 * Do permissions checks
852 */
853 ExecCheckPermissions(rangeTable, plannedstmt->permInfos, true);
854
855 /*
856 * initialize the node's execution state
857 */
858 ExecInitRangeTable(estate, rangeTable, plannedstmt->permInfos,
859 bms_copy(plannedstmt->unprunableRelids));
860
861 estate->es_plannedstmt = plannedstmt;
862 estate->es_part_prune_infos = plannedstmt->partPruneInfos;
863
864 /*
865 * Perform runtime "initial" pruning to identify which child subplans,
866 * corresponding to the children of plan nodes that contain
867 * PartitionPruneInfo such as Append, will not be executed. The results,
868 * which are bitmapsets of indexes of the child subplans that will be
869 * executed, are saved in es_part_prune_results. These results correspond
870 * to each PartitionPruneInfo entry, and the es_part_prune_results list is
871 * parallel to es_part_prune_infos.
872 */
873 ExecDoInitialPruning(estate);
874
875 /*
876 * Next, build the ExecRowMark array from the PlanRowMark(s), if any.
877 */
878 if (plannedstmt->rowMarks)
879 {
880 estate->es_rowmarks = (ExecRowMark **)
882 foreach(l, plannedstmt->rowMarks)
883 {
884 PlanRowMark *rc = (PlanRowMark *) lfirst(l);
885 RangeTblEntry *rte = exec_rt_fetch(rc->rti, estate);
886 Oid relid;
887 Relation relation;
889
890 /* ignore "parent" rowmarks; they are irrelevant at runtime */
891 if (rc->isParent)
892 continue;
893
894 /*
895 * Also ignore rowmarks belonging to child tables that have been
896 * pruned in ExecDoInitialPruning().
897 */
898 if (rte->rtekind == RTE_RELATION &&
899 !bms_is_member(rc->rti, estate->es_unpruned_relids))
900 continue;
901
902 /* get relation's OID (will produce InvalidOid if subquery) */
903 relid = rte->relid;
904
905 /* open relation, if we need to access it for this mark type */
906 switch (rc->markType)
907 {
910 case ROW_MARK_SHARE:
913 relation = ExecGetRangeTableRelation(estate, rc->rti, false);
914 break;
915 case ROW_MARK_COPY:
916 /* no physical table access is required */
917 relation = NULL;
918 break;
919 default:
920 elog(ERROR, "unrecognized markType: %d", rc->markType);
921 relation = NULL; /* keep compiler quiet */
922 break;
923 }
924
925 /* Check that relation is a legal target for marking */
926 if (relation)
927 CheckValidRowMarkRel(relation, rc->markType);
928
930 erm->relation = relation;
931 erm->relid = relid;
932 erm->rti = rc->rti;
933 erm->prti = rc->prti;
934 erm->rowmarkId = rc->rowmarkId;
935 erm->markType = rc->markType;
936 erm->strength = rc->strength;
937 erm->waitPolicy = rc->waitPolicy;
938 erm->ermActive = false;
939 ItemPointerSetInvalid(&(erm->curCtid));
940 erm->ermExtra = NULL;
941
942 Assert(erm->rti > 0 && erm->rti <= estate->es_range_table_size &&
943 estate->es_rowmarks[erm->rti - 1] == NULL);
944
945 estate->es_rowmarks[erm->rti - 1] = erm;
946 }
947 }
948
949 /*
950 * Initialize the executor's tuple table to empty.
951 */
952 estate->es_tupleTable = NIL;
953
954 /* signal that this EState is not used for EPQ */
955 estate->es_epq_active = NULL;
956
957 /*
958 * Initialize private state information for each SubPlan. We must do this
959 * before running ExecInitNode on the main query tree, since
960 * ExecInitSubPlan expects to be able to find these entries.
961 */
962 Assert(estate->es_subplanstates == NIL);
963 i = 1; /* subplan indices count from 1 */
964 foreach(l, plannedstmt->subplans)
965 {
966 Plan *subplan = (Plan *) lfirst(l);
968 int sp_eflags;
969
970 /*
971 * A subplan will never need to do BACKWARD scan nor MARK/RESTORE. If
972 * it is a parameterless subplan (not initplan), we suggest that it be
973 * prepared to handle REWIND efficiently; otherwise there is no need.
974 */
975 sp_eflags = eflags
977 if (bms_is_member(i, plannedstmt->rewindPlanIDs))
979
980 subplanstate = ExecInitNode(subplan, estate, sp_eflags);
981
982 estate->es_subplanstates = lappend(estate->es_subplanstates,
984
985 i++;
986 }
987
988 /*
989 * Initialize the private state information for all the nodes in the query
990 * tree. This opens files, allocates storage and leaves us ready to start
991 * processing tuples.
992 */
993 planstate = ExecInitNode(plan, estate, eflags);
994
995 /*
996 * Get the tuple descriptor describing the type of tuples to return.
997 */
998 tupType = ExecGetResultType(planstate);
999
1000 /*
1001 * Initialize the junk filter if needed. SELECT queries need a filter if
1002 * there are any junk attrs in the top-level tlist.
1003 */
1004 if (operation == CMD_SELECT)
1005 {
1006 bool junk_filter_needed = false;
1007 ListCell *tlist;
1008
1009 foreach(tlist, plan->targetlist)
1010 {
1011 TargetEntry *tle = (TargetEntry *) lfirst(tlist);
1012
1013 if (tle->resjunk)
1014 {
1015 junk_filter_needed = true;
1016 break;
1017 }
1018 }
1019
1021 {
1022 JunkFilter *j;
1023 TupleTableSlot *slot;
1024
1025 slot = ExecInitExtraTupleSlot(estate, NULL, &TTSOpsVirtual);
1026 j = ExecInitJunkFilter(planstate->plan->targetlist,
1027 slot);
1028 estate->es_junkFilter = j;
1029
1030 /* Want to return the cleaned tuple type */
1032 }
1033 }
1034
1035 queryDesc->tupDesc = tupType;
1036 queryDesc->planstate = planstate;
1037}
Bitmapset * bms_copy(const Bitmapset *a)
Definition bitmapset.c:122
JunkFilter * ExecInitJunkFilter(List *targetList, TupleTableSlot *slot)
Definition execJunk.c:60
static void CheckValidRowMarkRel(Relation rel, RowMarkType markType)
Definition execMain.c:1190
bool ExecCheckPermissions(List *rangeTable, List *rteperminfos, bool ereport_on_violation)
Definition execMain.c:584
void ExecDoInitialPruning(EState *estate)
TupleTableSlot * ExecInitExtraTupleSlot(EState *estate, TupleDesc tupledesc, const TupleTableSlotOps *tts_ops)
TupleDesc ExecGetResultType(PlanState *planstate)
Definition execUtils.c:500
Relation ExecGetRangeTableRelation(EState *estate, Index rti, bool isResultRel)
Definition execUtils.c:830
void ExecInitRangeTable(EState *estate, List *rangeTable, List *permInfos, Bitmapset *unpruned_relids)
Definition execUtils.c:778
#define EXEC_FLAG_REWIND
Definition executor.h:69
static RangeTblEntry * exec_rt_fetch(Index rti, EState *estate)
Definition executor.h:701
#define EXEC_FLAG_MARK
Definition executor.h:71
#define palloc_object(type)
Definition fe_memutils.h:74
int j
Definition isn.c:78
static void ItemPointerSetInvalid(ItemPointerData *pointer)
Definition itemptr.h:184
CmdType
Definition nodes.h:273
#define plan(x)
Definition pg_regress.c:161
@ ROW_MARK_SHARE
Definition plannodes.h:1555
@ ROW_MARK_EXCLUSIVE
Definition plannodes.h:1553
@ ROW_MARK_NOKEYEXCLUSIVE
Definition plannodes.h:1554
@ ROW_MARK_KEYSHARE
Definition plannodes.h:1556
struct EPQState * es_epq_active
Definition execnodes.h:754
TupleDesc jf_cleanTupType
Definition execnodes.h:430
LockClauseStrength strength
Definition plannodes.h:1617
RowMarkType markType
Definition plannodes.h:1613
LockWaitPolicy waitPolicy
Definition plannodes.h:1619
Index rowmarkId
Definition plannodes.h:1611
Plan * plan
Definition execnodes.h:1177
List * targetlist
Definition plannodes.h:233
struct Plan * planTree
Definition plannodes.h:99
List * rowMarks
Definition plannodes.h:139
Bitmapset * rewindPlanIDs
Definition plannodes.h:136
Bitmapset * unprunableRelids
Definition plannodes.h:113
List * rtable
Definition plannodes.h:107
List * partPruneInfos
Definition plannodes.h:104
TupleDesc tupDesc
Definition execdesc.h:47

References Assert, bms_copy(), bms_is_member(), CheckValidRowMarkRel(), CMD_SELECT, elog, ERROR, EState::es_epq_active, EState::es_junkFilter, EState::es_part_prune_infos, EState::es_plannedstmt, EState::es_range_table_size, EState::es_rowmarks, EState::es_subplanstates, EState::es_tupleTable, EState::es_unpruned_relids, QueryDesc::estate, EXEC_FLAG_BACKWARD, EXEC_FLAG_MARK, EXEC_FLAG_REWIND, exec_rt_fetch(), ExecCheckPermissions(), ExecDoInitialPruning(), ExecGetRangeTableRelation(), ExecGetResultType(), ExecInitExtraTupleSlot(), ExecInitJunkFilter(), ExecInitNode(), ExecInitRangeTable(), fb(), i, PlanRowMark::isParent, ItemPointerSetInvalid(), j, JunkFilter::jf_cleanTupType, lappend(), lfirst, PlanRowMark::markType, NIL, QueryDesc::operation, palloc0_array, palloc_object, PlannedStmt::partPruneInfos, PlannedStmt::permInfos, PlanState::plan, plan, QueryDesc::plannedstmt, QueryDesc::planstate, PlannedStmt::planTree, PlanRowMark::prti, ExecRowMark::relid, PlannedStmt::rewindPlanIDs, ROW_MARK_COPY, ROW_MARK_EXCLUSIVE, ROW_MARK_KEYSHARE, ROW_MARK_NOKEYEXCLUSIVE, ROW_MARK_REFERENCE, ROW_MARK_SHARE, PlanRowMark::rowmarkId, PlannedStmt::rowMarks, PlannedStmt::rtable, RTE_RELATION, PlanRowMark::rti, PlanRowMark::strength, PlannedStmt::subplans, Plan::targetlist, TTSOpsVirtual, QueryDesc::tupDesc, PlannedStmt::unprunableRelids, and PlanRowMark::waitPolicy.

Referenced by standard_ExecutorStart().

◆ InitResultRelInfo()

void InitResultRelInfo ( ResultRelInfo resultRelInfo,
Relation  resultRelationDesc,
Index  resultRelationIndex,
ResultRelInfo partition_root_rri,
int  instrument_options 
)

Definition at line 1262 of file execMain.c.

1267{
1268 MemSet(resultRelInfo, 0, sizeof(ResultRelInfo));
1269 resultRelInfo->type = T_ResultRelInfo;
1270 resultRelInfo->ri_RangeTableIndex = resultRelationIndex;
1271 resultRelInfo->ri_RelationDesc = resultRelationDesc;
1272 resultRelInfo->ri_NumIndices = 0;
1273 resultRelInfo->ri_IndexRelationDescs = NULL;
1274 resultRelInfo->ri_IndexRelationInfo = NULL;
1275 resultRelInfo->ri_needLockTagTuple =
1277 /* make a copy so as not to depend on relcache info not changing... */
1278 resultRelInfo->ri_TrigDesc = CopyTriggerDesc(resultRelationDesc->trigdesc);
1279 if (resultRelInfo->ri_TrigDesc)
1280 {
1281 int n = resultRelInfo->ri_TrigDesc->numtriggers;
1282
1283 resultRelInfo->ri_TrigFunctions = (FmgrInfo *)
1285 resultRelInfo->ri_TrigWhenExprs = (ExprState **)
1287 if (instrument_options)
1288 resultRelInfo->ri_TrigInstrument = InstrAlloc(n, instrument_options, false);
1289 }
1290 else
1291 {
1292 resultRelInfo->ri_TrigFunctions = NULL;
1293 resultRelInfo->ri_TrigWhenExprs = NULL;
1294 resultRelInfo->ri_TrigInstrument = NULL;
1295 }
1296 if (resultRelationDesc->rd_rel->relkind == RELKIND_FOREIGN_TABLE)
1298 else
1299 resultRelInfo->ri_FdwRoutine = NULL;
1300
1301 /* The following fields are set later if needed */
1302 resultRelInfo->ri_RowIdAttNo = 0;
1303 resultRelInfo->ri_extraUpdatedCols = NULL;
1304 resultRelInfo->ri_projectNew = NULL;
1305 resultRelInfo->ri_newTupleSlot = NULL;
1306 resultRelInfo->ri_oldTupleSlot = NULL;
1307 resultRelInfo->ri_projectNewInfoValid = false;
1308 resultRelInfo->ri_FdwState = NULL;
1309 resultRelInfo->ri_usesFdwDirectModify = false;
1310 resultRelInfo->ri_CheckConstraintExprs = NULL;
1312 resultRelInfo->ri_GeneratedExprsI = NULL;
1313 resultRelInfo->ri_GeneratedExprsU = NULL;
1314 resultRelInfo->ri_projectReturning = NULL;
1315 resultRelInfo->ri_onConflictArbiterIndexes = NIL;
1316 resultRelInfo->ri_onConflict = NULL;
1317 resultRelInfo->ri_ReturningSlot = NULL;
1318 resultRelInfo->ri_TrigOldSlot = NULL;
1319 resultRelInfo->ri_TrigNewSlot = NULL;
1320 resultRelInfo->ri_AllNullSlot = NULL;
1321 resultRelInfo->ri_MergeActions[MERGE_WHEN_MATCHED] = NIL;
1324 resultRelInfo->ri_MergeJoinCondition = NULL;
1325
1326 /*
1327 * Only ExecInitPartitionInfo() and ExecInitPartitionDispatchInfo() pass
1328 * non-NULL partition_root_rri. For child relations that are part of the
1329 * initial query rather than being dynamically added by tuple routing,
1330 * this field is filled in ExecInitModifyTable().
1331 */
1333 /* Set by ExecGetRootToChildMap */
1334 resultRelInfo->ri_RootToChildMap = NULL;
1335 resultRelInfo->ri_RootToChildMapValid = false;
1336 /* Set by ExecInitRoutingInfo */
1337 resultRelInfo->ri_PartitionTupleSlot = NULL;
1338 resultRelInfo->ri_ChildToRootMap = NULL;
1339 resultRelInfo->ri_ChildToRootMapValid = false;
1340 resultRelInfo->ri_CopyMultiInsertBuffer = NULL;
1341}
#define MemSet(start, val, len)
Definition c.h:1109
Instrumentation * InstrAlloc(int n, int instrument_options, bool async_mode)
Definition instrument.c:31
@ MERGE_WHEN_NOT_MATCHED_BY_TARGET
Definition primnodes.h:2025
@ MERGE_WHEN_NOT_MATCHED_BY_SOURCE
Definition primnodes.h:2024
@ MERGE_WHEN_MATCHED
Definition primnodes.h:2023
TupleConversionMap * ri_RootToChildMap
Definition execnodes.h:618
OnConflictActionState * ri_onConflict
Definition execnodes.h:595
TupleTableSlot * ri_PartitionTupleSlot
Definition execnodes.h:631
bool ri_projectNewInfoValid
Definition execnodes.h:521
List * ri_onConflictArbiterIndexes
Definition execnodes.h:592
Instrumentation * ri_TrigInstrument
Definition execnodes.h:536
ExprState * ri_MergeJoinCondition
Definition execnodes.h:601
RelationPtr ri_IndexRelationDescs
Definition execnodes.h:498
TupleTableSlot * ri_ReturningSlot
Definition execnodes.h:539
TupleTableSlot * ri_oldTupleSlot
Definition execnodes.h:519
bool ri_RootToChildMapValid
Definition execnodes.h:619
struct CopyMultiInsertBuffer * ri_CopyMultiInsertBuffer
Definition execnodes.h:634
TriggerDesc * ri_TrigDesc
Definition execnodes.h:527
TupleTableSlot * ri_AllNullSlot
Definition execnodes.h:542
Bitmapset * ri_extraUpdatedCols
Definition execnodes.h:510
ExprState ** ri_GeneratedExprsI
Definition execnodes.h:578
TupleConversionMap * ri_ChildToRootMap
Definition execnodes.h:612
void * ri_FdwState
Definition execnodes.h:548
bool ri_ChildToRootMapValid
Definition execnodes.h:613
List * ri_MergeActions[NUM_MERGE_MATCH_KINDS]
Definition execnodes.h:598
TupleTableSlot * ri_newTupleSlot
Definition execnodes.h:517
ProjectionInfo * ri_projectNew
Definition execnodes.h:515
NodeTag type
Definition execnodes.h:486
ProjectionInfo * ri_projectReturning
Definition execnodes.h:589
ExprState ** ri_GeneratedExprsU
Definition execnodes.h:579
ExprState ** ri_TrigWhenExprs
Definition execnodes.h:533
FmgrInfo * ri_TrigFunctions
Definition execnodes.h:530
bool ri_usesFdwDirectModify
Definition execnodes.h:551
AttrNumber ri_RowIdAttNo
Definition execnodes.h:507
IndexInfo ** ri_IndexRelationInfo
Definition execnodes.h:501
TupleTableSlot * ri_TrigNewSlot
Definition execnodes.h:541
TupleTableSlot * ri_TrigOldSlot
Definition execnodes.h:540
int numtriggers
Definition reltrigger.h:50
TriggerDesc * CopyTriggerDesc(TriggerDesc *trigdesc)
Definition trigger.c:2092

References CopyTriggerDesc(), fb(), GetFdwRoutineForRelation(), InstrAlloc(), IsInplaceUpdateRelation(), MemSet, MERGE_WHEN_MATCHED, MERGE_WHEN_NOT_MATCHED_BY_SOURCE, MERGE_WHEN_NOT_MATCHED_BY_TARGET, NIL, TriggerDesc::numtriggers, palloc0_array, ResultRelInfo::ri_AllNullSlot, ResultRelInfo::ri_CheckConstraintExprs, ResultRelInfo::ri_ChildToRootMap, ResultRelInfo::ri_ChildToRootMapValid, ResultRelInfo::ri_CopyMultiInsertBuffer, ResultRelInfo::ri_extraUpdatedCols, ResultRelInfo::ri_FdwRoutine, ResultRelInfo::ri_FdwState, ResultRelInfo::ri_GeneratedExprsI, ResultRelInfo::ri_GeneratedExprsU, ResultRelInfo::ri_GenVirtualNotNullConstraintExprs, ResultRelInfo::ri_IndexRelationDescs, ResultRelInfo::ri_IndexRelationInfo, ResultRelInfo::ri_MergeActions, ResultRelInfo::ri_MergeJoinCondition, ResultRelInfo::ri_needLockTagTuple, ResultRelInfo::ri_newTupleSlot, ResultRelInfo::ri_NumIndices, ResultRelInfo::ri_oldTupleSlot, ResultRelInfo::ri_onConflict, ResultRelInfo::ri_onConflictArbiterIndexes, ResultRelInfo::ri_PartitionTupleSlot, ResultRelInfo::ri_projectNew, ResultRelInfo::ri_projectNewInfoValid, ResultRelInfo::ri_projectReturning, ResultRelInfo::ri_RangeTableIndex, ResultRelInfo::ri_RelationDesc, ResultRelInfo::ri_ReturningSlot, ResultRelInfo::ri_RootResultRelInfo, ResultRelInfo::ri_RootToChildMap, ResultRelInfo::ri_RootToChildMapValid, ResultRelInfo::ri_RowIdAttNo, ResultRelInfo::ri_TrigDesc, ResultRelInfo::ri_TrigFunctions, ResultRelInfo::ri_TrigInstrument, ResultRelInfo::ri_TrigNewSlot, ResultRelInfo::ri_TrigOldSlot, ResultRelInfo::ri_TrigWhenExprs, ResultRelInfo::ri_usesFdwDirectModify, and ResultRelInfo::type.

Referenced by ATRewriteTable(), create_edata_for_relation(), ExecGetAncestorResultRels(), ExecGetTriggerResultRel(), ExecInitPartitionDispatchInfo(), ExecInitPartitionInfo(), ExecInitResultRelation(), and ExecuteTruncateGuts().

◆ ReportNotNullViolationError()

static void ReportNotNullViolationError ( ResultRelInfo resultRelInfo,
TupleTableSlot slot,
EState estate,
int  attnum 
)
static

Definition at line 2178 of file execMain.c.

2180{
2182 char *val_desc;
2183 Relation rel = resultRelInfo->ri_RelationDesc;
2184 Relation orig_rel = rel;
2185 TupleDesc tupdesc = RelationGetDescr(rel);
2187 Form_pg_attribute att = TupleDescAttr(tupdesc, attnum - 1);
2188
2189 Assert(attnum > 0);
2190
2191 /*
2192 * If the tuple has been routed, it's been converted to the partition's
2193 * rowtype, which might differ from the root table's. We must convert it
2194 * back to the root table's rowtype so that val_desc shown error message
2195 * matches the input tuple.
2196 */
2197 if (resultRelInfo->ri_RootResultRelInfo)
2198 {
2199 ResultRelInfo *rootrel = resultRelInfo->ri_RootResultRelInfo;
2200 AttrMap *map;
2201
2202 tupdesc = RelationGetDescr(rootrel->ri_RelationDesc);
2203 /* a reverse map */
2205 tupdesc,
2206 false);
2207
2208 /*
2209 * Partition-specific slot's tupdesc can't be changed, so allocate a
2210 * new one.
2211 */
2212 if (map != NULL)
2213 slot = execute_attr_map_slot(map, slot,
2214 MakeTupleTableSlot(tupdesc, &TTSOpsVirtual, 0));
2216 ExecGetUpdatedCols(rootrel, estate));
2217 rel = rootrel->ri_RelationDesc;
2218 }
2219 else
2220 modifiedCols = bms_union(ExecGetInsertedCols(resultRelInfo, estate),
2221 ExecGetUpdatedCols(resultRelInfo, estate));
2222
2224 slot,
2225 tupdesc,
2227 64);
2228 ereport(ERROR,
2230 errmsg("null value in column \"%s\" of relation \"%s\" violates not-null constraint",
2231 NameStr(att->attname),
2233 val_desc ? errdetail("Failing row contains %s.", val_desc) : 0,
2235}
int errtablecol(Relation rel, int attnum)
Definition relcache.c:6079

References Assert, attnum, bms_union(), build_attrmap_by_name_if_req(), ereport, errcode(), errdetail(), errmsg, ERROR, errtablecol(), ExecBuildSlotValueDescription(), ExecGetInsertedCols(), ExecGetUpdatedCols(), execute_attr_map_slot(), fb(), MakeTupleTableSlot(), NameStr, RelationGetDescr, RelationGetRelationName, RelationGetRelid, ResultRelInfo::ri_RelationDesc, ResultRelInfo::ri_RootResultRelInfo, TTSOpsVirtual, and TupleDescAttr().

Referenced by ExecConstraints().

◆ standard_ExecutorEnd()

void standard_ExecutorEnd ( QueryDesc queryDesc)

Definition at line 477 of file execMain.c.

478{
479 EState *estate;
480 MemoryContext oldcontext;
481
482 /* sanity checks */
483 Assert(queryDesc != NULL);
484
485 estate = queryDesc->estate;
486
487 Assert(estate != NULL);
488
489 if (estate->es_parallel_workers_to_launch > 0)
492
493 /*
494 * Check that ExecutorFinish was called, unless in EXPLAIN-only mode. This
495 * Assert is needed because ExecutorFinish is new as of 9.1, and callers
496 * might forget to call it.
497 */
498 Assert(estate->es_finished ||
500
501 /*
502 * Switch into per-query memory context to run ExecEndPlan
503 */
504 oldcontext = MemoryContextSwitchTo(estate->es_query_cxt);
505
506 ExecEndPlan(queryDesc->planstate, estate);
507
508 /* do away with our snapshots */
511
512 /*
513 * Must switch out of context before destroying it
514 */
515 MemoryContextSwitchTo(oldcontext);
516
517 /*
518 * Release EState and per-query memory context. This should release
519 * everything the executor has allocated.
520 */
521 FreeExecutorState(estate);
522
523 /* Reset queryDesc fields that no longer point to anything */
524 queryDesc->tupDesc = NULL;
525 queryDesc->estate = NULL;
526 queryDesc->planstate = NULL;
527 queryDesc->totaltime = NULL;
528}
static void ExecEndPlan(PlanState *planstate, EState *estate)
Definition execMain.c:1555
#define EXEC_FLAG_EXPLAIN_ONLY
Definition executor.h:67
int64 PgStat_Counter
Definition pgstat.h:70
void pgstat_update_parallel_workers_stats(PgStat_Counter workers_to_launch, PgStat_Counter workers_launched)
void UnregisterSnapshot(Snapshot snapshot)
Definition snapmgr.c:866
int es_parallel_workers_to_launch
Definition execnodes.h:758
bool es_finished
Definition execnodes.h:733
int es_parallel_workers_launched
Definition execnodes.h:760
struct Instrumentation * totaltime
Definition execdesc.h:55

References Assert, EState::es_crosscheck_snapshot, EState::es_finished, EState::es_parallel_workers_launched, EState::es_parallel_workers_to_launch, EState::es_query_cxt, EState::es_snapshot, EState::es_top_eflags, QueryDesc::estate, EXEC_FLAG_EXPLAIN_ONLY, ExecEndPlan(), fb(), FreeExecutorState(), MemoryContextSwitchTo(), pgstat_update_parallel_workers_stats(), QueryDesc::planstate, QueryDesc::totaltime, QueryDesc::tupDesc, and UnregisterSnapshot().

Referenced by ExecutorEnd(), explain_ExecutorEnd(), and pgss_ExecutorEnd().

◆ standard_ExecutorFinish()

void standard_ExecutorFinish ( QueryDesc queryDesc)

Definition at line 417 of file execMain.c.

418{
419 EState *estate;
420 MemoryContext oldcontext;
421
422 /* sanity checks */
423 Assert(queryDesc != NULL);
424
425 estate = queryDesc->estate;
426
427 Assert(estate != NULL);
429
430 /* This should be run once and only once per Executor instance */
431 Assert(!estate->es_finished);
432
433 /* Switch into per-query memory context */
434 oldcontext = MemoryContextSwitchTo(estate->es_query_cxt);
435
436 /* Allow instrumentation of Executor overall runtime */
437 if (queryDesc->totaltime)
438 InstrStartNode(queryDesc->totaltime);
439
440 /* Run ModifyTable nodes to completion */
441 ExecPostprocessPlan(estate);
442
443 /* Execute queued AFTER triggers, unless told not to */
444 if (!(estate->es_top_eflags & EXEC_FLAG_SKIP_TRIGGERS))
445 AfterTriggerEndQuery(estate);
446
447 if (queryDesc->totaltime)
448 InstrStopNode(queryDesc->totaltime, 0);
449
450 MemoryContextSwitchTo(oldcontext);
451
452 estate->es_finished = true;
453}
static void ExecPostprocessPlan(EState *estate)
Definition execMain.c:1509
#define EXEC_FLAG_SKIP_TRIGGERS
Definition executor.h:72
void InstrStartNode(Instrumentation *instr)
Definition instrument.c:68
void InstrStopNode(Instrumentation *instr, double nTuples)
Definition instrument.c:88
void AfterTriggerEndQuery(EState *estate)
Definition trigger.c:5137

References AfterTriggerEndQuery(), Assert, EState::es_finished, EState::es_query_cxt, EState::es_top_eflags, QueryDesc::estate, EXEC_FLAG_EXPLAIN_ONLY, EXEC_FLAG_SKIP_TRIGGERS, ExecPostprocessPlan(), fb(), InstrStartNode(), InstrStopNode(), MemoryContextSwitchTo(), and QueryDesc::totaltime.

Referenced by ExecutorFinish(), explain_ExecutorFinish(), and pgss_ExecutorFinish().

◆ standard_ExecutorRun()

void standard_ExecutorRun ( QueryDesc queryDesc,
ScanDirection  direction,
uint64  count 
)

Definition at line 309 of file execMain.c.

311{
312 EState *estate;
313 CmdType operation;
315 bool sendTuples;
316 MemoryContext oldcontext;
317
318 /* sanity checks */
319 Assert(queryDesc != NULL);
320
321 estate = queryDesc->estate;
322
323 Assert(estate != NULL);
325
326 /* caller must ensure the query's snapshot is active */
328
329 /*
330 * Switch into per-query memory context
331 */
332 oldcontext = MemoryContextSwitchTo(estate->es_query_cxt);
333
334 /* Allow instrumentation of Executor overall runtime */
335 if (queryDesc->totaltime)
336 InstrStartNode(queryDesc->totaltime);
337
338 /*
339 * extract information from the query descriptor and the query feature.
340 */
341 operation = queryDesc->operation;
342 dest = queryDesc->dest;
343
344 /*
345 * startup tuple receiver, if we will be emitting tuples
346 */
347 estate->es_processed = 0;
348
349 sendTuples = (operation == CMD_SELECT ||
350 queryDesc->plannedstmt->hasReturning);
351
352 if (sendTuples)
353 dest->rStartup(dest, operation, queryDesc->tupDesc);
354
355 /*
356 * Run plan, unless direction is NoMovement.
357 *
358 * Note: pquery.c selects NoMovement if a prior call already reached
359 * end-of-data in the user-specified fetch direction. This is important
360 * because various parts of the executor can misbehave if called again
361 * after reporting EOF. For example, heapam.c would actually restart a
362 * heapscan and return all its data afresh. There is also some doubt
363 * about whether a parallel plan would operate properly if an additional,
364 * necessarily non-parallel execution request occurs after completing a
365 * parallel execution. (That case should work, but it's untested.)
366 */
367 if (!ScanDirectionIsNoMovement(direction))
368 ExecutePlan(queryDesc,
369 operation,
371 count,
372 direction,
373 dest);
374
375 /*
376 * Update es_total_processed to keep track of the number of tuples
377 * processed across multiple ExecutorRun() calls.
378 */
379 estate->es_total_processed += estate->es_processed;
380
381 /*
382 * shutdown tuple receiver, if we started it
383 */
384 if (sendTuples)
385 dest->rShutdown(dest);
386
387 if (queryDesc->totaltime)
388 InstrStopNode(queryDesc->totaltime, estate->es_processed);
389
390 MemoryContextSwitchTo(oldcontext);
391}
static void ExecutePlan(QueryDesc *queryDesc, CmdType operation, bool sendTuples, uint64 numberTuples, ScanDirection direction, DestReceiver *dest)
Definition execMain.c:1675
#define ScanDirectionIsNoMovement(direction)
Definition sdir.h:57
Snapshot GetActiveSnapshot(void)
Definition snapmgr.c:800
uint64 es_total_processed
Definition execnodes.h:728
bool hasReturning
Definition plannodes.h:78
DestReceiver * dest
Definition execdesc.h:41

References Assert, CMD_SELECT, QueryDesc::dest, EState::es_processed, EState::es_query_cxt, EState::es_snapshot, EState::es_top_eflags, EState::es_total_processed, QueryDesc::estate, EXEC_FLAG_EXPLAIN_ONLY, ExecutePlan(), fb(), GetActiveSnapshot(), PlannedStmt::hasReturning, InstrStartNode(), InstrStopNode(), MemoryContextSwitchTo(), QueryDesc::operation, QueryDesc::plannedstmt, ScanDirectionIsNoMovement, QueryDesc::totaltime, and QueryDesc::tupDesc.

Referenced by ExecutorRun(), explain_ExecutorRun(), and pgss_ExecutorRun().

◆ standard_ExecutorStart()

void standard_ExecutorStart ( QueryDesc queryDesc,
int  eflags 
)

Definition at line 143 of file execMain.c.

144{
145 EState *estate;
146 MemoryContext oldcontext;
147
148 /* sanity checks: queryDesc must not be started already */
149 Assert(queryDesc != NULL);
150 Assert(queryDesc->estate == NULL);
151
152 /* caller must ensure the query's snapshot is active */
153 Assert(GetActiveSnapshot() == queryDesc->snapshot);
154
155 /*
156 * If the transaction is read-only, we need to check if any writes are
157 * planned to non-temporary tables. EXPLAIN is considered read-only.
158 *
159 * Don't allow writes in parallel mode. Supporting UPDATE and DELETE
160 * would require (a) storing the combo CID hash in shared memory, rather
161 * than synchronizing it just once at the start of parallelism, and (b) an
162 * alternative to heap_update()'s reliance on xmax for mutual exclusion.
163 * INSERT may have no such troubles, but we forbid it to simplify the
164 * checks.
165 *
166 * We have lower-level defenses in CommandCounterIncrement and elsewhere
167 * against performing unsafe operations in parallel mode, but this gives a
168 * more user-friendly error message.
169 */
170 if ((XactReadOnly || IsInParallelMode()) &&
171 !(eflags & EXEC_FLAG_EXPLAIN_ONLY))
173
174 /*
175 * Build EState, switch into per-query memory context for startup.
176 */
177 estate = CreateExecutorState();
178 queryDesc->estate = estate;
179
180 oldcontext = MemoryContextSwitchTo(estate->es_query_cxt);
181
182 /*
183 * Fill in external parameters, if any, from queryDesc; and allocate
184 * workspace for internal parameters
185 */
186 estate->es_param_list_info = queryDesc->params;
187
188 if (queryDesc->plannedstmt->paramExecTypes != NIL)
189 {
190 int nParamExec;
191
195 }
196
197 /* We now require all callers to provide sourceText */
198 Assert(queryDesc->sourceText != NULL);
199 estate->es_sourceText = queryDesc->sourceText;
200
201 /*
202 * Fill in the query environment, if any, from queryDesc.
203 */
204 estate->es_queryEnv = queryDesc->queryEnv;
205
206 /*
207 * If non-read-only query, set the command ID to mark output tuples with
208 */
209 switch (queryDesc->operation)
210 {
211 case CMD_SELECT:
212
213 /*
214 * SELECT FOR [KEY] UPDATE/SHARE and modifying CTEs need to mark
215 * tuples
216 */
217 if (queryDesc->plannedstmt->rowMarks != NIL ||
218 queryDesc->plannedstmt->hasModifyingCTE)
219 estate->es_output_cid = GetCurrentCommandId(true);
220
221 /*
222 * A SELECT without modifying CTEs can't possibly queue triggers,
223 * so force skip-triggers mode. This is just a marginal efficiency
224 * hack, since AfterTriggerBeginQuery/AfterTriggerEndQuery aren't
225 * all that expensive, but we might as well do it.
226 */
227 if (!queryDesc->plannedstmt->hasModifyingCTE)
228 eflags |= EXEC_FLAG_SKIP_TRIGGERS;
229 break;
230
231 case CMD_INSERT:
232 case CMD_DELETE:
233 case CMD_UPDATE:
234 case CMD_MERGE:
235 estate->es_output_cid = GetCurrentCommandId(true);
236 break;
237
238 default:
239 elog(ERROR, "unrecognized operation code: %d",
240 (int) queryDesc->operation);
241 break;
242 }
243
244 /*
245 * Copy other important information into the EState
246 */
247 estate->es_snapshot = RegisterSnapshot(queryDesc->snapshot);
249 estate->es_top_eflags = eflags;
250 estate->es_instrument = queryDesc->instrument_options;
251 estate->es_jit_flags = queryDesc->plannedstmt->jitFlags;
252
253 /*
254 * Set up an AFTER-trigger statement context, unless told not to, or
255 * unless it's EXPLAIN-only mode (when ExecutorFinish won't be called).
256 */
259
260 /*
261 * Initialize the plan state tree
262 */
263 InitPlan(queryDesc, eflags);
264
265 MemoryContextSwitchTo(oldcontext);
266}
static void ExecCheckXactReadOnly(PlannedStmt *plannedstmt)
Definition execMain.c:804
static void InitPlan(QueryDesc *queryDesc, int eflags)
Definition execMain.c:838
Snapshot RegisterSnapshot(Snapshot snapshot)
Definition snapmgr.c:824
int es_jit_flags
Definition execnodes.h:775
const char * es_sourceText
Definition execnodes.h:689
const char * sourceText
Definition execdesc.h:38
ParamListInfo params
Definition execdesc.h:42
int instrument_options
Definition execdesc.h:44
Snapshot snapshot
Definition execdesc.h:39
QueryEnvironment * queryEnv
Definition execdesc.h:43
Snapshot crosscheck_snapshot
Definition execdesc.h:40
void AfterTriggerBeginQuery(void)
Definition trigger.c:5117
bool XactReadOnly
Definition xact.c:84
bool IsInParallelMode(void)
Definition xact.c:1091
CommandId GetCurrentCommandId(bool used)
Definition xact.c:831

References AfterTriggerBeginQuery(), Assert, CMD_DELETE, CMD_INSERT, CMD_MERGE, CMD_SELECT, CMD_UPDATE, CreateExecutorState(), QueryDesc::crosscheck_snapshot, elog, ERROR, EState::es_crosscheck_snapshot, EState::es_instrument, EState::es_jit_flags, EState::es_output_cid, EState::es_param_exec_vals, EState::es_param_list_info, EState::es_query_cxt, EState::es_queryEnv, EState::es_snapshot, EState::es_sourceText, EState::es_top_eflags, QueryDesc::estate, EXEC_FLAG_EXPLAIN_ONLY, EXEC_FLAG_SKIP_TRIGGERS, ExecCheckXactReadOnly(), fb(), GetActiveSnapshot(), GetCurrentCommandId(), PlannedStmt::hasModifyingCTE, InitPlan(), QueryDesc::instrument_options, IsInParallelMode(), PlannedStmt::jitFlags, list_length(), MemoryContextSwitchTo(), NIL, QueryDesc::operation, palloc0_array, PlannedStmt::paramExecTypes, QueryDesc::params, QueryDesc::plannedstmt, QueryDesc::queryEnv, RegisterSnapshot(), PlannedStmt::rowMarks, QueryDesc::snapshot, QueryDesc::sourceText, and XactReadOnly.

Referenced by ExecutorStart(), explain_ExecutorStart(), and pgss_ExecutorStart().

Variable Documentation

◆ ExecutorCheckPerms_hook

ExecutorCheckPerms_hook_type ExecutorCheckPerms_hook = NULL

Definition at line 76 of file execMain.c.

Referenced by _PG_init(), and ExecCheckPermissions().

◆ ExecutorEnd_hook

ExecutorEnd_hook_type ExecutorEnd_hook = NULL

Definition at line 73 of file execMain.c.

Referenced by _PG_init(), and ExecutorEnd().

◆ ExecutorFinish_hook

ExecutorFinish_hook_type ExecutorFinish_hook = NULL

Definition at line 72 of file execMain.c.

Referenced by _PG_init(), and ExecutorFinish().

◆ ExecutorRun_hook

ExecutorRun_hook_type ExecutorRun_hook = NULL

Definition at line 71 of file execMain.c.

Referenced by _PG_init(), and ExecutorRun().

◆ ExecutorStart_hook

ExecutorStart_hook_type ExecutorStart_hook = NULL

Definition at line 70 of file execMain.c.

Referenced by _PG_init(), and ExecutorStart().