PostgreSQL Source Code git master
Loading...
Searching...
No Matches
execMain.c File Reference
#include "postgres.h"
#include "access/sysattr.h"
#include "access/table.h"
#include "access/tableam.h"
#include "access/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 "tcop/utility.h"
#include "utils/acl.h"
#include "utils/backend_status.h"
#include "utils/lsyscache.h"
#include "utils/partcache.h"
#include "utils/rls.h"
#include "utils/snapmgr.h"
Include dependency graph for execMain.c:

Go to the source code of this file.

Functions

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

Variables

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

Function Documentation

◆ CheckValidResultRel()

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

Definition at line 1054 of file execMain.c.

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

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

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

◆ CheckValidRowMarkRel()

static void CheckValidRowMarkRel ( Relation  rel,
RowMarkType  markType 
)
static

Definition at line 1182 of file execMain.c.

1183{
1184 FdwRoutine *fdwroutine;
1185
1186 switch (rel->rd_rel->relkind)
1187 {
1188 case RELKIND_RELATION:
1190 /* OK */
1191 break;
1192 case RELKIND_SEQUENCE:
1193 /* Must disallow this because we don't vacuum sequences */
1194 ereport(ERROR,
1196 errmsg("cannot lock rows in sequence \"%s\"",
1198 break;
1199 case RELKIND_TOASTVALUE:
1200 /* We could allow this, but there seems no good reason to */
1201 ereport(ERROR,
1203 errmsg("cannot lock rows in TOAST relation \"%s\"",
1205 break;
1206 case RELKIND_VIEW:
1207 /* Should not get here; planner should have expanded the view */
1208 ereport(ERROR,
1210 errmsg("cannot lock rows in view \"%s\"",
1212 break;
1213 case RELKIND_MATVIEW:
1214 /* Allow referencing a matview, but not actual locking clauses */
1215 if (markType != ROW_MARK_REFERENCE)
1216 ereport(ERROR,
1218 errmsg("cannot lock rows in materialized view \"%s\"",
1220 break;
1222 /* Okay only if the FDW supports it */
1223 fdwroutine = GetFdwRoutineForRelation(rel, false);
1224 if (fdwroutine->RefetchForeignRow == NULL)
1225 ereport(ERROR,
1227 errmsg("cannot lock rows in foreign table \"%s\"",
1229 break;
1230 default:
1231 ereport(ERROR,
1233 errmsg("cannot lock rows in relation \"%s\"",
1235 break;
1236 }
1237}
FdwRoutine * GetFdwRoutineForRelation(Relation relation, bool makecopy)
Definition foreign.c:443
@ ROW_MARK_REFERENCE
Definition plannodes.h:1540
RefetchForeignRow_function RefetchForeignRow
Definition fdwapi.h:248

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

Referenced by InitPlan().

◆ EvalPlanQual()

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

Definition at line 2653 of file execMain.c.

2655{
2656 TupleTableSlot *slot;
2658
2659 Assert(rti > 0);
2660
2661 /*
2662 * Need to run a recheck subquery. Initialize or reinitialize EPQ state.
2663 */
2664 EvalPlanQualBegin(epqstate);
2665
2666 /*
2667 * Callers will often use the EvalPlanQualSlot to store the tuple to avoid
2668 * an unnecessary copy.
2669 */
2670 testslot = EvalPlanQualSlot(epqstate, relation, rti);
2671 if (testslot != inputslot)
2672 ExecCopySlot(testslot, inputslot);
2673
2674 /*
2675 * Mark that an EPQ tuple is available for this relation. (If there is
2676 * more than one result relation, the others remain marked as having no
2677 * tuple available.)
2678 */
2679 epqstate->relsubs_done[rti - 1] = false;
2680 epqstate->relsubs_blocked[rti - 1] = false;
2681
2682 /*
2683 * Run the EPQ query. We assume it will return at most one tuple.
2684 */
2685 slot = EvalPlanQualNext(epqstate);
2686
2687 /*
2688 * If we got a tuple, force the slot to materialize the tuple so that it
2689 * is not dependent on any local state in the EPQ query (in particular,
2690 * it's highly likely that the slot contains references to any pass-by-ref
2691 * datums that may be present in copyTuple). As with the next step, this
2692 * is to guard against early re-use of the EPQ query.
2693 */
2694 if (!TupIsNull(slot))
2695 ExecMaterializeSlot(slot);
2696
2697 /*
2698 * Clear out the test tuple, and mark that no tuple is available here.
2699 * This is needed in case the EPQ state is re-used to test a tuple for a
2700 * different target relation.
2701 */
2703 epqstate->relsubs_blocked[rti - 1] = true;
2704
2705 return slot;
2706}
TupleTableSlot * EvalPlanQualSlot(EPQState *epqstate, Relation relation, Index rti)
Definition execMain.c:2780
void EvalPlanQualBegin(EPQState *epqstate)
Definition execMain.c:2935
TupleTableSlot * EvalPlanQualNext(EPQState *epqstate)
Definition execMain.c:2919
bool * relsubs_blocked
Definition execnodes.h:1358
bool * relsubs_done
Definition execnodes.h:1349
static TupleTableSlot * ExecClearTuple(TupleTableSlot *slot)
Definition tuptable.h:457
#define TupIsNull(slot)
Definition tuptable.h:309
static TupleTableSlot * ExecCopySlot(TupleTableSlot *dstslot, TupleTableSlot *srcslot)
Definition tuptable.h:524
static void ExecMaterializeSlot(TupleTableSlot *slot)
Definition tuptable.h:475

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

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

◆ EvalPlanQualBegin()

void EvalPlanQualBegin ( EPQState epqstate)

Definition at line 2935 of file execMain.c.

2936{
2937 EState *parentestate = epqstate->parentestate;
2938 EState *recheckestate = epqstate->recheckestate;
2939
2940 if (recheckestate == NULL)
2941 {
2942 /* First time through, so create a child EState */
2943 EvalPlanQualStart(epqstate, epqstate->plan);
2944 }
2945 else
2946 {
2947 /*
2948 * We already have a suitable child EPQ tree, so just reset it.
2949 */
2950 Index rtsize = parentestate->es_range_table_size;
2952
2953 /*
2954 * Reset the relsubs_done[] flags to equal relsubs_blocked[], so that
2955 * the EPQ run will never attempt to fetch tuples from blocked target
2956 * relations.
2957 */
2958 memcpy(epqstate->relsubs_done, epqstate->relsubs_blocked,
2959 rtsize * sizeof(bool));
2960
2961 /* Recopy current values of parent parameters */
2962 if (parentestate->es_plannedstmt->paramExecTypes != NIL)
2963 {
2964 int i;
2965
2966 /*
2967 * Force evaluation of any InitPlan outputs that could be needed
2968 * by the subplan, just in case they got reset since
2969 * EvalPlanQualStart (see comments therein).
2970 */
2971 ExecSetParamPlanMulti(rcplanstate->plan->extParam,
2972 GetPerTupleExprContext(parentestate));
2973
2974 i = list_length(parentestate->es_plannedstmt->paramExecTypes);
2975
2976 while (--i >= 0)
2977 {
2978 /* copy value if any, but not execPlan link */
2979 recheckestate->es_param_exec_vals[i].value =
2980 parentestate->es_param_exec_vals[i].value;
2981 recheckestate->es_param_exec_vals[i].isnull =
2982 parentestate->es_param_exec_vals[i].isnull;
2983 }
2984 }
2985
2986 /*
2987 * Mark child plan tree as needing rescan at all scan nodes. The
2988 * first ExecProcNode will take care of actually doing the rescan.
2989 */
2990 rcplanstate->chgParam = bms_add_member(rcplanstate->chgParam,
2991 epqstate->epqParam);
2992 }
2993}
Bitmapset * bms_add_member(Bitmapset *a, int x)
Definition bitmapset.c:814
unsigned int Index
Definition c.h:628
static void EvalPlanQualStart(EPQState *epqstate, Plan *planTree)
Definition execMain.c:3002
#define GetPerTupleExprContext(estate)
Definition executor.h:656
int i
Definition isn.c:77
void ExecSetParamPlanMulti(const Bitmapset *params, ExprContext *econtext)
static int list_length(const List *l)
Definition pg_list.h:152
#define NIL
Definition pg_list.h:68
Plan * plan
Definition execnodes.h:1321
int epqParam
Definition execnodes.h:1304
EState * parentestate
Definition execnodes.h:1303
EState * recheckestate
Definition execnodes.h:1335
PlanState * recheckplanstate
Definition execnodes.h:1360
PlannedStmt * es_plannedstmt
Definition execnodes.h:671
ParamExecData * es_param_exec_vals
Definition execnodes.h:707
Index es_range_table_size
Definition execnodes.h:665
bool isnull
Definition params.h:149
Datum value
Definition params.h:148
List * paramExecTypes
Definition plannodes.h:147

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

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

◆ EvalPlanQualEnd()

void EvalPlanQualEnd ( EPQState epqstate)

Definition at line 3183 of file execMain.c.

3184{
3185 EState *estate = epqstate->recheckestate;
3186 Index rtsize;
3187 MemoryContext oldcontext;
3188 ListCell *l;
3189
3191
3192 /*
3193 * We may have a tuple table, even if EPQ wasn't started, because we allow
3194 * use of EvalPlanQualSlot() without calling EvalPlanQualBegin().
3195 */
3196 if (epqstate->tuple_table != NIL)
3197 {
3198 memset(epqstate->relsubs_slot, 0,
3199 rtsize * sizeof(TupleTableSlot *));
3200 ExecResetTupleTable(epqstate->tuple_table, true);
3201 epqstate->tuple_table = NIL;
3202 }
3203
3204 /* EPQ wasn't started, nothing further to do */
3205 if (estate == NULL)
3206 return;
3207
3208 oldcontext = MemoryContextSwitchTo(estate->es_query_cxt);
3209
3210 ExecEndNode(epqstate->recheckplanstate);
3211
3212 foreach(l, estate->es_subplanstates)
3213 {
3215
3217 }
3218
3219 /* throw away the per-estate tuple table, some node may have used it */
3220 ExecResetTupleTable(estate->es_tupleTable, false);
3221
3222 /* Close any result and trigger target relations attached to this EState */
3224
3225 MemoryContextSwitchTo(oldcontext);
3226
3227 /*
3228 * NULLify the partition directory before freeing the executor state.
3229 * Since EvalPlanQualStart() just borrowed the parent EState's directory,
3230 * we'd better leave it up to the parent to delete it.
3231 */
3232 estate->es_partition_directory = NULL;
3233
3234 FreeExecutorState(estate);
3235
3236 /* Mark EPQState idle */
3237 epqstate->origslot = NULL;
3238 epqstate->recheckestate = NULL;
3239 epqstate->recheckplanstate = NULL;
3240 epqstate->relsubs_rowmark = NULL;
3241 epqstate->relsubs_done = NULL;
3242 epqstate->relsubs_blocked = NULL;
3243}
void ExecCloseResultRelations(EState *estate)
Definition execMain.c:1579
void ExecEndNode(PlanState *node)
void ExecResetTupleTable(List *tupleTable, bool shouldFree)
void FreeExecutorState(EState *estate)
Definition execUtils.c:192
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition palloc.h:124
#define lfirst(lc)
Definition pg_list.h:172
ExecAuxRowMark ** relsubs_rowmark
Definition execnodes.h:1342
TupleTableSlot * origslot
Definition execnodes.h:1330
TupleTableSlot ** relsubs_slot
Definition execnodes.h:1314
List * tuple_table
Definition execnodes.h:1313
MemoryContext es_query_cxt
Definition execnodes.h:712
List * es_tupleTable
Definition execnodes.h:714
PartitionDirectory es_partition_directory
Definition execnodes.h:694
List * es_subplanstates
Definition execnodes.h:727

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

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

◆ EvalPlanQualFetchRowMark()

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

Definition at line 2808 of file execMain.c.

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

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

Referenced by ExecScanFetch().

◆ EvalPlanQualInit()

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

Definition at line 2722 of file execMain.c.

2725{
2726 Index rtsize = parentestate->es_range_table_size;
2727
2728 /* initialize data not changing over EPQState's lifetime */
2729 epqstate->parentestate = parentestate;
2730 epqstate->epqParam = epqParam;
2731 epqstate->resultRelations = resultRelations;
2732
2733 /*
2734 * Allocate space to reference a slot for each potential rti - do so now
2735 * rather than in EvalPlanQualBegin(), as done for other dynamically
2736 * allocated resources, so EvalPlanQualSlot() can be used to hold tuples
2737 * that *may* need EPQ later, without forcing the overhead of
2738 * EvalPlanQualBegin().
2739 */
2740 epqstate->tuple_table = NIL;
2742
2743 /* ... and remember data that EvalPlanQualBegin will need */
2744 epqstate->plan = subplan;
2745 epqstate->arowMarks = auxrowmarks;
2746
2747 /* ... and mark the EPQ state inactive */
2748 epqstate->origslot = NULL;
2749 epqstate->recheckestate = NULL;
2750 epqstate->recheckplanstate = NULL;
2751 epqstate->relsubs_rowmark = NULL;
2752 epqstate->relsubs_done = NULL;
2753 epqstate->relsubs_blocked = NULL;
2754}
#define palloc0_array(type, count)
Definition fe_memutils.h:77
List * resultRelations
Definition execnodes.h:1305
List * arowMarks
Definition execnodes.h:1322

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

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

◆ EvalPlanQualNext()

TupleTableSlot * EvalPlanQualNext ( EPQState epqstate)

Definition at line 2919 of file execMain.c.

2920{
2921 MemoryContext oldcontext;
2922 TupleTableSlot *slot;
2923
2924 oldcontext = MemoryContextSwitchTo(epqstate->recheckestate->es_query_cxt);
2925 slot = ExecProcNode(epqstate->recheckplanstate);
2926 MemoryContextSwitchTo(oldcontext);
2927
2928 return slot;
2929}
static TupleTableSlot * ExecProcNode(PlanState *node)
Definition executor.h:314

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

2764{
2765 /* If we have a live EPQ query, shut it down */
2766 EvalPlanQualEnd(epqstate);
2767 /* And set/change the plan pointer */
2768 epqstate->plan = subplan;
2769 /* The rowmarks depend on the plan, too */
2770 epqstate->arowMarks = auxrowmarks;
2771}
void EvalPlanQualEnd(EPQState *epqstate)
Definition execMain.c:3183

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

Referenced by ExecInitModifyTable().

◆ EvalPlanQualSlot()

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

Definition at line 2780 of file execMain.c.

2782{
2783 TupleTableSlot **slot;
2784
2785 Assert(relation);
2786 Assert(rti > 0 && rti <= epqstate->parentestate->es_range_table_size);
2787 slot = &epqstate->relsubs_slot[rti - 1];
2788
2789 if (*slot == NULL)
2790 {
2791 MemoryContext oldcontext;
2792
2793 oldcontext = MemoryContextSwitchTo(epqstate->parentestate->es_query_cxt);
2794 *slot = table_slot_create(relation, &epqstate->tuple_table);
2795 MemoryContextSwitchTo(oldcontext);
2796 }
2797
2798 return *slot;
2799}
TupleTableSlot * table_slot_create(Relation relation, List **reglist)
Definition tableam.c:92

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

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

◆ EvalPlanQualStart()

static void EvalPlanQualStart ( EPQState epqstate,
Plan planTree 
)
static

Definition at line 3002 of file execMain.c.

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

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

Referenced by EvalPlanQualBegin().

◆ ExecBuildAuxRowMark()

ExecAuxRowMark * ExecBuildAuxRowMark ( ExecRowMark erm,
List targetlist 
)

Definition at line 2583 of file execMain.c.

2584{
2586 char resname[32];
2587
2588 aerm->rowmark = erm;
2589
2590 /* Look up the resjunk columns associated with this rowmark */
2591 if (erm->markType != ROW_MARK_COPY)
2592 {
2593 /* need ctid for all methods other than COPY */
2594 snprintf(resname, sizeof(resname), "ctid%u", erm->rowmarkId);
2595 aerm->ctidAttNo = ExecFindJunkAttributeInTlist(targetlist,
2596 resname);
2597 if (!AttributeNumberIsValid(aerm->ctidAttNo))
2598 elog(ERROR, "could not find junk %s column", resname);
2599 }
2600 else
2601 {
2602 /* need wholerow if COPY */
2603 snprintf(resname, sizeof(resname), "wholerow%u", erm->rowmarkId);
2604 aerm->wholeAttNo = ExecFindJunkAttributeInTlist(targetlist,
2605 resname);
2606 if (!AttributeNumberIsValid(aerm->wholeAttNo))
2607 elog(ERROR, "could not find junk %s column", resname);
2608 }
2609
2610 /* if child rel, need tableoid */
2611 if (erm->rti != erm->prti)
2612 {
2613 snprintf(resname, sizeof(resname), "tableoid%u", erm->rowmarkId);
2614 aerm->toidAttNo = ExecFindJunkAttributeInTlist(targetlist,
2615 resname);
2616 if (!AttributeNumberIsValid(aerm->toidAttNo))
2617 elog(ERROR, "could not find junk %s column", resname);
2618 }
2619
2620 return aerm;
2621}
#define AttributeNumberIsValid(attributeNumber)
Definition attnum.h:34
AttrNumber ExecFindJunkAttributeInTlist(List *targetlist, const char *attrName)
Definition execJunk.c:222
#define palloc0_object(type)
Definition fe_memutils.h:75
#define snprintf
Definition port.h:260

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

Referenced by ExecInitLockRows(), and ExecInitModifyTable().

◆ ExecBuildSlotValueDescription()

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

Definition at line 2395 of file execMain.c.

2400{
2403 bool write_comma = false;
2404 bool write_comma_collist = false;
2405 int i;
2407 bool table_perm = false;
2408 bool any_perm = false;
2409
2410 /*
2411 * Check if RLS is enabled and should be active for the relation; if so,
2412 * then don't return anything. Otherwise, go through normal permission
2413 * checks.
2414 */
2415 if (check_enable_rls(reloid, InvalidOid, true) == RLS_ENABLED)
2416 return NULL;
2417
2419
2421
2422 /*
2423 * Check if the user has permissions to see the row. Table-level SELECT
2424 * allows access to all columns. If the user does not have table-level
2425 * SELECT then we check each column and include those the user has SELECT
2426 * rights on. Additionally, we always include columns the user provided
2427 * data for.
2428 */
2430 if (aclresult != ACLCHECK_OK)
2431 {
2432 /* Set up the buffer for the column list */
2435 }
2436 else
2437 table_perm = any_perm = true;
2438
2439 /* Make sure the tuple is fully deconstructed */
2440 slot_getallattrs(slot);
2441
2442 for (i = 0; i < tupdesc->natts; i++)
2443 {
2444 bool column_perm = false;
2445 char *val;
2446 int vallen;
2448
2449 /* ignore dropped columns */
2450 if (att->attisdropped)
2451 continue;
2452
2453 if (!table_perm)
2454 {
2455 /*
2456 * No table-level SELECT, so need to make sure they either have
2457 * SELECT rights on the column or that they have provided the data
2458 * for the column. If not, omit this column from the error
2459 * message.
2460 */
2461 aclresult = pg_attribute_aclcheck(reloid, att->attnum,
2465 {
2466 column_perm = any_perm = true;
2467
2470 else
2471 write_comma_collist = true;
2472
2474 }
2475 }
2476
2477 if (table_perm || column_perm)
2478 {
2479 if (att->attgenerated == ATTRIBUTE_GENERATED_VIRTUAL)
2480 val = "virtual";
2481 else if (slot->tts_isnull[i])
2482 val = "null";
2483 else
2484 {
2485 Oid foutoid;
2486 bool typisvarlena;
2487
2488 getTypeOutputInfo(att->atttypid,
2489 &foutoid, &typisvarlena);
2491 }
2492
2493 if (write_comma)
2495 else
2496 write_comma = true;
2497
2498 /* truncate if needed */
2499 vallen = strlen(val);
2500 if (vallen <= maxfieldlen)
2501 appendBinaryStringInfo(&buf, val, vallen);
2502 else
2503 {
2504 vallen = pg_mbcliplen(val, vallen, maxfieldlen);
2505 appendBinaryStringInfo(&buf, val, vallen);
2506 appendStringInfoString(&buf, "...");
2507 }
2508 }
2509 }
2510
2511 /* If we end up with zero columns being returned, then return NULL. */
2512 if (!any_perm)
2513 return NULL;
2514
2516
2517 if (!table_perm)
2518 {
2521
2522 return collist.data;
2523 }
2524
2525 return buf.data;
2526}
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:3868
AclResult pg_class_aclcheck(Oid table_oid, Oid roleid, AclMode mode)
Definition aclchk.c:4039
bool bms_is_member(int x, const Bitmapset *a)
Definition bitmapset.c:510
#define NameStr(name)
Definition c.h:765
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:3057
int pg_mbcliplen(const char *mbstr, int len, int limit)
Definition mbutils.c:1086
Oid GetUserId(void)
Definition miscinit.c:469
#define ACL_SELECT
Definition parsenodes.h:77
FormData_pg_attribute * Form_pg_attribute
static char buf[DEFAULT_XLOG_SEG_SIZE]
#define InvalidOid
int check_enable_rls(Oid relid, Oid checkAsUser, bool noError)
Definition rls.c:52
@ RLS_ENABLED
Definition rls.h:45
void appendBinaryStringInfo(StringInfo str, const void *data, int datalen)
Definition stringinfo.c:281
void appendStringInfoString(StringInfo str, const char *s)
Definition stringinfo.c:230
void appendStringInfoChar(StringInfo str, char ch)
Definition stringinfo.c:242
void initStringInfo(StringInfo str)
Definition stringinfo.c:97
bool * tts_isnull
Definition tuptable.h:126
Datum * tts_values
Definition tuptable.h:124
#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:371

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

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

◆ ExecCheckOneRelPerms()

bool ExecCheckOneRelPerms ( RTEPermissionInfo perminfo)

Definition at line 646 of file execMain.c.

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

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

Referenced by ExecCheckPermissions(), and subquery_planner().

◆ ExecCheckPermissions()

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

Definition at line 582 of file execMain.c.

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

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

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

◆ ExecCheckPermissionsModified()

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

Definition at line 755 of file execMain.c.

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

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

Referenced by ExecCheckOneRelPerms().

◆ ExecCheckXactReadOnly()

static void ExecCheckXactReadOnly ( PlannedStmt plannedstmt)
static

Definition at line 802 of file execMain.c.

803{
804 ListCell *l;
805
806 /*
807 * Fail if write permissions are requested in parallel mode for table
808 * (temp or non-temp), otherwise fail for any non-temp table.
809 */
810 foreach(l, plannedstmt->permInfos)
811 {
813
814 if ((perminfo->requiredPerms & (~ACL_SELECT)) == 0)
815 continue;
816
818 continue;
819
821 }
822
823 if (plannedstmt->commandType != CMD_SELECT || plannedstmt->hasModifyingCTE)
825}
Oid get_rel_namespace(Oid relid)
Definition lsyscache.c:2102
bool isTempNamespace(Oid namespaceId)
Definition namespace.c:3719
@ CMD_SELECT
Definition nodes.h:275
Definition nodes.h:135
bool hasModifyingCTE
Definition plannodes.h:83
List * permInfos
Definition plannodes.h:120
CmdType commandType
Definition plannodes.h:68
void PreventCommandIfReadOnly(const char *cmdname)
Definition utility.c:406
void PreventCommandIfParallelMode(const char *cmdname)
Definition utility.c:424
static const char * CreateCommandName(Node *parsetree)
Definition utility.h:103

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

Referenced by standard_ExecutorStart().

◆ ExecCloseRangeTableRelations()

void ExecCloseRangeTableRelations ( EState estate)

Definition at line 1639 of file execMain.c.

1640{
1641 int i;
1642
1643 for (i = 0; i < estate->es_range_table_size; i++)
1644 {
1645 if (estate->es_relations[i])
1646 table_close(estate->es_relations[i], NoLock);
1647 }
1648}
#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 1579 of file execMain.c.

1580{
1581 ListCell *l;
1582
1583 /*
1584 * close indexes of result relation(s) if any. (Rels themselves are
1585 * closed in ExecCloseRangeTableRelations())
1586 *
1587 * In addition, close the stub RTs that may be in each resultrel's
1588 * ri_ancestorResultRels.
1589 */
1590 foreach(l, estate->es_opened_result_relations)
1591 {
1592 ResultRelInfo *resultRelInfo = lfirst(l);
1593 ListCell *lc;
1594
1595 ExecCloseIndices(resultRelInfo);
1596 foreach(lc, resultRelInfo->ri_ancestorResultRels)
1597 {
1599
1600 /*
1601 * Ancestors with RTI > 0 (should only be the root ancestor) are
1602 * closed by ExecCloseRangeTableRelations.
1603 */
1604 if (rInfo->ri_RangeTableIndex > 0)
1605 continue;
1606
1607 table_close(rInfo->ri_RelationDesc, NoLock);
1608 }
1609 }
1610
1611 /* Close any relations that have been opened by ExecGetTriggerResultRel(). */
1612 foreach(l, estate->es_trig_target_relations)
1613 {
1614 ResultRelInfo *resultRelInfo = (ResultRelInfo *) lfirst(l);
1615
1616 /*
1617 * Assert this is a "dummy" ResultRelInfo, see above. Otherwise we
1618 * might be issuing a duplicate close against a Relation opened by
1619 * ExecGetRangeTableRelation.
1620 */
1621 Assert(resultRelInfo->ri_RangeTableIndex == 0);
1622
1623 /*
1624 * Since ExecGetTriggerResultRel doesn't call ExecOpenIndices for
1625 * these rels, we needn't call ExecCloseIndices either.
1626 */
1627 Assert(resultRelInfo->ri_NumIndices == 0);
1628
1629 table_close(resultRelInfo->ri_RelationDesc, NoLock);
1630 }
1631}
void ExecCloseIndices(ResultRelInfo *resultRelInfo)
List * es_trig_target_relations
Definition execnodes.h:703
List * es_opened_result_relations
Definition execnodes.h:690
Index ri_RangeTableIndex
Definition execnodes.h:479
List * ri_ancestorResultRels
Definition execnodes.h:630

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

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

◆ ExecConstraints()

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

Definition at line 1984 of file execMain.c.

1986{
1987 Relation rel = resultRelInfo->ri_RelationDesc;
1988 TupleDesc tupdesc = RelationGetDescr(rel);
1989 TupleConstr *constr = tupdesc->constr;
1992
1993 Assert(constr); /* we should not be called otherwise */
1994
1995 /*
1996 * Verify not-null constraints.
1997 *
1998 * Not-null constraints on virtual generated columns are collected and
1999 * checked separately below.
2000 */
2001 if (constr->has_not_null)
2002 {
2003 for (AttrNumber attnum = 1; attnum <= tupdesc->natts; attnum++)
2004 {
2005 Form_pg_attribute att = TupleDescAttr(tupdesc, attnum - 1);
2006
2007 if (att->attnotnull && att->attgenerated == ATTRIBUTE_GENERATED_VIRTUAL)
2009 else if (att->attnotnull && slot_attisnull(slot, attnum))
2010 ReportNotNullViolationError(resultRelInfo, slot, estate, attnum);
2011 }
2012 }
2013
2014 /*
2015 * Verify not-null constraints on virtual generated column, if any.
2016 */
2018 {
2020
2021 attnum = ExecRelGenVirtualNotNull(resultRelInfo, slot, estate,
2024 ReportNotNullViolationError(resultRelInfo, slot, estate, attnum);
2025 }
2026
2027 /*
2028 * Verify check constraints.
2029 */
2030 if (rel->rd_rel->relchecks > 0)
2031 {
2032 const char *failed;
2033
2034 if ((failed = ExecRelCheck(resultRelInfo, slot, estate)) != NULL)
2035 {
2036 char *val_desc;
2037 Relation orig_rel = rel;
2038
2039 /*
2040 * If the tuple has been routed, it's been converted to the
2041 * partition's rowtype, which might differ from the root table's.
2042 * We must convert it back to the root table's rowtype so that
2043 * val_desc shown error message matches the input tuple.
2044 */
2045 if (resultRelInfo->ri_RootResultRelInfo)
2046 {
2047 ResultRelInfo *rootrel = resultRelInfo->ri_RootResultRelInfo;
2049 AttrMap *map;
2050
2051 tupdesc = RelationGetDescr(rootrel->ri_RelationDesc);
2052 /* a reverse map */
2054 tupdesc,
2055 false);
2056
2057 /*
2058 * Partition-specific slot's tupdesc can't be changed, so
2059 * allocate a new one.
2060 */
2061 if (map != NULL)
2062 slot = execute_attr_map_slot(map, slot,
2065 ExecGetUpdatedCols(rootrel, estate));
2066 rel = rootrel->ri_RelationDesc;
2067 }
2068 else
2069 modifiedCols = bms_union(ExecGetInsertedCols(resultRelInfo, estate),
2070 ExecGetUpdatedCols(resultRelInfo, estate));
2072 slot,
2073 tupdesc,
2075 64);
2076 ereport(ERROR,
2078 errmsg("new row for relation \"%s\" violates check constraint \"%s\"",
2080 val_desc ? errdetail("Failing row contains %s.", val_desc) : 0,
2081 errtableconstraint(orig_rel, failed)));
2082 }
2083 }
2084}
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:1216
static void ReportNotNullViolationError(ResultRelInfo *resultRelInfo, TupleTableSlot *slot, EState *estate, int attnum)
Definition execMain.c:2163
char * ExecBuildSlotValueDescription(Oid reloid, TupleTableSlot *slot, TupleDesc tupdesc, Bitmapset *modifiedCols, int maxfieldlen)
Definition execMain.c:2395
AttrNumber ExecRelGenVirtualNotNull(ResultRelInfo *resultRelInfo, TupleTableSlot *slot, EState *estate, List *notnull_virtual_attrs)
Definition execMain.c:2098
static const char * ExecRelCheck(ResultRelInfo *resultRelInfo, TupleTableSlot *slot, EState *estate)
Definition execMain.c:1782
const TupleTableSlotOps TTSOpsVirtual
Definition execTuples.c:84
TupleTableSlot * MakeTupleTableSlot(TupleDesc tupleDesc, const TupleTableSlotOps *tts_ops)
Bitmapset * ExecGetInsertedCols(ResultRelInfo *relinfo, EState *estate)
Definition execUtils.c:1361
Bitmapset * ExecGetUpdatedCols(ResultRelInfo *relinfo, EState *estate)
Definition execUtils.c:1382
List * lappend_int(List *list, int datum)
Definition list.c:357
int16 attnum
#define RelationGetRelid(relation)
Definition rel.h:514
#define RelationGetDescr(relation)
Definition rel.h:540
int errtableconstraint(Relation rel, const char *conname)
Definition relcache.c:6098
Definition pg_list.h:54
struct ResultRelInfo * ri_RootResultRelInfo
Definition execnodes.h:620
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:193
static bool slot_attisnull(TupleTableSlot *slot, int attnum)
Definition tuptable.h:384

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

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

◆ ExecEndPlan()

static void ExecEndPlan ( PlanState planstate,
EState estate 
)
static

Definition at line 1540 of file execMain.c.

1541{
1542 ListCell *l;
1543
1544 /*
1545 * shut down the node-type-specific query processing
1546 */
1547 ExecEndNode(planstate);
1548
1549 /*
1550 * for subplans too
1551 */
1552 foreach(l, estate->es_subplanstates)
1553 {
1555
1557 }
1558
1559 /*
1560 * destroy the executor's tuple table. Actually we only care about
1561 * releasing buffer pins and tupdesc refcounts; there's no need to pfree
1562 * the TupleTableSlots, since the containing memory context is about to go
1563 * away anyway.
1564 */
1565 ExecResetTupleTable(estate->es_tupleTable, false);
1566
1567 /*
1568 * Close any Relations that have been opened for range table entries or
1569 * result relations.
1570 */
1573}
void ExecCloseRangeTableRelations(EState *estate)
Definition execMain.c:1639

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

Referenced by standard_ExecutorEnd().

◆ ExecFindRowMark()

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

Definition at line 2560 of file execMain.c.

2561{
2562 if (rti > 0 && rti <= estate->es_range_table_size &&
2563 estate->es_rowmarks != NULL)
2564 {
2565 ExecRowMark *erm = estate->es_rowmarks[rti - 1];
2566
2567 if (erm)
2568 return erm;
2569 }
2570 if (!missing_ok)
2571 elog(ERROR, "failed to find ExecRowMark for rangetable index %u", rti);
2572 return NULL;
2573}

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

Referenced by ExecInitLockRows(), and ExecInitModifyTable().

◆ ExecGetAncestorResultRels()

List * ExecGetAncestorResultRels ( EState estate,
ResultRelInfo resultRelInfo 
)

Definition at line 1434 of file execMain.c.

1435{
1437 Relation partRel = resultRelInfo->ri_RelationDesc;
1439
1440 if (!partRel->rd_rel->relispartition)
1441 elog(ERROR, "cannot find ancestors of a non-partition result relation");
1443 rootRelOid = RelationGetRelid(rootRelInfo->ri_RelationDesc);
1444 if (resultRelInfo->ri_ancestorResultRels == NIL)
1445 {
1446 ListCell *lc;
1449
1450 foreach(lc, oids)
1451 {
1455
1456 /*
1457 * Ignore the root ancestor here, and use ri_RootResultRelInfo
1458 * (below) for it instead. Also, we stop climbing up the
1459 * hierarchy when we find the table that was mentioned in the
1460 * query.
1461 */
1462 if (ancOid == rootRelOid)
1463 break;
1464
1465 /*
1466 * All ancestors up to the root target relation must have been
1467 * locked by the planner or AcquireExecutorLocks().
1468 */
1471
1472 /* dummy rangetable index */
1474 estate->es_instrument);
1476 }
1478 resultRelInfo->ri_ancestorResultRels = ancResultRels;
1479 }
1480
1481 /* We must have found some ancestor */
1482 Assert(resultRelInfo->ri_ancestorResultRels != NIL);
1483
1484 return resultRelInfo->ri_ancestorResultRels;
1485}
void InitResultRelInfo(ResultRelInfo *resultRelInfo, Relation resultRelationDesc, Index resultRelationIndex, ResultRelInfo *partition_root_rri, int instrument_options)
Definition execMain.c:1247
#define makeNode(_type_)
Definition nodes.h:161
List * get_partition_ancestors(Oid relid)
Definition partition.c:134
#define lfirst_oid(lc)
Definition pg_list.h:174
Relation table_open(Oid relationId, LOCKMODE lockmode)
Definition table.c:40

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

Referenced by ExecCrossPartitionUpdateForeignKey().

◆ ExecGetTriggerResultRel()

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

Definition at line 1347 of file execMain.c.

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

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

Referenced by afterTriggerInvokeEvents().

◆ ExecPartitionCheck()

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

Definition at line 1860 of file execMain.c.

1862{
1863 ExprContext *econtext;
1864 bool success;
1865
1866 /*
1867 * If first time through, build expression state tree for the partition
1868 * check expression. (In the corner case where the partition check
1869 * expression is empty, ie there's a default partition and nothing else,
1870 * we'll be fooled into executing this code each time through. But it's
1871 * pretty darn cheap in that case, so we don't worry about it.)
1872 */
1873 if (resultRelInfo->ri_PartitionCheckExpr == NULL)
1874 {
1875 /*
1876 * Ensure that the qual tree and prepared expression are in the
1877 * query-lifespan context.
1878 */
1880 List *qual = RelationGetPartitionQual(resultRelInfo->ri_RelationDesc);
1881
1882 resultRelInfo->ri_PartitionCheckExpr = ExecPrepareCheck(qual, estate);
1884 }
1885
1886 /*
1887 * We will use the EState's per-tuple context for evaluating constraint
1888 * expressions (creating it if it's not already there).
1889 */
1890 econtext = GetPerTupleExprContext(estate);
1891
1892 /* Arrange for econtext's scan tuple to be the tuple under test */
1893 econtext->ecxt_scantuple = slot;
1894
1895 /*
1896 * As in case of the cataloged constraints, we treat a NULL result as
1897 * success here, not a failure.
1898 */
1899 success = ExecCheck(resultRelInfo->ri_PartitionCheckExpr, econtext);
1900
1901 /* if asked to emit error, don't actually return on failure */
1902 if (!success && emitError)
1903 ExecPartitionCheckEmitError(resultRelInfo, slot, estate);
1904
1905 return success;
1906}
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:1913
static bool success
Definition initdb.c:187
List * RelationGetPartitionQual(Relation rel)
Definition partcache.c:277
TupleTableSlot * ecxt_scantuple
Definition execnodes.h:275
ExprState * ri_PartitionCheckExpr
Definition execnodes.h:594

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

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

◆ ExecPartitionCheckEmitError()

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

Definition at line 1913 of file execMain.c.

1916{
1918 TupleDesc tupdesc;
1919 char *val_desc;
1921
1922 /*
1923 * If the tuple has been routed, it's been converted to the partition's
1924 * rowtype, which might differ from the root table's. We must convert it
1925 * back to the root table's rowtype so that val_desc in the error message
1926 * matches the input tuple.
1927 */
1928 if (resultRelInfo->ri_RootResultRelInfo)
1929 {
1930 ResultRelInfo *rootrel = resultRelInfo->ri_RootResultRelInfo;
1932 AttrMap *map;
1933
1934 root_relid = RelationGetRelid(rootrel->ri_RelationDesc);
1935 tupdesc = RelationGetDescr(rootrel->ri_RelationDesc);
1936
1938 /* a reverse map */
1939 map = build_attrmap_by_name_if_req(old_tupdesc, tupdesc, false);
1940
1941 /*
1942 * Partition-specific slot's tupdesc can't be changed, so allocate a
1943 * new one.
1944 */
1945 if (map != NULL)
1946 slot = execute_attr_map_slot(map, slot,
1949 ExecGetUpdatedCols(rootrel, estate));
1950 }
1951 else
1952 {
1954 tupdesc = RelationGetDescr(resultRelInfo->ri_RelationDesc);
1955 modifiedCols = bms_union(ExecGetInsertedCols(resultRelInfo, estate),
1956 ExecGetUpdatedCols(resultRelInfo, estate));
1957 }
1958
1960 slot,
1961 tupdesc,
1963 64);
1964 ereport(ERROR,
1966 errmsg("new row for relation \"%s\" violates partition constraint",
1968 val_desc ? errdetail("Failing row contains %s.", val_desc) : 0,
1969 errtable(resultRelInfo->ri_RelationDesc)));
1970}
int errtable(Relation rel)
Definition relcache.c:6044

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

Referenced by ExecCrossPartitionUpdate(), and ExecPartitionCheck().

◆ ExecPostprocessPlan()

static void ExecPostprocessPlan ( EState estate)
static

Definition at line 1494 of file execMain.c.

1495{
1496 ListCell *lc;
1497
1498 /*
1499 * Make sure nodes run forward.
1500 */
1502
1503 /*
1504 * Run any secondary ModifyTable nodes to completion, in case the main
1505 * query did not fetch all rows from them. (We do this to ensure that
1506 * such nodes have predictable results.)
1507 */
1508 foreach(lc, estate->es_auxmodifytables)
1509 {
1510 PlanState *ps = (PlanState *) lfirst(lc);
1511
1512 for (;;)
1513 {
1514 TupleTableSlot *slot;
1515
1516 /* Reset the per-output-tuple exprcontext each time */
1518
1519 slot = ExecProcNode(ps);
1520
1521 if (TupIsNull(slot))
1522 break;
1523 }
1524 }
1525}
#define ResetPerTupleExprContext(estate)
Definition executor.h:665
struct parser_state ps
ScanDirection es_direction
Definition execnodes.h:661
List * es_auxmodifytables
Definition execnodes.h:729

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

Referenced by standard_ExecutorFinish().

◆ ExecRelCheck()

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

Definition at line 1782 of file execMain.c.

1784{
1785 Relation rel = resultRelInfo->ri_RelationDesc;
1786 int ncheck = rel->rd_att->constr->num_check;
1787 ConstrCheck *check = rel->rd_att->constr->check;
1788 ExprContext *econtext;
1790
1791 /*
1792 * CheckNNConstraintFetch let this pass with only a warning, but now we
1793 * should fail rather than possibly failing to enforce an important
1794 * constraint.
1795 */
1796 if (ncheck != rel->rd_rel->relchecks)
1797 elog(ERROR, "%d pg_constraint record(s) missing for relation \"%s\"",
1798 rel->rd_rel->relchecks - ncheck, RelationGetRelationName(rel));
1799
1800 /*
1801 * If first time through for this result relation, build expression
1802 * nodetrees for rel's constraint expressions. Keep them in the per-query
1803 * memory context so they'll survive throughout the query.
1804 */
1805 if (resultRelInfo->ri_CheckConstraintExprs == NULL)
1806 {
1808 resultRelInfo->ri_CheckConstraintExprs = palloc0_array(ExprState *, ncheck);
1809 for (int i = 0; i < ncheck; i++)
1810 {
1812
1813 /* Skip not enforced constraint */
1814 if (!check[i].ccenforced)
1815 continue;
1816
1817 checkconstr = stringToNode(check[i].ccbin);
1819 resultRelInfo->ri_CheckConstraintExprs[i] =
1821 }
1823 }
1824
1825 /*
1826 * We will use the EState's per-tuple context for evaluating constraint
1827 * expressions (creating it if it's not already there).
1828 */
1829 econtext = GetPerTupleExprContext(estate);
1830
1831 /* Arrange for econtext's scan tuple to be the tuple under test */
1832 econtext->ecxt_scantuple = slot;
1833
1834 /* And evaluate the constraints */
1835 for (int i = 0; i < ncheck; i++)
1836 {
1838
1839 /*
1840 * NOTE: SQL specifies that a NULL result from a constraint expression
1841 * is not to be treated as a failure. Therefore, use ExecCheck not
1842 * ExecQual.
1843 */
1844 if (checkconstr && !ExecCheck(checkconstr, econtext))
1845 return check[i].ccname;
1846 }
1847
1848 /* NULL result means no error */
1849 return NULL;
1850}
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:557
ConstrCheck * check
Definition tupdesc.h:41
uint16 num_check
Definition tupdesc.h:44

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

Referenced by ExecConstraints().

◆ ExecRelGenVirtualNotNull()

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

Definition at line 2098 of file execMain.c.

2100{
2101 Relation rel = resultRelInfo->ri_RelationDesc;
2102 ExprContext *econtext;
2104
2105 /*
2106 * We implement this by building a NullTest node for each virtual
2107 * generated column, which we cache in resultRelInfo, and running those
2108 * through ExecCheck().
2109 */
2110 if (resultRelInfo->ri_GenVirtualNotNullConstraintExprs == NULL)
2111 {
2115
2117 {
2120
2121 /* "generated_expression IS NOT NULL" check. */
2124 nnulltest->nulltesttype = IS_NOT_NULL;
2125 nnulltest->argisrow = false;
2126 nnulltest->location = -1;
2127
2128 resultRelInfo->ri_GenVirtualNotNullConstraintExprs[i] =
2129 ExecPrepareExpr((Expr *) nnulltest, estate);
2130 }
2132 }
2133
2134 /*
2135 * We will use the EState's per-tuple context for evaluating virtual
2136 * generated column not null constraint expressions (creating it if it's
2137 * not already there).
2138 */
2139 econtext = GetPerTupleExprContext(estate);
2140
2141 /* Arrange for econtext's scan tuple to be the tuple under test */
2142 econtext->ecxt_scantuple = slot;
2143
2144 /* And evaluate the check constraints for virtual generated column */
2146 {
2148 ExprState *exprstate = resultRelInfo->ri_GenVirtualNotNullConstraintExprs[i];
2149
2150 Assert(exprstate != NULL);
2151 if (!ExecCheck(exprstate, econtext))
2152 return attnum;
2153 }
2154
2155 /* InvalidAttrNumber result means no error */
2156 return InvalidAttrNumber;
2157}
#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:1977
Node * build_generation_expression(Relation rel, int attrno)
ExprState ** ri_GenVirtualNotNullConstraintExprs
Definition execnodes.h:563

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

Referenced by ATRewriteTable(), and ExecConstraints().

◆ ExecUpdateLockMode()

LockTupleMode ExecUpdateLockMode ( EState estate,
ResultRelInfo relinfo 
)

Definition at line 2534 of file execMain.c.

2535{
2537 Bitmapset *updatedCols;
2538
2539 /*
2540 * Compute lock mode to use. If columns that are part of the key have not
2541 * been modified, then we can use a weaker lock, allowing for better
2542 * concurrency.
2543 */
2544 updatedCols = ExecGetAllUpdatedCols(relinfo, estate);
2545 keyCols = RelationGetIndexAttrBitmap(relinfo->ri_RelationDesc,
2547
2548 if (bms_overlap(keyCols, updatedCols))
2549 return LockTupleExclusive;
2550
2552}
bool bms_overlap(const Bitmapset *a, const Bitmapset *b)
Definition bitmapset.c:581
Bitmapset * ExecGetAllUpdatedCols(ResultRelInfo *relinfo, EState *estate)
Definition execUtils.c:1418
@ LockTupleExclusive
Definition lockoptions.h:58
@ LockTupleNoKeyExclusive
Definition lockoptions.h:56
Bitmapset * RelationGetIndexAttrBitmap(Relation relation, IndexAttrBitmapKind attrKind)
Definition relcache.c:5298
@ INDEX_ATTR_BITMAP_KEY
Definition relcache.h:69

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

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

◆ ExecutePlan()

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

Definition at line 1660 of file execMain.c.

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

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

Referenced by standard_ExecutorRun().

◆ ExecutorEnd()

void ExecutorEnd ( QueryDesc queryDesc)

Definition at line 466 of file execMain.c.

467{
469 (*ExecutorEnd_hook) (queryDesc);
470 else
471 standard_ExecutorEnd(queryDesc);
472}
ExecutorEnd_hook_type ExecutorEnd_hook
Definition execMain.c:71
void standard_ExecutorEnd(QueryDesc *queryDesc)
Definition execMain.c:475

References ExecutorEnd_hook, and standard_ExecutorEnd().

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

◆ ExecutorFinish()

void ExecutorFinish ( QueryDesc queryDesc)

Definition at line 406 of file execMain.c.

407{
409 (*ExecutorFinish_hook) (queryDesc);
410 else
411 standard_ExecutorFinish(queryDesc);
412}
ExecutorFinish_hook_type ExecutorFinish_hook
Definition execMain.c:70
void standard_ExecutorFinish(QueryDesc *queryDesc)
Definition execMain.c:415

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

537{
538 EState *estate;
539 MemoryContext oldcontext;
540
541 /* sanity checks */
542 Assert(queryDesc != NULL);
543
544 estate = queryDesc->estate;
545
546 Assert(estate != NULL);
547
548 /* It's probably not sensible to rescan updating queries */
549 Assert(queryDesc->operation == CMD_SELECT);
550
551 /*
552 * Switch into per-query memory context
553 */
554 oldcontext = MemoryContextSwitchTo(estate->es_query_cxt);
555
556 /*
557 * rescan plan
558 */
559 ExecReScan(queryDesc->planstate);
560
561 MemoryContextSwitchTo(oldcontext);
562}
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(), fb(), MemoryContextSwitchTo(), QueryDesc::operation, and QueryDesc::planstate.

Referenced by DoPortalRewind(), and PersistHoldablePortal().

◆ ExecutorRun()

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

Definition at line 297 of file execMain.c.

299{
301 (*ExecutorRun_hook) (queryDesc, direction, count);
302 else
303 standard_ExecutorRun(queryDesc, direction, count);
304}
ExecutorRun_hook_type ExecutorRun_hook
Definition execMain.c:69
void standard_ExecutorRun(QueryDesc *queryDesc, ScanDirection direction, uint64 count)
Definition execMain.c:307

References ExecutorRun_hook, and standard_ExecutorRun().

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

◆ ExecutorStart()

void ExecutorStart ( QueryDesc queryDesc,
int  eflags 
)

Definition at line 122 of file execMain.c.

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

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

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

◆ ExecWithCheckOptions()

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

Definition at line 2232 of file execMain.c.

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

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

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

◆ InitPlan()

static void InitPlan ( QueryDesc queryDesc,
int  eflags 
)
static

Definition at line 836 of file execMain.c.

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

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

Referenced by standard_ExecutorStart().

◆ InitResultRelInfo()

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

Definition at line 1247 of file execMain.c.

1252{
1253 MemSet(resultRelInfo, 0, sizeof(ResultRelInfo));
1254 resultRelInfo->type = T_ResultRelInfo;
1255 resultRelInfo->ri_RangeTableIndex = resultRelationIndex;
1256 resultRelInfo->ri_RelationDesc = resultRelationDesc;
1257 resultRelInfo->ri_NumIndices = 0;
1258 resultRelInfo->ri_IndexRelationDescs = NULL;
1259 resultRelInfo->ri_IndexRelationInfo = NULL;
1260 resultRelInfo->ri_needLockTagTuple =
1262 /* make a copy so as not to depend on relcache info not changing... */
1263 resultRelInfo->ri_TrigDesc = CopyTriggerDesc(resultRelationDesc->trigdesc);
1264 if (resultRelInfo->ri_TrigDesc)
1265 {
1266 int n = resultRelInfo->ri_TrigDesc->numtriggers;
1267
1268 resultRelInfo->ri_TrigFunctions = (FmgrInfo *)
1270 resultRelInfo->ri_TrigWhenExprs = (ExprState **)
1272 if (instrument_options)
1273 resultRelInfo->ri_TrigInstrument = InstrAlloc(n, instrument_options, false);
1274 }
1275 else
1276 {
1277 resultRelInfo->ri_TrigFunctions = NULL;
1278 resultRelInfo->ri_TrigWhenExprs = NULL;
1279 resultRelInfo->ri_TrigInstrument = NULL;
1280 }
1281 if (resultRelationDesc->rd_rel->relkind == RELKIND_FOREIGN_TABLE)
1283 else
1284 resultRelInfo->ri_FdwRoutine = NULL;
1285
1286 /* The following fields are set later if needed */
1287 resultRelInfo->ri_RowIdAttNo = 0;
1288 resultRelInfo->ri_extraUpdatedCols = NULL;
1289 resultRelInfo->ri_projectNew = NULL;
1290 resultRelInfo->ri_newTupleSlot = NULL;
1291 resultRelInfo->ri_oldTupleSlot = NULL;
1292 resultRelInfo->ri_projectNewInfoValid = false;
1293 resultRelInfo->ri_FdwState = NULL;
1294 resultRelInfo->ri_usesFdwDirectModify = false;
1295 resultRelInfo->ri_CheckConstraintExprs = NULL;
1297 resultRelInfo->ri_GeneratedExprsI = NULL;
1298 resultRelInfo->ri_GeneratedExprsU = NULL;
1299 resultRelInfo->ri_projectReturning = NULL;
1300 resultRelInfo->ri_onConflictArbiterIndexes = NIL;
1301 resultRelInfo->ri_onConflict = NULL;
1302 resultRelInfo->ri_ReturningSlot = NULL;
1303 resultRelInfo->ri_TrigOldSlot = NULL;
1304 resultRelInfo->ri_TrigNewSlot = NULL;
1305 resultRelInfo->ri_AllNullSlot = NULL;
1306 resultRelInfo->ri_MergeActions[MERGE_WHEN_MATCHED] = NIL;
1309 resultRelInfo->ri_MergeJoinCondition = NULL;
1310
1311 /*
1312 * Only ExecInitPartitionInfo() and ExecInitPartitionDispatchInfo() pass
1313 * non-NULL partition_root_rri. For child relations that are part of the
1314 * initial query rather than being dynamically added by tuple routing,
1315 * this field is filled in ExecInitModifyTable().
1316 */
1318 /* Set by ExecGetRootToChildMap */
1319 resultRelInfo->ri_RootToChildMap = NULL;
1320 resultRelInfo->ri_RootToChildMapValid = false;
1321 /* Set by ExecInitRoutingInfo */
1322 resultRelInfo->ri_PartitionTupleSlot = NULL;
1323 resultRelInfo->ri_ChildToRootMap = NULL;
1324 resultRelInfo->ri_ChildToRootMapValid = false;
1325 resultRelInfo->ri_CopyMultiInsertBuffer = NULL;
1326}
#define MemSet(start, val, len)
Definition c.h:1013
Instrumentation * InstrAlloc(int n, int instrument_options, bool async_mode)
Definition instrument.c:31
@ MERGE_WHEN_NOT_MATCHED_BY_TARGET
Definition primnodes.h:2023
@ MERGE_WHEN_NOT_MATCHED_BY_SOURCE
Definition primnodes.h:2022
@ MERGE_WHEN_MATCHED
Definition primnodes.h:2021
TupleConversionMap * ri_RootToChildMap
Definition execnodes.h:608
TupleTableSlot * ri_PartitionTupleSlot
Definition execnodes.h:621
bool ri_projectNewInfoValid
Definition execnodes.h:511
OnConflictSetState * ri_onConflict
Definition execnodes.h:585
List * ri_onConflictArbiterIndexes
Definition execnodes.h:582
Instrumentation * ri_TrigInstrument
Definition execnodes.h:526
ExprState * ri_MergeJoinCondition
Definition execnodes.h:591
RelationPtr ri_IndexRelationDescs
Definition execnodes.h:488
TupleTableSlot * ri_ReturningSlot
Definition execnodes.h:529
TupleTableSlot * ri_oldTupleSlot
Definition execnodes.h:509
bool ri_RootToChildMapValid
Definition execnodes.h:609
struct CopyMultiInsertBuffer * ri_CopyMultiInsertBuffer
Definition execnodes.h:624
TriggerDesc * ri_TrigDesc
Definition execnodes.h:517
TupleTableSlot * ri_AllNullSlot
Definition execnodes.h:532
Bitmapset * ri_extraUpdatedCols
Definition execnodes.h:500
ExprState ** ri_GeneratedExprsI
Definition execnodes.h:568
TupleConversionMap * ri_ChildToRootMap
Definition execnodes.h:602
void * ri_FdwState
Definition execnodes.h:538
bool ri_ChildToRootMapValid
Definition execnodes.h:603
List * ri_MergeActions[NUM_MERGE_MATCH_KINDS]
Definition execnodes.h:588
TupleTableSlot * ri_newTupleSlot
Definition execnodes.h:507
ProjectionInfo * ri_projectNew
Definition execnodes.h:505
NodeTag type
Definition execnodes.h:476
ProjectionInfo * ri_projectReturning
Definition execnodes.h:579
ExprState ** ri_GeneratedExprsU
Definition execnodes.h:569
ExprState ** ri_TrigWhenExprs
Definition execnodes.h:523
FmgrInfo * ri_TrigFunctions
Definition execnodes.h:520
bool ri_usesFdwDirectModify
Definition execnodes.h:541
AttrNumber ri_RowIdAttNo
Definition execnodes.h:497
IndexInfo ** ri_IndexRelationInfo
Definition execnodes.h:491
TupleTableSlot * ri_TrigNewSlot
Definition execnodes.h:531
TupleTableSlot * ri_TrigOldSlot
Definition execnodes.h:530
int numtriggers
Definition reltrigger.h:50
TriggerDesc * CopyTriggerDesc(TriggerDesc *trigdesc)
Definition trigger.c:2090

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

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

◆ ReportNotNullViolationError()

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

Definition at line 2163 of file execMain.c.

2165{
2167 char *val_desc;
2168 Relation rel = resultRelInfo->ri_RelationDesc;
2169 Relation orig_rel = rel;
2170 TupleDesc tupdesc = RelationGetDescr(rel);
2172 Form_pg_attribute att = TupleDescAttr(tupdesc, attnum - 1);
2173
2174 Assert(attnum > 0);
2175
2176 /*
2177 * If the tuple has been routed, it's been converted to the partition's
2178 * rowtype, which might differ from the root table's. We must convert it
2179 * back to the root table's rowtype so that val_desc shown error message
2180 * matches the input tuple.
2181 */
2182 if (resultRelInfo->ri_RootResultRelInfo)
2183 {
2184 ResultRelInfo *rootrel = resultRelInfo->ri_RootResultRelInfo;
2185 AttrMap *map;
2186
2187 tupdesc = RelationGetDescr(rootrel->ri_RelationDesc);
2188 /* a reverse map */
2190 tupdesc,
2191 false);
2192
2193 /*
2194 * Partition-specific slot's tupdesc can't be changed, so allocate a
2195 * new one.
2196 */
2197 if (map != NULL)
2198 slot = execute_attr_map_slot(map, slot,
2201 ExecGetUpdatedCols(rootrel, estate));
2202 rel = rootrel->ri_RelationDesc;
2203 }
2204 else
2205 modifiedCols = bms_union(ExecGetInsertedCols(resultRelInfo, estate),
2206 ExecGetUpdatedCols(resultRelInfo, estate));
2207
2209 slot,
2210 tupdesc,
2212 64);
2213 ereport(ERROR,
2215 errmsg("null value in column \"%s\" of relation \"%s\" violates not-null constraint",
2216 NameStr(att->attname),
2218 val_desc ? errdetail("Failing row contains %s.", val_desc) : 0,
2220}
int errtablecol(Relation rel, int attnum)
Definition relcache.c:6061

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

Referenced by ExecConstraints().

◆ standard_ExecutorEnd()

void standard_ExecutorEnd ( QueryDesc queryDesc)

Definition at line 475 of file execMain.c.

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

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

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

◆ standard_ExecutorFinish()

void standard_ExecutorFinish ( QueryDesc queryDesc)

Definition at line 415 of file execMain.c.

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

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

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

◆ standard_ExecutorRun()

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

Definition at line 307 of file execMain.c.

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

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

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

◆ standard_ExecutorStart()

void standard_ExecutorStart ( QueryDesc queryDesc,
int  eflags 
)

Definition at line 141 of file execMain.c.

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

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

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

Variable Documentation

◆ ExecutorCheckPerms_hook

ExecutorCheckPerms_hook_type ExecutorCheckPerms_hook = NULL

Definition at line 74 of file execMain.c.

Referenced by _PG_init(), and ExecCheckPermissions().

◆ ExecutorEnd_hook

ExecutorEnd_hook_type ExecutorEnd_hook = NULL

Definition at line 71 of file execMain.c.

Referenced by _PG_init(), and ExecutorEnd().

◆ ExecutorFinish_hook

ExecutorFinish_hook_type ExecutorFinish_hook = NULL

Definition at line 70 of file execMain.c.

Referenced by _PG_init(), and ExecutorFinish().

◆ ExecutorRun_hook

ExecutorRun_hook_type ExecutorRun_hook = NULL

Definition at line 69 of file execMain.c.

Referenced by _PG_init(), and ExecutorRun().

◆ ExecutorStart_hook

ExecutorStart_hook_type ExecutorStart_hook = NULL

Definition at line 68 of file execMain.c.

Referenced by _PG_init(), and ExecutorStart().