PostgreSQL Source Code git master
All Data Structures Namespaces Files Functions Variables Typedefs Enumerations Enumerator Macros Pages
execMain.c File Reference
#include "postgres.h"
#include "access/sysattr.h"
#include "access/table.h"
#include "access/tableam.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/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 "storage/lmgr.h"
#include "tcop/utility.h"
#include "utils/acl.h"
#include "utils/backend_status.h"
#include "utils/lsyscache.h"
#include "utils/partcache.h"
#include "utils/plancache.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 ExecCheckOneRelPerms (RTEPermissionInfo *perminfo)
 
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)
 
bool ExecutorStart (QueryDesc *queryDesc, int eflags)
 
bool standard_ExecutorStart (QueryDesc *queryDesc, int eflags)
 
void ExecutorStartCachedPlan (QueryDesc *queryDesc, int eflags, CachedPlanSource *plansource, int query_index)
 
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)
 
void CheckValidResultRel (ResultRelInfo *resultRelInfo, CmdType operation, 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 char * ExecRelCheck (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)
 
char * ExecBuildSlotValueDescription (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,
List mergeActions 
)

Definition at line 1152 of file execMain.c.

1154{
1155 Relation resultRel = resultRelInfo->ri_RelationDesc;
1156 FdwRoutine *fdwroutine;
1157
1158 /* Expect a fully-formed ResultRelInfo from InitResultRelInfo(). */
1159 Assert(resultRelInfo->ri_needLockTagTuple ==
1160 IsInplaceUpdateRelation(resultRel));
1161
1162 switch (resultRel->rd_rel->relkind)
1163 {
1164 case RELKIND_RELATION:
1165 case RELKIND_PARTITIONED_TABLE:
1166 CheckCmdReplicaIdentity(resultRel, operation);
1167 break;
1168 case RELKIND_SEQUENCE:
1169 ereport(ERROR,
1170 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1171 errmsg("cannot change sequence \"%s\"",
1172 RelationGetRelationName(resultRel))));
1173 break;
1174 case RELKIND_TOASTVALUE:
1175 ereport(ERROR,
1176 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1177 errmsg("cannot change TOAST relation \"%s\"",
1178 RelationGetRelationName(resultRel))));
1179 break;
1180 case RELKIND_VIEW:
1181
1182 /*
1183 * Okay only if there's a suitable INSTEAD OF trigger. Otherwise,
1184 * complain, but omit errdetail because we haven't got the
1185 * information handy (and given that it really shouldn't happen,
1186 * it's not worth great exertion to get).
1187 */
1188 if (!view_has_instead_trigger(resultRel, operation, mergeActions))
1189 error_view_not_updatable(resultRel, operation, mergeActions,
1190 NULL);
1191 break;
1192 case RELKIND_MATVIEW:
1194 ereport(ERROR,
1195 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1196 errmsg("cannot change materialized view \"%s\"",
1197 RelationGetRelationName(resultRel))));
1198 break;
1199 case RELKIND_FOREIGN_TABLE:
1200 /* Okay only if the FDW supports it */
1201 fdwroutine = resultRelInfo->ri_FdwRoutine;
1202 switch (operation)
1203 {
1204 case CMD_INSERT:
1205 if (fdwroutine->ExecForeignInsert == NULL)
1206 ereport(ERROR,
1207 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1208 errmsg("cannot insert into foreign table \"%s\"",
1209 RelationGetRelationName(resultRel))));
1210 if (fdwroutine->IsForeignRelUpdatable != NULL &&
1211 (fdwroutine->IsForeignRelUpdatable(resultRel) & (1 << CMD_INSERT)) == 0)
1212 ereport(ERROR,
1213 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
1214 errmsg("foreign table \"%s\" does not allow inserts",
1215 RelationGetRelationName(resultRel))));
1216 break;
1217 case CMD_UPDATE:
1218 if (fdwroutine->ExecForeignUpdate == NULL)
1219 ereport(ERROR,
1220 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1221 errmsg("cannot update foreign table \"%s\"",
1222 RelationGetRelationName(resultRel))));
1223 if (fdwroutine->IsForeignRelUpdatable != NULL &&
1224 (fdwroutine->IsForeignRelUpdatable(resultRel) & (1 << CMD_UPDATE)) == 0)
1225 ereport(ERROR,
1226 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
1227 errmsg("foreign table \"%s\" does not allow updates",
1228 RelationGetRelationName(resultRel))));
1229 break;
1230 case CMD_DELETE:
1231 if (fdwroutine->ExecForeignDelete == NULL)
1232 ereport(ERROR,
1233 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1234 errmsg("cannot delete from foreign table \"%s\"",
1235 RelationGetRelationName(resultRel))));
1236 if (fdwroutine->IsForeignRelUpdatable != NULL &&
1237 (fdwroutine->IsForeignRelUpdatable(resultRel) & (1 << CMD_DELETE)) == 0)
1238 ereport(ERROR,
1239 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
1240 errmsg("foreign table \"%s\" does not allow deletes",
1241 RelationGetRelationName(resultRel))));
1242 break;
1243 default:
1244 elog(ERROR, "unrecognized CmdType: %d", (int) operation);
1245 break;
1246 }
1247 break;
1248 default:
1249 ereport(ERROR,
1250 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1251 errmsg("cannot change relation \"%s\"",
1252 RelationGetRelationName(resultRel))));
1253 break;
1254 }
1255}
bool IsInplaceUpdateRelation(Relation relation)
Definition: catalog.c:183
int errcode(int sqlerrcode)
Definition: elog.c:854
int errmsg(const char *fmt,...)
Definition: elog.c:1071
#define ERROR
Definition: elog.h:39
#define elog(elevel,...)
Definition: elog.h:226
#define ereport(elevel,...)
Definition: elog.h:149
void CheckCmdReplicaIdentity(Relation rel, CmdType cmd)
Assert(PointerIsAligned(start, uint64))
bool MatViewIncrementalMaintenanceIsEnabled(void)
Definition: matview.c:964
@ CMD_INSERT
Definition: nodes.h:273
@ CMD_DELETE
Definition: nodes.h:274
@ CMD_UPDATE
Definition: nodes.h:272
#define RelationGetRelationName(relation)
Definition: rel.h:550
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:507
Relation ri_RelationDesc
Definition: execnodes.h:475
struct FdwRoutine * ri_FdwRoutine
Definition: execnodes.h:528

References Assert(), CheckCmdReplicaIdentity(), CMD_DELETE, CMD_INSERT, CMD_UPDATE, elog, ereport, errcode(), errmsg(), ERROR, error_view_not_updatable(), FdwRoutine::ExecForeignDelete, FdwRoutine::ExecForeignInsert, FdwRoutine::ExecForeignUpdate, FdwRoutine::IsForeignRelUpdatable, IsInplaceUpdateRelation(), MatViewIncrementalMaintenanceIsEnabled(), 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 1264 of file execMain.c.

1265{
1266 FdwRoutine *fdwroutine;
1267
1268 switch (rel->rd_rel->relkind)
1269 {
1270 case RELKIND_RELATION:
1271 case RELKIND_PARTITIONED_TABLE:
1272 /* OK */
1273 break;
1274 case RELKIND_SEQUENCE:
1275 /* Must disallow this because we don't vacuum sequences */
1276 ereport(ERROR,
1277 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1278 errmsg("cannot lock rows in sequence \"%s\"",
1280 break;
1281 case RELKIND_TOASTVALUE:
1282 /* We could allow this, but there seems no good reason to */
1283 ereport(ERROR,
1284 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1285 errmsg("cannot lock rows in TOAST relation \"%s\"",
1287 break;
1288 case RELKIND_VIEW:
1289 /* Should not get here; planner should have expanded the view */
1290 ereport(ERROR,
1291 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1292 errmsg("cannot lock rows in view \"%s\"",
1294 break;
1295 case RELKIND_MATVIEW:
1296 /* Allow referencing a matview, but not actual locking clauses */
1297 if (markType != ROW_MARK_REFERENCE)
1298 ereport(ERROR,
1299 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1300 errmsg("cannot lock rows in materialized view \"%s\"",
1302 break;
1303 case RELKIND_FOREIGN_TABLE:
1304 /* Okay only if the FDW supports it */
1305 fdwroutine = GetFdwRoutineForRelation(rel, false);
1306 if (fdwroutine->RefetchForeignRow == NULL)
1307 ereport(ERROR,
1308 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1309 errmsg("cannot lock rows in foreign table \"%s\"",
1311 break;
1312 default:
1313 ereport(ERROR,
1314 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1315 errmsg("cannot lock rows in relation \"%s\"",
1317 break;
1318 }
1319}
FdwRoutine * GetFdwRoutineForRelation(Relation relation, bool makecopy)
Definition: foreign.c:442
@ ROW_MARK_REFERENCE
Definition: plannodes.h:1490
RefetchForeignRow_function RefetchForeignRow
Definition: fdwapi.h:248

References ereport, errcode(), errmsg(), ERROR, 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 2725 of file execMain.c.

2727{
2728 TupleTableSlot *slot;
2729 TupleTableSlot *testslot;
2730
2731 Assert(rti > 0);
2732
2733 /*
2734 * Need to run a recheck subquery. Initialize or reinitialize EPQ state.
2735 */
2736 EvalPlanQualBegin(epqstate);
2737
2738 /*
2739 * Callers will often use the EvalPlanQualSlot to store the tuple to avoid
2740 * an unnecessary copy.
2741 */
2742 testslot = EvalPlanQualSlot(epqstate, relation, rti);
2743 if (testslot != inputslot)
2744 ExecCopySlot(testslot, inputslot);
2745
2746 /*
2747 * Mark that an EPQ tuple is available for this relation. (If there is
2748 * more than one result relation, the others remain marked as having no
2749 * tuple available.)
2750 */
2751 epqstate->relsubs_done[rti - 1] = false;
2752 epqstate->relsubs_blocked[rti - 1] = false;
2753
2754 /*
2755 * Run the EPQ query. We assume it will return at most one tuple.
2756 */
2757 slot = EvalPlanQualNext(epqstate);
2758
2759 /*
2760 * If we got a tuple, force the slot to materialize the tuple so that it
2761 * is not dependent on any local state in the EPQ query (in particular,
2762 * it's highly likely that the slot contains references to any pass-by-ref
2763 * datums that may be present in copyTuple). As with the next step, this
2764 * is to guard against early re-use of the EPQ query.
2765 */
2766 if (!TupIsNull(slot))
2767 ExecMaterializeSlot(slot);
2768
2769 /*
2770 * Clear out the test tuple, and mark that no tuple is available here.
2771 * This is needed in case the EPQ state is re-used to test a tuple for a
2772 * different target relation.
2773 */
2774 ExecClearTuple(testslot);
2775 epqstate->relsubs_blocked[rti - 1] = true;
2776
2777 return slot;
2778}
TupleTableSlot * EvalPlanQualSlot(EPQState *epqstate, Relation relation, Index rti)
Definition: execMain.c:2853
void EvalPlanQualBegin(EPQState *epqstate)
Definition: execMain.c:3008
TupleTableSlot * EvalPlanQualNext(EPQState *epqstate)
Definition: execMain.c:2992
bool * relsubs_blocked
Definition: execnodes.h:1350
bool * relsubs_done
Definition: execnodes.h:1341
static TupleTableSlot * ExecClearTuple(TupleTableSlot *slot)
Definition: tuptable.h:458
#define TupIsNull(slot)
Definition: tuptable.h:310
static TupleTableSlot * ExecCopySlot(TupleTableSlot *dstslot, TupleTableSlot *srcslot)
Definition: tuptable.h:525
static void ExecMaterializeSlot(TupleTableSlot *slot)
Definition: tuptable.h:476

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

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

◆ EvalPlanQualBegin()

void EvalPlanQualBegin ( EPQState epqstate)

Definition at line 3008 of file execMain.c.

3009{
3010 EState *parentestate = epqstate->parentestate;
3011 EState *recheckestate = epqstate->recheckestate;
3012
3013 if (recheckestate == NULL)
3014 {
3015 /* First time through, so create a child EState */
3016 EvalPlanQualStart(epqstate, epqstate->plan);
3017 }
3018 else
3019 {
3020 /*
3021 * We already have a suitable child EPQ tree, so just reset it.
3022 */
3023 Index rtsize = parentestate->es_range_table_size;
3024 PlanState *rcplanstate = epqstate->recheckplanstate;
3025
3026 /*
3027 * Reset the relsubs_done[] flags to equal relsubs_blocked[], so that
3028 * the EPQ run will never attempt to fetch tuples from blocked target
3029 * relations.
3030 */
3031 memcpy(epqstate->relsubs_done, epqstate->relsubs_blocked,
3032 rtsize * sizeof(bool));
3033
3034 /* Recopy current values of parent parameters */
3035 if (parentestate->es_plannedstmt->paramExecTypes != NIL)
3036 {
3037 int i;
3038
3039 /*
3040 * Force evaluation of any InitPlan outputs that could be needed
3041 * by the subplan, just in case they got reset since
3042 * EvalPlanQualStart (see comments therein).
3043 */
3044 ExecSetParamPlanMulti(rcplanstate->plan->extParam,
3045 GetPerTupleExprContext(parentestate));
3046
3047 i = list_length(parentestate->es_plannedstmt->paramExecTypes);
3048
3049 while (--i >= 0)
3050 {
3051 /* copy value if any, but not execPlan link */
3052 recheckestate->es_param_exec_vals[i].value =
3053 parentestate->es_param_exec_vals[i].value;
3054 recheckestate->es_param_exec_vals[i].isnull =
3055 parentestate->es_param_exec_vals[i].isnull;
3056 }
3057 }
3058
3059 /*
3060 * Mark child plan tree as needing rescan at all scan nodes. The
3061 * first ExecProcNode will take care of actually doing the rescan.
3062 */
3063 rcplanstate->chgParam = bms_add_member(rcplanstate->chgParam,
3064 epqstate->epqParam);
3065 }
3066}
Bitmapset * bms_add_member(Bitmapset *a, int x)
Definition: bitmapset.c:815
unsigned int Index
Definition: c.h:585
static void EvalPlanQualStart(EPQState *epqstate, Plan *planTree)
Definition: execMain.c:3075
#define GetPerTupleExprContext(estate)
Definition: executor.h:678
int i
Definition: isn.c:77
void ExecSetParamPlanMulti(const Bitmapset *params, ExprContext *econtext)
Definition: nodeSubplan.c:1276
static int list_length(const List *l)
Definition: pg_list.h:152
#define NIL
Definition: pg_list.h:68
Plan * plan
Definition: execnodes.h:1313
int epqParam
Definition: execnodes.h:1296
EState * parentestate
Definition: execnodes.h:1295
EState * recheckestate
Definition: execnodes.h:1327
PlanState * recheckplanstate
Definition: execnodes.h:1352
PlannedStmt * es_plannedstmt
Definition: execnodes.h:666
ParamExecData * es_param_exec_vals
Definition: execnodes.h:703
Index es_range_table_size
Definition: execnodes.h:660
bool isnull
Definition: params.h:150
Datum value
Definition: params.h:149
Plan * plan
Definition: execnodes.h:1159
Bitmapset * chgParam
Definition: execnodes.h:1191
Bitmapset * extParam
Definition: plannodes.h:229
List * paramExecTypes
Definition: plannodes.h:136

References bms_add_member(), PlanState::chgParam, EPQState::epqParam, EState::es_param_exec_vals, EState::es_plannedstmt, EState::es_range_table_size, EvalPlanQualStart(), ExecSetParamPlanMulti(), Plan::extParam, GetPerTupleExprContext, i, ParamExecData::isnull, list_length(), NIL, PlannedStmt::paramExecTypes, EPQState::parentestate, PlanState::plan, 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 3249 of file execMain.c.

3250{
3251 EState *estate = epqstate->recheckestate;
3252 Index rtsize;
3253 MemoryContext oldcontext;
3254 ListCell *l;
3255
3256 rtsize = epqstate->parentestate->es_range_table_size;
3257
3258 /*
3259 * We may have a tuple table, even if EPQ wasn't started, because we allow
3260 * use of EvalPlanQualSlot() without calling EvalPlanQualBegin().
3261 */
3262 if (epqstate->tuple_table != NIL)
3263 {
3264 memset(epqstate->relsubs_slot, 0,
3265 rtsize * sizeof(TupleTableSlot *));
3266 ExecResetTupleTable(epqstate->tuple_table, true);
3267 epqstate->tuple_table = NIL;
3268 }
3269
3270 /* EPQ wasn't started, nothing further to do */
3271 if (estate == NULL)
3272 return;
3273
3274 oldcontext = MemoryContextSwitchTo(estate->es_query_cxt);
3275
3276 ExecEndNode(epqstate->recheckplanstate);
3277
3278 foreach(l, estate->es_subplanstates)
3279 {
3280 PlanState *subplanstate = (PlanState *) lfirst(l);
3281
3282 ExecEndNode(subplanstate);
3283 }
3284
3285 /* throw away the per-estate tuple table, some node may have used it */
3286 ExecResetTupleTable(estate->es_tupleTable, false);
3287
3288 /* Close any result and trigger target relations attached to this EState */
3290
3291 MemoryContextSwitchTo(oldcontext);
3292
3293 FreeExecutorState(estate);
3294
3295 /* Mark EPQState idle */
3296 epqstate->origslot = NULL;
3297 epqstate->recheckestate = NULL;
3298 epqstate->recheckplanstate = NULL;
3299 epqstate->relsubs_rowmark = NULL;
3300 epqstate->relsubs_done = NULL;
3301 epqstate->relsubs_blocked = NULL;
3302}
void ExecCloseResultRelations(EState *estate)
Definition: execMain.c:1651
void ExecEndNode(PlanState *node)
Definition: execProcnode.c:562
void ExecResetTupleTable(List *tupleTable, bool shouldFree)
Definition: execTuples.c:1380
void FreeExecutorState(EState *estate)
Definition: execUtils.c:193
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:124
#define lfirst(lc)
Definition: pg_list.h:172
ExecAuxRowMark ** relsubs_rowmark
Definition: execnodes.h:1334
TupleTableSlot * origslot
Definition: execnodes.h:1322
TupleTableSlot ** relsubs_slot
Definition: execnodes.h:1306
List * tuple_table
Definition: execnodes.h:1305
MemoryContext es_query_cxt
Definition: execnodes.h:708
List * es_tupleTable
Definition: execnodes.h:710
List * es_subplanstates
Definition: execnodes.h:724

References EState::es_query_cxt, EState::es_range_table_size, EState::es_subplanstates, EState::es_tupleTable, ExecCloseResultRelations(), ExecEndNode(), ExecResetTupleTable(), 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 2881 of file execMain.c.

2882{
2883 ExecAuxRowMark *earm = epqstate->relsubs_rowmark[rti - 1];
2884 ExecRowMark *erm;
2885 Datum datum;
2886 bool isNull;
2887
2888 Assert(earm != NULL);
2889 Assert(epqstate->origslot != NULL);
2890
2891 erm = earm->rowmark;
2892
2894 elog(ERROR, "EvalPlanQual doesn't support locking rowmarks");
2895
2896 /* if child rel, must check whether it produced this row */
2897 if (erm->rti != erm->prti)
2898 {
2899 Oid tableoid;
2900
2901 datum = ExecGetJunkAttribute(epqstate->origslot,
2902 earm->toidAttNo,
2903 &isNull);
2904 /* non-locked rels could be on the inside of outer joins */
2905 if (isNull)
2906 return false;
2907
2908 tableoid = DatumGetObjectId(datum);
2909
2910 Assert(OidIsValid(erm->relid));
2911 if (tableoid != erm->relid)
2912 {
2913 /* this child is inactive right now */
2914 return false;
2915 }
2916 }
2917
2918 if (erm->markType == ROW_MARK_REFERENCE)
2919 {
2920 Assert(erm->relation != NULL);
2921
2922 /* fetch the tuple's ctid */
2923 datum = ExecGetJunkAttribute(epqstate->origslot,
2924 earm->ctidAttNo,
2925 &isNull);
2926 /* non-locked rels could be on the inside of outer joins */
2927 if (isNull)
2928 return false;
2929
2930 /* fetch requests on foreign tables must be passed to their FDW */
2931 if (erm->relation->rd_rel->relkind == RELKIND_FOREIGN_TABLE)
2932 {
2933 FdwRoutine *fdwroutine;
2934 bool updated = false;
2935
2936 fdwroutine = GetFdwRoutineForRelation(erm->relation, false);
2937 /* this should have been checked already, but let's be safe */
2938 if (fdwroutine->RefetchForeignRow == NULL)
2939 ereport(ERROR,
2940 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2941 errmsg("cannot lock rows in foreign table \"%s\"",
2943
2944 fdwroutine->RefetchForeignRow(epqstate->recheckestate,
2945 erm,
2946 datum,
2947 slot,
2948 &updated);
2949 if (TupIsNull(slot))
2950 elog(ERROR, "failed to fetch tuple for EvalPlanQual recheck");
2951
2952 /*
2953 * Ideally we'd insist on updated == false here, but that assumes
2954 * that FDWs can track that exactly, which they might not be able
2955 * to. So just ignore the flag.
2956 */
2957 return true;
2958 }
2959 else
2960 {
2961 /* ordinary table, fetch the tuple */
2964 SnapshotAny, slot))
2965 elog(ERROR, "failed to fetch tuple for EvalPlanQual recheck");
2966 return true;
2967 }
2968 }
2969 else
2970 {
2971 Assert(erm->markType == ROW_MARK_COPY);
2972
2973 /* fetch the whole-row Var for the relation */
2974 datum = ExecGetJunkAttribute(epqstate->origslot,
2975 earm->wholeAttNo,
2976 &isNull);
2977 /* non-locked rels could be on the inside of outer joins */
2978 if (isNull)
2979 return false;
2980
2981 ExecStoreHeapTupleDatum(datum, slot);
2982 return true;
2983 }
2984}
#define OidIsValid(objectId)
Definition: c.h:746
void ExecStoreHeapTupleDatum(Datum data, TupleTableSlot *slot)
Definition: execTuples.c:1795
static Datum ExecGetJunkAttribute(TupleTableSlot *slot, AttrNumber attno, bool *isNull)
Definition: executor.h:222
#define RowMarkRequiresRowShareLock(marktype)
Definition: plannodes.h:1494
@ ROW_MARK_COPY
Definition: plannodes.h:1491
uintptr_t Datum
Definition: postgres.h:69
static Oid DatumGetObjectId(Datum X)
Definition: postgres.h:247
static Pointer DatumGetPointer(Datum X)
Definition: postgres.h:317
unsigned int Oid
Definition: postgres_ext.h:30
#define SnapshotAny
Definition: snapmgr.h:33
AttrNumber wholeAttNo
Definition: execnodes.h:823
ExecRowMark * rowmark
Definition: execnodes.h:820
AttrNumber toidAttNo
Definition: execnodes.h:822
AttrNumber ctidAttNo
Definition: execnodes.h:821
Index rti
Definition: execnodes.h:798
Index prti
Definition: execnodes.h:799
Relation relation
Definition: execnodes.h:796
RowMarkType markType
Definition: execnodes.h:801
static bool table_tuple_fetch_row_version(Relation rel, ItemPointer tid, Snapshot snapshot, TupleTableSlot *slot)
Definition: tableam.h:1248

References Assert(), ExecAuxRowMark::ctidAttNo, DatumGetObjectId(), DatumGetPointer(), elog, ereport, errcode(), errmsg(), ERROR, ExecGetJunkAttribute(), ExecStoreHeapTupleDatum(), GetFdwRoutineForRelation(), ExecRowMark::markType, OidIsValid, EPQState::origslot, ExecRowMark::prti, RelationData::rd_rel, EPQState::recheckestate, FdwRoutine::RefetchForeignRow, ExecRowMark::relation, RelationGetRelationName, ExecRowMark::relid, EPQState::relsubs_rowmark, ROW_MARK_COPY, ROW_MARK_REFERENCE, ExecAuxRowMark::rowmark, RowMarkRequiresRowShareLock, ExecRowMark::rti, SnapshotAny, table_tuple_fetch_row_version(), ExecAuxRowMark::toidAttNo, TupIsNull, and ExecAuxRowMark::wholeAttNo.

Referenced by ExecScanFetch().

◆ EvalPlanQualInit()

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

Definition at line 2794 of file execMain.c.

2797{
2798 Index rtsize = parentestate->es_range_table_size;
2799
2800 /* initialize data not changing over EPQState's lifetime */
2801 epqstate->parentestate = parentestate;
2802 epqstate->epqParam = epqParam;
2803 epqstate->resultRelations = resultRelations;
2804
2805 /*
2806 * Allocate space to reference a slot for each potential rti - do so now
2807 * rather than in EvalPlanQualBegin(), as done for other dynamically
2808 * allocated resources, so EvalPlanQualSlot() can be used to hold tuples
2809 * that *may* need EPQ later, without forcing the overhead of
2810 * EvalPlanQualBegin().
2811 */
2812 epqstate->tuple_table = NIL;
2813 epqstate->relsubs_slot = (TupleTableSlot **)
2814 palloc0(rtsize * sizeof(TupleTableSlot *));
2815
2816 /* ... and remember data that EvalPlanQualBegin will need */
2817 epqstate->plan = subplan;
2818 epqstate->arowMarks = auxrowmarks;
2819
2820 /* ... and mark the EPQ state inactive */
2821 epqstate->origslot = NULL;
2822 epqstate->recheckestate = NULL;
2823 epqstate->recheckplanstate = NULL;
2824 epqstate->relsubs_rowmark = NULL;
2825 epqstate->relsubs_done = NULL;
2826 epqstate->relsubs_blocked = NULL;
2827}
void * palloc0(Size size)
Definition: mcxt.c:1970
List * resultRelations
Definition: execnodes.h:1297
List * arowMarks
Definition: execnodes.h:1314

References EPQState::arowMarks, EPQState::epqParam, EState::es_range_table_size, NIL, EPQState::origslot, palloc0(), 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 2992 of file execMain.c.

2993{
2994 MemoryContext oldcontext;
2995 TupleTableSlot *slot;
2996
2997 oldcontext = MemoryContextSwitchTo(epqstate->recheckestate->es_query_cxt);
2998 slot = ExecProcNode(epqstate->recheckplanstate);
2999 MemoryContextSwitchTo(oldcontext);
3000
3001 return slot;
3002}
static TupleTableSlot * ExecProcNode(PlanState *node)
Definition: executor.h:336

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 2836 of file execMain.c.

2837{
2838 /* If we have a live EPQ query, shut it down */
2839 EvalPlanQualEnd(epqstate);
2840 /* And set/change the plan pointer */
2841 epqstate->plan = subplan;
2842 /* The rowmarks depend on the plan, too */
2843 epqstate->arowMarks = auxrowmarks;
2844}
void EvalPlanQualEnd(EPQState *epqstate)
Definition: execMain.c:3249

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

Referenced by ExecInitModifyTable().

◆ EvalPlanQualSlot()

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

Definition at line 2853 of file execMain.c.

2855{
2856 TupleTableSlot **slot;
2857
2858 Assert(relation);
2859 Assert(rti > 0 && rti <= epqstate->parentestate->es_range_table_size);
2860 slot = &epqstate->relsubs_slot[rti - 1];
2861
2862 if (*slot == NULL)
2863 {
2864 MemoryContext oldcontext;
2865
2866 oldcontext = MemoryContextSwitchTo(epqstate->parentestate->es_query_cxt);
2867 *slot = table_slot_create(relation, &epqstate->tuple_table);
2868 MemoryContextSwitchTo(oldcontext);
2869 }
2870
2871 return *slot;
2872}
TupleTableSlot * table_slot_create(Relation relation, List **reglist)
Definition: tableam.c:92

References Assert(), EState::es_query_cxt, 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 3075 of file execMain.c.

3076{
3077 EState *parentestate = epqstate->parentestate;
3078 Index rtsize = parentestate->es_range_table_size;
3079 EState *rcestate;
3080 MemoryContext oldcontext;
3081 ListCell *l;
3082
3083 epqstate->recheckestate = rcestate = CreateExecutorState();
3084
3085 oldcontext = MemoryContextSwitchTo(rcestate->es_query_cxt);
3086
3087 /* signal that this is an EState for executing EPQ */
3088 rcestate->es_epq_active = epqstate;
3089
3090 /*
3091 * Child EPQ EStates share the parent's copy of unchanging state such as
3092 * the snapshot, rangetable, and external Param info. They need their own
3093 * copies of local state, including a tuple table, es_param_exec_vals,
3094 * result-rel info, etc.
3095 *
3096 * es_cachedplan is not copied because EPQ plan execution does not acquire
3097 * any new locks that could invalidate the CachedPlan.
3098 */
3100 rcestate->es_snapshot = parentestate->es_snapshot;
3101 rcestate->es_crosscheck_snapshot = parentestate->es_crosscheck_snapshot;
3102 rcestate->es_range_table = parentestate->es_range_table;
3103 rcestate->es_range_table_size = parentestate->es_range_table_size;
3104 rcestate->es_relations = parentestate->es_relations;
3105 rcestate->es_rowmarks = parentestate->es_rowmarks;
3106 rcestate->es_rteperminfos = parentestate->es_rteperminfos;
3107 rcestate->es_plannedstmt = parentestate->es_plannedstmt;
3108 rcestate->es_junkFilter = parentestate->es_junkFilter;
3109 rcestate->es_output_cid = parentestate->es_output_cid;
3110 rcestate->es_queryEnv = parentestate->es_queryEnv;
3111
3112 /*
3113 * ResultRelInfos needed by subplans are initialized from scratch when the
3114 * subplans themselves are initialized.
3115 */
3116 rcestate->es_result_relations = NULL;
3117 /* es_trig_target_relations must NOT be copied */
3118 rcestate->es_top_eflags = parentestate->es_top_eflags;
3119 rcestate->es_instrument = parentestate->es_instrument;
3120 /* es_auxmodifytables must NOT be copied */
3121
3122 /*
3123 * The external param list is simply shared from parent. The internal
3124 * param workspace has to be local state, but we copy the initial values
3125 * from the parent, so as to have access to any param values that were
3126 * already set from other parts of the parent's plan tree.
3127 */
3128 rcestate->es_param_list_info = parentestate->es_param_list_info;
3129 if (parentestate->es_plannedstmt->paramExecTypes != NIL)
3130 {
3131 int i;
3132
3133 /*
3134 * Force evaluation of any InitPlan outputs that could be needed by
3135 * the subplan. (With more complexity, maybe we could postpone this
3136 * till the subplan actually demands them, but it doesn't seem worth
3137 * the trouble; this is a corner case already, since usually the
3138 * InitPlans would have been evaluated before reaching EvalPlanQual.)
3139 *
3140 * This will not touch output params of InitPlans that occur somewhere
3141 * within the subplan tree, only those that are attached to the
3142 * ModifyTable node or above it and are referenced within the subplan.
3143 * That's OK though, because the planner would only attach such
3144 * InitPlans to a lower-level SubqueryScan node, and EPQ execution
3145 * will not descend into a SubqueryScan.
3146 *
3147 * The EState's per-output-tuple econtext is sufficiently short-lived
3148 * for this, since it should get reset before there is any chance of
3149 * doing EvalPlanQual again.
3150 */
3152 GetPerTupleExprContext(parentestate));
3153
3154 /* now make the internal param workspace ... */
3155 i = list_length(parentestate->es_plannedstmt->paramExecTypes);
3156 rcestate->es_param_exec_vals = (ParamExecData *)
3157 palloc0(i * sizeof(ParamExecData));
3158 /* ... and copy down all values, whether really needed or not */
3159 while (--i >= 0)
3160 {
3161 /* copy value if any, but not execPlan link */
3162 rcestate->es_param_exec_vals[i].value =
3163 parentestate->es_param_exec_vals[i].value;
3164 rcestate->es_param_exec_vals[i].isnull =
3165 parentestate->es_param_exec_vals[i].isnull;
3166 }
3167 }
3168
3169 /*
3170 * Copy es_unpruned_relids so that pruned relations are ignored by
3171 * ExecInitLockRows() and ExecInitModifyTable() when initializing the plan
3172 * trees below.
3173 */
3174 rcestate->es_unpruned_relids = parentestate->es_unpruned_relids;
3175
3176 /*
3177 * Initialize private state information for each SubPlan. We must do this
3178 * before running ExecInitNode on the main query tree, since
3179 * ExecInitSubPlan expects to be able to find these entries. Some of the
3180 * SubPlans might not be used in the part of the plan tree we intend to
3181 * run, but since it's not easy to tell which, we just initialize them
3182 * all.
3183 */
3184 Assert(rcestate->es_subplanstates == NIL);
3185 foreach(l, parentestate->es_plannedstmt->subplans)
3186 {
3187 Plan *subplan = (Plan *) lfirst(l);
3188 PlanState *subplanstate;
3189
3190 subplanstate = ExecInitNode(subplan, rcestate, 0);
3191 rcestate->es_subplanstates = lappend(rcestate->es_subplanstates,
3192 subplanstate);
3193 }
3194
3195 /*
3196 * Build an RTI indexed array of rowmarks, so that
3197 * EvalPlanQualFetchRowMark() can efficiently access the to be fetched
3198 * rowmark.
3199 */
3200 epqstate->relsubs_rowmark = (ExecAuxRowMark **)
3201 palloc0(rtsize * sizeof(ExecAuxRowMark *));
3202 foreach(l, epqstate->arowMarks)
3203 {
3204 ExecAuxRowMark *earm = (ExecAuxRowMark *) lfirst(l);
3205
3206 epqstate->relsubs_rowmark[earm->rowmark->rti - 1] = earm;
3207 }
3208
3209 /*
3210 * Initialize per-relation EPQ tuple states. Result relations, if any,
3211 * get marked as blocked; others as not-fetched.
3212 */
3213 epqstate->relsubs_done = palloc_array(bool, rtsize);
3214 epqstate->relsubs_blocked = palloc0_array(bool, rtsize);
3215
3216 foreach(l, epqstate->resultRelations)
3217 {
3218 int rtindex = lfirst_int(l);
3219
3220 Assert(rtindex > 0 && rtindex <= rtsize);
3221 epqstate->relsubs_blocked[rtindex - 1] = true;
3222 }
3223
3224 memcpy(epqstate->relsubs_done, epqstate->relsubs_blocked,
3225 rtsize * sizeof(bool));
3226
3227 /*
3228 * Initialize the private state information for all the nodes in the part
3229 * of the plan tree we need to run. This opens files, allocates storage
3230 * and leaves us ready to start processing tuples.
3231 */
3232 epqstate->recheckplanstate = ExecInitNode(planTree, rcestate, 0);
3233
3234 MemoryContextSwitchTo(oldcontext);
3235}
PlanState * ExecInitNode(Plan *node, EState *estate, int eflags)
Definition: execProcnode.c:142
EState * CreateExecutorState(void)
Definition: execUtils.c:88
#define palloc_array(type, count)
Definition: fe_memutils.h:76
#define palloc0_array(type, count)
Definition: fe_memutils.h:77
List * lappend(List *list, void *datum)
Definition: list.c:339
#define lfirst_int(lc)
Definition: pg_list.h:173
@ ForwardScanDirection
Definition: sdir.h:28
struct ExecRowMark ** es_rowmarks
Definition: execnodes.h:663
int es_top_eflags
Definition: execnodes.h:717
int es_instrument
Definition: execnodes.h:718
QueryEnvironment * es_queryEnv
Definition: execnodes.h:705
ResultRelInfo ** es_result_relations
Definition: execnodes.h:683
List * es_range_table
Definition: execnodes.h:659
List * es_rteperminfos
Definition: execnodes.h:665
Bitmapset * es_unpruned_relids
Definition: execnodes.h:671
ParamListInfo es_param_list_info
Definition: execnodes.h:702
ScanDirection es_direction
Definition: execnodes.h:656
struct EPQState * es_epq_active
Definition: execnodes.h:741
Relation * es_relations
Definition: execnodes.h:661
CommandId es_output_cid
Definition: execnodes.h:680
Snapshot es_snapshot
Definition: execnodes.h:657
JunkFilter * es_junkFilter
Definition: execnodes.h:677
Snapshot es_crosscheck_snapshot
Definition: execnodes.h:658
List * subplans
Definition: plannodes.h:121

References EPQState::arowMarks, Assert(), CreateExecutorState(), EState::es_crosscheck_snapshot, EState::es_direction, EState::es_epq_active, EState::es_instrument, EState::es_junkFilter, EState::es_output_cid, EState::es_param_exec_vals, EState::es_param_list_info, EState::es_plannedstmt, EState::es_query_cxt, EState::es_queryEnv, EState::es_range_table, EState::es_range_table_size, EState::es_relations, EState::es_result_relations, EState::es_rowmarks, EState::es_rteperminfos, EState::es_snapshot, EState::es_subplanstates, EState::es_top_eflags, EState::es_unpruned_relids, ExecInitNode(), ExecSetParamPlanMulti(), Plan::extParam, ForwardScanDirection, GetPerTupleExprContext, i, ParamExecData::isnull, lappend(), lfirst, lfirst_int, list_length(), MemoryContextSwitchTo(), NIL, palloc0(), palloc0_array, palloc_array, PlannedStmt::paramExecTypes, EPQState::parentestate, EPQState::recheckestate, EPQState::recheckplanstate, EPQState::relsubs_blocked, EPQState::relsubs_done, EPQState::relsubs_rowmark, EPQState::resultRelations, ExecAuxRowMark::rowmark, ExecRowMark::rti, PlannedStmt::subplans, and ParamExecData::value.

Referenced by EvalPlanQualBegin().

◆ ExecBuildAuxRowMark()

ExecAuxRowMark * ExecBuildAuxRowMark ( ExecRowMark erm,
List targetlist 
)

Definition at line 2655 of file execMain.c.

2656{
2658 char resname[32];
2659
2660 aerm->rowmark = erm;
2661
2662 /* Look up the resjunk columns associated with this rowmark */
2663 if (erm->markType != ROW_MARK_COPY)
2664 {
2665 /* need ctid for all methods other than COPY */
2666 snprintf(resname, sizeof(resname), "ctid%u", erm->rowmarkId);
2667 aerm->ctidAttNo = ExecFindJunkAttributeInTlist(targetlist,
2668 resname);
2670 elog(ERROR, "could not find junk %s column", resname);
2671 }
2672 else
2673 {
2674 /* need wholerow if COPY */
2675 snprintf(resname, sizeof(resname), "wholerow%u", erm->rowmarkId);
2676 aerm->wholeAttNo = ExecFindJunkAttributeInTlist(targetlist,
2677 resname);
2679 elog(ERROR, "could not find junk %s column", resname);
2680 }
2681
2682 /* if child rel, need tableoid */
2683 if (erm->rti != erm->prti)
2684 {
2685 snprintf(resname, sizeof(resname), "tableoid%u", erm->rowmarkId);
2686 aerm->toidAttNo = ExecFindJunkAttributeInTlist(targetlist,
2687 resname);
2689 elog(ERROR, "could not find junk %s column", resname);
2690 }
2691
2692 return aerm;
2693}
#define AttributeNumberIsValid(attributeNumber)
Definition: attnum.h:34
AttrNumber ExecFindJunkAttributeInTlist(List *targetlist, const char *attrName)
Definition: execJunk.c:222
#define snprintf
Definition: port.h:239
Index rowmarkId
Definition: execnodes.h:800

References AttributeNumberIsValid, ExecAuxRowMark::ctidAttNo, elog, ERROR, ExecFindJunkAttributeInTlist(), ExecRowMark::markType, palloc0(), ExecRowMark::prti, ROW_MARK_COPY, ExecAuxRowMark::rowmark, ExecRowMark::rowmarkId, ExecRowMark::rti, snprintf, ExecAuxRowMark::toidAttNo, and ExecAuxRowMark::wholeAttNo.

Referenced by ExecInitLockRows(), and ExecInitModifyTable().

◆ ExecBuildSlotValueDescription()

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

Definition at line 2467 of file execMain.c.

2472{
2474 StringInfoData collist;
2475 bool write_comma = false;
2476 bool write_comma_collist = false;
2477 int i;
2478 AclResult aclresult;
2479 bool table_perm = false;
2480 bool any_perm = false;
2481
2482 /*
2483 * Check if RLS is enabled and should be active for the relation; if so,
2484 * then don't return anything. Otherwise, go through normal permission
2485 * checks.
2486 */
2487 if (check_enable_rls(reloid, InvalidOid, true) == RLS_ENABLED)
2488 return NULL;
2489
2491
2493
2494 /*
2495 * Check if the user has permissions to see the row. Table-level SELECT
2496 * allows access to all columns. If the user does not have table-level
2497 * SELECT then we check each column and include those the user has SELECT
2498 * rights on. Additionally, we always include columns the user provided
2499 * data for.
2500 */
2501 aclresult = pg_class_aclcheck(reloid, GetUserId(), ACL_SELECT);
2502 if (aclresult != ACLCHECK_OK)
2503 {
2504 /* Set up the buffer for the column list */
2505 initStringInfo(&collist);
2506 appendStringInfoChar(&collist, '(');
2507 }
2508 else
2509 table_perm = any_perm = true;
2510
2511 /* Make sure the tuple is fully deconstructed */
2512 slot_getallattrs(slot);
2513
2514 for (i = 0; i < tupdesc->natts; i++)
2515 {
2516 bool column_perm = false;
2517 char *val;
2518 int vallen;
2519 Form_pg_attribute att = TupleDescAttr(tupdesc, i);
2520
2521 /* ignore dropped columns */
2522 if (att->attisdropped)
2523 continue;
2524
2525 if (!table_perm)
2526 {
2527 /*
2528 * No table-level SELECT, so need to make sure they either have
2529 * SELECT rights on the column or that they have provided the data
2530 * for the column. If not, omit this column from the error
2531 * message.
2532 */
2533 aclresult = pg_attribute_aclcheck(reloid, att->attnum,
2536 modifiedCols) || aclresult == ACLCHECK_OK)
2537 {
2538 column_perm = any_perm = true;
2539
2540 if (write_comma_collist)
2541 appendStringInfoString(&collist, ", ");
2542 else
2543 write_comma_collist = true;
2544
2545 appendStringInfoString(&collist, NameStr(att->attname));
2546 }
2547 }
2548
2549 if (table_perm || column_perm)
2550 {
2551 if (att->attgenerated == ATTRIBUTE_GENERATED_VIRTUAL)
2552 val = "virtual";
2553 else if (slot->tts_isnull[i])
2554 val = "null";
2555 else
2556 {
2557 Oid foutoid;
2558 bool typisvarlena;
2559
2560 getTypeOutputInfo(att->atttypid,
2561 &foutoid, &typisvarlena);
2562 val = OidOutputFunctionCall(foutoid, slot->tts_values[i]);
2563 }
2564
2565 if (write_comma)
2567 else
2568 write_comma = true;
2569
2570 /* truncate if needed */
2571 vallen = strlen(val);
2572 if (vallen <= maxfieldlen)
2573 appendBinaryStringInfo(&buf, val, vallen);
2574 else
2575 {
2576 vallen = pg_mbcliplen(val, vallen, maxfieldlen);
2577 appendBinaryStringInfo(&buf, val, vallen);
2578 appendStringInfoString(&buf, "...");
2579 }
2580 }
2581 }
2582
2583 /* If we end up with zero columns being returned, then return NULL. */
2584 if (!any_perm)
2585 return NULL;
2586
2588
2589 if (!table_perm)
2590 {
2591 appendStringInfoString(&collist, ") = ");
2592 appendBinaryStringInfo(&collist, buf.data, buf.len);
2593
2594 return collist.data;
2595 }
2596
2597 return buf.data;
2598}
AclResult
Definition: acl.h:182
@ ACLCHECK_OK
Definition: acl.h:183
AclResult pg_attribute_aclcheck(Oid table_oid, AttrNumber attnum, Oid roleid, AclMode mode)
Definition: aclchk.c:3853
AclResult pg_class_aclcheck(Oid table_oid, Oid roleid, AclMode mode)
Definition: aclchk.c:4024
bool bms_is_member(int x, const Bitmapset *a)
Definition: bitmapset.c:510
#define NameStr(name)
Definition: c.h:717
char * OidOutputFunctionCall(Oid functionId, Datum val)
Definition: fmgr.c:1763
long val
Definition: informix.c:689
void getTypeOutputInfo(Oid type, Oid *typOutput, bool *typIsVarlena)
Definition: lsyscache.c:3047
int pg_mbcliplen(const char *mbstr, int len, int limit)
Definition: mbutils.c:1083
Oid GetUserId(void)
Definition: miscinit.c:520
#define ACL_SELECT
Definition: parsenodes.h:77
FormData_pg_attribute * Form_pg_attribute
Definition: pg_attribute.h:202
static char * buf
Definition: pg_test_fsync.c:72
#define InvalidOid
Definition: postgres_ext.h:35
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:127
Datum * tts_values
Definition: tuptable.h:125
#define FirstLowInvalidHeapAttributeNumber
Definition: sysattr.h:27
static FormData_pg_attribute * TupleDescAttr(TupleDesc tupdesc, int i)
Definition: tupdesc.h:160
static void slot_getallattrs(TupleTableSlot *slot)
Definition: tuptable.h:372

References ACL_SELECT, ACLCHECK_OK, appendBinaryStringInfo(), appendStringInfoChar(), appendStringInfoString(), bms_is_member(), buf, check_enable_rls(), StringInfoData::data, 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 build_tuple_value_details(), ExecConstraints(), ExecPartitionCheckEmitError(), ExecWithCheckOptions(), and ReportNotNullViolationError().

◆ ExecCheckOneRelPerms()

static bool ExecCheckOneRelPerms ( RTEPermissionInfo perminfo)
static

Definition at line 740 of file execMain.c.

741{
742 AclMode requiredPerms;
743 AclMode relPerms;
744 AclMode remainingPerms;
745 Oid userid;
746 Oid relOid = perminfo->relid;
747
748 requiredPerms = perminfo->requiredPerms;
749 Assert(requiredPerms != 0);
750
751 /*
752 * userid to check as: current user unless we have a setuid indication.
753 *
754 * Note: GetUserId() is presently fast enough that there's no harm in
755 * calling it separately for each relation. If that stops being true, we
756 * could call it once in ExecCheckPermissions and pass the userid down
757 * from there. But for now, no need for the extra clutter.
758 */
759 userid = OidIsValid(perminfo->checkAsUser) ?
760 perminfo->checkAsUser : GetUserId();
761
762 /*
763 * We must have *all* the requiredPerms bits, but some of the bits can be
764 * satisfied from column-level rather than relation-level permissions.
765 * First, remove any bits that are satisfied by relation permissions.
766 */
767 relPerms = pg_class_aclmask(relOid, userid, requiredPerms, ACLMASK_ALL);
768 remainingPerms = requiredPerms & ~relPerms;
769 if (remainingPerms != 0)
770 {
771 int col = -1;
772
773 /*
774 * If we lack any permissions that exist only as relation permissions,
775 * we can fail straight away.
776 */
777 if (remainingPerms & ~(ACL_SELECT | ACL_INSERT | ACL_UPDATE))
778 return false;
779
780 /*
781 * Check to see if we have the needed privileges at column level.
782 *
783 * Note: failures just report a table-level error; it would be nicer
784 * to report a column-level error if we have some but not all of the
785 * column privileges.
786 */
787 if (remainingPerms & ACL_SELECT)
788 {
789 /*
790 * When the query doesn't explicitly reference any columns (for
791 * example, SELECT COUNT(*) FROM table), allow the query if we
792 * have SELECT on any column of the rel, as per SQL spec.
793 */
794 if (bms_is_empty(perminfo->selectedCols))
795 {
796 if (pg_attribute_aclcheck_all(relOid, userid, ACL_SELECT,
798 return false;
799 }
800
801 while ((col = bms_next_member(perminfo->selectedCols, col)) >= 0)
802 {
803 /* bit #s are offset by FirstLowInvalidHeapAttributeNumber */
805
806 if (attno == InvalidAttrNumber)
807 {
808 /* Whole-row reference, must have priv on all cols */
809 if (pg_attribute_aclcheck_all(relOid, userid, ACL_SELECT,
811 return false;
812 }
813 else
814 {
815 if (pg_attribute_aclcheck(relOid, attno, userid,
817 return false;
818 }
819 }
820 }
821
822 /*
823 * Basically the same for the mod columns, for both INSERT and UPDATE
824 * privilege as specified by remainingPerms.
825 */
826 if (remainingPerms & ACL_INSERT &&
828 userid,
829 perminfo->insertedCols,
830 ACL_INSERT))
831 return false;
832
833 if (remainingPerms & ACL_UPDATE &&
835 userid,
836 perminfo->updatedCols,
837 ACL_UPDATE))
838 return false;
839 }
840 return true;
841}
@ ACLMASK_ANY
Definition: acl.h:177
@ ACLMASK_ALL
Definition: acl.h:176
AclResult pg_attribute_aclcheck_all(Oid table_oid, Oid roleid, AclMode mode, AclMaskHow how)
Definition: aclchk.c:3895
AclMode pg_class_aclmask(Oid table_oid, Oid roleid, AclMode mask, AclMaskHow how)
Definition: aclchk.c:3257
int16 AttrNumber
Definition: attnum.h:21
#define InvalidAttrNumber
Definition: attnum.h:23
int bms_next_member(const Bitmapset *a, int prevbit)
Definition: bitmapset.c:1306
#define bms_is_empty(a)
Definition: bitmapset.h:118
static bool ExecCheckPermissionsModified(Oid relOid, Oid userid, Bitmapset *modifiedCols, AclMode requiredPerms)
Definition: execMain.c:849
uint64 AclMode
Definition: parsenodes.h:74
#define ACL_INSERT
Definition: parsenodes.h:76
#define ACL_UPDATE
Definition: parsenodes.h:78
Bitmapset * selectedCols
Definition: parsenodes.h:1307
AclMode requiredPerms
Definition: parsenodes.h:1305
Bitmapset * insertedCols
Definition: parsenodes.h:1308
Bitmapset * updatedCols
Definition: parsenodes.h:1309

References ACL_INSERT, ACL_SELECT, ACL_UPDATE, ACLCHECK_OK, ACLMASK_ALL, ACLMASK_ANY, Assert(), bms_is_empty, bms_next_member(), RTEPermissionInfo::checkAsUser, ExecCheckPermissionsModified(), FirstLowInvalidHeapAttributeNumber, GetUserId(), RTEPermissionInfo::insertedCols, InvalidAttrNumber, OidIsValid, pg_attribute_aclcheck(), pg_attribute_aclcheck_all(), pg_class_aclmask(), RTEPermissionInfo::relid, RTEPermissionInfo::requiredPerms, RTEPermissionInfo::selectedCols, and RTEPermissionInfo::updatedCols.

Referenced by ExecCheckPermissions().

◆ ExecCheckPermissions()

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

Definition at line 661 of file execMain.c.

663{
664 ListCell *l;
665 bool result = true;
666
667#ifdef USE_ASSERT_CHECKING
668 Bitmapset *indexset = NULL;
669
670 /* Check that rteperminfos is consistent with rangeTable */
671 foreach(l, rangeTable)
672 {
674
675 if (rte->perminfoindex != 0)
676 {
677 /* Sanity checks */
678
679 /*
680 * Only relation RTEs and subquery RTEs that were once relation
681 * RTEs (views) have their perminfoindex set.
682 */
683 Assert(rte->rtekind == RTE_RELATION ||
684 (rte->rtekind == RTE_SUBQUERY &&
685 rte->relkind == RELKIND_VIEW));
686
687 /*
688 * Ensure that we have at least an AccessShareLock on relations
689 * whose permissions need to be checked.
690 *
691 * Skip this check in a parallel worker because locks won't be
692 * taken until ExecInitNode() performs plan initialization.
693 *
694 * XXX: ExecCheckPermissions() in a parallel worker may be
695 * redundant with the checks done in the leader process, so this
696 * should be reviewed to ensure it’s necessary.
697 */
700 true));
701
702 (void) getRTEPermissionInfo(rteperminfos, rte);
703 /* Many-to-one mapping not allowed */
704 Assert(!bms_is_member(rte->perminfoindex, indexset));
705 indexset = bms_add_member(indexset, rte->perminfoindex);
706 }
707 }
708
709 /* All rteperminfos are referenced */
710 Assert(bms_num_members(indexset) == list_length(rteperminfos));
711#endif
712
713 foreach(l, rteperminfos)
714 {
716
717 Assert(OidIsValid(perminfo->relid));
718 result = ExecCheckOneRelPerms(perminfo);
719 if (!result)
720 {
721 if (ereport_on_violation)
724 get_rel_name(perminfo->relid));
725 return false;
726 }
727 }
728
730 result = (*ExecutorCheckPerms_hook) (rangeTable, rteperminfos,
731 ereport_on_violation);
732 return result;
733}
@ ACLCHECK_NO_PRIV
Definition: acl.h:184
void aclcheck_error(AclResult aclerr, ObjectType objtype, const char *objectname)
Definition: aclchk.c:2639
int bms_num_members(const Bitmapset *a)
Definition: bitmapset.c:751
static bool ExecCheckOneRelPerms(RTEPermissionInfo *perminfo)
Definition: execMain.c:740
ExecutorCheckPerms_hook_type ExecutorCheckPerms_hook
Definition: execMain.c:76
#define IsParallelWorker()
Definition: parallel.h:60
bool CheckRelationOidLockedByMe(Oid relid, LOCKMODE lockmode, bool orstronger)
Definition: lmgr.c:351
#define AccessShareLock
Definition: lockdefs.h:36
char * get_rel_name(Oid relid)
Definition: lsyscache.c:2068
char get_rel_relkind(Oid relid)
Definition: lsyscache.c:2143
ObjectType get_relkind_objtype(char relkind)
RTEPermissionInfo * getRTEPermissionInfo(List *rteperminfos, RangeTblEntry *rte)
@ RTE_SUBQUERY
Definition: parsenodes.h:1027
@ RTE_RELATION
Definition: parsenodes.h:1026
#define lfirst_node(type, lc)
Definition: pg_list.h:176
RTEKind rtekind
Definition: parsenodes.h:1061

References AccessShareLock, aclcheck_error(), ACLCHECK_NO_PRIV, Assert(), bms_add_member(), bms_is_member(), bms_num_members(), CheckRelationOidLockedByMe(), ExecCheckOneRelPerms(), ExecutorCheckPerms_hook, get_rel_name(), get_rel_relkind(), get_relkind_objtype(), getRTEPermissionInfo(), IsParallelWorker, lfirst_node, list_length(), OidIsValid, RTEPermissionInfo::relid, RTE_RELATION, RTE_SUBQUERY, and RangeTblEntry::rtekind.

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

◆ ExecCheckPermissionsModified()

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

Definition at line 849 of file execMain.c.

851{
852 int col = -1;
853
854 /*
855 * When the query doesn't explicitly update any columns, allow the query
856 * if we have permission on any column of the rel. This is to handle
857 * SELECT FOR UPDATE as well as possible corner cases in UPDATE.
858 */
859 if (bms_is_empty(modifiedCols))
860 {
861 if (pg_attribute_aclcheck_all(relOid, userid, requiredPerms,
863 return false;
864 }
865
866 while ((col = bms_next_member(modifiedCols, col)) >= 0)
867 {
868 /* bit #s are offset by FirstLowInvalidHeapAttributeNumber */
870
871 if (attno == InvalidAttrNumber)
872 {
873 /* whole-row reference can't happen here */
874 elog(ERROR, "whole-row update is not implemented");
875 }
876 else
877 {
878 if (pg_attribute_aclcheck(relOid, attno, userid,
879 requiredPerms) != ACLCHECK_OK)
880 return false;
881 }
882 }
883 return true;
884}

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

Referenced by ExecCheckOneRelPerms().

◆ ExecCheckXactReadOnly()

static void ExecCheckXactReadOnly ( PlannedStmt plannedstmt)
static

Definition at line 896 of file execMain.c.

897{
898 ListCell *l;
899
900 /*
901 * Fail if write permissions are requested in parallel mode for table
902 * (temp or non-temp), otherwise fail for any non-temp table.
903 */
904 foreach(l, plannedstmt->permInfos)
905 {
907
908 if ((perminfo->requiredPerms & (~ACL_SELECT)) == 0)
909 continue;
910
912 continue;
913
915 }
916
917 if (plannedstmt->commandType != CMD_SELECT || plannedstmt->hasModifyingCTE)
919}
Oid get_rel_namespace(Oid relid)
Definition: lsyscache.c:2092
bool isTempNamespace(Oid namespaceId)
Definition: namespace.c:3649
@ CMD_SELECT
Definition: nodes.h:271
Definition: nodes.h:135
bool hasModifyingCTE
Definition: plannodes.h:65
List * permInfos
Definition: plannodes.h:102
CmdType commandType
Definition: plannodes.h:53
void PreventCommandIfReadOnly(const char *cmdname)
Definition: utility.c:404
void PreventCommandIfParallelMode(const char *cmdname)
Definition: utility.c:422
static const char * CreateCommandName(Node *parsetree)
Definition: utility.h:103

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

Referenced by standard_ExecutorStart().

◆ ExecCloseRangeTableRelations()

void ExecCloseRangeTableRelations ( EState estate)

Definition at line 1711 of file execMain.c.

1712{
1713 int i;
1714
1715 for (i = 0; i < estate->es_range_table_size; i++)
1716 {
1717 if (estate->es_relations[i])
1718 table_close(estate->es_relations[i], NoLock);
1719 }
1720}
#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 1651 of file execMain.c.

1652{
1653 ListCell *l;
1654
1655 /*
1656 * close indexes of result relation(s) if any. (Rels themselves are
1657 * closed in ExecCloseRangeTableRelations())
1658 *
1659 * In addition, close the stub RTs that may be in each resultrel's
1660 * ri_ancestorResultRels.
1661 */
1662 foreach(l, estate->es_opened_result_relations)
1663 {
1664 ResultRelInfo *resultRelInfo = lfirst(l);
1665 ListCell *lc;
1666
1667 ExecCloseIndices(resultRelInfo);
1668 foreach(lc, resultRelInfo->ri_ancestorResultRels)
1669 {
1670 ResultRelInfo *rInfo = lfirst(lc);
1671
1672 /*
1673 * Ancestors with RTI > 0 (should only be the root ancestor) are
1674 * closed by ExecCloseRangeTableRelations.
1675 */
1676 if (rInfo->ri_RangeTableIndex > 0)
1677 continue;
1678
1680 }
1681 }
1682
1683 /* Close any relations that have been opened by ExecGetTriggerResultRel(). */
1684 foreach(l, estate->es_trig_target_relations)
1685 {
1686 ResultRelInfo *resultRelInfo = (ResultRelInfo *) lfirst(l);
1687
1688 /*
1689 * Assert this is a "dummy" ResultRelInfo, see above. Otherwise we
1690 * might be issuing a duplicate close against a Relation opened by
1691 * ExecGetRangeTableRelation.
1692 */
1693 Assert(resultRelInfo->ri_RangeTableIndex == 0);
1694
1695 /*
1696 * Since ExecGetTriggerResultRel doesn't call ExecOpenIndices for
1697 * these rels, we needn't call ExecCloseIndices either.
1698 */
1699 Assert(resultRelInfo->ri_NumIndices == 0);
1700
1701 table_close(resultRelInfo->ri_RelationDesc, NoLock);
1702 }
1703}
void ExecCloseIndices(ResultRelInfo *resultRelInfo)
Definition: execIndexing.c:238
List * es_trig_target_relations
Definition: execnodes.h:699
List * es_opened_result_relations
Definition: execnodes.h:686
int ri_NumIndices
Definition: execnodes.h:478
Index ri_RangeTableIndex
Definition: execnodes.h:472
List * ri_ancestorResultRels
Definition: execnodes.h:625

References Assert(), EState::es_opened_result_relations, EState::es_trig_target_relations, ExecCloseIndices(), 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 2056 of file execMain.c.

2058{
2059 Relation rel = resultRelInfo->ri_RelationDesc;
2060 TupleDesc tupdesc = RelationGetDescr(rel);
2061 TupleConstr *constr = tupdesc->constr;
2062 Bitmapset *modifiedCols;
2063 List *notnull_virtual_attrs = NIL;
2064
2065 Assert(constr); /* we should not be called otherwise */
2066
2067 /*
2068 * Verify not-null constraints.
2069 *
2070 * Not-null constraints on virtual generated columns are collected and
2071 * checked separately below.
2072 */
2073 if (constr->has_not_null)
2074 {
2075 for (AttrNumber attnum = 1; attnum <= tupdesc->natts; attnum++)
2076 {
2077 Form_pg_attribute att = TupleDescAttr(tupdesc, attnum - 1);
2078
2079 if (att->attnotnull && att->attgenerated == ATTRIBUTE_GENERATED_VIRTUAL)
2080 notnull_virtual_attrs = lappend_int(notnull_virtual_attrs, attnum);
2081 else if (att->attnotnull && slot_attisnull(slot, attnum))
2082 ReportNotNullViolationError(resultRelInfo, slot, estate, attnum);
2083 }
2084 }
2085
2086 /*
2087 * Verify not-null constraints on virtual generated column, if any.
2088 */
2089 if (notnull_virtual_attrs)
2090 {
2092
2093 attnum = ExecRelGenVirtualNotNull(resultRelInfo, slot, estate,
2094 notnull_virtual_attrs);
2096 ReportNotNullViolationError(resultRelInfo, slot, estate, attnum);
2097 }
2098
2099 /*
2100 * Verify check constraints.
2101 */
2102 if (rel->rd_rel->relchecks > 0)
2103 {
2104 const char *failed;
2105
2106 if ((failed = ExecRelCheck(resultRelInfo, slot, estate)) != NULL)
2107 {
2108 char *val_desc;
2109 Relation orig_rel = rel;
2110
2111 /*
2112 * If the tuple has been routed, it's been converted to the
2113 * partition's rowtype, which might differ from the root table's.
2114 * We must convert it back to the root table's rowtype so that
2115 * val_desc shown error message matches the input tuple.
2116 */
2117 if (resultRelInfo->ri_RootResultRelInfo)
2118 {
2119 ResultRelInfo *rootrel = resultRelInfo->ri_RootResultRelInfo;
2120 TupleDesc old_tupdesc = RelationGetDescr(rel);
2121 AttrMap *map;
2122
2123 tupdesc = RelationGetDescr(rootrel->ri_RelationDesc);
2124 /* a reverse map */
2125 map = build_attrmap_by_name_if_req(old_tupdesc,
2126 tupdesc,
2127 false);
2128
2129 /*
2130 * Partition-specific slot's tupdesc can't be changed, so
2131 * allocate a new one.
2132 */
2133 if (map != NULL)
2134 slot = execute_attr_map_slot(map, slot,
2136 modifiedCols = bms_union(ExecGetInsertedCols(rootrel, estate),
2137 ExecGetUpdatedCols(rootrel, estate));
2138 rel = rootrel->ri_RelationDesc;
2139 }
2140 else
2141 modifiedCols = bms_union(ExecGetInsertedCols(resultRelInfo, estate),
2142 ExecGetUpdatedCols(resultRelInfo, estate));
2144 slot,
2145 tupdesc,
2146 modifiedCols,
2147 64);
2148 ereport(ERROR,
2149 (errcode(ERRCODE_CHECK_VIOLATION),
2150 errmsg("new row for relation \"%s\" violates check constraint \"%s\"",
2151 RelationGetRelationName(orig_rel), failed),
2152 val_desc ? errdetail("Failing row contains %s.", val_desc) : 0,
2153 errtableconstraint(orig_rel, failed)));
2154 }
2155 }
2156}
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,...)
Definition: elog.c:1204
static void ReportNotNullViolationError(ResultRelInfo *resultRelInfo, TupleTableSlot *slot, EState *estate, int attnum)
Definition: execMain.c:2235
char * ExecBuildSlotValueDescription(Oid reloid, TupleTableSlot *slot, TupleDesc tupdesc, Bitmapset *modifiedCols, int maxfieldlen)
Definition: execMain.c:2467
AttrNumber ExecRelGenVirtualNotNull(ResultRelInfo *resultRelInfo, TupleTableSlot *slot, EState *estate, List *notnull_virtual_attrs)
Definition: execMain.c:2170
static const char * ExecRelCheck(ResultRelInfo *resultRelInfo, TupleTableSlot *slot, EState *estate)
Definition: execMain.c:1854
const TupleTableSlotOps TTSOpsVirtual
Definition: execTuples.c:84
TupleTableSlot * MakeTupleTableSlot(TupleDesc tupleDesc, const TupleTableSlotOps *tts_ops)
Definition: execTuples.c:1301
Bitmapset * ExecGetInsertedCols(ResultRelInfo *relinfo, EState *estate)
Definition: execUtils.c:1362
Bitmapset * ExecGetUpdatedCols(ResultRelInfo *relinfo, EState *estate)
Definition: execUtils.c:1383
List * lappend_int(List *list, int datum)
Definition: list.c:357
int16 attnum
Definition: pg_attribute.h:74
#define RelationGetRelid(relation)
Definition: rel.h:516
#define RelationGetDescr(relation)
Definition: rel.h:542
int errtableconstraint(Relation rel, const char *conname)
Definition: relcache.c:6100
Definition: attmap.h:35
Definition: pg_list.h:54
struct ResultRelInfo * ri_RootResultRelInfo
Definition: execnodes.h:615
bool has_not_null
Definition: tupdesc.h:45
TupleConstr * constr
Definition: tupdesc.h:141
TupleTableSlot * execute_attr_map_slot(AttrMap *attrMap, TupleTableSlot *in_slot, TupleTableSlot *out_slot)
Definition: tupconvert.c:192
static bool slot_attisnull(TupleTableSlot *slot, int attnum)
Definition: tuptable.h:385

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(), 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 1612 of file execMain.c.

1613{
1614 ListCell *l;
1615
1616 /*
1617 * shut down the node-type-specific query processing
1618 */
1619 ExecEndNode(planstate);
1620
1621 /*
1622 * for subplans too
1623 */
1624 foreach(l, estate->es_subplanstates)
1625 {
1626 PlanState *subplanstate = (PlanState *) lfirst(l);
1627
1628 ExecEndNode(subplanstate);
1629 }
1630
1631 /*
1632 * destroy the executor's tuple table. Actually we only care about
1633 * releasing buffer pins and tupdesc refcounts; there's no need to pfree
1634 * the TupleTableSlots, since the containing memory context is about to go
1635 * away anyway.
1636 */
1637 ExecResetTupleTable(estate->es_tupleTable, false);
1638
1639 /*
1640 * Close any Relations that have been opened for range table entries or
1641 * result relations.
1642 */
1645}
void ExecCloseRangeTableRelations(EState *estate)
Definition: execMain.c:1711

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

Referenced by standard_ExecutorEnd().

◆ ExecFindRowMark()

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

Definition at line 2632 of file execMain.c.

2633{
2634 if (rti > 0 && rti <= estate->es_range_table_size &&
2635 estate->es_rowmarks != NULL)
2636 {
2637 ExecRowMark *erm = estate->es_rowmarks[rti - 1];
2638
2639 if (erm)
2640 return erm;
2641 }
2642 if (!missing_ok)
2643 elog(ERROR, "failed to find ExecRowMark for rangetable index %u", rti);
2644 return NULL;
2645}

References elog, ERROR, and EState::es_rowmarks.

Referenced by ExecInitLockRows(), and ExecInitModifyTable().

◆ ExecGetAncestorResultRels()

List * ExecGetAncestorResultRels ( EState estate,
ResultRelInfo resultRelInfo 
)

Definition at line 1506 of file execMain.c.

1507{
1508 ResultRelInfo *rootRelInfo = resultRelInfo->ri_RootResultRelInfo;
1509 Relation partRel = resultRelInfo->ri_RelationDesc;
1510 Oid rootRelOid;
1511
1512 if (!partRel->rd_rel->relispartition)
1513 elog(ERROR, "cannot find ancestors of a non-partition result relation");
1514 Assert(rootRelInfo != NULL);
1515 rootRelOid = RelationGetRelid(rootRelInfo->ri_RelationDesc);
1516 if (resultRelInfo->ri_ancestorResultRels == NIL)
1517 {
1518 ListCell *lc;
1520 List *ancResultRels = NIL;
1521
1522 foreach(lc, oids)
1523 {
1524 Oid ancOid = lfirst_oid(lc);
1525 Relation ancRel;
1526 ResultRelInfo *rInfo;
1527
1528 /*
1529 * Ignore the root ancestor here, and use ri_RootResultRelInfo
1530 * (below) for it instead. Also, we stop climbing up the
1531 * hierarchy when we find the table that was mentioned in the
1532 * query.
1533 */
1534 if (ancOid == rootRelOid)
1535 break;
1536
1537 /*
1538 * All ancestors up to the root target relation must have been
1539 * locked by the planner or AcquireExecutorLocks().
1540 */
1541 ancRel = table_open(ancOid, NoLock);
1542 rInfo = makeNode(ResultRelInfo);
1543
1544 /* dummy rangetable index */
1545 InitResultRelInfo(rInfo, ancRel, 0, NULL,
1546 estate->es_instrument);
1547 ancResultRels = lappend(ancResultRels, rInfo);
1548 }
1549 ancResultRels = lappend(ancResultRels, rootRelInfo);
1550 resultRelInfo->ri_ancestorResultRels = ancResultRels;
1551 }
1552
1553 /* We must have found some ancestor */
1554 Assert(resultRelInfo->ri_ancestorResultRels != NIL);
1555
1556 return resultRelInfo->ri_ancestorResultRels;
1557}
void InitResultRelInfo(ResultRelInfo *resultRelInfo, Relation resultRelationDesc, Index resultRelationIndex, ResultRelInfo *partition_root_rri, int instrument_options)
Definition: execMain.c:1329
#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, 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 1430 of file execMain.c.

1432{
1433 ResultRelInfo *rInfo;
1434 ListCell *l;
1435 Relation rel;
1436 MemoryContext oldcontext;
1437
1438 /* Search through the query result relations */
1439 foreach(l, estate->es_opened_result_relations)
1440 {
1441 rInfo = lfirst(l);
1442 if (RelationGetRelid(rInfo->ri_RelationDesc) == relid)
1443 return rInfo;
1444 }
1445
1446 /*
1447 * Search through the result relations that were created during tuple
1448 * routing, if any.
1449 */
1450 foreach(l, estate->es_tuple_routing_result_relations)
1451 {
1452 rInfo = (ResultRelInfo *) lfirst(l);
1453 if (RelationGetRelid(rInfo->ri_RelationDesc) == relid)
1454 return rInfo;
1455 }
1456
1457 /* Nope, but maybe we already made an extra ResultRelInfo for it */
1458 foreach(l, estate->es_trig_target_relations)
1459 {
1460 rInfo = (ResultRelInfo *) lfirst(l);
1461 if (RelationGetRelid(rInfo->ri_RelationDesc) == relid)
1462 return rInfo;
1463 }
1464 /* Nope, so we need a new one */
1465
1466 /*
1467 * Open the target relation's relcache entry. We assume that an
1468 * appropriate lock is still held by the backend from whenever the trigger
1469 * event got queued, so we need take no new lock here. Also, we need not
1470 * recheck the relkind, so no need for CheckValidResultRel.
1471 */
1472 rel = table_open(relid, NoLock);
1473
1474 /*
1475 * Make the new entry in the right context.
1476 */
1477 oldcontext = MemoryContextSwitchTo(estate->es_query_cxt);
1478 rInfo = makeNode(ResultRelInfo);
1479 InitResultRelInfo(rInfo,
1480 rel,
1481 0, /* dummy rangetable index */
1482 rootRelInfo,
1483 estate->es_instrument);
1484 estate->es_trig_target_relations =
1485 lappend(estate->es_trig_target_relations, rInfo);
1486 MemoryContextSwitchTo(oldcontext);
1487
1488 /*
1489 * Currently, we don't need any index information in ResultRelInfos used
1490 * only for triggers, so no need to call ExecOpenIndices.
1491 */
1492
1493 return rInfo;
1494}
List * es_tuple_routing_result_relations
Definition: execnodes.h:696

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

Referenced by afterTriggerInvokeEvents().

◆ ExecPartitionCheck()

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

Definition at line 1932 of file execMain.c.

1934{
1935 ExprContext *econtext;
1936 bool success;
1937
1938 /*
1939 * If first time through, build expression state tree for the partition
1940 * check expression. (In the corner case where the partition check
1941 * expression is empty, ie there's a default partition and nothing else,
1942 * we'll be fooled into executing this code each time through. But it's
1943 * pretty darn cheap in that case, so we don't worry about it.)
1944 */
1945 if (resultRelInfo->ri_PartitionCheckExpr == NULL)
1946 {
1947 /*
1948 * Ensure that the qual tree and prepared expression are in the
1949 * query-lifespan context.
1950 */
1952 List *qual = RelationGetPartitionQual(resultRelInfo->ri_RelationDesc);
1953
1954 resultRelInfo->ri_PartitionCheckExpr = ExecPrepareCheck(qual, estate);
1955 MemoryContextSwitchTo(oldcxt);
1956 }
1957
1958 /*
1959 * We will use the EState's per-tuple context for evaluating constraint
1960 * expressions (creating it if it's not already there).
1961 */
1962 econtext = GetPerTupleExprContext(estate);
1963
1964 /* Arrange for econtext's scan tuple to be the tuple under test */
1965 econtext->ecxt_scantuple = slot;
1966
1967 /*
1968 * As in case of the cataloged constraints, we treat a NULL result as
1969 * success here, not a failure.
1970 */
1971 success = ExecCheck(resultRelInfo->ri_PartitionCheckExpr, econtext);
1972
1973 /* if asked to emit error, don't actually return on failure */
1974 if (!success && emitError)
1975 ExecPartitionCheckEmitError(resultRelInfo, slot, estate);
1976
1977 return success;
1978}
bool ExecCheck(ExprState *state, ExprContext *econtext)
Definition: execExpr.c:872
ExprState * ExecPrepareCheck(List *qual, EState *estate)
Definition: execExpr.c:816
void ExecPartitionCheckEmitError(ResultRelInfo *resultRelInfo, TupleTableSlot *slot, EState *estate)
Definition: execMain.c:1985
static bool success
Definition: initdb.c:187
List * RelationGetPartitionQual(Relation rel)
Definition: partcache.c:277
TupleTableSlot * ecxt_scantuple
Definition: execnodes.h:268
ExprState * ri_PartitionCheckExpr
Definition: execnodes.h:587

References ExprContext::ecxt_scantuple, EState::es_query_cxt, ExecCheck(), ExecPartitionCheckEmitError(), ExecPrepareCheck(), 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 1985 of file execMain.c.

1988{
1989 Oid root_relid;
1990 TupleDesc tupdesc;
1991 char *val_desc;
1992 Bitmapset *modifiedCols;
1993
1994 /*
1995 * If the tuple has been routed, it's been converted to the partition's
1996 * rowtype, which might differ from the root table's. We must convert it
1997 * back to the root table's rowtype so that val_desc in the error message
1998 * matches the input tuple.
1999 */
2000 if (resultRelInfo->ri_RootResultRelInfo)
2001 {
2002 ResultRelInfo *rootrel = resultRelInfo->ri_RootResultRelInfo;
2003 TupleDesc old_tupdesc;
2004 AttrMap *map;
2005
2006 root_relid = RelationGetRelid(rootrel->ri_RelationDesc);
2007 tupdesc = RelationGetDescr(rootrel->ri_RelationDesc);
2008
2009 old_tupdesc = RelationGetDescr(resultRelInfo->ri_RelationDesc);
2010 /* a reverse map */
2011 map = build_attrmap_by_name_if_req(old_tupdesc, tupdesc, false);
2012
2013 /*
2014 * Partition-specific slot's tupdesc can't be changed, so allocate a
2015 * new one.
2016 */
2017 if (map != NULL)
2018 slot = execute_attr_map_slot(map, slot,
2020 modifiedCols = bms_union(ExecGetInsertedCols(rootrel, estate),
2021 ExecGetUpdatedCols(rootrel, estate));
2022 }
2023 else
2024 {
2025 root_relid = RelationGetRelid(resultRelInfo->ri_RelationDesc);
2026 tupdesc = RelationGetDescr(resultRelInfo->ri_RelationDesc);
2027 modifiedCols = bms_union(ExecGetInsertedCols(resultRelInfo, estate),
2028 ExecGetUpdatedCols(resultRelInfo, estate));
2029 }
2030
2031 val_desc = ExecBuildSlotValueDescription(root_relid,
2032 slot,
2033 tupdesc,
2034 modifiedCols,
2035 64);
2036 ereport(ERROR,
2037 (errcode(ERRCODE_CHECK_VIOLATION),
2038 errmsg("new row for relation \"%s\" violates partition constraint",
2040 val_desc ? errdetail("Failing row contains %s.", val_desc) : 0,
2041 errtable(resultRelInfo->ri_RelationDesc)));
2042}
int errtable(Relation rel)
Definition: relcache.c:6046

References bms_union(), build_attrmap_by_name_if_req(), ereport, errcode(), errdetail(), errmsg(), ERROR, errtable(), ExecBuildSlotValueDescription(), ExecGetInsertedCols(), ExecGetUpdatedCols(), execute_attr_map_slot(), 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 1566 of file execMain.c.

1567{
1568 ListCell *lc;
1569
1570 /*
1571 * Make sure nodes run forward.
1572 */
1574
1575 /*
1576 * Run any secondary ModifyTable nodes to completion, in case the main
1577 * query did not fetch all rows from them. (We do this to ensure that
1578 * such nodes have predictable results.)
1579 */
1580 foreach(lc, estate->es_auxmodifytables)
1581 {
1582 PlanState *ps = (PlanState *) lfirst(lc);
1583
1584 for (;;)
1585 {
1586 TupleTableSlot *slot;
1587
1588 /* Reset the per-output-tuple exprcontext each time */
1590
1591 slot = ExecProcNode(ps);
1592
1593 if (TupIsNull(slot))
1594 break;
1595 }
1596 }
1597}
#define ResetPerTupleExprContext(estate)
Definition: executor.h:687
struct parser_state ps
List * es_auxmodifytables
Definition: execnodes.h:726

References EState::es_auxmodifytables, EState::es_direction, ExecProcNode(), 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 1854 of file execMain.c.

1856{
1857 Relation rel = resultRelInfo->ri_RelationDesc;
1858 int ncheck = rel->rd_att->constr->num_check;
1859 ConstrCheck *check = rel->rd_att->constr->check;
1860 ExprContext *econtext;
1861 MemoryContext oldContext;
1862
1863 /*
1864 * CheckConstraintFetch let this pass with only a warning, but now we
1865 * should fail rather than possibly failing to enforce an important
1866 * constraint.
1867 */
1868 if (ncheck != rel->rd_rel->relchecks)
1869 elog(ERROR, "%d pg_constraint record(s) missing for relation \"%s\"",
1870 rel->rd_rel->relchecks - ncheck, RelationGetRelationName(rel));
1871
1872 /*
1873 * If first time through for this result relation, build expression
1874 * nodetrees for rel's constraint expressions. Keep them in the per-query
1875 * memory context so they'll survive throughout the query.
1876 */
1877 if (resultRelInfo->ri_CheckConstraintExprs == NULL)
1878 {
1879 oldContext = MemoryContextSwitchTo(estate->es_query_cxt);
1880 resultRelInfo->ri_CheckConstraintExprs = palloc0_array(ExprState *, ncheck);
1881 for (int i = 0; i < ncheck; i++)
1882 {
1883 Expr *checkconstr;
1884
1885 /* Skip not enforced constraint */
1886 if (!check[i].ccenforced)
1887 continue;
1888
1889 checkconstr = stringToNode(check[i].ccbin);
1890 checkconstr = (Expr *) expand_generated_columns_in_expr((Node *) checkconstr, rel, 1);
1891 resultRelInfo->ri_CheckConstraintExprs[i] =
1892 ExecPrepareExpr(checkconstr, estate);
1893 }
1894 MemoryContextSwitchTo(oldContext);
1895 }
1896
1897 /*
1898 * We will use the EState's per-tuple context for evaluating constraint
1899 * expressions (creating it if it's not already there).
1900 */
1901 econtext = GetPerTupleExprContext(estate);
1902
1903 /* Arrange for econtext's scan tuple to be the tuple under test */
1904 econtext->ecxt_scantuple = slot;
1905
1906 /* And evaluate the constraints */
1907 for (int i = 0; i < ncheck; i++)
1908 {
1909 ExprState *checkconstr = resultRelInfo->ri_CheckConstraintExprs[i];
1910
1911 /*
1912 * NOTE: SQL specifies that a NULL result from a constraint expression
1913 * is not to be treated as a failure. Therefore, use ExecCheck not
1914 * ExecQual.
1915 */
1916 if (checkconstr && !ExecCheck(checkconstr, econtext))
1917 return check[i].ccname;
1918 }
1919
1920 /* NULL result means no error */
1921 return NULL;
1922}
ExprState * ExecPrepareExpr(Expr *node, EState *estate)
Definition: execExpr.c:765
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:550
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(), 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 2170 of file execMain.c.

2172{
2173 Relation rel = resultRelInfo->ri_RelationDesc;
2174 ExprContext *econtext;
2175 MemoryContext oldContext;
2176
2177 /*
2178 * We implement this by building a NullTest node for each virtual
2179 * generated column, which we cache in resultRelInfo, and running those
2180 * through ExecCheck().
2181 */
2182 if (resultRelInfo->ri_GenVirtualNotNullConstraintExprs == NULL)
2183 {
2184 oldContext = MemoryContextSwitchTo(estate->es_query_cxt);
2186 palloc0_array(ExprState *, list_length(notnull_virtual_attrs));
2187
2188 foreach_int(attnum, notnull_virtual_attrs)
2189 {
2191 NullTest *nnulltest;
2192
2193 /* "generated_expression IS NOT NULL" check. */
2194 nnulltest = makeNode(NullTest);
2195 nnulltest->arg = (Expr *) build_generation_expression(rel, attnum);
2196 nnulltest->nulltesttype = IS_NOT_NULL;
2197 nnulltest->argisrow = false;
2198 nnulltest->location = -1;
2199
2200 resultRelInfo->ri_GenVirtualNotNullConstraintExprs[i] =
2201 ExecPrepareExpr((Expr *) nnulltest, estate);
2202 }
2203 MemoryContextSwitchTo(oldContext);
2204 }
2205
2206 /*
2207 * We will use the EState's per-tuple context for evaluating virtual
2208 * generated column not null constraint expressions (creating it if it's
2209 * not already there).
2210 */
2211 econtext = GetPerTupleExprContext(estate);
2212
2213 /* Arrange for econtext's scan tuple to be the tuple under test */
2214 econtext->ecxt_scantuple = slot;
2215
2216 /* And evaluate the check constraints for virtual generated column */
2217 foreach_int(attnum, notnull_virtual_attrs)
2218 {
2220 ExprState *exprstate = resultRelInfo->ri_GenVirtualNotNullConstraintExprs[i];
2221
2222 Assert(exprstate != NULL);
2223 if (!ExecCheck(exprstate, econtext))
2224 return attnum;
2225 }
2226
2227 /* InvalidAttrNumber result means no error */
2228 return InvalidAttrNumber;
2229}
#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:1957
Node * build_generation_expression(Relation rel, int attrno)
NullTestType nulltesttype
Definition: primnodes.h:1964
ParseLoc location
Definition: primnodes.h:1967
Expr * arg
Definition: primnodes.h:1963
ExprState ** ri_GenVirtualNotNullConstraintExprs
Definition: execnodes.h:556

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

Referenced by ATRewriteTable(), and ExecConstraints().

◆ ExecUpdateLockMode()

LockTupleMode ExecUpdateLockMode ( EState estate,
ResultRelInfo relinfo 
)

Definition at line 2606 of file execMain.c.

2607{
2608 Bitmapset *keyCols;
2609 Bitmapset *updatedCols;
2610
2611 /*
2612 * Compute lock mode to use. If columns that are part of the key have not
2613 * been modified, then we can use a weaker lock, allowing for better
2614 * concurrency.
2615 */
2616 updatedCols = ExecGetAllUpdatedCols(relinfo, estate);
2619
2620 if (bms_overlap(keyCols, updatedCols))
2621 return LockTupleExclusive;
2622
2624}
bool bms_overlap(const Bitmapset *a, const Bitmapset *b)
Definition: bitmapset.c:582
Bitmapset * ExecGetAllUpdatedCols(ResultRelInfo *relinfo, EState *estate)
Definition: execUtils.c:1419
@ LockTupleExclusive
Definition: lockoptions.h:58
@ LockTupleNoKeyExclusive
Definition: lockoptions.h:56
Bitmapset * RelationGetIndexAttrBitmap(Relation relation, IndexAttrBitmapKind attrKind)
Definition: relcache.c:5300
@ INDEX_ATTR_BITMAP_KEY
Definition: relcache.h:69

References bms_overlap(), ExecGetAllUpdatedCols(), INDEX_ATTR_BITMAP_KEY, LockTupleExclusive, LockTupleNoKeyExclusive, RelationGetIndexAttrBitmap(), and ResultRelInfo::ri_RelationDesc.

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 1732 of file execMain.c.

1738{
1739 EState *estate = queryDesc->estate;
1740 PlanState *planstate = queryDesc->planstate;
1741 bool use_parallel_mode;
1742 TupleTableSlot *slot;
1743 uint64 current_tuple_count;
1744
1745 /*
1746 * initialize local variables
1747 */
1748 current_tuple_count = 0;
1749
1750 /*
1751 * Set the direction.
1752 */
1753 estate->es_direction = direction;
1754
1755 /*
1756 * Set up parallel mode if appropriate.
1757 *
1758 * Parallel mode only supports complete execution of a plan. If we've
1759 * already partially executed it, or if the caller asks us to exit early,
1760 * we must force the plan to run without parallelism.
1761 */
1762 if (queryDesc->already_executed || numberTuples != 0)
1763 use_parallel_mode = false;
1764 else
1765 use_parallel_mode = queryDesc->plannedstmt->parallelModeNeeded;
1766 queryDesc->already_executed = true;
1767
1768 estate->es_use_parallel_mode = use_parallel_mode;
1769 if (use_parallel_mode)
1771
1772 /*
1773 * Loop until we've processed the proper number of tuples from the plan.
1774 */
1775 for (;;)
1776 {
1777 /* Reset the per-output-tuple exprcontext */
1779
1780 /*
1781 * Execute the plan and obtain a tuple
1782 */
1783 slot = ExecProcNode(planstate);
1784
1785 /*
1786 * if the tuple is null, then we assume there is nothing more to
1787 * process so we just end the loop...
1788 */
1789 if (TupIsNull(slot))
1790 break;
1791
1792 /*
1793 * If we have a junk filter, then project a new tuple with the junk
1794 * removed.
1795 *
1796 * Store this new "clean" tuple in the junkfilter's resultSlot.
1797 * (Formerly, we stored it back over the "dirty" tuple, which is WRONG
1798 * because that tuple slot has the wrong descriptor.)
1799 */
1800 if (estate->es_junkFilter != NULL)
1801 slot = ExecFilterJunk(estate->es_junkFilter, slot);
1802
1803 /*
1804 * If we are supposed to send the tuple somewhere, do so. (In
1805 * practice, this is probably always the case at this point.)
1806 */
1807 if (sendTuples)
1808 {
1809 /*
1810 * If we are not able to send the tuple, we assume the destination
1811 * has closed and no more tuples can be sent. If that's the case,
1812 * end the loop.
1813 */
1814 if (!dest->receiveSlot(slot, dest))
1815 break;
1816 }
1817
1818 /*
1819 * Count tuples processed, if this is a SELECT. (For other operation
1820 * types, the ModifyTable plan node must count the appropriate
1821 * events.)
1822 */
1823 if (operation == CMD_SELECT)
1824 (estate->es_processed)++;
1825
1826 /*
1827 * check our tuple count.. if we've processed the proper number then
1828 * quit, else loop again and process more tuples. Zero numberTuples
1829 * means no limit.
1830 */
1831 current_tuple_count++;
1832 if (numberTuples && numberTuples == current_tuple_count)
1833 break;
1834 }
1835
1836 /*
1837 * If we know we won't need to back up, we can release resources at this
1838 * point.
1839 */
1840 if (!(estate->es_top_eflags & EXEC_FLAG_BACKWARD))
1841 ExecShutdownNode(planstate);
1842
1843 if (use_parallel_mode)
1845}
uint64_t uint64
Definition: c.h:503
TupleTableSlot * ExecFilterJunk(JunkFilter *junkfilter, TupleTableSlot *slot)
Definition: execJunk.c:247
void ExecShutdownNode(PlanState *node)
Definition: execProcnode.c:772
#define EXEC_FLAG_BACKWARD
Definition: executor.h:69
uint64 es_processed
Definition: execnodes.h:712
bool es_use_parallel_mode
Definition: execnodes.h:743
bool parallelModeNeeded
Definition: plannodes.h:77
EState * estate
Definition: execdesc.h:49
bool already_executed
Definition: execdesc.h:53
PlannedStmt * plannedstmt
Definition: execdesc.h:37
PlanState * planstate
Definition: execdesc.h:50
void ExitParallelMode(void)
Definition: xact.c:1064
void EnterParallelMode(void)
Definition: xact.c:1051

References QueryDesc::already_executed, CMD_SELECT, generate_unaccent_rules::dest, 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(), PlannedStmt::parallelModeNeeded, QueryDesc::plannedstmt, QueryDesc::planstate, ResetPerTupleExprContext, and TupIsNull.

Referenced by standard_ExecutorRun().

◆ ExecutorEnd()

void ExecutorEnd ( QueryDesc queryDesc)

Definition at line 538 of file execMain.c.

539{
541 (*ExecutorEnd_hook) (queryDesc);
542 else
543 standard_ExecutorEnd(queryDesc);
544}
ExecutorEnd_hook_type ExecutorEnd_hook
Definition: execMain.c:73
void standard_ExecutorEnd(QueryDesc *queryDesc)
Definition: execMain.c:547

References ExecutorEnd_hook, and standard_ExecutorEnd().

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

◆ ExecutorFinish()

void ExecutorFinish ( QueryDesc queryDesc)

Definition at line 475 of file execMain.c.

476{
478 (*ExecutorFinish_hook) (queryDesc);
479 else
480 standard_ExecutorFinish(queryDesc);
481}
ExecutorFinish_hook_type ExecutorFinish_hook
Definition: execMain.c:72
void standard_ExecutorFinish(QueryDesc *queryDesc)
Definition: execMain.c:484

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 615 of file execMain.c.

616{
617 EState *estate;
618 MemoryContext oldcontext;
619
620 /* sanity checks */
621 Assert(queryDesc != NULL);
622
623 estate = queryDesc->estate;
624
625 Assert(estate != NULL);
626
627 /* It's probably not sensible to rescan updating queries */
628 Assert(queryDesc->operation == CMD_SELECT);
629
630 /*
631 * Switch into per-query memory context
632 */
633 oldcontext = MemoryContextSwitchTo(estate->es_query_cxt);
634
635 /*
636 * rescan plan
637 */
638 ExecReScan(queryDesc->planstate);
639
640 MemoryContextSwitchTo(oldcontext);
641}
void ExecReScan(PlanState *node)
Definition: execAmi.c:77
CmdType operation
Definition: execdesc.h:36

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

Referenced by DoPortalRewind(), and PersistHoldablePortal().

◆ ExecutorRun()

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

Definition at line 365 of file execMain.c.

367{
369 (*ExecutorRun_hook) (queryDesc, direction, count);
370 else
371 standard_ExecutorRun(queryDesc, direction, count);
372}
ExecutorRun_hook_type ExecutorRun_hook
Definition: execMain.c:71
void standard_ExecutorRun(QueryDesc *queryDesc, ScanDirection direction, uint64 count)
Definition: execMain.c:375

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()

bool ExecutorStart ( QueryDesc queryDesc,
int  eflags 
)

Definition at line 128 of file execMain.c.

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

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

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

◆ ExecutorStartCachedPlan()

void ExecutorStartCachedPlan ( QueryDesc queryDesc,
int  eflags,
CachedPlanSource plansource,
int  query_index 
)

Definition at line 295 of file execMain.c.

298{
299 if (unlikely(queryDesc->cplan == NULL))
300 elog(ERROR, "ExecutorStartCachedPlan(): missing CachedPlan");
301 if (unlikely(plansource == NULL))
302 elog(ERROR, "ExecutorStartCachedPlan(): missing CachedPlanSource");
303
304 /*
305 * Loop and retry with an updated plan until no further invalidation
306 * occurs.
307 */
308 while (1)
309 {
310 if (!ExecutorStart(queryDesc, eflags))
311 {
312 /*
313 * Clean up the current execution state before creating the new
314 * plan to retry ExecutorStart(). Mark execution as aborted to
315 * ensure that AFTER trigger state is properly reset.
316 */
317 queryDesc->estate->es_aborted = true;
318 ExecutorEnd(queryDesc);
319
320 /* Retry ExecutorStart() with an updated plan tree. */
321 queryDesc->plannedstmt = UpdateCachedPlan(plansource, query_index,
322 queryDesc->queryEnv);
323 }
324 else
325
326 /*
327 * Exit the loop if the plan is initialized successfully and no
328 * sinval messages were received that invalidated the CachedPlan.
329 */
330 break;
331 }
332}
#define unlikely(x)
Definition: c.h:347
bool ExecutorStart(QueryDesc *queryDesc, int eflags)
Definition: execMain.c:128
void ExecutorEnd(QueryDesc *queryDesc)
Definition: execMain.c:538
PlannedStmt * UpdateCachedPlan(CachedPlanSource *plansource, int query_index, QueryEnvironment *queryEnv)
Definition: plancache.c:1205
bool es_aborted
Definition: execnodes.h:720
CachedPlan * cplan
Definition: execdesc.h:38
QueryEnvironment * queryEnv
Definition: execdesc.h:44

References QueryDesc::cplan, elog, ERROR, EState::es_aborted, QueryDesc::estate, ExecutorEnd(), ExecutorStart(), QueryDesc::plannedstmt, QueryDesc::queryEnv, unlikely, and UpdateCachedPlan().

Referenced by _SPI_pquery(), ExplainOnePlan(), PortalStart(), and ProcessQuery().

◆ ExecWithCheckOptions()

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

Definition at line 2304 of file execMain.c.

2306{
2307 Relation rel = resultRelInfo->ri_RelationDesc;
2308 TupleDesc tupdesc = RelationGetDescr(rel);
2309 ExprContext *econtext;
2310 ListCell *l1,
2311 *l2;
2312
2313 /*
2314 * We will use the EState's per-tuple context for evaluating constraint
2315 * expressions (creating it if it's not already there).
2316 */
2317 econtext = GetPerTupleExprContext(estate);
2318
2319 /* Arrange for econtext's scan tuple to be the tuple under test */
2320 econtext->ecxt_scantuple = slot;
2321
2322 /* Check each of the constraints */
2323 forboth(l1, resultRelInfo->ri_WithCheckOptions,
2324 l2, resultRelInfo->ri_WithCheckOptionExprs)
2325 {
2326 WithCheckOption *wco = (WithCheckOption *) lfirst(l1);
2327 ExprState *wcoExpr = (ExprState *) lfirst(l2);
2328
2329 /*
2330 * Skip any WCOs which are not the kind we are looking for at this
2331 * time.
2332 */
2333 if (wco->kind != kind)
2334 continue;
2335
2336 /*
2337 * WITH CHECK OPTION checks are intended to ensure that the new tuple
2338 * is visible (in the case of a view) or that it passes the
2339 * 'with-check' policy (in the case of row security). If the qual
2340 * evaluates to NULL or FALSE, then the new tuple won't be included in
2341 * the view or doesn't pass the 'with-check' policy for the table.
2342 */
2343 if (!ExecQual(wcoExpr, econtext))
2344 {
2345 char *val_desc;
2346 Bitmapset *modifiedCols;
2347
2348 switch (wco->kind)
2349 {
2350 /*
2351 * For WITH CHECK OPTIONs coming from views, we might be
2352 * able to provide the details on the row, depending on
2353 * the permissions on the relation (that is, if the user
2354 * could view it directly anyway). For RLS violations, we
2355 * don't include the data since we don't know if the user
2356 * should be able to view the tuple as that depends on the
2357 * USING policy.
2358 */
2359 case WCO_VIEW_CHECK:
2360 /* See the comment in ExecConstraints(). */
2361 if (resultRelInfo->ri_RootResultRelInfo)
2362 {
2363 ResultRelInfo *rootrel = resultRelInfo->ri_RootResultRelInfo;
2364 TupleDesc old_tupdesc = RelationGetDescr(rel);
2365 AttrMap *map;
2366
2367 tupdesc = RelationGetDescr(rootrel->ri_RelationDesc);
2368 /* a reverse map */
2369 map = build_attrmap_by_name_if_req(old_tupdesc,
2370 tupdesc,
2371 false);
2372
2373 /*
2374 * Partition-specific slot's tupdesc can't be changed,
2375 * so allocate a new one.
2376 */
2377 if (map != NULL)
2378 slot = execute_attr_map_slot(map, slot,
2380
2381 modifiedCols = bms_union(ExecGetInsertedCols(rootrel, estate),
2382 ExecGetUpdatedCols(rootrel, estate));
2383 rel = rootrel->ri_RelationDesc;
2384 }
2385 else
2386 modifiedCols = bms_union(ExecGetInsertedCols(resultRelInfo, estate),
2387 ExecGetUpdatedCols(resultRelInfo, estate));
2389 slot,
2390 tupdesc,
2391 modifiedCols,
2392 64);
2393
2394 ereport(ERROR,
2395 (errcode(ERRCODE_WITH_CHECK_OPTION_VIOLATION),
2396 errmsg("new row violates check option for view \"%s\"",
2397 wco->relname),
2398 val_desc ? errdetail("Failing row contains %s.",
2399 val_desc) : 0));
2400 break;
2403 if (wco->polname != NULL)
2404 ereport(ERROR,
2405 (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
2406 errmsg("new row violates row-level security policy \"%s\" for table \"%s\"",
2407 wco->polname, wco->relname)));
2408 else
2409 ereport(ERROR,
2410 (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
2411 errmsg("new row violates row-level security policy for table \"%s\"",
2412 wco->relname)));
2413 break;
2416 if (wco->polname != NULL)
2417 ereport(ERROR,
2418 (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
2419 errmsg("target row violates row-level security policy \"%s\" (USING expression) for table \"%s\"",
2420 wco->polname, wco->relname)));
2421 else
2422 ereport(ERROR,
2423 (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
2424 errmsg("target row violates row-level security policy (USING expression) for table \"%s\"",
2425 wco->relname)));
2426 break;
2428 if (wco->polname != NULL)
2429 ereport(ERROR,
2430 (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
2431 errmsg("new row violates row-level security policy \"%s\" (USING expression) for table \"%s\"",
2432 wco->polname, wco->relname)));
2433 else
2434 ereport(ERROR,
2435 (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
2436 errmsg("new row violates row-level security policy (USING expression) for table \"%s\"",
2437 wco->relname)));
2438 break;
2439 default:
2440 elog(ERROR, "unrecognized WCO kind: %u", wco->kind);
2441 break;
2442 }
2443 }
2444 }
2445}
static bool ExecQual(ExprState *state, ExprContext *econtext)
Definition: executor.h:541
@ WCO_RLS_MERGE_UPDATE_CHECK
Definition: parsenodes.h:1377
@ WCO_RLS_CONFLICT_CHECK
Definition: parsenodes.h:1376
@ WCO_RLS_INSERT_CHECK
Definition: parsenodes.h:1374
@ WCO_VIEW_CHECK
Definition: parsenodes.h:1373
@ WCO_RLS_UPDATE_CHECK
Definition: parsenodes.h:1375
@ WCO_RLS_MERGE_DELETE_CHECK
Definition: parsenodes.h:1378
#define forboth(cell1, list1, cell2, list2)
Definition: pg_list.h:518
List * ri_WithCheckOptions
Definition: execnodes.h:544
List * ri_WithCheckOptionExprs
Definition: execnodes.h:547

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(), forboth, GetPerTupleExprContext, WithCheckOption::kind, lfirst, MakeTupleTableSlot(), WithCheckOption::polname, RelationGetDescr, RelationGetRelid, WithCheckOption::relname, 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(), ExecOnConflictUpdate(), ExecUpdateAct(), and ExecUpdateEpilogue().

◆ InitPlan()

static void InitPlan ( QueryDesc queryDesc,
int  eflags 
)
static

Definition at line 936 of file execMain.c.

937{
938 CmdType operation = queryDesc->operation;
939 PlannedStmt *plannedstmt = queryDesc->plannedstmt;
940 CachedPlan *cachedplan = queryDesc->cplan;
941 Plan *plan = plannedstmt->planTree;
942 List *rangeTable = plannedstmt->rtable;
943 EState *estate = queryDesc->estate;
944 PlanState *planstate;
945 TupleDesc tupType;
946 ListCell *l;
947 int i;
948
949 /*
950 * Do permissions checks
951 */
952 ExecCheckPermissions(rangeTable, plannedstmt->permInfos, true);
953
954 /*
955 * initialize the node's execution state
956 */
957 ExecInitRangeTable(estate, rangeTable, plannedstmt->permInfos,
958 bms_copy(plannedstmt->unprunableRelids));
959
960 estate->es_plannedstmt = plannedstmt;
961 estate->es_cachedplan = cachedplan;
962 estate->es_part_prune_infos = plannedstmt->partPruneInfos;
963
964 /*
965 * Perform runtime "initial" pruning to identify which child subplans,
966 * corresponding to the children of plan nodes that contain
967 * PartitionPruneInfo such as Append, will not be executed. The results,
968 * which are bitmapsets of indexes of the child subplans that will be
969 * executed, are saved in es_part_prune_results. These results correspond
970 * to each PartitionPruneInfo entry, and the es_part_prune_results list is
971 * parallel to es_part_prune_infos.
972 */
973 ExecDoInitialPruning(estate);
974
975 if (!ExecPlanStillValid(estate))
976 return;
977
978 /*
979 * Next, build the ExecRowMark array from the PlanRowMark(s), if any.
980 */
981 if (plannedstmt->rowMarks)
982 {
983 estate->es_rowmarks = (ExecRowMark **)
984 palloc0(estate->es_range_table_size * sizeof(ExecRowMark *));
985 foreach(l, plannedstmt->rowMarks)
986 {
987 PlanRowMark *rc = (PlanRowMark *) lfirst(l);
988 Oid relid;
989 Relation relation;
990 ExecRowMark *erm;
991
992 /*
993 * Ignore "parent" rowmarks, because they are irrelevant at
994 * runtime. Also ignore the rowmarks belonging to child tables
995 * that have been pruned in ExecDoInitialPruning().
996 */
997 if (rc->isParent ||
998 !bms_is_member(rc->rti, estate->es_unpruned_relids))
999 continue;
1000
1001 /* get relation's OID (will produce InvalidOid if subquery) */
1002 relid = exec_rt_fetch(rc->rti, estate)->relid;
1003
1004 /* open relation, if we need to access it for this mark type */
1005 switch (rc->markType)
1006 {
1007 case ROW_MARK_EXCLUSIVE:
1009 case ROW_MARK_SHARE:
1010 case ROW_MARK_KEYSHARE:
1011 case ROW_MARK_REFERENCE:
1012 relation = ExecGetRangeTableRelation(estate, rc->rti, false);
1013 break;
1014 case ROW_MARK_COPY:
1015 /* no physical table access is required */
1016 relation = NULL;
1017 break;
1018 default:
1019 elog(ERROR, "unrecognized markType: %d", rc->markType);
1020 relation = NULL; /* keep compiler quiet */
1021 break;
1022 }
1023
1024 /* Check that relation is a legal target for marking */
1025 if (relation)
1026 CheckValidRowMarkRel(relation, rc->markType);
1027
1028 erm = (ExecRowMark *) palloc(sizeof(ExecRowMark));
1029 erm->relation = relation;
1030 erm->relid = relid;
1031 erm->rti = rc->rti;
1032 erm->prti = rc->prti;
1033 erm->rowmarkId = rc->rowmarkId;
1034 erm->markType = rc->markType;
1035 erm->strength = rc->strength;
1036 erm->waitPolicy = rc->waitPolicy;
1037 erm->ermActive = false;
1039 erm->ermExtra = NULL;
1040
1041 Assert(erm->rti > 0 && erm->rti <= estate->es_range_table_size &&
1042 estate->es_rowmarks[erm->rti - 1] == NULL);
1043
1044 estate->es_rowmarks[erm->rti - 1] = erm;
1045 }
1046 }
1047
1048 /*
1049 * Initialize the executor's tuple table to empty.
1050 */
1051 estate->es_tupleTable = NIL;
1052
1053 /* signal that this EState is not used for EPQ */
1054 estate->es_epq_active = NULL;
1055
1056 /*
1057 * Initialize private state information for each SubPlan. We must do this
1058 * before running ExecInitNode on the main query tree, since
1059 * ExecInitSubPlan expects to be able to find these entries.
1060 */
1061 Assert(estate->es_subplanstates == NIL);
1062 i = 1; /* subplan indices count from 1 */
1063 foreach(l, plannedstmt->subplans)
1064 {
1065 Plan *subplan = (Plan *) lfirst(l);
1066 PlanState *subplanstate;
1067 int sp_eflags;
1068
1069 /*
1070 * A subplan will never need to do BACKWARD scan nor MARK/RESTORE. If
1071 * it is a parameterless subplan (not initplan), we suggest that it be
1072 * prepared to handle REWIND efficiently; otherwise there is no need.
1073 */
1074 sp_eflags = eflags
1076 if (bms_is_member(i, plannedstmt->rewindPlanIDs))
1077 sp_eflags |= EXEC_FLAG_REWIND;
1078
1079 subplanstate = ExecInitNode(subplan, estate, sp_eflags);
1080
1081 estate->es_subplanstates = lappend(estate->es_subplanstates,
1082 subplanstate);
1083
1084 i++;
1085 }
1086
1087 /*
1088 * Initialize the private state information for all the nodes in the query
1089 * tree. This opens files, allocates storage and leaves us ready to start
1090 * processing tuples.
1091 */
1092 planstate = ExecInitNode(plan, estate, eflags);
1093
1094 /*
1095 * Get the tuple descriptor describing the type of tuples to return.
1096 */
1097 tupType = ExecGetResultType(planstate);
1098
1099 /*
1100 * Initialize the junk filter if needed. SELECT queries need a filter if
1101 * there are any junk attrs in the top-level tlist.
1102 */
1103 if (operation == CMD_SELECT)
1104 {
1105 bool junk_filter_needed = false;
1106 ListCell *tlist;
1107
1108 foreach(tlist, plan->targetlist)
1109 {
1110 TargetEntry *tle = (TargetEntry *) lfirst(tlist);
1111
1112 if (tle->resjunk)
1113 {
1114 junk_filter_needed = true;
1115 break;
1116 }
1117 }
1118
1119 if (junk_filter_needed)
1120 {
1121 JunkFilter *j;
1122 TupleTableSlot *slot;
1123
1124 slot = ExecInitExtraTupleSlot(estate, NULL, &TTSOpsVirtual);
1125 j = ExecInitJunkFilter(planstate->plan->targetlist,
1126 slot);
1127 estate->es_junkFilter = j;
1128
1129 /* Want to return the cleaned tuple type */
1130 tupType = j->jf_cleanTupType;
1131 }
1132 }
1133
1134 queryDesc->tupDesc = tupType;
1135 queryDesc->planstate = planstate;
1136}
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:1264
bool ExecCheckPermissions(List *rangeTable, List *rteperminfos, bool ereport_on_violation)
Definition: execMain.c:661
void ExecDoInitialPruning(EState *estate)
TupleTableSlot * ExecInitExtraTupleSlot(EState *estate, TupleDesc tupledesc, const TupleTableSlotOps *tts_ops)
Definition: execTuples.c:2020
TupleDesc ExecGetResultType(PlanState *planstate)
Definition: execUtils.c:496
Relation ExecGetRangeTableRelation(EState *estate, Index rti, bool isResultRel)
Definition: execUtils.c:826
void ExecInitRangeTable(EState *estate, List *rangeTable, List *permInfos, Bitmapset *unpruned_relids)
Definition: execUtils.c:774
#define EXEC_FLAG_REWIND
Definition: executor.h:68
static RangeTblEntry * exec_rt_fetch(Index rti, EState *estate)
Definition: executor.h:719
static bool ExecPlanStillValid(EState *estate)
Definition: executor.h:311
#define EXEC_FLAG_MARK
Definition: executor.h:70
int j
Definition: isn.c:78
static void ItemPointerSetInvalid(ItemPointerData *pointer)
Definition: itemptr.h:184
void * palloc(Size size)
Definition: mcxt.c:1940
CmdType
Definition: nodes.h:269
#define plan(x)
Definition: pg_regress.c:161
@ ROW_MARK_SHARE
Definition: plannodes.h:1488
@ ROW_MARK_EXCLUSIVE
Definition: plannodes.h:1486
@ ROW_MARK_NOKEYEXCLUSIVE
Definition: plannodes.h:1487
@ ROW_MARK_KEYSHARE
Definition: plannodes.h:1489
List * es_part_prune_infos
Definition: execnodes.h:668
CachedPlan * es_cachedplan
Definition: execnodes.h:667
ItemPointerData curCtid
Definition: execnodes.h:805
LockClauseStrength strength
Definition: execnodes.h:802
bool ermActive
Definition: execnodes.h:804
LockWaitPolicy waitPolicy
Definition: execnodes.h:803
void * ermExtra
Definition: execnodes.h:806
LockClauseStrength strength
Definition: plannodes.h:1550
Index prti
Definition: plannodes.h:1542
RowMarkType markType
Definition: plannodes.h:1546
LockWaitPolicy waitPolicy
Definition: plannodes.h:1552
bool isParent
Definition: plannodes.h:1554
Index rowmarkId
Definition: plannodes.h:1544
List * targetlist
Definition: plannodes.h:209
struct Plan * planTree
Definition: plannodes.h:83
List * rowMarks
Definition: plannodes.h:127
Bitmapset * rewindPlanIDs
Definition: plannodes.h:124
Bitmapset * unprunableRelids
Definition: plannodes.h:97
List * rtable
Definition: plannodes.h:91
List * partPruneInfos
Definition: plannodes.h:88
TupleDesc tupDesc
Definition: execdesc.h:48

References Assert(), bms_copy(), bms_is_member(), CheckValidRowMarkRel(), CMD_SELECT, QueryDesc::cplan, ExecRowMark::curCtid, elog, ExecRowMark::ermActive, ExecRowMark::ermExtra, ERROR, EState::es_cachedplan, 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(), ExecPlanStillValid(), i, PlanRowMark::isParent, ItemPointerSetInvalid(), j, lappend(), lfirst, ExecRowMark::markType, PlanRowMark::markType, NIL, QueryDesc::operation, palloc(), palloc0(), PlannedStmt::partPruneInfos, PlannedStmt::permInfos, PlanState::plan, plan, QueryDesc::plannedstmt, QueryDesc::planstate, PlannedStmt::planTree, ExecRowMark::prti, PlanRowMark::prti, ExecRowMark::relation, ExecRowMark::relid, PlannedStmt::rewindPlanIDs, ROW_MARK_COPY, ROW_MARK_EXCLUSIVE, ROW_MARK_KEYSHARE, ROW_MARK_NOKEYEXCLUSIVE, ROW_MARK_REFERENCE, ROW_MARK_SHARE, ExecRowMark::rowmarkId, PlanRowMark::rowmarkId, PlannedStmt::rowMarks, PlannedStmt::rtable, ExecRowMark::rti, PlanRowMark::rti, ExecRowMark::strength, PlanRowMark::strength, PlannedStmt::subplans, Plan::targetlist, TTSOpsVirtual, QueryDesc::tupDesc, PlannedStmt::unprunableRelids, ExecRowMark::waitPolicy, 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 1329 of file execMain.c.

1334{
1335 MemSet(resultRelInfo, 0, sizeof(ResultRelInfo));
1336 resultRelInfo->type = T_ResultRelInfo;
1337 resultRelInfo->ri_RangeTableIndex = resultRelationIndex;
1338 resultRelInfo->ri_RelationDesc = resultRelationDesc;
1339 resultRelInfo->ri_NumIndices = 0;
1340 resultRelInfo->ri_IndexRelationDescs = NULL;
1341 resultRelInfo->ri_IndexRelationInfo = NULL;
1342 resultRelInfo->ri_needLockTagTuple =
1343 IsInplaceUpdateRelation(resultRelationDesc);
1344 /* make a copy so as not to depend on relcache info not changing... */
1345 resultRelInfo->ri_TrigDesc = CopyTriggerDesc(resultRelationDesc->trigdesc);
1346 if (resultRelInfo->ri_TrigDesc)
1347 {
1348 int n = resultRelInfo->ri_TrigDesc->numtriggers;
1349
1350 resultRelInfo->ri_TrigFunctions = (FmgrInfo *)
1351 palloc0(n * sizeof(FmgrInfo));
1352 resultRelInfo->ri_TrigWhenExprs = (ExprState **)
1353 palloc0(n * sizeof(ExprState *));
1354 if (instrument_options)
1355 resultRelInfo->ri_TrigInstrument = InstrAlloc(n, instrument_options, false);
1356 }
1357 else
1358 {
1359 resultRelInfo->ri_TrigFunctions = NULL;
1360 resultRelInfo->ri_TrigWhenExprs = NULL;
1361 resultRelInfo->ri_TrigInstrument = NULL;
1362 }
1363 if (resultRelationDesc->rd_rel->relkind == RELKIND_FOREIGN_TABLE)
1364 resultRelInfo->ri_FdwRoutine = GetFdwRoutineForRelation(resultRelationDesc, true);
1365 else
1366 resultRelInfo->ri_FdwRoutine = NULL;
1367
1368 /* The following fields are set later if needed */
1369 resultRelInfo->ri_RowIdAttNo = 0;
1370 resultRelInfo->ri_extraUpdatedCols = NULL;
1371 resultRelInfo->ri_projectNew = NULL;
1372 resultRelInfo->ri_newTupleSlot = NULL;
1373 resultRelInfo->ri_oldTupleSlot = NULL;
1374 resultRelInfo->ri_projectNewInfoValid = false;
1375 resultRelInfo->ri_FdwState = NULL;
1376 resultRelInfo->ri_usesFdwDirectModify = false;
1377 resultRelInfo->ri_CheckConstraintExprs = NULL;
1378 resultRelInfo->ri_GenVirtualNotNullConstraintExprs = NULL;
1379 resultRelInfo->ri_GeneratedExprsI = NULL;
1380 resultRelInfo->ri_GeneratedExprsU = NULL;
1381 resultRelInfo->ri_projectReturning = NULL;
1382 resultRelInfo->ri_onConflictArbiterIndexes = NIL;
1383 resultRelInfo->ri_onConflict = NULL;
1384 resultRelInfo->ri_ReturningSlot = NULL;
1385 resultRelInfo->ri_TrigOldSlot = NULL;
1386 resultRelInfo->ri_TrigNewSlot = NULL;
1387 resultRelInfo->ri_AllNullSlot = NULL;
1388 resultRelInfo->ri_MergeActions[MERGE_WHEN_MATCHED] = NIL;
1391 resultRelInfo->ri_MergeJoinCondition = NULL;
1392
1393 /*
1394 * Only ExecInitPartitionInfo() and ExecInitPartitionDispatchInfo() pass
1395 * non-NULL partition_root_rri. For child relations that are part of the
1396 * initial query rather than being dynamically added by tuple routing,
1397 * this field is filled in ExecInitModifyTable().
1398 */
1399 resultRelInfo->ri_RootResultRelInfo = partition_root_rri;
1400 /* Set by ExecGetRootToChildMap */
1401 resultRelInfo->ri_RootToChildMap = NULL;
1402 resultRelInfo->ri_RootToChildMapValid = false;
1403 /* Set by ExecInitRoutingInfo */
1404 resultRelInfo->ri_PartitionTupleSlot = NULL;
1405 resultRelInfo->ri_ChildToRootMap = NULL;
1406 resultRelInfo->ri_ChildToRootMapValid = false;
1407 resultRelInfo->ri_CopyMultiInsertBuffer = NULL;
1408}
#define MemSet(start, val, len)
Definition: c.h:991
Instrumentation * InstrAlloc(int n, int instrument_options, bool async_mode)
Definition: instrument.c:31
@ MERGE_WHEN_NOT_MATCHED_BY_TARGET
Definition: primnodes.h:2003
@ MERGE_WHEN_NOT_MATCHED_BY_SOURCE
Definition: primnodes.h:2002
@ MERGE_WHEN_MATCHED
Definition: primnodes.h:2001
Definition: fmgr.h:57
TriggerDesc * trigdesc
Definition: rel.h:117
TupleConversionMap * ri_RootToChildMap
Definition: execnodes.h:601
TupleTableSlot * ri_PartitionTupleSlot
Definition: execnodes.h:616
bool ri_projectNewInfoValid
Definition: execnodes.h:504
OnConflictSetState * ri_onConflict
Definition: execnodes.h:578
List * ri_onConflictArbiterIndexes
Definition: execnodes.h:575
Instrumentation * ri_TrigInstrument
Definition: execnodes.h:519
ExprState * ri_MergeJoinCondition
Definition: execnodes.h:584
RelationPtr ri_IndexRelationDescs
Definition: execnodes.h:481
TupleTableSlot * ri_ReturningSlot
Definition: execnodes.h:522
TupleTableSlot * ri_oldTupleSlot
Definition: execnodes.h:502
bool ri_RootToChildMapValid
Definition: execnodes.h:602
struct CopyMultiInsertBuffer * ri_CopyMultiInsertBuffer
Definition: execnodes.h:619
TriggerDesc * ri_TrigDesc
Definition: execnodes.h:510
TupleTableSlot * ri_AllNullSlot
Definition: execnodes.h:525
Bitmapset * ri_extraUpdatedCols
Definition: execnodes.h:493
ExprState ** ri_GeneratedExprsI
Definition: execnodes.h:561
TupleConversionMap * ri_ChildToRootMap
Definition: execnodes.h:595
void * ri_FdwState
Definition: execnodes.h:531
bool ri_ChildToRootMapValid
Definition: execnodes.h:596
List * ri_MergeActions[NUM_MERGE_MATCH_KINDS]
Definition: execnodes.h:581
TupleTableSlot * ri_newTupleSlot
Definition: execnodes.h:500
ProjectionInfo * ri_projectNew
Definition: execnodes.h:498
NodeTag type
Definition: execnodes.h:469
ProjectionInfo * ri_projectReturning
Definition: execnodes.h:572
ExprState ** ri_GeneratedExprsU
Definition: execnodes.h:562
ExprState ** ri_TrigWhenExprs
Definition: execnodes.h:516
FmgrInfo * ri_TrigFunctions
Definition: execnodes.h:513
bool ri_usesFdwDirectModify
Definition: execnodes.h:534
AttrNumber ri_RowIdAttNo
Definition: execnodes.h:490
IndexInfo ** ri_IndexRelationInfo
Definition: execnodes.h:484
TupleTableSlot * ri_TrigNewSlot
Definition: execnodes.h:524
TupleTableSlot * ri_TrigOldSlot
Definition: execnodes.h:523
int numtriggers
Definition: reltrigger.h:50
TriggerDesc * CopyTriggerDesc(TriggerDesc *trigdesc)
Definition: trigger.c:2090

References CopyTriggerDesc(), GetFdwRoutineForRelation(), InstrAlloc(), IsInplaceUpdateRelation(), MemSet, MERGE_WHEN_MATCHED, MERGE_WHEN_NOT_MATCHED_BY_SOURCE, MERGE_WHEN_NOT_MATCHED_BY_TARGET, NIL, TriggerDesc::numtriggers, palloc0(), RelationData::rd_rel, 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, RelationData::trigdesc, 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 2235 of file execMain.c.

2237{
2238 Bitmapset *modifiedCols;
2239 char *val_desc;
2240 Relation rel = resultRelInfo->ri_RelationDesc;
2241 Relation orig_rel = rel;
2242 TupleDesc tupdesc = RelationGetDescr(rel);
2243 TupleDesc orig_tupdesc = RelationGetDescr(rel);
2244 Form_pg_attribute att = TupleDescAttr(tupdesc, attnum - 1);
2245
2246 Assert(attnum > 0);
2247
2248 /*
2249 * If the tuple has been routed, it's been converted to the partition's
2250 * rowtype, which might differ from the root table's. We must convert it
2251 * back to the root table's rowtype so that val_desc shown error message
2252 * matches the input tuple.
2253 */
2254 if (resultRelInfo->ri_RootResultRelInfo)
2255 {
2256 ResultRelInfo *rootrel = resultRelInfo->ri_RootResultRelInfo;
2257 AttrMap *map;
2258
2259 tupdesc = RelationGetDescr(rootrel->ri_RelationDesc);
2260 /* a reverse map */
2261 map = build_attrmap_by_name_if_req(orig_tupdesc,
2262 tupdesc,
2263 false);
2264
2265 /*
2266 * Partition-specific slot's tupdesc can't be changed, so allocate a
2267 * new one.
2268 */
2269 if (map != NULL)
2270 slot = execute_attr_map_slot(map, slot,
2272 modifiedCols = bms_union(ExecGetInsertedCols(rootrel, estate),
2273 ExecGetUpdatedCols(rootrel, estate));
2274 rel = rootrel->ri_RelationDesc;
2275 }
2276 else
2277 modifiedCols = bms_union(ExecGetInsertedCols(resultRelInfo, estate),
2278 ExecGetUpdatedCols(resultRelInfo, estate));
2279
2281 slot,
2282 tupdesc,
2283 modifiedCols,
2284 64);
2285 ereport(ERROR,
2286 errcode(ERRCODE_NOT_NULL_VIOLATION),
2287 errmsg("null value in column \"%s\" of relation \"%s\" violates not-null constraint",
2288 NameStr(att->attname),
2289 RelationGetRelationName(orig_rel)),
2290 val_desc ? errdetail("Failing row contains %s.", val_desc) : 0,
2291 errtablecol(orig_rel, attnum));
2292}
int errtablecol(Relation rel, int attnum)
Definition: relcache.c:6063

References Assert(), attnum, bms_union(), build_attrmap_by_name_if_req(), ereport, errcode(), errdetail(), errmsg(), ERROR, errtablecol(), ExecBuildSlotValueDescription(), ExecGetInsertedCols(), ExecGetUpdatedCols(), execute_attr_map_slot(), 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 547 of file execMain.c.

548{
549 EState *estate;
550 MemoryContext oldcontext;
551
552 /* sanity checks */
553 Assert(queryDesc != NULL);
554
555 estate = queryDesc->estate;
556
557 Assert(estate != NULL);
558
559 if (estate->es_parallel_workers_to_launch > 0)
562
563 /*
564 * Check that ExecutorFinish was called, unless in EXPLAIN-only mode or if
565 * execution was aborted.
566 */
567 Assert(estate->es_finished || estate->es_aborted ||
569
570 /*
571 * Switch into per-query memory context to run ExecEndPlan
572 */
573 oldcontext = MemoryContextSwitchTo(estate->es_query_cxt);
574
575 ExecEndPlan(queryDesc->planstate, estate);
576
577 /* do away with our snapshots */
580
581 /*
582 * Reset AFTER trigger module if the query execution was aborted.
583 */
584 if (estate->es_aborted &&
585 !(estate->es_top_eflags &
588
589 /*
590 * Must switch out of context before destroying it
591 */
592 MemoryContextSwitchTo(oldcontext);
593
594 /*
595 * Release EState and per-query memory context. This should release
596 * everything the executor has allocated.
597 */
598 FreeExecutorState(estate);
599
600 /* Reset queryDesc fields that no longer point to anything */
601 queryDesc->tupDesc = NULL;
602 queryDesc->estate = NULL;
603 queryDesc->planstate = NULL;
604 queryDesc->totaltime = NULL;
605}
static void ExecEndPlan(PlanState *planstate, EState *estate)
Definition: execMain.c:1612
#define EXEC_FLAG_SKIP_TRIGGERS
Definition: executor.h:71
#define EXEC_FLAG_EXPLAIN_ONLY
Definition: executor.h:66
int64 PgStat_Counter
Definition: pgstat.h:65
void pgstat_update_parallel_workers_stats(PgStat_Counter workers_to_launch, PgStat_Counter workers_launched)
void UnregisterSnapshot(Snapshot snapshot)
Definition: snapmgr.c:853
int es_parallel_workers_to_launch
Definition: execnodes.h:745
bool es_finished
Definition: execnodes.h:719
int es_parallel_workers_launched
Definition: execnodes.h:747
struct Instrumentation * totaltime
Definition: execdesc.h:56
void AfterTriggerAbortQuery(void)
Definition: trigger.c:5068

References AfterTriggerAbortQuery(), Assert(), EState::es_aborted, 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, EXEC_FLAG_SKIP_TRIGGERS, ExecEndPlan(), 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 484 of file execMain.c.

485{
486 EState *estate;
487 MemoryContext oldcontext;
488
489 /* sanity checks */
490 Assert(queryDesc != NULL);
491
492 estate = queryDesc->estate;
493
494 Assert(estate != NULL);
496
497 /*
498 * This should be run once and only once per Executor instance and never
499 * if the execution was aborted.
500 */
501 Assert(!estate->es_finished && !estate->es_aborted);
502
503 /* Switch into per-query memory context */
504 oldcontext = MemoryContextSwitchTo(estate->es_query_cxt);
505
506 /* Allow instrumentation of Executor overall runtime */
507 if (queryDesc->totaltime)
508 InstrStartNode(queryDesc->totaltime);
509
510 /* Run ModifyTable nodes to completion */
511 ExecPostprocessPlan(estate);
512
513 /* Execute queued AFTER triggers, unless told not to */
514 if (!(estate->es_top_eflags & EXEC_FLAG_SKIP_TRIGGERS))
515 AfterTriggerEndQuery(estate);
516
517 if (queryDesc->totaltime)
518 InstrStopNode(queryDesc->totaltime, 0);
519
520 MemoryContextSwitchTo(oldcontext);
521
522 estate->es_finished = true;
523}
static void ExecPostprocessPlan(EState *estate)
Definition: execMain.c:1566
void InstrStartNode(Instrumentation *instr)
Definition: instrument.c:68
void InstrStopNode(Instrumentation *instr, double nTuples)
Definition: instrument.c:84
void AfterTriggerEndQuery(EState *estate)
Definition: trigger.c:5088

References AfterTriggerEndQuery(), Assert(), EState::es_aborted, EState::es_finished, EState::es_query_cxt, EState::es_top_eflags, QueryDesc::estate, EXEC_FLAG_EXPLAIN_ONLY, EXEC_FLAG_SKIP_TRIGGERS, ExecPostprocessPlan(), 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 375 of file execMain.c.

377{
378 EState *estate;
379 CmdType operation;
381 bool sendTuples;
382 MemoryContext oldcontext;
383
384 /* sanity checks */
385 Assert(queryDesc != NULL);
386
387 estate = queryDesc->estate;
388
389 Assert(estate != NULL);
390 Assert(!estate->es_aborted);
392
393 /* caller must ensure the query's snapshot is active */
395
396 /*
397 * Switch into per-query memory context
398 */
399 oldcontext = MemoryContextSwitchTo(estate->es_query_cxt);
400
401 /* Allow instrumentation of Executor overall runtime */
402 if (queryDesc->totaltime)
403 InstrStartNode(queryDesc->totaltime);
404
405 /*
406 * extract information from the query descriptor and the query feature.
407 */
408 operation = queryDesc->operation;
409 dest = queryDesc->dest;
410
411 /*
412 * startup tuple receiver, if we will be emitting tuples
413 */
414 estate->es_processed = 0;
415
416 sendTuples = (operation == CMD_SELECT ||
417 queryDesc->plannedstmt->hasReturning);
418
419 if (sendTuples)
420 dest->rStartup(dest, operation, queryDesc->tupDesc);
421
422 /*
423 * Run plan, unless direction is NoMovement.
424 *
425 * Note: pquery.c selects NoMovement if a prior call already reached
426 * end-of-data in the user-specified fetch direction. This is important
427 * because various parts of the executor can misbehave if called again
428 * after reporting EOF. For example, heapam.c would actually restart a
429 * heapscan and return all its data afresh. There is also some doubt
430 * about whether a parallel plan would operate properly if an additional,
431 * necessarily non-parallel execution request occurs after completing a
432 * parallel execution. (That case should work, but it's untested.)
433 */
434 if (!ScanDirectionIsNoMovement(direction))
435 ExecutePlan(queryDesc,
436 operation,
437 sendTuples,
438 count,
439 direction,
440 dest);
441
442 /*
443 * Update es_total_processed to keep track of the number of tuples
444 * processed across multiple ExecutorRun() calls.
445 */
446 estate->es_total_processed += estate->es_processed;
447
448 /*
449 * shutdown tuple receiver, if we started it
450 */
451 if (sendTuples)
452 dest->rShutdown(dest);
453
454 if (queryDesc->totaltime)
455 InstrStopNode(queryDesc->totaltime, estate->es_processed);
456
457 MemoryContextSwitchTo(oldcontext);
458}
static void ExecutePlan(QueryDesc *queryDesc, CmdType operation, bool sendTuples, uint64 numberTuples, ScanDirection direction, DestReceiver *dest)
Definition: execMain.c:1732
#define ScanDirectionIsNoMovement(direction)
Definition: sdir.h:57
Snapshot GetActiveSnapshot(void)
Definition: snapmgr.c:787
uint64 es_total_processed
Definition: execnodes.h:714
bool hasReturning
Definition: plannodes.h:62
DestReceiver * dest
Definition: execdesc.h:42

References Assert(), CMD_SELECT, generate_unaccent_rules::dest, QueryDesc::dest, EState::es_aborted, 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(), 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()

bool standard_ExecutorStart ( QueryDesc queryDesc,
int  eflags 
)

Definition at line 151 of file execMain.c.

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

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(), ExecPlanStillValid(), GetActiveSnapshot(), GetCurrentCommandId(), PlannedStmt::hasModifyingCTE, InitPlan(), QueryDesc::instrument_options, IsInParallelMode(), PlannedStmt::jitFlags, list_length(), MemoryContextSwitchTo(), NIL, QueryDesc::operation, palloc0(), 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().