PostgreSQL Source Code  git master
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/nodeSubplan.h"
#include "foreign/fdwapi.h"
#include "mb/pg_wchar.h"
#include "miscadmin.h"
#include "nodes/queryjumble.h"
#include "parser/parse_relation.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.

Macros

#define EXEC_CHECK_QUERY_ID
 

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 (EState *estate, PlanState *planstate, bool use_parallel_mode, CmdType operation, bool sendTuples, uint64 numberTuples, ScanDirection direction, DestReceiver *dest, bool execute_once)
 
static bool ExecCheckOneRelPerms (RTEPermissionInfo *perminfo)
 
static bool ExecCheckPermissionsModified (Oid relOid, Oid userid, Bitmapset *modifiedCols, AclMode requiredPerms)
 
static void ExecCheckXactReadOnly (PlannedStmt *plannedstmt)
 
static void EvalPlanQualStart (EPQState *epqstate, Plan *planTree)
 
void ExecutorStart (QueryDesc *queryDesc, int eflags)
 
void standard_ExecutorStart (QueryDesc *queryDesc, int eflags)
 
void ExecutorRun (QueryDesc *queryDesc, ScanDirection direction, uint64 count, bool execute_once)
 
void standard_ExecutorRun (QueryDesc *queryDesc, ScanDirection direction, uint64 count, bool execute_once)
 
void ExecutorFinish (QueryDesc *queryDesc)
 
void standard_ExecutorFinish (QueryDesc *queryDesc)
 
void ExecutorEnd (QueryDesc *queryDesc)
 
void standard_ExecutorEnd (QueryDesc *queryDesc)
 
void ExecutorRewind (QueryDesc *queryDesc)
 
bool ExecCheckPermissions (List *rangeTable, List *rteperminfos, bool ereport_on_violation)
 
void CheckValidResultRel (ResultRelInfo *resultRelInfo, CmdType operation, List *mergeActions)
 
void InitResultRelInfo (ResultRelInfo *resultRelInfo, Relation resultRelationDesc, Index resultRelationIndex, ResultRelInfo *partition_root_rri, int instrument_options)
 
ResultRelInfoExecGetTriggerResultRel (EState *estate, Oid relid, ResultRelInfo *rootRelInfo)
 
ListExecGetAncestorResultRels (EState *estate, ResultRelInfo *resultRelInfo)
 
void ExecCloseResultRelations (EState *estate)
 
void ExecCloseRangeTableRelations (EState *estate)
 
static const char * ExecRelCheck (ResultRelInfo *resultRelInfo, TupleTableSlot *slot, EState *estate)
 
bool ExecPartitionCheck (ResultRelInfo *resultRelInfo, TupleTableSlot *slot, EState *estate, bool emitError)
 
void ExecPartitionCheckEmitError (ResultRelInfo *resultRelInfo, TupleTableSlot *slot, EState *estate)
 
void ExecConstraints (ResultRelInfo *resultRelInfo, TupleTableSlot *slot, EState *estate)
 
void ExecWithCheckOptions (WCOKind kind, ResultRelInfo *resultRelInfo, TupleTableSlot *slot, EState *estate)
 
char * ExecBuildSlotValueDescription (Oid reloid, TupleTableSlot *slot, TupleDesc tupdesc, Bitmapset *modifiedCols, int maxfieldlen)
 
LockTupleMode ExecUpdateLockMode (EState *estate, ResultRelInfo *relinfo)
 
ExecRowMarkExecFindRowMark (EState *estate, Index rti, bool missing_ok)
 
ExecAuxRowMarkExecBuildAuxRowMark (ExecRowMark *erm, List *targetlist)
 
TupleTableSlotEvalPlanQual (EPQState *epqstate, Relation relation, Index rti, TupleTableSlot *inputslot)
 
void EvalPlanQualInit (EPQState *epqstate, EState *parentestate, Plan *subplan, List *auxrowmarks, int epqParam, List *resultRelations)
 
void EvalPlanQualSetPlan (EPQState *epqstate, Plan *subplan, List *auxrowmarks)
 
TupleTableSlotEvalPlanQualSlot (EPQState *epqstate, Relation relation, Index rti)
 
bool EvalPlanQualFetchRowMark (EPQState *epqstate, Index rti, TupleTableSlot *slot)
 
TupleTableSlotEvalPlanQualNext (EPQState *epqstate)
 
void EvalPlanQualBegin (EPQState *epqstate)
 
void EvalPlanQualEnd (EPQState *epqstate)
 

Variables

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

Macro Definition Documentation

◆ EXEC_CHECK_QUERY_ID

#define EXEC_CHECK_QUERY_ID
Value:
do { \
} while(0)
uint64 pgstat_get_my_query_id(void)
bool pgstat_track_activities
const char * debug_query_string
Definition: postgres.c:88
static bool IsQueryIdEnabled(void)
Definition: queryjumble.h:77

Definition at line 80 of file execMain.c.

Function Documentation

◆ CheckValidResultRel()

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

Definition at line 1045 of file execMain.c.

1047 {
1048  Relation resultRel = resultRelInfo->ri_RelationDesc;
1049  FdwRoutine *fdwroutine;
1050 
1051  /* Expect a fully-formed ResultRelInfo from InitResultRelInfo(). */
1052  Assert(resultRelInfo->ri_needLockTagTuple ==
1053  IsInplaceUpdateRelation(resultRel));
1054 
1055  switch (resultRel->rd_rel->relkind)
1056  {
1057  case RELKIND_RELATION:
1058  case RELKIND_PARTITIONED_TABLE:
1059  CheckCmdReplicaIdentity(resultRel, operation);
1060  break;
1061  case RELKIND_SEQUENCE:
1062  ereport(ERROR,
1063  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1064  errmsg("cannot change sequence \"%s\"",
1065  RelationGetRelationName(resultRel))));
1066  break;
1067  case RELKIND_TOASTVALUE:
1068  ereport(ERROR,
1069  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1070  errmsg("cannot change TOAST relation \"%s\"",
1071  RelationGetRelationName(resultRel))));
1072  break;
1073  case RELKIND_VIEW:
1074 
1075  /*
1076  * Okay only if there's a suitable INSTEAD OF trigger. Otherwise,
1077  * complain, but omit errdetail because we haven't got the
1078  * information handy (and given that it really shouldn't happen,
1079  * it's not worth great exertion to get).
1080  */
1081  if (!view_has_instead_trigger(resultRel, operation, mergeActions))
1082  error_view_not_updatable(resultRel, operation, mergeActions,
1083  NULL);
1084  break;
1085  case RELKIND_MATVIEW:
1087  ereport(ERROR,
1088  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1089  errmsg("cannot change materialized view \"%s\"",
1090  RelationGetRelationName(resultRel))));
1091  break;
1092  case RELKIND_FOREIGN_TABLE:
1093  /* Okay only if the FDW supports it */
1094  fdwroutine = resultRelInfo->ri_FdwRoutine;
1095  switch (operation)
1096  {
1097  case CMD_INSERT:
1098  if (fdwroutine->ExecForeignInsert == NULL)
1099  ereport(ERROR,
1100  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1101  errmsg("cannot insert into foreign table \"%s\"",
1102  RelationGetRelationName(resultRel))));
1103  if (fdwroutine->IsForeignRelUpdatable != NULL &&
1104  (fdwroutine->IsForeignRelUpdatable(resultRel) & (1 << CMD_INSERT)) == 0)
1105  ereport(ERROR,
1106  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
1107  errmsg("foreign table \"%s\" does not allow inserts",
1108  RelationGetRelationName(resultRel))));
1109  break;
1110  case CMD_UPDATE:
1111  if (fdwroutine->ExecForeignUpdate == NULL)
1112  ereport(ERROR,
1113  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1114  errmsg("cannot update foreign table \"%s\"",
1115  RelationGetRelationName(resultRel))));
1116  if (fdwroutine->IsForeignRelUpdatable != NULL &&
1117  (fdwroutine->IsForeignRelUpdatable(resultRel) & (1 << CMD_UPDATE)) == 0)
1118  ereport(ERROR,
1119  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
1120  errmsg("foreign table \"%s\" does not allow updates",
1121  RelationGetRelationName(resultRel))));
1122  break;
1123  case CMD_DELETE:
1124  if (fdwroutine->ExecForeignDelete == NULL)
1125  ereport(ERROR,
1126  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1127  errmsg("cannot delete from foreign table \"%s\"",
1128  RelationGetRelationName(resultRel))));
1129  if (fdwroutine->IsForeignRelUpdatable != NULL &&
1130  (fdwroutine->IsForeignRelUpdatable(resultRel) & (1 << CMD_DELETE)) == 0)
1131  ereport(ERROR,
1132  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
1133  errmsg("foreign table \"%s\" does not allow deletes",
1134  RelationGetRelationName(resultRel))));
1135  break;
1136  default:
1137  elog(ERROR, "unrecognized CmdType: %d", (int) operation);
1138  break;
1139  }
1140  break;
1141  default:
1142  ereport(ERROR,
1143  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1144  errmsg("cannot change relation \"%s\"",
1145  RelationGetRelationName(resultRel))));
1146  break;
1147  }
1148 }
#define Assert(condition)
Definition: c.h:861
bool IsInplaceUpdateRelation(Relation relation)
Definition: catalog.c:152
int errcode(int sqlerrcode)
Definition: elog.c:853
int errmsg(const char *fmt,...)
Definition: elog.c:1070
#define ERROR
Definition: elog.h:39
#define elog(elevel,...)
Definition: elog.h:225
#define ereport(elevel,...)
Definition: elog.h:149
void CheckCmdReplicaIdentity(Relation rel, CmdType cmd)
bool MatViewIncrementalMaintenanceIsEnabled(void)
Definition: matview.c:970
@ CMD_INSERT
Definition: nodes.h:267
@ CMD_DELETE
Definition: nodes.h:268
@ CMD_UPDATE
Definition: nodes.h:266
#define RelationGetRelationName(relation)
Definition: rel.h:539
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:489
Relation ri_RelationDesc
Definition: execnodes.h:459
struct FdwRoutine * ri_FdwRoutine
Definition: execnodes.h:509

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

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

◆ CheckValidRowMarkRel()

static void CheckValidRowMarkRel ( Relation  rel,
RowMarkType  markType 
)
static

Definition at line 1157 of file execMain.c.

1158 {
1159  FdwRoutine *fdwroutine;
1160 
1161  switch (rel->rd_rel->relkind)
1162  {
1163  case RELKIND_RELATION:
1164  case RELKIND_PARTITIONED_TABLE:
1165  /* OK */
1166  break;
1167  case RELKIND_SEQUENCE:
1168  /* Must disallow this because we don't vacuum sequences */
1169  ereport(ERROR,
1170  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1171  errmsg("cannot lock rows in sequence \"%s\"",
1172  RelationGetRelationName(rel))));
1173  break;
1174  case RELKIND_TOASTVALUE:
1175  /* We could allow this, but there seems no good reason to */
1176  ereport(ERROR,
1177  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1178  errmsg("cannot lock rows in TOAST relation \"%s\"",
1179  RelationGetRelationName(rel))));
1180  break;
1181  case RELKIND_VIEW:
1182  /* Should not get here; planner should have expanded the view */
1183  ereport(ERROR,
1184  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1185  errmsg("cannot lock rows in view \"%s\"",
1186  RelationGetRelationName(rel))));
1187  break;
1188  case RELKIND_MATVIEW:
1189  /* Allow referencing a matview, but not actual locking clauses */
1190  if (markType != ROW_MARK_REFERENCE)
1191  ereport(ERROR,
1192  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1193  errmsg("cannot lock rows in materialized view \"%s\"",
1194  RelationGetRelationName(rel))));
1195  break;
1196  case RELKIND_FOREIGN_TABLE:
1197  /* Okay only if the FDW supports it */
1198  fdwroutine = GetFdwRoutineForRelation(rel, false);
1199  if (fdwroutine->RefetchForeignRow == NULL)
1200  ereport(ERROR,
1201  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1202  errmsg("cannot lock rows in foreign table \"%s\"",
1203  RelationGetRelationName(rel))));
1204  break;
1205  default:
1206  ereport(ERROR,
1207  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1208  errmsg("cannot lock rows in relation \"%s\"",
1209  RelationGetRelationName(rel))));
1210  break;
1211  }
1212 }
FdwRoutine * GetFdwRoutineForRelation(Relation relation, bool makecopy)
Definition: foreign.c:442
@ ROW_MARK_REFERENCE
Definition: plannodes.h:1334
RefetchForeignRow_function RefetchForeignRow
Definition: fdwapi.h:248

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

Referenced by InitPlan().

◆ EvalPlanQual()

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

Definition at line 2495 of file execMain.c.

2497 {
2498  TupleTableSlot *slot;
2499  TupleTableSlot *testslot;
2500 
2501  Assert(rti > 0);
2502 
2503  /*
2504  * Need to run a recheck subquery. Initialize or reinitialize EPQ state.
2505  */
2506  EvalPlanQualBegin(epqstate);
2507 
2508  /*
2509  * Callers will often use the EvalPlanQualSlot to store the tuple to avoid
2510  * an unnecessary copy.
2511  */
2512  testslot = EvalPlanQualSlot(epqstate, relation, rti);
2513  if (testslot != inputslot)
2514  ExecCopySlot(testslot, inputslot);
2515 
2516  /*
2517  * Mark that an EPQ tuple is available for this relation. (If there is
2518  * more than one result relation, the others remain marked as having no
2519  * tuple available.)
2520  */
2521  epqstate->relsubs_done[rti - 1] = false;
2522  epqstate->relsubs_blocked[rti - 1] = false;
2523 
2524  /*
2525  * Run the EPQ query. We assume it will return at most one tuple.
2526  */
2527  slot = EvalPlanQualNext(epqstate);
2528 
2529  /*
2530  * If we got a tuple, force the slot to materialize the tuple so that it
2531  * is not dependent on any local state in the EPQ query (in particular,
2532  * it's highly likely that the slot contains references to any pass-by-ref
2533  * datums that may be present in copyTuple). As with the next step, this
2534  * is to guard against early re-use of the EPQ query.
2535  */
2536  if (!TupIsNull(slot))
2537  ExecMaterializeSlot(slot);
2538 
2539  /*
2540  * Clear out the test tuple, and mark that no tuple is available here.
2541  * This is needed in case the EPQ state is re-used to test a tuple for a
2542  * different target relation.
2543  */
2544  ExecClearTuple(testslot);
2545  epqstate->relsubs_blocked[rti - 1] = true;
2546 
2547  return slot;
2548 }
void EvalPlanQualBegin(EPQState *epqstate)
Definition: execMain.c:2776
TupleTableSlot * EvalPlanQualNext(EPQState *epqstate)
Definition: execMain.c:2760
TupleTableSlot * EvalPlanQualSlot(EPQState *epqstate, Relation relation, Index rti)
Definition: execMain.c:2623
bool * relsubs_blocked
Definition: execnodes.h:1314
bool * relsubs_done
Definition: execnodes.h:1305
static TupleTableSlot * ExecClearTuple(TupleTableSlot *slot)
Definition: tuptable.h:454
static TupleTableSlot * ExecCopySlot(TupleTableSlot *dstslot, TupleTableSlot *srcslot)
Definition: tuptable.h:509
#define TupIsNull(slot)
Definition: tuptable.h:306
static void ExecMaterializeSlot(TupleTableSlot *slot)
Definition: tuptable.h:472

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

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

◆ EvalPlanQualBegin()

void EvalPlanQualBegin ( EPQState epqstate)

Definition at line 2776 of file execMain.c.

2777 {
2778  EState *parentestate = epqstate->parentestate;
2779  EState *recheckestate = epqstate->recheckestate;
2780 
2781  if (recheckestate == NULL)
2782  {
2783  /* First time through, so create a child EState */
2784  EvalPlanQualStart(epqstate, epqstate->plan);
2785  }
2786  else
2787  {
2788  /*
2789  * We already have a suitable child EPQ tree, so just reset it.
2790  */
2791  Index rtsize = parentestate->es_range_table_size;
2792  PlanState *rcplanstate = epqstate->recheckplanstate;
2793 
2794  /*
2795  * Reset the relsubs_done[] flags to equal relsubs_blocked[], so that
2796  * the EPQ run will never attempt to fetch tuples from blocked target
2797  * relations.
2798  */
2799  memcpy(epqstate->relsubs_done, epqstate->relsubs_blocked,
2800  rtsize * sizeof(bool));
2801 
2802  /* Recopy current values of parent parameters */
2803  if (parentestate->es_plannedstmt->paramExecTypes != NIL)
2804  {
2805  int i;
2806 
2807  /*
2808  * Force evaluation of any InitPlan outputs that could be needed
2809  * by the subplan, just in case they got reset since
2810  * EvalPlanQualStart (see comments therein).
2811  */
2812  ExecSetParamPlanMulti(rcplanstate->plan->extParam,
2813  GetPerTupleExprContext(parentestate));
2814 
2815  i = list_length(parentestate->es_plannedstmt->paramExecTypes);
2816 
2817  while (--i >= 0)
2818  {
2819  /* copy value if any, but not execPlan link */
2820  recheckestate->es_param_exec_vals[i].value =
2821  parentestate->es_param_exec_vals[i].value;
2822  recheckestate->es_param_exec_vals[i].isnull =
2823  parentestate->es_param_exec_vals[i].isnull;
2824  }
2825  }
2826 
2827  /*
2828  * Mark child plan tree as needing rescan at all scan nodes. The
2829  * first ExecProcNode will take care of actually doing the rescan.
2830  */
2831  rcplanstate->chgParam = bms_add_member(rcplanstate->chgParam,
2832  epqstate->epqParam);
2833  }
2834 }
Bitmapset * bms_add_member(Bitmapset *a, int x)
Definition: bitmapset.c:815
unsigned int Index
Definition: c.h:617
static void EvalPlanQualStart(EPQState *epqstate, Plan *planTree)
Definition: execMain.c:2843
#define GetPerTupleExprContext(estate)
Definition: executor.h:561
int i
Definition: isn.c:73
void ExecSetParamPlanMulti(const Bitmapset *params, ExprContext *econtext)
Definition: nodeSubplan.c:1263
static int list_length(const List *l)
Definition: pg_list.h:152
#define NIL
Definition: pg_list.h:68
Plan * plan
Definition: execnodes.h:1277
int epqParam
Definition: execnodes.h:1260
EState * parentestate
Definition: execnodes.h:1259
EState * recheckestate
Definition: execnodes.h:1291
PlanState * recheckplanstate
Definition: execnodes.h:1316
PlannedStmt * es_plannedstmt
Definition: execnodes.h:641
ParamExecData * es_param_exec_vals
Definition: execnodes.h:670
Index es_range_table_size
Definition: execnodes.h:635
bool isnull
Definition: params.h:150
Datum value
Definition: params.h:149
Plan * plan
Definition: execnodes.h:1123
Bitmapset * chgParam
Definition: execnodes.h:1155
Bitmapset * extParam
Definition: plannodes.h:171
List * paramExecTypes
Definition: plannodes.h:93

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

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

◆ EvalPlanQualEnd()

void EvalPlanQualEnd ( EPQState epqstate)

Definition at line 3007 of file execMain.c.

3008 {
3009  EState *estate = epqstate->recheckestate;
3010  Index rtsize;
3011  MemoryContext oldcontext;
3012  ListCell *l;
3013 
3014  rtsize = epqstate->parentestate->es_range_table_size;
3015 
3016  /*
3017  * We may have a tuple table, even if EPQ wasn't started, because we allow
3018  * use of EvalPlanQualSlot() without calling EvalPlanQualBegin().
3019  */
3020  if (epqstate->tuple_table != NIL)
3021  {
3022  memset(epqstate->relsubs_slot, 0,
3023  rtsize * sizeof(TupleTableSlot *));
3024  ExecResetTupleTable(epqstate->tuple_table, true);
3025  epqstate->tuple_table = NIL;
3026  }
3027 
3028  /* EPQ wasn't started, nothing further to do */
3029  if (estate == NULL)
3030  return;
3031 
3032  oldcontext = MemoryContextSwitchTo(estate->es_query_cxt);
3033 
3034  ExecEndNode(epqstate->recheckplanstate);
3035 
3036  foreach(l, estate->es_subplanstates)
3037  {
3038  PlanState *subplanstate = (PlanState *) lfirst(l);
3039 
3040  ExecEndNode(subplanstate);
3041  }
3042 
3043  /* throw away the per-estate tuple table, some node may have used it */
3044  ExecResetTupleTable(estate->es_tupleTable, false);
3045 
3046  /* Close any result and trigger target relations attached to this EState */
3047  ExecCloseResultRelations(estate);
3048 
3049  MemoryContextSwitchTo(oldcontext);
3050 
3051  FreeExecutorState(estate);
3052 
3053  /* Mark EPQState idle */
3054  epqstate->origslot = NULL;
3055  epqstate->recheckestate = NULL;
3056  epqstate->recheckplanstate = NULL;
3057  epqstate->relsubs_rowmark = NULL;
3058  epqstate->relsubs_done = NULL;
3059  epqstate->relsubs_blocked = NULL;
3060 }
void ExecCloseResultRelations(EState *estate)
Definition: execMain.c:1542
void ExecEndNode(PlanState *node)
Definition: execProcnode.c:562
void ExecResetTupleTable(List *tupleTable, bool shouldFree)
Definition: execTuples.c:1278
void FreeExecutorState(EState *estate)
Definition: execUtils.c:189
#define lfirst(lc)
Definition: pg_list.h:172
MemoryContextSwitchTo(old_ctx)
ExecAuxRowMark ** relsubs_rowmark
Definition: execnodes.h:1298
TupleTableSlot * origslot
Definition: execnodes.h:1286
TupleTableSlot ** relsubs_slot
Definition: execnodes.h:1270
List * tuple_table
Definition: execnodes.h:1269
MemoryContext es_query_cxt
Definition: execnodes.h:675
List * es_tupleTable
Definition: execnodes.h:677
List * es_subplanstates
Definition: execnodes.h:690

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

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

◆ EvalPlanQualFetchRowMark()

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

Definition at line 2651 of file execMain.c.

2652 {
2653  ExecAuxRowMark *earm = epqstate->relsubs_rowmark[rti - 1];
2654  ExecRowMark *erm = earm->rowmark;
2655  Datum datum;
2656  bool isNull;
2657 
2658  Assert(earm != NULL);
2659  Assert(epqstate->origslot != NULL);
2660 
2662  elog(ERROR, "EvalPlanQual doesn't support locking rowmarks");
2663 
2664  /* if child rel, must check whether it produced this row */
2665  if (erm->rti != erm->prti)
2666  {
2667  Oid tableoid;
2668 
2669  datum = ExecGetJunkAttribute(epqstate->origslot,
2670  earm->toidAttNo,
2671  &isNull);
2672  /* non-locked rels could be on the inside of outer joins */
2673  if (isNull)
2674  return false;
2675 
2676  tableoid = DatumGetObjectId(datum);
2677 
2678  Assert(OidIsValid(erm->relid));
2679  if (tableoid != erm->relid)
2680  {
2681  /* this child is inactive right now */
2682  return false;
2683  }
2684  }
2685 
2686  if (erm->markType == ROW_MARK_REFERENCE)
2687  {
2688  Assert(erm->relation != NULL);
2689 
2690  /* fetch the tuple's ctid */
2691  datum = ExecGetJunkAttribute(epqstate->origslot,
2692  earm->ctidAttNo,
2693  &isNull);
2694  /* non-locked rels could be on the inside of outer joins */
2695  if (isNull)
2696  return false;
2697 
2698  /* fetch requests on foreign tables must be passed to their FDW */
2699  if (erm->relation->rd_rel->relkind == RELKIND_FOREIGN_TABLE)
2700  {
2701  FdwRoutine *fdwroutine;
2702  bool updated = false;
2703 
2704  fdwroutine = GetFdwRoutineForRelation(erm->relation, false);
2705  /* this should have been checked already, but let's be safe */
2706  if (fdwroutine->RefetchForeignRow == NULL)
2707  ereport(ERROR,
2708  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2709  errmsg("cannot lock rows in foreign table \"%s\"",
2711 
2712  fdwroutine->RefetchForeignRow(epqstate->recheckestate,
2713  erm,
2714  datum,
2715  slot,
2716  &updated);
2717  if (TupIsNull(slot))
2718  elog(ERROR, "failed to fetch tuple for EvalPlanQual recheck");
2719 
2720  /*
2721  * Ideally we'd insist on updated == false here, but that assumes
2722  * that FDWs can track that exactly, which they might not be able
2723  * to. So just ignore the flag.
2724  */
2725  return true;
2726  }
2727  else
2728  {
2729  /* ordinary table, fetch the tuple */
2731  (ItemPointer) DatumGetPointer(datum),
2732  SnapshotAny, slot))
2733  elog(ERROR, "failed to fetch tuple for EvalPlanQual recheck");
2734  return true;
2735  }
2736  }
2737  else
2738  {
2739  Assert(erm->markType == ROW_MARK_COPY);
2740 
2741  /* fetch the whole-row Var for the relation */
2742  datum = ExecGetJunkAttribute(epqstate->origslot,
2743  earm->wholeAttNo,
2744  &isNull);
2745  /* non-locked rels could be on the inside of outer joins */
2746  if (isNull)
2747  return false;
2748 
2749  ExecStoreHeapTupleDatum(datum, slot);
2750  return true;
2751  }
2752 }
#define OidIsValid(objectId)
Definition: c.h:778
void ExecStoreHeapTupleDatum(Datum data, TupleTableSlot *slot)
Definition: execTuples.c:1693
static Datum ExecGetJunkAttribute(TupleTableSlot *slot, AttrNumber attno, bool *isNull)
Definition: executor.h:190
#define RowMarkRequiresRowShareLock(marktype)
Definition: plannodes.h:1338
@ ROW_MARK_COPY
Definition: plannodes.h:1335
uintptr_t Datum
Definition: postgres.h:64
static Oid DatumGetObjectId(Datum X)
Definition: postgres.h:242
static Pointer DatumGetPointer(Datum X)
Definition: postgres.h:312
unsigned int Oid
Definition: postgres_ext.h:31
#define SnapshotAny
Definition: snapmgr.h:33
AttrNumber wholeAttNo
Definition: execnodes.h:784
ExecRowMark * rowmark
Definition: execnodes.h:781
AttrNumber toidAttNo
Definition: execnodes.h:783
AttrNumber ctidAttNo
Definition: execnodes.h:782
Index rti
Definition: execnodes.h:759
Index prti
Definition: execnodes.h:760
Relation relation
Definition: execnodes.h:757
RowMarkType markType
Definition: execnodes.h:762
static bool table_tuple_fetch_row_version(Relation rel, ItemPointer tid, Snapshot snapshot, TupleTableSlot *slot)
Definition: tableam.h:1288

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

Referenced by ExecScanFetch().

◆ EvalPlanQualInit()

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

Definition at line 2564 of file execMain.c.

2567 {
2568  Index rtsize = parentestate->es_range_table_size;
2569 
2570  /* initialize data not changing over EPQState's lifetime */
2571  epqstate->parentestate = parentestate;
2572  epqstate->epqParam = epqParam;
2573  epqstate->resultRelations = resultRelations;
2574 
2575  /*
2576  * Allocate space to reference a slot for each potential rti - do so now
2577  * rather than in EvalPlanQualBegin(), as done for other dynamically
2578  * allocated resources, so EvalPlanQualSlot() can be used to hold tuples
2579  * that *may* need EPQ later, without forcing the overhead of
2580  * EvalPlanQualBegin().
2581  */
2582  epqstate->tuple_table = NIL;
2583  epqstate->relsubs_slot = (TupleTableSlot **)
2584  palloc0(rtsize * sizeof(TupleTableSlot *));
2585 
2586  /* ... and remember data that EvalPlanQualBegin will need */
2587  epqstate->plan = subplan;
2588  epqstate->arowMarks = auxrowmarks;
2589 
2590  /* ... and mark the EPQ state inactive */
2591  epqstate->origslot = NULL;
2592  epqstate->recheckestate = NULL;
2593  epqstate->recheckplanstate = NULL;
2594  epqstate->relsubs_rowmark = NULL;
2595  epqstate->relsubs_done = NULL;
2596  epqstate->relsubs_blocked = NULL;
2597 }
void * palloc0(Size size)
Definition: mcxt.c:1347
List * resultRelations
Definition: execnodes.h:1261
List * arowMarks
Definition: execnodes.h:1278

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

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

◆ EvalPlanQualNext()

TupleTableSlot* EvalPlanQualNext ( EPQState epqstate)

Definition at line 2760 of file execMain.c.

2761 {
2762  MemoryContext oldcontext;
2763  TupleTableSlot *slot;
2764 
2765  oldcontext = MemoryContextSwitchTo(epqstate->recheckestate->es_query_cxt);
2766  slot = ExecProcNode(epqstate->recheckplanstate);
2767  MemoryContextSwitchTo(oldcontext);
2768 
2769  return slot;
2770 }
static TupleTableSlot * ExecProcNode(PlanState *node)
Definition: executor.h:273

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

2607 {
2608  /* If we have a live EPQ query, shut it down */
2609  EvalPlanQualEnd(epqstate);
2610  /* And set/change the plan pointer */
2611  epqstate->plan = subplan;
2612  /* The rowmarks depend on the plan, too */
2613  epqstate->arowMarks = auxrowmarks;
2614 }
void EvalPlanQualEnd(EPQState *epqstate)
Definition: execMain.c:3007

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

Referenced by ExecInitModifyTable().

◆ EvalPlanQualSlot()

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

Definition at line 2623 of file execMain.c.

2625 {
2626  TupleTableSlot **slot;
2627 
2628  Assert(relation);
2629  Assert(rti > 0 && rti <= epqstate->parentestate->es_range_table_size);
2630  slot = &epqstate->relsubs_slot[rti - 1];
2631 
2632  if (*slot == NULL)
2633  {
2634  MemoryContext oldcontext;
2635 
2636  oldcontext = MemoryContextSwitchTo(epqstate->parentestate->es_query_cxt);
2637  *slot = table_slot_create(relation, &epqstate->tuple_table);
2638  MemoryContextSwitchTo(oldcontext);
2639  }
2640 
2641  return *slot;
2642 }
TupleTableSlot * table_slot_create(Relation relation, List **reglist)
Definition: tableam.c:91

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

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

◆ EvalPlanQualStart()

static void EvalPlanQualStart ( EPQState epqstate,
Plan planTree 
)
static

Definition at line 2843 of file execMain.c.

2844 {
2845  EState *parentestate = epqstate->parentestate;
2846  Index rtsize = parentestate->es_range_table_size;
2847  EState *rcestate;
2848  MemoryContext oldcontext;
2849  ListCell *l;
2850 
2851  epqstate->recheckestate = rcestate = CreateExecutorState();
2852 
2853  oldcontext = MemoryContextSwitchTo(rcestate->es_query_cxt);
2854 
2855  /* signal that this is an EState for executing EPQ */
2856  rcestate->es_epq_active = epqstate;
2857 
2858  /*
2859  * Child EPQ EStates share the parent's copy of unchanging state such as
2860  * the snapshot, rangetable, and external Param info. They need their own
2861  * copies of local state, including a tuple table, es_param_exec_vals,
2862  * result-rel info, etc.
2863  */
2864  rcestate->es_direction = ForwardScanDirection;
2865  rcestate->es_snapshot = parentestate->es_snapshot;
2866  rcestate->es_crosscheck_snapshot = parentestate->es_crosscheck_snapshot;
2867  rcestate->es_range_table = parentestate->es_range_table;
2868  rcestate->es_range_table_size = parentestate->es_range_table_size;
2869  rcestate->es_relations = parentestate->es_relations;
2870  rcestate->es_rowmarks = parentestate->es_rowmarks;
2871  rcestate->es_rteperminfos = parentestate->es_rteperminfos;
2872  rcestate->es_plannedstmt = parentestate->es_plannedstmt;
2873  rcestate->es_junkFilter = parentestate->es_junkFilter;
2874  rcestate->es_output_cid = parentestate->es_output_cid;
2875  rcestate->es_queryEnv = parentestate->es_queryEnv;
2876 
2877  /*
2878  * ResultRelInfos needed by subplans are initialized from scratch when the
2879  * subplans themselves are initialized.
2880  */
2881  rcestate->es_result_relations = NULL;
2882  /* es_trig_target_relations must NOT be copied */
2883  rcestate->es_top_eflags = parentestate->es_top_eflags;
2884  rcestate->es_instrument = parentestate->es_instrument;
2885  /* es_auxmodifytables must NOT be copied */
2886 
2887  /*
2888  * The external param list is simply shared from parent. The internal
2889  * param workspace has to be local state, but we copy the initial values
2890  * from the parent, so as to have access to any param values that were
2891  * already set from other parts of the parent's plan tree.
2892  */
2893  rcestate->es_param_list_info = parentestate->es_param_list_info;
2894  if (parentestate->es_plannedstmt->paramExecTypes != NIL)
2895  {
2896  int i;
2897 
2898  /*
2899  * Force evaluation of any InitPlan outputs that could be needed by
2900  * the subplan. (With more complexity, maybe we could postpone this
2901  * till the subplan actually demands them, but it doesn't seem worth
2902  * the trouble; this is a corner case already, since usually the
2903  * InitPlans would have been evaluated before reaching EvalPlanQual.)
2904  *
2905  * This will not touch output params of InitPlans that occur somewhere
2906  * within the subplan tree, only those that are attached to the
2907  * ModifyTable node or above it and are referenced within the subplan.
2908  * That's OK though, because the planner would only attach such
2909  * InitPlans to a lower-level SubqueryScan node, and EPQ execution
2910  * will not descend into a SubqueryScan.
2911  *
2912  * The EState's per-output-tuple econtext is sufficiently short-lived
2913  * for this, since it should get reset before there is any chance of
2914  * doing EvalPlanQual again.
2915  */
2916  ExecSetParamPlanMulti(planTree->extParam,
2917  GetPerTupleExprContext(parentestate));
2918 
2919  /* now make the internal param workspace ... */
2920  i = list_length(parentestate->es_plannedstmt->paramExecTypes);
2921  rcestate->es_param_exec_vals = (ParamExecData *)
2922  palloc0(i * sizeof(ParamExecData));
2923  /* ... and copy down all values, whether really needed or not */
2924  while (--i >= 0)
2925  {
2926  /* copy value if any, but not execPlan link */
2927  rcestate->es_param_exec_vals[i].value =
2928  parentestate->es_param_exec_vals[i].value;
2929  rcestate->es_param_exec_vals[i].isnull =
2930  parentestate->es_param_exec_vals[i].isnull;
2931  }
2932  }
2933 
2934  /*
2935  * Initialize private state information for each SubPlan. We must do this
2936  * before running ExecInitNode on the main query tree, since
2937  * ExecInitSubPlan expects to be able to find these entries. Some of the
2938  * SubPlans might not be used in the part of the plan tree we intend to
2939  * run, but since it's not easy to tell which, we just initialize them
2940  * all.
2941  */
2942  Assert(rcestate->es_subplanstates == NIL);
2943  foreach(l, parentestate->es_plannedstmt->subplans)
2944  {
2945  Plan *subplan = (Plan *) lfirst(l);
2946  PlanState *subplanstate;
2947 
2948  subplanstate = ExecInitNode(subplan, rcestate, 0);
2949  rcestate->es_subplanstates = lappend(rcestate->es_subplanstates,
2950  subplanstate);
2951  }
2952 
2953  /*
2954  * Build an RTI indexed array of rowmarks, so that
2955  * EvalPlanQualFetchRowMark() can efficiently access the to be fetched
2956  * rowmark.
2957  */
2958  epqstate->relsubs_rowmark = (ExecAuxRowMark **)
2959  palloc0(rtsize * sizeof(ExecAuxRowMark *));
2960  foreach(l, epqstate->arowMarks)
2961  {
2962  ExecAuxRowMark *earm = (ExecAuxRowMark *) lfirst(l);
2963 
2964  epqstate->relsubs_rowmark[earm->rowmark->rti - 1] = earm;
2965  }
2966 
2967  /*
2968  * Initialize per-relation EPQ tuple states. Result relations, if any,
2969  * get marked as blocked; others as not-fetched.
2970  */
2971  epqstate->relsubs_done = palloc_array(bool, rtsize);
2972  epqstate->relsubs_blocked = palloc0_array(bool, rtsize);
2973 
2974  foreach(l, epqstate->resultRelations)
2975  {
2976  int rtindex = lfirst_int(l);
2977 
2978  Assert(rtindex > 0 && rtindex <= rtsize);
2979  epqstate->relsubs_blocked[rtindex - 1] = true;
2980  }
2981 
2982  memcpy(epqstate->relsubs_done, epqstate->relsubs_blocked,
2983  rtsize * sizeof(bool));
2984 
2985  /*
2986  * Initialize the private state information for all the nodes in the part
2987  * of the plan tree we need to run. This opens files, allocates storage
2988  * and leaves us ready to start processing tuples.
2989  */
2990  epqstate->recheckplanstate = ExecInitNode(planTree, rcestate, 0);
2991 
2992  MemoryContextSwitchTo(oldcontext);
2993 }
PlanState * ExecInitNode(Plan *node, EState *estate, int eflags)
Definition: execProcnode.c:142
EState * CreateExecutorState(void)
Definition: execUtils.c:88
#define palloc_array(type, count)
Definition: fe_memutils.h:64
#define palloc0_array(type, count)
Definition: fe_memutils.h:65
List * lappend(List *list, void *datum)
Definition: list.c:339
#define lfirst_int(lc)
Definition: pg_list.h:173
@ ForwardScanDirection
Definition: sdir.h:28
struct ExecRowMark ** es_rowmarks
Definition: execnodes.h:638
int es_top_eflags
Definition: execnodes.h:684
int es_instrument
Definition: execnodes.h:685
QueryEnvironment * es_queryEnv
Definition: execnodes.h:672
ResultRelInfo ** es_result_relations
Definition: execnodes.h:650
List * es_range_table
Definition: execnodes.h:634
List * es_rteperminfos
Definition: execnodes.h:640
ParamListInfo es_param_list_info
Definition: execnodes.h:669
ScanDirection es_direction
Definition: execnodes.h:631
struct EPQState * es_epq_active
Definition: execnodes.h:707
Relation * es_relations
Definition: execnodes.h:636
CommandId es_output_cid
Definition: execnodes.h:647
Snapshot es_snapshot
Definition: execnodes.h:632
JunkFilter * es_junkFilter
Definition: execnodes.h:644
Snapshot es_crosscheck_snapshot
Definition: execnodes.h:633
List * subplans
Definition: plannodes.h:82

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

Referenced by EvalPlanQualBegin().

◆ ExecBuildAuxRowMark()

ExecAuxRowMark* ExecBuildAuxRowMark ( ExecRowMark erm,
List targetlist 
)

Definition at line 2425 of file execMain.c.

2426 {
2427  ExecAuxRowMark *aerm = (ExecAuxRowMark *) palloc0(sizeof(ExecAuxRowMark));
2428  char resname[32];
2429 
2430  aerm->rowmark = erm;
2431 
2432  /* Look up the resjunk columns associated with this rowmark */
2433  if (erm->markType != ROW_MARK_COPY)
2434  {
2435  /* need ctid for all methods other than COPY */
2436  snprintf(resname, sizeof(resname), "ctid%u", erm->rowmarkId);
2437  aerm->ctidAttNo = ExecFindJunkAttributeInTlist(targetlist,
2438  resname);
2439  if (!AttributeNumberIsValid(aerm->ctidAttNo))
2440  elog(ERROR, "could not find junk %s column", resname);
2441  }
2442  else
2443  {
2444  /* need wholerow if COPY */
2445  snprintf(resname, sizeof(resname), "wholerow%u", erm->rowmarkId);
2446  aerm->wholeAttNo = ExecFindJunkAttributeInTlist(targetlist,
2447  resname);
2448  if (!AttributeNumberIsValid(aerm->wholeAttNo))
2449  elog(ERROR, "could not find junk %s column", resname);
2450  }
2451 
2452  /* if child rel, need tableoid */
2453  if (erm->rti != erm->prti)
2454  {
2455  snprintf(resname, sizeof(resname), "tableoid%u", erm->rowmarkId);
2456  aerm->toidAttNo = ExecFindJunkAttributeInTlist(targetlist,
2457  resname);
2458  if (!AttributeNumberIsValid(aerm->toidAttNo))
2459  elog(ERROR, "could not find junk %s column", resname);
2460  }
2461 
2462  return aerm;
2463 }
#define AttributeNumberIsValid(attributeNumber)
Definition: attnum.h:34
AttrNumber ExecFindJunkAttributeInTlist(List *targetlist, const char *attrName)
Definition: execJunk.c:222
#define snprintf
Definition: port.h:238
Index rowmarkId
Definition: execnodes.h:761

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

Referenced by ExecInitLockRows(), and ExecInitModifyTable().

◆ ExecBuildSlotValueDescription()

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

Definition at line 2239 of file execMain.c.

2244 {
2246  StringInfoData collist;
2247  bool write_comma = false;
2248  bool write_comma_collist = false;
2249  int i;
2250  AclResult aclresult;
2251  bool table_perm = false;
2252  bool any_perm = false;
2253 
2254  /*
2255  * Check if RLS is enabled and should be active for the relation; if so,
2256  * then don't return anything. Otherwise, go through normal permission
2257  * checks.
2258  */
2259  if (check_enable_rls(reloid, InvalidOid, true) == RLS_ENABLED)
2260  return NULL;
2261 
2262  initStringInfo(&buf);
2263 
2264  appendStringInfoChar(&buf, '(');
2265 
2266  /*
2267  * Check if the user has permissions to see the row. Table-level SELECT
2268  * allows access to all columns. If the user does not have table-level
2269  * SELECT then we check each column and include those the user has SELECT
2270  * rights on. Additionally, we always include columns the user provided
2271  * data for.
2272  */
2273  aclresult = pg_class_aclcheck(reloid, GetUserId(), ACL_SELECT);
2274  if (aclresult != ACLCHECK_OK)
2275  {
2276  /* Set up the buffer for the column list */
2277  initStringInfo(&collist);
2278  appendStringInfoChar(&collist, '(');
2279  }
2280  else
2281  table_perm = any_perm = true;
2282 
2283  /* Make sure the tuple is fully deconstructed */
2284  slot_getallattrs(slot);
2285 
2286  for (i = 0; i < tupdesc->natts; i++)
2287  {
2288  bool column_perm = false;
2289  char *val;
2290  int vallen;
2291  Form_pg_attribute att = TupleDescAttr(tupdesc, i);
2292 
2293  /* ignore dropped columns */
2294  if (att->attisdropped)
2295  continue;
2296 
2297  if (!table_perm)
2298  {
2299  /*
2300  * No table-level SELECT, so need to make sure they either have
2301  * SELECT rights on the column or that they have provided the data
2302  * for the column. If not, omit this column from the error
2303  * message.
2304  */
2305  aclresult = pg_attribute_aclcheck(reloid, att->attnum,
2306  GetUserId(), ACL_SELECT);
2308  modifiedCols) || aclresult == ACLCHECK_OK)
2309  {
2310  column_perm = any_perm = true;
2311 
2312  if (write_comma_collist)
2313  appendStringInfoString(&collist, ", ");
2314  else
2315  write_comma_collist = true;
2316 
2317  appendStringInfoString(&collist, NameStr(att->attname));
2318  }
2319  }
2320 
2321  if (table_perm || column_perm)
2322  {
2323  if (slot->tts_isnull[i])
2324  val = "null";
2325  else
2326  {
2327  Oid foutoid;
2328  bool typisvarlena;
2329 
2330  getTypeOutputInfo(att->atttypid,
2331  &foutoid, &typisvarlena);
2332  val = OidOutputFunctionCall(foutoid, slot->tts_values[i]);
2333  }
2334 
2335  if (write_comma)
2336  appendStringInfoString(&buf, ", ");
2337  else
2338  write_comma = true;
2339 
2340  /* truncate if needed */
2341  vallen = strlen(val);
2342  if (vallen <= maxfieldlen)
2343  appendBinaryStringInfo(&buf, val, vallen);
2344  else
2345  {
2346  vallen = pg_mbcliplen(val, vallen, maxfieldlen);
2347  appendBinaryStringInfo(&buf, val, vallen);
2348  appendStringInfoString(&buf, "...");
2349  }
2350  }
2351  }
2352 
2353  /* If we end up with zero columns being returned, then return NULL. */
2354  if (!any_perm)
2355  return NULL;
2356 
2357  appendStringInfoChar(&buf, ')');
2358 
2359  if (!table_perm)
2360  {
2361  appendStringInfoString(&collist, ") = ");
2362  appendBinaryStringInfo(&collist, buf.data, buf.len);
2363 
2364  return collist.data;
2365  }
2366 
2367  return buf.data;
2368 }
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:3923
AclResult pg_class_aclcheck(Oid table_oid, Oid roleid, AclMode mode)
Definition: aclchk.c:4094
bool bms_is_member(int x, const Bitmapset *a)
Definition: bitmapset.c:510
#define NameStr(name)
Definition: c.h:749
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:2907
int pg_mbcliplen(const char *mbstr, int len, int limit)
Definition: mbutils.c:1083
Oid GetUserId(void)
Definition: miscinit.c:514
#define ACL_SELECT
Definition: parsenodes.h:77
FormData_pg_attribute * Form_pg_attribute
Definition: pg_attribute.h:209
static char * buf
Definition: pg_test_fsync.c:73
#define InvalidOid
Definition: postgres_ext.h:36
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:233
void appendStringInfoString(StringInfo str, const char *s)
Definition: stringinfo.c:182
void appendStringInfoChar(StringInfo str, char ch)
Definition: stringinfo.c:194
void initStringInfo(StringInfo str)
Definition: stringinfo.c:59
bool * tts_isnull
Definition: tuptable.h:127
Datum * tts_values
Definition: tuptable.h:125
#define FirstLowInvalidHeapAttributeNumber
Definition: sysattr.h:27
#define TupleDescAttr(tupdesc, i)
Definition: tupdesc.h:92
static void slot_getallattrs(TupleTableSlot *slot)
Definition: tuptable.h:368

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

Referenced by build_tuple_value_details(), ExecConstraints(), ExecPartitionCheckEmitError(), and ExecWithCheckOptions().

◆ ExecCheckOneRelPerms()

static bool ExecCheckOneRelPerms ( RTEPermissionInfo perminfo)
static

Definition at line 662 of file execMain.c.

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

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

Referenced by ExecCheckPermissions().

◆ ExecCheckPermissions()

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

Definition at line 598 of file execMain.c.

600 {
601  ListCell *l;
602  bool result = true;
603 
604 #ifdef USE_ASSERT_CHECKING
605  Bitmapset *indexset = NULL;
606 
607  /* Check that rteperminfos is consistent with rangeTable */
608  foreach(l, rangeTable)
609  {
611 
612  if (rte->perminfoindex != 0)
613  {
614  /* Sanity checks */
615 
616  /*
617  * Only relation RTEs and subquery RTEs that were once relation
618  * RTEs (views) have their perminfoindex set.
619  */
620  Assert(rte->rtekind == RTE_RELATION ||
621  (rte->rtekind == RTE_SUBQUERY &&
622  rte->relkind == RELKIND_VIEW));
623 
624  (void) getRTEPermissionInfo(rteperminfos, rte);
625  /* Many-to-one mapping not allowed */
626  Assert(!bms_is_member(rte->perminfoindex, indexset));
627  indexset = bms_add_member(indexset, rte->perminfoindex);
628  }
629  }
630 
631  /* All rteperminfos are referenced */
632  Assert(bms_num_members(indexset) == list_length(rteperminfos));
633 #endif
634 
635  foreach(l, rteperminfos)
636  {
638 
639  Assert(OidIsValid(perminfo->relid));
640  result = ExecCheckOneRelPerms(perminfo);
641  if (!result)
642  {
643  if (ereport_on_violation)
646  get_rel_name(perminfo->relid));
647  return false;
648  }
649  }
650 
652  result = (*ExecutorCheckPerms_hook) (rangeTable, rteperminfos,
653  ereport_on_violation);
654  return result;
655 }
@ ACLCHECK_NO_PRIV
Definition: acl.h:184
void aclcheck_error(AclResult aclerr, ObjectType objtype, const char *objectname)
Definition: aclchk.c:2703
int bms_num_members(const Bitmapset *a)
Definition: bitmapset.c:751
static bool ExecCheckOneRelPerms(RTEPermissionInfo *perminfo)
Definition: execMain.c:662
ExecutorCheckPerms_hook_type ExecutorCheckPerms_hook
Definition: execMain.c:72
char get_rel_relkind(Oid relid)
Definition: lsyscache.c:2003
char * get_rel_name(Oid relid)
Definition: lsyscache.c:1928
ObjectType get_relkind_objtype(char relkind)
RTEPermissionInfo * getRTEPermissionInfo(List *rteperminfos, RangeTblEntry *rte)
@ RTE_SUBQUERY
Definition: parsenodes.h:1018
@ RTE_RELATION
Definition: parsenodes.h:1017
#define lfirst_node(type, lc)
Definition: pg_list.h:176
RTEKind rtekind
Definition: parsenodes.h:1047

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

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

◆ ExecCheckPermissionsModified()

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

Definition at line 771 of file execMain.c.

773 {
774  int col = -1;
775 
776  /*
777  * When the query doesn't explicitly update any columns, allow the query
778  * if we have permission on any column of the rel. This is to handle
779  * SELECT FOR UPDATE as well as possible corner cases in UPDATE.
780  */
781  if (bms_is_empty(modifiedCols))
782  {
783  if (pg_attribute_aclcheck_all(relOid, userid, requiredPerms,
785  return false;
786  }
787 
788  while ((col = bms_next_member(modifiedCols, col)) >= 0)
789  {
790  /* bit #s are offset by FirstLowInvalidHeapAttributeNumber */
792 
793  if (attno == InvalidAttrNumber)
794  {
795  /* whole-row reference can't happen here */
796  elog(ERROR, "whole-row update is not implemented");
797  }
798  else
799  {
800  if (pg_attribute_aclcheck(relOid, attno, userid,
801  requiredPerms) != ACLCHECK_OK)
802  return false;
803  }
804  }
805  return true;
806 }

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

Referenced by ExecCheckOneRelPerms().

◆ ExecCheckXactReadOnly()

static void ExecCheckXactReadOnly ( PlannedStmt plannedstmt)
static

Definition at line 818 of file execMain.c.

819 {
820  ListCell *l;
821 
822  /*
823  * Fail if write permissions are requested in parallel mode for table
824  * (temp or non-temp), otherwise fail for any non-temp table.
825  */
826  foreach(l, plannedstmt->permInfos)
827  {
829 
830  if ((perminfo->requiredPerms & (~ACL_SELECT)) == 0)
831  continue;
832 
833  if (isTempNamespace(get_rel_namespace(perminfo->relid)))
834  continue;
835 
837  }
838 
839  if (plannedstmt->commandType != CMD_SELECT || plannedstmt->hasModifyingCTE)
841 }
Oid get_rel_namespace(Oid relid)
Definition: lsyscache.c:1952
bool isTempNamespace(Oid namespaceId)
Definition: namespace.c:3634
@ CMD_SELECT
Definition: nodes.h:265
Definition: nodes.h:129
bool hasModifyingCTE
Definition: plannodes.h:58
List * permInfos
Definition: plannodes.h:74
CmdType commandType
Definition: plannodes.h:52
void PreventCommandIfReadOnly(const char *cmdname)
Definition: utility.c:404
void PreventCommandIfParallelMode(const char *cmdname)
Definition: utility.c:422
static const char * CreateCommandName(Node *parsetree)
Definition: utility.h:103

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

Referenced by standard_ExecutorStart().

◆ ExecCloseRangeTableRelations()

void ExecCloseRangeTableRelations ( EState estate)

Definition at line 1602 of file execMain.c.

1603 {
1604  int i;
1605 
1606  for (i = 0; i < estate->es_range_table_size; i++)
1607  {
1608  if (estate->es_relations[i])
1609  table_close(estate->es_relations[i], NoLock);
1610  }
1611 }
#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 1542 of file execMain.c.

1543 {
1544  ListCell *l;
1545 
1546  /*
1547  * close indexes of result relation(s) if any. (Rels themselves are
1548  * closed in ExecCloseRangeTableRelations())
1549  *
1550  * In addition, close the stub RTs that may be in each resultrel's
1551  * ri_ancestorResultRels.
1552  */
1553  foreach(l, estate->es_opened_result_relations)
1554  {
1555  ResultRelInfo *resultRelInfo = lfirst(l);
1556  ListCell *lc;
1557 
1558  ExecCloseIndices(resultRelInfo);
1559  foreach(lc, resultRelInfo->ri_ancestorResultRels)
1560  {
1561  ResultRelInfo *rInfo = lfirst(lc);
1562 
1563  /*
1564  * Ancestors with RTI > 0 (should only be the root ancestor) are
1565  * closed by ExecCloseRangeTableRelations.
1566  */
1567  if (rInfo->ri_RangeTableIndex > 0)
1568  continue;
1569 
1571  }
1572  }
1573 
1574  /* Close any relations that have been opened by ExecGetTriggerResultRel(). */
1575  foreach(l, estate->es_trig_target_relations)
1576  {
1577  ResultRelInfo *resultRelInfo = (ResultRelInfo *) lfirst(l);
1578 
1579  /*
1580  * Assert this is a "dummy" ResultRelInfo, see above. Otherwise we
1581  * might be issuing a duplicate close against a Relation opened by
1582  * ExecGetRangeTableRelation.
1583  */
1584  Assert(resultRelInfo->ri_RangeTableIndex == 0);
1585 
1586  /*
1587  * Since ExecGetTriggerResultRel doesn't call ExecOpenIndices for
1588  * these rels, we needn't call ExecCloseIndices either.
1589  */
1590  Assert(resultRelInfo->ri_NumIndices == 0);
1591 
1592  table_close(resultRelInfo->ri_RelationDesc, NoLock);
1593  }
1594 }
void ExecCloseIndices(ResultRelInfo *resultRelInfo)
Definition: execIndexing.c:236
List * es_trig_target_relations
Definition: execnodes.h:666
List * es_opened_result_relations
Definition: execnodes.h:653
int ri_NumIndices
Definition: execnodes.h:462
Index ri_RangeTableIndex
Definition: execnodes.h:456
List * ri_ancestorResultRels
Definition: execnodes.h:600

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

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

◆ ExecConstraints()

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

Definition at line 1941 of file execMain.c.

1943 {
1944  Relation rel = resultRelInfo->ri_RelationDesc;
1945  TupleDesc tupdesc = RelationGetDescr(rel);
1946  TupleConstr *constr = tupdesc->constr;
1947  Bitmapset *modifiedCols;
1948 
1949  Assert(constr); /* we should not be called otherwise */
1950 
1951  if (constr->has_not_null)
1952  {
1953  int natts = tupdesc->natts;
1954  int attrChk;
1955 
1956  for (attrChk = 1; attrChk <= natts; attrChk++)
1957  {
1958  Form_pg_attribute att = TupleDescAttr(tupdesc, attrChk - 1);
1959 
1960  if (att->attnotnull && slot_attisnull(slot, attrChk))
1961  {
1962  char *val_desc;
1963  Relation orig_rel = rel;
1964  TupleDesc orig_tupdesc = RelationGetDescr(rel);
1965 
1966  /*
1967  * If the tuple has been routed, it's been converted to the
1968  * partition's rowtype, which might differ from the root
1969  * table's. We must convert it back to the root table's
1970  * rowtype so that val_desc shown error message matches the
1971  * input tuple.
1972  */
1973  if (resultRelInfo->ri_RootResultRelInfo)
1974  {
1975  ResultRelInfo *rootrel = resultRelInfo->ri_RootResultRelInfo;
1976  AttrMap *map;
1977 
1978  tupdesc = RelationGetDescr(rootrel->ri_RelationDesc);
1979  /* a reverse map */
1980  map = build_attrmap_by_name_if_req(orig_tupdesc,
1981  tupdesc,
1982  false);
1983 
1984  /*
1985  * Partition-specific slot's tupdesc can't be changed, so
1986  * allocate a new one.
1987  */
1988  if (map != NULL)
1989  slot = execute_attr_map_slot(map, slot,
1990  MakeTupleTableSlot(tupdesc, &TTSOpsVirtual));
1991  modifiedCols = bms_union(ExecGetInsertedCols(rootrel, estate),
1992  ExecGetUpdatedCols(rootrel, estate));
1993  rel = rootrel->ri_RelationDesc;
1994  }
1995  else
1996  modifiedCols = bms_union(ExecGetInsertedCols(resultRelInfo, estate),
1997  ExecGetUpdatedCols(resultRelInfo, estate));
1999  slot,
2000  tupdesc,
2001  modifiedCols,
2002  64);
2003 
2004  ereport(ERROR,
2005  (errcode(ERRCODE_NOT_NULL_VIOLATION),
2006  errmsg("null value in column \"%s\" of relation \"%s\" violates not-null constraint",
2007  NameStr(att->attname),
2008  RelationGetRelationName(orig_rel)),
2009  val_desc ? errdetail("Failing row contains %s.", val_desc) : 0,
2010  errtablecol(orig_rel, attrChk)));
2011  }
2012  }
2013  }
2014 
2015  if (rel->rd_rel->relchecks > 0)
2016  {
2017  const char *failed;
2018 
2019  if ((failed = ExecRelCheck(resultRelInfo, slot, estate)) != NULL)
2020  {
2021  char *val_desc;
2022  Relation orig_rel = rel;
2023 
2024  /* See the comment above. */
2025  if (resultRelInfo->ri_RootResultRelInfo)
2026  {
2027  ResultRelInfo *rootrel = resultRelInfo->ri_RootResultRelInfo;
2028  TupleDesc old_tupdesc = RelationGetDescr(rel);
2029  AttrMap *map;
2030 
2031  tupdesc = RelationGetDescr(rootrel->ri_RelationDesc);
2032  /* a reverse map */
2033  map = build_attrmap_by_name_if_req(old_tupdesc,
2034  tupdesc,
2035  false);
2036 
2037  /*
2038  * Partition-specific slot's tupdesc can't be changed, so
2039  * allocate a new one.
2040  */
2041  if (map != NULL)
2042  slot = execute_attr_map_slot(map, slot,
2043  MakeTupleTableSlot(tupdesc, &TTSOpsVirtual));
2044  modifiedCols = bms_union(ExecGetInsertedCols(rootrel, estate),
2045  ExecGetUpdatedCols(rootrel, estate));
2046  rel = rootrel->ri_RelationDesc;
2047  }
2048  else
2049  modifiedCols = bms_union(ExecGetInsertedCols(resultRelInfo, estate),
2050  ExecGetUpdatedCols(resultRelInfo, estate));
2052  slot,
2053  tupdesc,
2054  modifiedCols,
2055  64);
2056  ereport(ERROR,
2057  (errcode(ERRCODE_CHECK_VIOLATION),
2058  errmsg("new row for relation \"%s\" violates check constraint \"%s\"",
2059  RelationGetRelationName(orig_rel), failed),
2060  val_desc ? errdetail("Failing row contains %s.", val_desc) : 0,
2061  errtableconstraint(orig_rel, failed)));
2062  }
2063  }
2064 }
AttrMap * build_attrmap_by_name_if_req(TupleDesc indesc, TupleDesc outdesc, bool missing_ok)
Definition: attmap.c:263
Bitmapset * bms_union(const Bitmapset *a, const Bitmapset *b)
Definition: bitmapset.c:251
int errdetail(const char *fmt,...)
Definition: elog.c:1203
static const char * ExecRelCheck(ResultRelInfo *resultRelInfo, TupleTableSlot *slot, EState *estate)
Definition: execMain.c:1742
char * ExecBuildSlotValueDescription(Oid reloid, TupleTableSlot *slot, TupleDesc tupdesc, Bitmapset *modifiedCols, int maxfieldlen)
Definition: execMain.c:2239
TupleTableSlot * MakeTupleTableSlot(TupleDesc tupleDesc, const TupleTableSlotOps *tts_ops)
Definition: execTuples.c:1199
const TupleTableSlotOps TTSOpsVirtual
Definition: execTuples.c:84
Bitmapset * ExecGetUpdatedCols(ResultRelInfo *relinfo, EState *estate)
Definition: execUtils.c:1288
Bitmapset * ExecGetInsertedCols(ResultRelInfo *relinfo, EState *estate)
Definition: execUtils.c:1267
#define RelationGetRelid(relation)
Definition: rel.h:505
#define RelationGetDescr(relation)
Definition: rel.h:531
int errtableconstraint(Relation rel, const char *conname)
Definition: relcache.c:6015
int errtablecol(Relation rel, int attnum)
Definition: relcache.c:5978
Definition: attmap.h:35
struct ResultRelInfo * ri_RootResultRelInfo
Definition: execnodes.h:590
bool has_not_null
Definition: tupdesc.h:44
TupleConstr * constr
Definition: tupdesc.h:85
TupleTableSlot * execute_attr_map_slot(AttrMap *attrMap, TupleTableSlot *in_slot, TupleTableSlot *out_slot)
Definition: tupconvert.c:192
static bool slot_attisnull(TupleTableSlot *slot, int attnum)
Definition: tuptable.h:381

References Assert, bms_union(), build_attrmap_by_name_if_req(), TupleDescData::constr, ereport, errcode(), errdetail(), errmsg(), ERROR, errtablecol(), errtableconstraint(), ExecBuildSlotValueDescription(), ExecGetInsertedCols(), ExecGetUpdatedCols(), ExecRelCheck(), execute_attr_map_slot(), TupleConstr::has_not_null, MakeTupleTableSlot(), NameStr, TupleDescData::natts, RelationData::rd_rel, RelationGetDescr, RelationGetRelationName, RelationGetRelid, 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 1503 of file execMain.c.

1504 {
1505  ListCell *l;
1506 
1507  /*
1508  * shut down the node-type-specific query processing
1509  */
1510  ExecEndNode(planstate);
1511 
1512  /*
1513  * for subplans too
1514  */
1515  foreach(l, estate->es_subplanstates)
1516  {
1517  PlanState *subplanstate = (PlanState *) lfirst(l);
1518 
1519  ExecEndNode(subplanstate);
1520  }
1521 
1522  /*
1523  * destroy the executor's tuple table. Actually we only care about
1524  * releasing buffer pins and tupdesc refcounts; there's no need to pfree
1525  * the TupleTableSlots, since the containing memory context is about to go
1526  * away anyway.
1527  */
1528  ExecResetTupleTable(estate->es_tupleTable, false);
1529 
1530  /*
1531  * Close any Relations that have been opened for range table entries or
1532  * result relations.
1533  */
1534  ExecCloseResultRelations(estate);
1536 }
void ExecCloseRangeTableRelations(EState *estate)
Definition: execMain.c:1602

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

Referenced by standard_ExecutorEnd().

◆ ExecFindRowMark()

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

Definition at line 2402 of file execMain.c.

2403 {
2404  if (rti > 0 && rti <= estate->es_range_table_size &&
2405  estate->es_rowmarks != NULL)
2406  {
2407  ExecRowMark *erm = estate->es_rowmarks[rti - 1];
2408 
2409  if (erm)
2410  return erm;
2411  }
2412  if (!missing_ok)
2413  elog(ERROR, "failed to find ExecRowMark for rangetable index %u", rti);
2414  return NULL;
2415 }

References elog, ERROR, and EState::es_rowmarks.

Referenced by ExecInitLockRows(), and ExecInitModifyTable().

◆ ExecGetAncestorResultRels()

List* ExecGetAncestorResultRels ( EState estate,
ResultRelInfo resultRelInfo 
)

Definition at line 1397 of file execMain.c.

1398 {
1399  ResultRelInfo *rootRelInfo = resultRelInfo->ri_RootResultRelInfo;
1400  Relation partRel = resultRelInfo->ri_RelationDesc;
1401  Oid rootRelOid;
1402 
1403  if (!partRel->rd_rel->relispartition)
1404  elog(ERROR, "cannot find ancestors of a non-partition result relation");
1405  Assert(rootRelInfo != NULL);
1406  rootRelOid = RelationGetRelid(rootRelInfo->ri_RelationDesc);
1407  if (resultRelInfo->ri_ancestorResultRels == NIL)
1408  {
1409  ListCell *lc;
1410  List *oids = get_partition_ancestors(RelationGetRelid(partRel));
1411  List *ancResultRels = NIL;
1412 
1413  foreach(lc, oids)
1414  {
1415  Oid ancOid = lfirst_oid(lc);
1416  Relation ancRel;
1417  ResultRelInfo *rInfo;
1418 
1419  /*
1420  * Ignore the root ancestor here, and use ri_RootResultRelInfo
1421  * (below) for it instead. Also, we stop climbing up the
1422  * hierarchy when we find the table that was mentioned in the
1423  * query.
1424  */
1425  if (ancOid == rootRelOid)
1426  break;
1427 
1428  /*
1429  * All ancestors up to the root target relation must have been
1430  * locked by the planner or AcquireExecutorLocks().
1431  */
1432  ancRel = table_open(ancOid, NoLock);
1433  rInfo = makeNode(ResultRelInfo);
1434 
1435  /* dummy rangetable index */
1436  InitResultRelInfo(rInfo, ancRel, 0, NULL,
1437  estate->es_instrument);
1438  ancResultRels = lappend(ancResultRels, rInfo);
1439  }
1440  ancResultRels = lappend(ancResultRels, rootRelInfo);
1441  resultRelInfo->ri_ancestorResultRels = ancResultRels;
1442  }
1443 
1444  /* We must have found some ancestor */
1445  Assert(resultRelInfo->ri_ancestorResultRels != NIL);
1446 
1447  return resultRelInfo->ri_ancestorResultRels;
1448 }
void InitResultRelInfo(ResultRelInfo *resultRelInfo, Relation resultRelationDesc, Index resultRelationIndex, ResultRelInfo *partition_root_rri, int instrument_options)
Definition: execMain.c:1222
#define makeNode(_type_)
Definition: nodes.h:155
List * get_partition_ancestors(Oid relid)
Definition: partition.c:134
#define lfirst_oid(lc)
Definition: pg_list.h:174
Definition: pg_list.h:54
Relation table_open(Oid relationId, LOCKMODE lockmode)
Definition: table.c:40

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

Referenced by ExecCrossPartitionUpdateForeignKey().

◆ ExecGetTriggerResultRel()

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

Definition at line 1321 of file execMain.c.

1323 {
1324  ResultRelInfo *rInfo;
1325  ListCell *l;
1326  Relation rel;
1327  MemoryContext oldcontext;
1328 
1329  /* Search through the query result relations */
1330  foreach(l, estate->es_opened_result_relations)
1331  {
1332  rInfo = lfirst(l);
1333  if (RelationGetRelid(rInfo->ri_RelationDesc) == relid)
1334  return rInfo;
1335  }
1336 
1337  /*
1338  * Search through the result relations that were created during tuple
1339  * routing, if any.
1340  */
1341  foreach(l, estate->es_tuple_routing_result_relations)
1342  {
1343  rInfo = (ResultRelInfo *) lfirst(l);
1344  if (RelationGetRelid(rInfo->ri_RelationDesc) == relid)
1345  return rInfo;
1346  }
1347 
1348  /* Nope, but maybe we already made an extra ResultRelInfo for it */
1349  foreach(l, estate->es_trig_target_relations)
1350  {
1351  rInfo = (ResultRelInfo *) lfirst(l);
1352  if (RelationGetRelid(rInfo->ri_RelationDesc) == relid)
1353  return rInfo;
1354  }
1355  /* Nope, so we need a new one */
1356 
1357  /*
1358  * Open the target relation's relcache entry. We assume that an
1359  * appropriate lock is still held by the backend from whenever the trigger
1360  * event got queued, so we need take no new lock here. Also, we need not
1361  * recheck the relkind, so no need for CheckValidResultRel.
1362  */
1363  rel = table_open(relid, NoLock);
1364 
1365  /*
1366  * Make the new entry in the right context.
1367  */
1368  oldcontext = MemoryContextSwitchTo(estate->es_query_cxt);
1369  rInfo = makeNode(ResultRelInfo);
1370  InitResultRelInfo(rInfo,
1371  rel,
1372  0, /* dummy rangetable index */
1373  rootRelInfo,
1374  estate->es_instrument);
1375  estate->es_trig_target_relations =
1376  lappend(estate->es_trig_target_relations, rInfo);
1377  MemoryContextSwitchTo(oldcontext);
1378 
1379  /*
1380  * Currently, we don't need any index information in ResultRelInfos used
1381  * only for triggers, so no need to call ExecOpenIndices.
1382  */
1383 
1384  return rInfo;
1385 }
List * es_tuple_routing_result_relations
Definition: execnodes.h:663

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

Referenced by afterTriggerInvokeEvents().

◆ ExecPartitionCheck()

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

Definition at line 1817 of file execMain.c.

1819 {
1820  ExprContext *econtext;
1821  bool success;
1822 
1823  /*
1824  * If first time through, build expression state tree for the partition
1825  * check expression. (In the corner case where the partition check
1826  * expression is empty, ie there's a default partition and nothing else,
1827  * we'll be fooled into executing this code each time through. But it's
1828  * pretty darn cheap in that case, so we don't worry about it.)
1829  */
1830  if (resultRelInfo->ri_PartitionCheckExpr == NULL)
1831  {
1832  /*
1833  * Ensure that the qual tree and prepared expression are in the
1834  * query-lifespan context.
1835  */
1837  List *qual = RelationGetPartitionQual(resultRelInfo->ri_RelationDesc);
1838 
1839  resultRelInfo->ri_PartitionCheckExpr = ExecPrepareCheck(qual, estate);
1840  MemoryContextSwitchTo(oldcxt);
1841  }
1842 
1843  /*
1844  * We will use the EState's per-tuple context for evaluating constraint
1845  * expressions (creating it if it's not already there).
1846  */
1847  econtext = GetPerTupleExprContext(estate);
1848 
1849  /* Arrange for econtext's scan tuple to be the tuple under test */
1850  econtext->ecxt_scantuple = slot;
1851 
1852  /*
1853  * As in case of the cataloged constraints, we treat a NULL result as
1854  * success here, not a failure.
1855  */
1856  success = ExecCheck(resultRelInfo->ri_PartitionCheckExpr, econtext);
1857 
1858  /* if asked to emit error, don't actually return on failure */
1859  if (!success && emitError)
1860  ExecPartitionCheckEmitError(resultRelInfo, slot, estate);
1861 
1862  return success;
1863 }
bool ExecCheck(ExprState *state, ExprContext *econtext)
Definition: execExpr.c:850
ExprState * ExecPrepareCheck(List *qual, EState *estate)
Definition: execExpr.c:794
void ExecPartitionCheckEmitError(ResultRelInfo *resultRelInfo, TupleTableSlot *slot, EState *estate)
Definition: execMain.c:1870
static bool success
Definition: initdb.c:186
List * RelationGetPartitionQual(Relation rel)
Definition: partcache.c:277
TupleTableSlot * ecxt_scantuple
Definition: execnodes.h:258
ExprState * ri_PartitionCheckExpr
Definition: execnodes.h:562

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

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

◆ ExecPartitionCheckEmitError()

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

Definition at line 1870 of file execMain.c.

1873 {
1874  Oid root_relid;
1875  TupleDesc tupdesc;
1876  char *val_desc;
1877  Bitmapset *modifiedCols;
1878 
1879  /*
1880  * If the tuple has been routed, it's been converted to the partition's
1881  * rowtype, which might differ from the root table's. We must convert it
1882  * back to the root table's rowtype so that val_desc in the error message
1883  * matches the input tuple.
1884  */
1885  if (resultRelInfo->ri_RootResultRelInfo)
1886  {
1887  ResultRelInfo *rootrel = resultRelInfo->ri_RootResultRelInfo;
1888  TupleDesc old_tupdesc;
1889  AttrMap *map;
1890 
1891  root_relid = RelationGetRelid(rootrel->ri_RelationDesc);
1892  tupdesc = RelationGetDescr(rootrel->ri_RelationDesc);
1893 
1894  old_tupdesc = RelationGetDescr(resultRelInfo->ri_RelationDesc);
1895  /* a reverse map */
1896  map = build_attrmap_by_name_if_req(old_tupdesc, tupdesc, false);
1897 
1898  /*
1899  * Partition-specific slot's tupdesc can't be changed, so allocate a
1900  * new one.
1901  */
1902  if (map != NULL)
1903  slot = execute_attr_map_slot(map, slot,
1904  MakeTupleTableSlot(tupdesc, &TTSOpsVirtual));
1905  modifiedCols = bms_union(ExecGetInsertedCols(rootrel, estate),
1906  ExecGetUpdatedCols(rootrel, estate));
1907  }
1908  else
1909  {
1910  root_relid = RelationGetRelid(resultRelInfo->ri_RelationDesc);
1911  tupdesc = RelationGetDescr(resultRelInfo->ri_RelationDesc);
1912  modifiedCols = bms_union(ExecGetInsertedCols(resultRelInfo, estate),
1913  ExecGetUpdatedCols(resultRelInfo, estate));
1914  }
1915 
1916  val_desc = ExecBuildSlotValueDescription(root_relid,
1917  slot,
1918  tupdesc,
1919  modifiedCols,
1920  64);
1921  ereport(ERROR,
1922  (errcode(ERRCODE_CHECK_VIOLATION),
1923  errmsg("new row for relation \"%s\" violates partition constraint",
1924  RelationGetRelationName(resultRelInfo->ri_RelationDesc)),
1925  val_desc ? errdetail("Failing row contains %s.", val_desc) : 0,
1926  errtable(resultRelInfo->ri_RelationDesc)));
1927 }
int errtable(Relation rel)
Definition: relcache.c:5961

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

Referenced by ExecCrossPartitionUpdate(), and ExecPartitionCheck().

◆ ExecPostprocessPlan()

static void ExecPostprocessPlan ( EState estate)
static

Definition at line 1457 of file execMain.c.

1458 {
1459  ListCell *lc;
1460 
1461  /*
1462  * Make sure nodes run forward.
1463  */
1465 
1466  /*
1467  * Run any secondary ModifyTable nodes to completion, in case the main
1468  * query did not fetch all rows from them. (We do this to ensure that
1469  * such nodes have predictable results.)
1470  */
1471  foreach(lc, estate->es_auxmodifytables)
1472  {
1473  PlanState *ps = (PlanState *) lfirst(lc);
1474 
1475  for (;;)
1476  {
1477  TupleTableSlot *slot;
1478 
1479  /* Reset the per-output-tuple exprcontext each time */
1480  ResetPerTupleExprContext(estate);
1481 
1482  slot = ExecProcNode(ps);
1483 
1484  if (TupIsNull(slot))
1485  break;
1486  }
1487  }
1488 }
#define ResetPerTupleExprContext(estate)
Definition: executor.h:570
struct parser_state ps
List * es_auxmodifytables
Definition: execnodes.h:692

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

Referenced by standard_ExecutorFinish().

◆ ExecRelCheck()

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

Definition at line 1742 of file execMain.c.

1744 {
1745  Relation rel = resultRelInfo->ri_RelationDesc;
1746  int ncheck = rel->rd_att->constr->num_check;
1747  ConstrCheck *check = rel->rd_att->constr->check;
1748  ExprContext *econtext;
1749  MemoryContext oldContext;
1750  int i;
1751 
1752  /*
1753  * CheckConstraintFetch let this pass with only a warning, but now we
1754  * should fail rather than possibly failing to enforce an important
1755  * constraint.
1756  */
1757  if (ncheck != rel->rd_rel->relchecks)
1758  elog(ERROR, "%d pg_constraint record(s) missing for relation \"%s\"",
1759  rel->rd_rel->relchecks - ncheck, RelationGetRelationName(rel));
1760 
1761  /*
1762  * If first time through for this result relation, build expression
1763  * nodetrees for rel's constraint expressions. Keep them in the per-query
1764  * memory context so they'll survive throughout the query.
1765  */
1766  if (resultRelInfo->ri_ConstraintExprs == NULL)
1767  {
1768  oldContext = MemoryContextSwitchTo(estate->es_query_cxt);
1769  resultRelInfo->ri_ConstraintExprs =
1770  (ExprState **) palloc(ncheck * sizeof(ExprState *));
1771  for (i = 0; i < ncheck; i++)
1772  {
1773  Expr *checkconstr;
1774 
1775  checkconstr = stringToNode(check[i].ccbin);
1776  resultRelInfo->ri_ConstraintExprs[i] =
1777  ExecPrepareExpr(checkconstr, estate);
1778  }
1779  MemoryContextSwitchTo(oldContext);
1780  }
1781 
1782  /*
1783  * We will use the EState's per-tuple context for evaluating constraint
1784  * expressions (creating it if it's not already there).
1785  */
1786  econtext = GetPerTupleExprContext(estate);
1787 
1788  /* Arrange for econtext's scan tuple to be the tuple under test */
1789  econtext->ecxt_scantuple = slot;
1790 
1791  /* And evaluate the constraints */
1792  for (i = 0; i < ncheck; i++)
1793  {
1794  ExprState *checkconstr = resultRelInfo->ri_ConstraintExprs[i];
1795 
1796  /*
1797  * NOTE: SQL specifies that a NULL result from a constraint expression
1798  * is not to be treated as a failure. Therefore, use ExecCheck not
1799  * ExecQual.
1800  */
1801  if (!ExecCheck(checkconstr, econtext))
1802  return check[i].ccname;
1803  }
1804 
1805  /* NULL result means no error */
1806  return NULL;
1807 }
ExprState * ExecPrepareExpr(Expr *node, EState *estate)
Definition: execExpr.c:743
void * palloc(Size size)
Definition: mcxt.c:1317
void * stringToNode(const char *str)
Definition: read.c:90
char * ccname
Definition: tupdesc.h:30
TupleDesc rd_att
Definition: rel.h:112
ExprState ** ri_ConstraintExprs
Definition: execnodes.h:531
ConstrCheck * check
Definition: tupdesc.h:40
uint16 num_check
Definition: tupdesc.h:43

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

Referenced by ExecConstraints().

◆ ExecUpdateLockMode()

LockTupleMode ExecUpdateLockMode ( EState estate,
ResultRelInfo relinfo 
)

Definition at line 2376 of file execMain.c.

2377 {
2378  Bitmapset *keyCols;
2379  Bitmapset *updatedCols;
2380 
2381  /*
2382  * Compute lock mode to use. If columns that are part of the key have not
2383  * been modified, then we can use a weaker lock, allowing for better
2384  * concurrency.
2385  */
2386  updatedCols = ExecGetAllUpdatedCols(relinfo, estate);
2387  keyCols = RelationGetIndexAttrBitmap(relinfo->ri_RelationDesc,
2389 
2390  if (bms_overlap(keyCols, updatedCols))
2391  return LockTupleExclusive;
2392 
2393  return LockTupleNoKeyExclusive;
2394 }
bool bms_overlap(const Bitmapset *a, const Bitmapset *b)
Definition: bitmapset.c:582
Bitmapset * ExecGetAllUpdatedCols(ResultRelInfo *relinfo, EState *estate)
Definition: execUtils.c:1324
@ LockTupleExclusive
Definition: lockoptions.h:58
@ LockTupleNoKeyExclusive
Definition: lockoptions.h:56
Bitmapset * RelationGetIndexAttrBitmap(Relation relation, IndexAttrBitmapKind attrKind)
Definition: relcache.c:5247
@ INDEX_ATTR_BITMAP_KEY
Definition: relcache.h:61

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

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

◆ ExecutePlan()

static void ExecutePlan ( EState estate,
PlanState planstate,
bool  use_parallel_mode,
CmdType  operation,
bool  sendTuples,
uint64  numberTuples,
ScanDirection  direction,
DestReceiver dest,
bool  execute_once 
)
static

Definition at line 1626 of file execMain.c.

1635 {
1636  TupleTableSlot *slot;
1637  uint64 current_tuple_count;
1638 
1639  /*
1640  * initialize local variables
1641  */
1642  current_tuple_count = 0;
1643 
1644  /*
1645  * Set the direction.
1646  */
1647  estate->es_direction = direction;
1648 
1649  /*
1650  * If the plan might potentially be executed multiple times, we must force
1651  * it to run without parallelism, because we might exit early.
1652  */
1653  if (!execute_once)
1654  use_parallel_mode = false;
1655 
1656  estate->es_use_parallel_mode = use_parallel_mode;
1657  if (use_parallel_mode)
1659 
1660  /*
1661  * Loop until we've processed the proper number of tuples from the plan.
1662  */
1663  for (;;)
1664  {
1665  /* Reset the per-output-tuple exprcontext */
1666  ResetPerTupleExprContext(estate);
1667 
1668  /*
1669  * Execute the plan and obtain a tuple
1670  */
1671  slot = ExecProcNode(planstate);
1672 
1673  /*
1674  * if the tuple is null, then we assume there is nothing more to
1675  * process so we just end the loop...
1676  */
1677  if (TupIsNull(slot))
1678  break;
1679 
1680  /*
1681  * If we have a junk filter, then project a new tuple with the junk
1682  * removed.
1683  *
1684  * Store this new "clean" tuple in the junkfilter's resultSlot.
1685  * (Formerly, we stored it back over the "dirty" tuple, which is WRONG
1686  * because that tuple slot has the wrong descriptor.)
1687  */
1688  if (estate->es_junkFilter != NULL)
1689  slot = ExecFilterJunk(estate->es_junkFilter, slot);
1690 
1691  /*
1692  * If we are supposed to send the tuple somewhere, do so. (In
1693  * practice, this is probably always the case at this point.)
1694  */
1695  if (sendTuples)
1696  {
1697  /*
1698  * If we are not able to send the tuple, we assume the destination
1699  * has closed and no more tuples can be sent. If that's the case,
1700  * end the loop.
1701  */
1702  if (!dest->receiveSlot(slot, dest))
1703  break;
1704  }
1705 
1706  /*
1707  * Count tuples processed, if this is a SELECT. (For other operation
1708  * types, the ModifyTable plan node must count the appropriate
1709  * events.)
1710  */
1711  if (operation == CMD_SELECT)
1712  (estate->es_processed)++;
1713 
1714  /*
1715  * check our tuple count.. if we've processed the proper number then
1716  * quit, else loop again and process more tuples. Zero numberTuples
1717  * means no limit.
1718  */
1719  current_tuple_count++;
1720  if (numberTuples && numberTuples == current_tuple_count)
1721  break;
1722  }
1723 
1724  /*
1725  * If we know we won't need to back up, we can release resources at this
1726  * point.
1727  */
1728  if (!(estate->es_top_eflags & EXEC_FLAG_BACKWARD))
1729  ExecShutdownNode(planstate);
1730 
1731  if (use_parallel_mode)
1732  ExitParallelMode();
1733 }
TupleTableSlot * ExecFilterJunk(JunkFilter *junkfilter, TupleTableSlot *slot)
Definition: execJunk.c:247
void ExecShutdownNode(PlanState *node)
Definition: execProcnode.c:772
#define EXEC_FLAG_BACKWARD
Definition: executor.h:68
uint64 es_processed
Definition: execnodes.h:679
bool es_use_parallel_mode
Definition: execnodes.h:709
void ExitParallelMode(void)
Definition: xact.c:1063
void EnterParallelMode(void)
Definition: xact.c:1050

References CMD_SELECT, generate_unaccent_rules::dest, EnterParallelMode(), EState::es_direction, EState::es_junkFilter, EState::es_processed, EState::es_top_eflags, EState::es_use_parallel_mode, EXEC_FLAG_BACKWARD, ExecFilterJunk(), ExecProcNode(), ExecShutdownNode(), ExitParallelMode(), ResetPerTupleExprContext, and TupIsNull.

Referenced by standard_ExecutorRun().

◆ ExecutorEnd()

void ExecutorEnd ( QueryDesc queryDesc)

Definition at line 483 of file execMain.c.

484 {
485  /* If enabled, the query ID should be set. */
487 
488  if (ExecutorEnd_hook)
489  (*ExecutorEnd_hook) (queryDesc);
490  else
491  standard_ExecutorEnd(queryDesc);
492 }
ExecutorEnd_hook_type ExecutorEnd_hook
Definition: execMain.c:69
void standard_ExecutorEnd(QueryDesc *queryDesc)
Definition: execMain.c:495
#define EXEC_CHECK_QUERY_ID
Definition: execMain.c:80

References EXEC_CHECK_QUERY_ID, 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 420 of file execMain.c.

421 {
422  /* If enabled, the query ID should be set. */
424 
426  (*ExecutorFinish_hook) (queryDesc);
427  else
428  standard_ExecutorFinish(queryDesc);
429 }
ExecutorFinish_hook_type ExecutorFinish_hook
Definition: execMain.c:68
void standard_ExecutorFinish(QueryDesc *queryDesc)
Definition: execMain.c:432

References EXEC_CHECK_QUERY_ID, 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 552 of file execMain.c.

553 {
554  EState *estate;
555  MemoryContext oldcontext;
556 
557  /* sanity checks */
558  Assert(queryDesc != NULL);
559 
560  estate = queryDesc->estate;
561 
562  Assert(estate != NULL);
563 
564  /* It's probably not sensible to rescan updating queries */
565  Assert(queryDesc->operation == CMD_SELECT);
566 
567  /*
568  * Switch into per-query memory context
569  */
570  oldcontext = MemoryContextSwitchTo(estate->es_query_cxt);
571 
572  /*
573  * rescan plan
574  */
575  ExecReScan(queryDesc->planstate);
576 
577  MemoryContextSwitchTo(oldcontext);
578 }
void ExecReScan(PlanState *node)
Definition: execAmi.c:76
EState * estate
Definition: execdesc.h:48
CmdType operation
Definition: execdesc.h:36
PlanState * planstate
Definition: execdesc.h:49

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

Referenced by DoPortalRewind(), and PersistHoldablePortal().

◆ ExecutorRun()

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

Definition at line 307 of file execMain.c.

310 {
311  /* If enabled, the query ID should be set. */
313 
314  if (ExecutorRun_hook)
315  (*ExecutorRun_hook) (queryDesc, direction, count, execute_once);
316  else
317  standard_ExecutorRun(queryDesc, direction, count, execute_once);
318 }
void standard_ExecutorRun(QueryDesc *queryDesc, ScanDirection direction, uint64 count, bool execute_once)
Definition: execMain.c:321
ExecutorRun_hook_type ExecutorRun_hook
Definition: execMain.c:67

References EXEC_CHECK_QUERY_ID, 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 132 of file execMain.c.

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

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

2078 {
2079  Relation rel = resultRelInfo->ri_RelationDesc;
2080  TupleDesc tupdesc = RelationGetDescr(rel);
2081  ExprContext *econtext;
2082  ListCell *l1,
2083  *l2;
2084 
2085  /*
2086  * We will use the EState's per-tuple context for evaluating constraint
2087  * expressions (creating it if it's not already there).
2088  */
2089  econtext = GetPerTupleExprContext(estate);
2090 
2091  /* Arrange for econtext's scan tuple to be the tuple under test */
2092  econtext->ecxt_scantuple = slot;
2093 
2094  /* Check each of the constraints */
2095  forboth(l1, resultRelInfo->ri_WithCheckOptions,
2096  l2, resultRelInfo->ri_WithCheckOptionExprs)
2097  {
2098  WithCheckOption *wco = (WithCheckOption *) lfirst(l1);
2099  ExprState *wcoExpr = (ExprState *) lfirst(l2);
2100 
2101  /*
2102  * Skip any WCOs which are not the kind we are looking for at this
2103  * time.
2104  */
2105  if (wco->kind != kind)
2106  continue;
2107 
2108  /*
2109  * WITH CHECK OPTION checks are intended to ensure that the new tuple
2110  * is visible (in the case of a view) or that it passes the
2111  * 'with-check' policy (in the case of row security). If the qual
2112  * evaluates to NULL or FALSE, then the new tuple won't be included in
2113  * the view or doesn't pass the 'with-check' policy for the table.
2114  */
2115  if (!ExecQual(wcoExpr, econtext))
2116  {
2117  char *val_desc;
2118  Bitmapset *modifiedCols;
2119 
2120  switch (wco->kind)
2121  {
2122  /*
2123  * For WITH CHECK OPTIONs coming from views, we might be
2124  * able to provide the details on the row, depending on
2125  * the permissions on the relation (that is, if the user
2126  * could view it directly anyway). For RLS violations, we
2127  * don't include the data since we don't know if the user
2128  * should be able to view the tuple as that depends on the
2129  * USING policy.
2130  */
2131  case WCO_VIEW_CHECK:
2132  /* See the comment in ExecConstraints(). */
2133  if (resultRelInfo->ri_RootResultRelInfo)
2134  {
2135  ResultRelInfo *rootrel = resultRelInfo->ri_RootResultRelInfo;
2136  TupleDesc old_tupdesc = RelationGetDescr(rel);
2137  AttrMap *map;
2138 
2139  tupdesc = RelationGetDescr(rootrel->ri_RelationDesc);
2140  /* a reverse map */
2141  map = build_attrmap_by_name_if_req(old_tupdesc,
2142  tupdesc,
2143  false);
2144 
2145  /*
2146  * Partition-specific slot's tupdesc can't be changed,
2147  * so allocate a new one.
2148  */
2149  if (map != NULL)
2150  slot = execute_attr_map_slot(map, slot,
2151  MakeTupleTableSlot(tupdesc, &TTSOpsVirtual));
2152 
2153  modifiedCols = bms_union(ExecGetInsertedCols(rootrel, estate),
2154  ExecGetUpdatedCols(rootrel, estate));
2155  rel = rootrel->ri_RelationDesc;
2156  }
2157  else
2158  modifiedCols = bms_union(ExecGetInsertedCols(resultRelInfo, estate),
2159  ExecGetUpdatedCols(resultRelInfo, estate));
2161  slot,
2162  tupdesc,
2163  modifiedCols,
2164  64);
2165 
2166  ereport(ERROR,
2167  (errcode(ERRCODE_WITH_CHECK_OPTION_VIOLATION),
2168  errmsg("new row violates check option for view \"%s\"",
2169  wco->relname),
2170  val_desc ? errdetail("Failing row contains %s.",
2171  val_desc) : 0));
2172  break;
2173  case WCO_RLS_INSERT_CHECK:
2174  case WCO_RLS_UPDATE_CHECK:
2175  if (wco->polname != NULL)
2176  ereport(ERROR,
2177  (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
2178  errmsg("new row violates row-level security policy \"%s\" for table \"%s\"",
2179  wco->polname, wco->relname)));
2180  else
2181  ereport(ERROR,
2182  (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
2183  errmsg("new row violates row-level security policy for table \"%s\"",
2184  wco->relname)));
2185  break;
2188  if (wco->polname != NULL)
2189  ereport(ERROR,
2190  (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
2191  errmsg("target row violates row-level security policy \"%s\" (USING expression) for table \"%s\"",
2192  wco->polname, wco->relname)));
2193  else
2194  ereport(ERROR,
2195  (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
2196  errmsg("target row violates row-level security policy (USING expression) for table \"%s\"",
2197  wco->relname)));
2198  break;
2200  if (wco->polname != NULL)
2201  ereport(ERROR,
2202  (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
2203  errmsg("new row violates row-level security policy \"%s\" (USING expression) for table \"%s\"",
2204  wco->polname, wco->relname)));
2205  else
2206  ereport(ERROR,
2207  (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
2208  errmsg("new row violates row-level security policy (USING expression) for table \"%s\"",
2209  wco->relname)));
2210  break;
2211  default:
2212  elog(ERROR, "unrecognized WCO kind: %u", wco->kind);
2213  break;
2214  }
2215  }
2216  }
2217 }
static bool ExecQual(ExprState *state, ExprContext *econtext)
Definition: executor.h:424
@ WCO_RLS_MERGE_UPDATE_CHECK
Definition: parsenodes.h:1363
@ WCO_RLS_CONFLICT_CHECK
Definition: parsenodes.h:1362
@ WCO_RLS_INSERT_CHECK
Definition: parsenodes.h:1360
@ WCO_VIEW_CHECK
Definition: parsenodes.h:1359
@ WCO_RLS_UPDATE_CHECK
Definition: parsenodes.h:1361
@ WCO_RLS_MERGE_DELETE_CHECK
Definition: parsenodes.h:1364
#define forboth(cell1, list1, cell2, list2)
Definition: pg_list.h:518
List * ri_WithCheckOptions
Definition: execnodes.h:525
List * ri_WithCheckOptionExprs
Definition: execnodes.h:528

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

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

◆ InitPlan()

static void InitPlan ( QueryDesc queryDesc,
int  eflags 
)
static

Definition at line 852 of file execMain.c.

853 {
854  CmdType operation = queryDesc->operation;
855  PlannedStmt *plannedstmt = queryDesc->plannedstmt;
856  Plan *plan = plannedstmt->planTree;
857  List *rangeTable = plannedstmt->rtable;
858  EState *estate = queryDesc->estate;
859  PlanState *planstate;
860  TupleDesc tupType;
861  ListCell *l;
862  int i;
863 
864  /*
865  * Do permissions checks
866  */
867  ExecCheckPermissions(rangeTable, plannedstmt->permInfos, true);
868 
869  /*
870  * initialize the node's execution state
871  */
872  ExecInitRangeTable(estate, rangeTable, plannedstmt->permInfos);
873 
874  estate->es_plannedstmt = plannedstmt;
875 
876  /*
877  * Next, build the ExecRowMark array from the PlanRowMark(s), if any.
878  */
879  if (plannedstmt->rowMarks)
880  {
881  estate->es_rowmarks = (ExecRowMark **)
882  palloc0(estate->es_range_table_size * sizeof(ExecRowMark *));
883  foreach(l, plannedstmt->rowMarks)
884  {
885  PlanRowMark *rc = (PlanRowMark *) lfirst(l);
886  Oid relid;
887  Relation relation;
888  ExecRowMark *erm;
889 
890  /* ignore "parent" rowmarks; they are irrelevant at runtime */
891  if (rc->isParent)
892  continue;
893 
894  /* get relation's OID (will produce InvalidOid if subquery) */
895  relid = exec_rt_fetch(rc->rti, estate)->relid;
896 
897  /* open relation, if we need to access it for this mark type */
898  switch (rc->markType)
899  {
900  case ROW_MARK_EXCLUSIVE:
902  case ROW_MARK_SHARE:
903  case ROW_MARK_KEYSHARE:
904  case ROW_MARK_REFERENCE:
905  relation = ExecGetRangeTableRelation(estate, rc->rti);
906  break;
907  case ROW_MARK_COPY:
908  /* no physical table access is required */
909  relation = NULL;
910  break;
911  default:
912  elog(ERROR, "unrecognized markType: %d", rc->markType);
913  relation = NULL; /* keep compiler quiet */
914  break;
915  }
916 
917  /* Check that relation is a legal target for marking */
918  if (relation)
919  CheckValidRowMarkRel(relation, rc->markType);
920 
921  erm = (ExecRowMark *) palloc(sizeof(ExecRowMark));
922  erm->relation = relation;
923  erm->relid = relid;
924  erm->rti = rc->rti;
925  erm->prti = rc->prti;
926  erm->rowmarkId = rc->rowmarkId;
927  erm->markType = rc->markType;
928  erm->strength = rc->strength;
929  erm->waitPolicy = rc->waitPolicy;
930  erm->ermActive = false;
932  erm->ermExtra = NULL;
933 
934  Assert(erm->rti > 0 && erm->rti <= estate->es_range_table_size &&
935  estate->es_rowmarks[erm->rti - 1] == NULL);
936 
937  estate->es_rowmarks[erm->rti - 1] = erm;
938  }
939  }
940 
941  /*
942  * Initialize the executor's tuple table to empty.
943  */
944  estate->es_tupleTable = NIL;
945 
946  /* signal that this EState is not used for EPQ */
947  estate->es_epq_active = NULL;
948 
949  /*
950  * Initialize private state information for each SubPlan. We must do this
951  * before running ExecInitNode on the main query tree, since
952  * ExecInitSubPlan expects to be able to find these entries.
953  */
954  Assert(estate->es_subplanstates == NIL);
955  i = 1; /* subplan indices count from 1 */
956  foreach(l, plannedstmt->subplans)
957  {
958  Plan *subplan = (Plan *) lfirst(l);
959  PlanState *subplanstate;
960  int sp_eflags;
961 
962  /*
963  * A subplan will never need to do BACKWARD scan nor MARK/RESTORE. If
964  * it is a parameterless subplan (not initplan), we suggest that it be
965  * prepared to handle REWIND efficiently; otherwise there is no need.
966  */
967  sp_eflags = eflags
969  if (bms_is_member(i, plannedstmt->rewindPlanIDs))
970  sp_eflags |= EXEC_FLAG_REWIND;
971 
972  subplanstate = ExecInitNode(subplan, estate, sp_eflags);
973 
974  estate->es_subplanstates = lappend(estate->es_subplanstates,
975  subplanstate);
976 
977  i++;
978  }
979 
980  /*
981  * Initialize the private state information for all the nodes in the query
982  * tree. This opens files, allocates storage and leaves us ready to start
983  * processing tuples.
984  */
985  planstate = ExecInitNode(plan, estate, eflags);
986 
987  /*
988  * Get the tuple descriptor describing the type of tuples to return.
989  */
990  tupType = ExecGetResultType(planstate);
991 
992  /*
993  * Initialize the junk filter if needed. SELECT queries need a filter if
994  * there are any junk attrs in the top-level tlist.
995  */
996  if (operation == CMD_SELECT)
997  {
998  bool junk_filter_needed = false;
999  ListCell *tlist;
1000 
1001  foreach(tlist, plan->targetlist)
1002  {
1003  TargetEntry *tle = (TargetEntry *) lfirst(tlist);
1004 
1005  if (tle->resjunk)
1006  {
1007  junk_filter_needed = true;
1008  break;
1009  }
1010  }
1011 
1012  if (junk_filter_needed)
1013  {
1014  JunkFilter *j;
1015  TupleTableSlot *slot;
1016 
1017  slot = ExecInitExtraTupleSlot(estate, NULL, &TTSOpsVirtual);
1018  j = ExecInitJunkFilter(planstate->plan->targetlist,
1019  slot);
1020  estate->es_junkFilter = j;
1021 
1022  /* Want to return the cleaned tuple type */
1023  tupType = j->jf_cleanTupType;
1024  }
1025  }
1026 
1027  queryDesc->tupDesc = tupType;
1028  queryDesc->planstate = planstate;
1029 }
JunkFilter * ExecInitJunkFilter(List *targetList, TupleTableSlot *slot)
Definition: execJunk.c:60
static void CheckValidRowMarkRel(Relation rel, RowMarkType markType)
Definition: execMain.c:1157
bool ExecCheckPermissions(List *rangeTable, List *rteperminfos, bool ereport_on_violation)
Definition: execMain.c:598
TupleTableSlot * ExecInitExtraTupleSlot(EState *estate, TupleDesc tupledesc, const TupleTableSlotOps *tts_ops)
Definition: execTuples.c:1918
TupleDesc ExecGetResultType(PlanState *planstate)
Definition: execUtils.c:493
void ExecInitRangeTable(EState *estate, List *rangeTable, List *permInfos)
Definition: execUtils.c:728
Relation ExecGetRangeTableRelation(EState *estate, Index rti)
Definition: execUtils.c:762
#define EXEC_FLAG_REWIND
Definition: executor.h:67
static RangeTblEntry * exec_rt_fetch(Index rti, EState *estate)
Definition: executor.h:598
#define EXEC_FLAG_MARK
Definition: executor.h:69
int j
Definition: isn.c:74
static void ItemPointerSetInvalid(ItemPointerData *pointer)
Definition: itemptr.h:184
CmdType
Definition: nodes.h:263
#define plan(x)
Definition: pg_regress.c:162
@ ROW_MARK_SHARE
Definition: plannodes.h:1332
@ ROW_MARK_EXCLUSIVE
Definition: plannodes.h:1330
@ ROW_MARK_NOKEYEXCLUSIVE
Definition: plannodes.h:1331
@ ROW_MARK_KEYSHARE
Definition: plannodes.h:1333
ItemPointerData curCtid
Definition: execnodes.h:766
LockClauseStrength strength
Definition: execnodes.h:763
bool ermActive
Definition: execnodes.h:765
LockWaitPolicy waitPolicy
Definition: execnodes.h:764
void * ermExtra
Definition: execnodes.h:767
LockClauseStrength strength
Definition: plannodes.h:1388
Index prti
Definition: plannodes.h:1384
RowMarkType markType
Definition: plannodes.h:1386
LockWaitPolicy waitPolicy
Definition: plannodes.h:1389
bool isParent
Definition: plannodes.h:1390
Index rowmarkId
Definition: plannodes.h:1385
List * targetlist
Definition: plannodes.h:153
struct Plan * planTree
Definition: plannodes.h:70
List * rowMarks
Definition: plannodes.h:87
Bitmapset * rewindPlanIDs
Definition: plannodes.h:85
List * rtable
Definition: plannodes.h:72
TupleDesc tupDesc
Definition: execdesc.h:47

References Assert, bms_is_member(), CheckValidRowMarkRel(), CMD_SELECT, ExecRowMark::curCtid, elog, ExecRowMark::ermActive, ExecRowMark::ermExtra, ERROR, EState::es_epq_active, EState::es_junkFilter, EState::es_plannedstmt, EState::es_range_table_size, EState::es_rowmarks, EState::es_subplanstates, EState::es_tupleTable, QueryDesc::estate, EXEC_FLAG_BACKWARD, EXEC_FLAG_MARK, EXEC_FLAG_REWIND, exec_rt_fetch(), ExecCheckPermissions(), ExecGetRangeTableRelation(), ExecGetResultType(), ExecInitExtraTupleSlot(), ExecInitJunkFilter(), ExecInitNode(), ExecInitRangeTable(), i, PlanRowMark::isParent, ItemPointerSetInvalid(), j, lappend(), lfirst, ExecRowMark::markType, PlanRowMark::markType, NIL, QueryDesc::operation, palloc(), palloc0(), PlannedStmt::permInfos, PlanState::plan, plan, QueryDesc::plannedstmt, QueryDesc::planstate, PlannedStmt::planTree, ExecRowMark::prti, PlanRowMark::prti, ExecRowMark::relation, ExecRowMark::relid, RangeTblEntry::relid, PlannedStmt::rewindPlanIDs, ROW_MARK_COPY, ROW_MARK_EXCLUSIVE, ROW_MARK_KEYSHARE, ROW_MARK_NOKEYEXCLUSIVE, ROW_MARK_REFERENCE, ROW_MARK_SHARE, ExecRowMark::rowmarkId, PlanRowMark::rowmarkId, PlannedStmt::rowMarks, PlannedStmt::rtable, ExecRowMark::rti, PlanRowMark::rti, ExecRowMark::strength, PlanRowMark::strength, PlannedStmt::subplans, Plan::targetlist, TTSOpsVirtual, QueryDesc::tupDesc, ExecRowMark::waitPolicy, and PlanRowMark::waitPolicy.

Referenced by standard_ExecutorStart().

◆ InitResultRelInfo()

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

Definition at line 1222 of file execMain.c.

1227 {
1228  MemSet(resultRelInfo, 0, sizeof(ResultRelInfo));
1229  resultRelInfo->type = T_ResultRelInfo;
1230  resultRelInfo->ri_RangeTableIndex = resultRelationIndex;
1231  resultRelInfo->ri_RelationDesc = resultRelationDesc;
1232  resultRelInfo->ri_NumIndices = 0;
1233  resultRelInfo->ri_IndexRelationDescs = NULL;
1234  resultRelInfo->ri_IndexRelationInfo = NULL;
1235  resultRelInfo->ri_needLockTagTuple =
1236  IsInplaceUpdateRelation(resultRelationDesc);
1237  /* make a copy so as not to depend on relcache info not changing... */
1238  resultRelInfo->ri_TrigDesc = CopyTriggerDesc(resultRelationDesc->trigdesc);
1239  if (resultRelInfo->ri_TrigDesc)
1240  {
1241  int n = resultRelInfo->ri_TrigDesc->numtriggers;
1242 
1243  resultRelInfo->ri_TrigFunctions = (FmgrInfo *)
1244  palloc0(n * sizeof(FmgrInfo));
1245  resultRelInfo->ri_TrigWhenExprs = (ExprState **)
1246  palloc0(n * sizeof(ExprState *));
1247  if (instrument_options)
1248  resultRelInfo->ri_TrigInstrument = InstrAlloc(n, instrument_options, false);
1249  }
1250  else
1251  {
1252  resultRelInfo->ri_TrigFunctions = NULL;
1253  resultRelInfo->ri_TrigWhenExprs = NULL;
1254  resultRelInfo->ri_TrigInstrument = NULL;
1255  }
1256  if (resultRelationDesc->rd_rel->relkind == RELKIND_FOREIGN_TABLE)
1257  resultRelInfo->ri_FdwRoutine = GetFdwRoutineForRelation(resultRelationDesc, true);
1258  else
1259  resultRelInfo->ri_FdwRoutine = NULL;
1260 
1261  /* The following fields are set later if needed */
1262  resultRelInfo->ri_RowIdAttNo = 0;
1263  resultRelInfo->ri_extraUpdatedCols = NULL;
1264  resultRelInfo->ri_projectNew = NULL;
1265  resultRelInfo->ri_newTupleSlot = NULL;
1266  resultRelInfo->ri_oldTupleSlot = NULL;
1267  resultRelInfo->ri_projectNewInfoValid = false;
1268  resultRelInfo->ri_FdwState = NULL;
1269  resultRelInfo->ri_usesFdwDirectModify = false;
1270  resultRelInfo->ri_ConstraintExprs = NULL;
1271  resultRelInfo->ri_GeneratedExprsI = NULL;
1272  resultRelInfo->ri_GeneratedExprsU = NULL;
1273  resultRelInfo->ri_projectReturning = NULL;
1274  resultRelInfo->ri_onConflictArbiterIndexes = NIL;
1275  resultRelInfo->ri_onConflict = NULL;
1276  resultRelInfo->ri_ReturningSlot = NULL;
1277  resultRelInfo->ri_TrigOldSlot = NULL;
1278  resultRelInfo->ri_TrigNewSlot = NULL;
1279  resultRelInfo->ri_MergeActions[MERGE_WHEN_MATCHED] = NIL;
1282  resultRelInfo->ri_MergeJoinCondition = NULL;
1283 
1284  /*
1285  * Only ExecInitPartitionInfo() and ExecInitPartitionDispatchInfo() pass
1286  * non-NULL partition_root_rri. For child relations that are part of the
1287  * initial query rather than being dynamically added by tuple routing,
1288  * this field is filled in ExecInitModifyTable().
1289  */
1290  resultRelInfo->ri_RootResultRelInfo = partition_root_rri;
1291  /* Set by ExecGetRootToChildMap */
1292  resultRelInfo->ri_RootToChildMap = NULL;
1293  resultRelInfo->ri_RootToChildMapValid = false;
1294  /* Set by ExecInitRoutingInfo */
1295  resultRelInfo->ri_PartitionTupleSlot = NULL;
1296  resultRelInfo->ri_ChildToRootMap = NULL;
1297  resultRelInfo->ri_ChildToRootMapValid = false;
1298  resultRelInfo->ri_CopyMultiInsertBuffer = NULL;
1299 }
#define MemSet(start, val, len)
Definition: c.h:1023
Instrumentation * InstrAlloc(int n, int instrument_options, bool async_mode)
Definition: instrument.c:31
@ MERGE_WHEN_NOT_MATCHED_BY_TARGET
Definition: primnodes.h:1994
@ MERGE_WHEN_NOT_MATCHED_BY_SOURCE
Definition: primnodes.h:1993
@ MERGE_WHEN_MATCHED
Definition: primnodes.h:1992
Definition: fmgr.h:57
TriggerDesc * trigdesc
Definition: rel.h:117
TupleConversionMap * ri_RootToChildMap
Definition: execnodes.h:576
TupleTableSlot * ri_PartitionTupleSlot
Definition: execnodes.h:591
bool ri_projectNewInfoValid
Definition: execnodes.h:486
OnConflictSetState * ri_onConflict
Definition: execnodes.h:553
List * ri_onConflictArbiterIndexes
Definition: execnodes.h:550
Instrumentation * ri_TrigInstrument
Definition: execnodes.h:501
ExprState * ri_MergeJoinCondition
Definition: execnodes.h:559
RelationPtr ri_IndexRelationDescs
Definition: execnodes.h:465
TupleTableSlot * ri_ReturningSlot
Definition: execnodes.h:504
TupleTableSlot * ri_oldTupleSlot
Definition: execnodes.h:484
bool ri_RootToChildMapValid
Definition: execnodes.h:577
struct CopyMultiInsertBuffer * ri_CopyMultiInsertBuffer
Definition: execnodes.h:594
TriggerDesc * ri_TrigDesc
Definition: execnodes.h:492
Bitmapset * ri_extraUpdatedCols
Definition: execnodes.h:477
ExprState ** ri_GeneratedExprsI
Definition: execnodes.h:536
TupleConversionMap * ri_ChildToRootMap
Definition: execnodes.h:570
void * ri_FdwState
Definition: execnodes.h:512
bool ri_ChildToRootMapValid
Definition: execnodes.h:571
List * ri_MergeActions[NUM_MERGE_MATCH_KINDS]
Definition: execnodes.h:556
TupleTableSlot * ri_newTupleSlot
Definition: execnodes.h:482
ProjectionInfo * ri_projectNew
Definition: execnodes.h:480
NodeTag type
Definition: execnodes.h:453
ProjectionInfo * ri_projectReturning
Definition: execnodes.h:547
ExprState ** ri_GeneratedExprsU
Definition: execnodes.h:537
ExprState ** ri_TrigWhenExprs
Definition: execnodes.h:498
FmgrInfo * ri_TrigFunctions
Definition: execnodes.h:495
bool ri_usesFdwDirectModify
Definition: execnodes.h:515
AttrNumber ri_RowIdAttNo
Definition: execnodes.h:474
IndexInfo ** ri_IndexRelationInfo
Definition: execnodes.h:468
TupleTableSlot * ri_TrigNewSlot
Definition: execnodes.h:506
TupleTableSlot * ri_TrigOldSlot
Definition: execnodes.h:505
int numtriggers
Definition: reltrigger.h:50
TriggerDesc * CopyTriggerDesc(TriggerDesc *trigdesc)
Definition: trigger.c:2086

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

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

◆ standard_ExecutorEnd()

void standard_ExecutorEnd ( QueryDesc queryDesc)

Definition at line 495 of file execMain.c.

496 {
497  EState *estate;
498  MemoryContext oldcontext;
499 
500  /* sanity checks */
501  Assert(queryDesc != NULL);
502 
503  estate = queryDesc->estate;
504 
505  Assert(estate != NULL);
506 
507  /*
508  * Check that ExecutorFinish was called, unless in EXPLAIN-only mode. This
509  * Assert is needed because ExecutorFinish is new as of 9.1, and callers
510  * might forget to call it.
511  */
512  Assert(estate->es_finished ||
514 
515  /*
516  * Switch into per-query memory context to run ExecEndPlan
517  */
518  oldcontext = MemoryContextSwitchTo(estate->es_query_cxt);
519 
520  ExecEndPlan(queryDesc->planstate, estate);
521 
522  /* do away with our snapshots */
525 
526  /*
527  * Must switch out of context before destroying it
528  */
529  MemoryContextSwitchTo(oldcontext);
530 
531  /*
532  * Release EState and per-query memory context. This should release
533  * everything the executor has allocated.
534  */
535  FreeExecutorState(estate);
536 
537  /* Reset queryDesc fields that no longer point to anything */
538  queryDesc->tupDesc = NULL;
539  queryDesc->estate = NULL;
540  queryDesc->planstate = NULL;
541  queryDesc->totaltime = NULL;
542 }
static void ExecEndPlan(PlanState *planstate, EState *estate)
Definition: execMain.c:1503
#define EXEC_FLAG_EXPLAIN_ONLY
Definition: executor.h:65
void UnregisterSnapshot(Snapshot snapshot)
Definition: snapmgr.c:836
bool es_finished
Definition: execnodes.h:686
struct Instrumentation * totaltime
Definition: execdesc.h:55

References Assert, EState::es_crosscheck_snapshot, EState::es_finished, EState::es_query_cxt, EState::es_snapshot, EState::es_top_eflags, QueryDesc::estate, EXEC_FLAG_EXPLAIN_ONLY, ExecEndPlan(), FreeExecutorState(), MemoryContextSwitchTo(), 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 432 of file execMain.c.

433 {
434  EState *estate;
435  MemoryContext oldcontext;
436 
437  /* sanity checks */
438  Assert(queryDesc != NULL);
439 
440  estate = queryDesc->estate;
441 
442  Assert(estate != NULL);
444 
445  /* This should be run once and only once per Executor instance */
446  Assert(!estate->es_finished);
447 
448  /* Switch into per-query memory context */
449  oldcontext = MemoryContextSwitchTo(estate->es_query_cxt);
450 
451  /* Allow instrumentation of Executor overall runtime */
452  if (queryDesc->totaltime)
453  InstrStartNode(queryDesc->totaltime);
454 
455  /* Run ModifyTable nodes to completion */
456  ExecPostprocessPlan(estate);
457 
458  /* Execute queued AFTER triggers, unless told not to */
459  if (!(estate->es_top_eflags & EXEC_FLAG_SKIP_TRIGGERS))
460  AfterTriggerEndQuery(estate);
461 
462  if (queryDesc->totaltime)
463  InstrStopNode(queryDesc->totaltime, 0);
464 
465  MemoryContextSwitchTo(oldcontext);
466 
467  estate->es_finished = true;
468 }
static void ExecPostprocessPlan(EState *estate)
Definition: execMain.c:1457
#define EXEC_FLAG_SKIP_TRIGGERS
Definition: executor.h:70
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:5044

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(), 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,
bool  execute_once 
)

Definition at line 321 of file execMain.c.

323 {
324  EState *estate;
325  CmdType operation;
327  bool sendTuples;
328  MemoryContext oldcontext;
329 
330  /* sanity checks */
331  Assert(queryDesc != NULL);
332 
333  estate = queryDesc->estate;
334 
335  Assert(estate != NULL);
337 
338  /* caller must ensure the query's snapshot is active */
339  Assert(GetActiveSnapshot() == estate->es_snapshot);
340 
341  /*
342  * Switch into per-query memory context
343  */
344  oldcontext = MemoryContextSwitchTo(estate->es_query_cxt);
345 
346  /* Allow instrumentation of Executor overall runtime */
347  if (queryDesc->totaltime)
348  InstrStartNode(queryDesc->totaltime);
349 
350  /*
351  * extract information from the query descriptor and the query feature.
352  */
353  operation = queryDesc->operation;
354  dest = queryDesc->dest;
355 
356  /*
357  * startup tuple receiver, if we will be emitting tuples
358  */
359  estate->es_processed = 0;
360 
361  sendTuples = (operation == CMD_SELECT ||
362  queryDesc->plannedstmt->hasReturning);
363 
364  if (sendTuples)
365  dest->rStartup(dest, operation, queryDesc->tupDesc);
366 
367  /*
368  * run plan
369  */
370  if (!ScanDirectionIsNoMovement(direction))
371  {
372  if (execute_once && queryDesc->already_executed)
373  elog(ERROR, "can't re-execute query flagged for single execution");
374  queryDesc->already_executed = true;
375 
376  ExecutePlan(estate,
377  queryDesc->planstate,
378  queryDesc->plannedstmt->parallelModeNeeded,
379  operation,
380  sendTuples,
381  count,
382  direction,
383  dest,
384  execute_once);
385  }
386 
387  /*
388  * Update es_total_processed to keep track of the number of tuples
389  * processed across multiple ExecutorRun() calls.
390  */
391  estate->es_total_processed += estate->es_processed;
392 
393  /*
394  * shutdown tuple receiver, if we started it
395  */
396  if (sendTuples)
397  dest->rShutdown(dest);
398 
399  if (queryDesc->totaltime)
400  InstrStopNode(queryDesc->totaltime, estate->es_processed);
401 
402  MemoryContextSwitchTo(oldcontext);
403 }
static void ExecutePlan(EState *estate, PlanState *planstate, bool use_parallel_mode, CmdType operation, bool sendTuples, uint64 numberTuples, ScanDirection direction, DestReceiver *dest, bool execute_once)
Definition: execMain.c:1626
#define ScanDirectionIsNoMovement(direction)
Definition: sdir.h:57
Snapshot GetActiveSnapshot(void)
Definition: snapmgr.c:770
uint64 es_total_processed
Definition: execnodes.h:681
bool hasReturning
Definition: plannodes.h:56
bool parallelModeNeeded
Definition: plannodes.h:66
DestReceiver * dest
Definition: execdesc.h:41
bool already_executed
Definition: execdesc.h:52

References QueryDesc::already_executed, Assert, CMD_SELECT, generate_unaccent_rules::dest, QueryDesc::dest, elog, ERROR, EState::es_processed, EState::es_query_cxt, EState::es_snapshot, EState::es_top_eflags, EState::es_total_processed, QueryDesc::estate, EXEC_FLAG_EXPLAIN_ONLY, ExecutePlan(), GetActiveSnapshot(), PlannedStmt::hasReturning, InstrStartNode(), InstrStopNode(), MemoryContextSwitchTo(), QueryDesc::operation, PlannedStmt::parallelModeNeeded, QueryDesc::plannedstmt, QueryDesc::planstate, 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 151 of file execMain.c.

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

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(), GetActiveSnapshot(), GetCurrentCommandId(), PlannedStmt::hasModifyingCTE, InitPlan(), QueryDesc::instrument_options, IsInParallelMode(), PlannedStmt::jitFlags, list_length(), MemoryContextSwitchTo(), NIL, QueryDesc::operation, palloc0(), PlannedStmt::paramExecTypes, QueryDesc::params, QueryDesc::plannedstmt, QueryDesc::queryEnv, RegisterSnapshot(), PlannedStmt::rowMarks, QueryDesc::snapshot, QueryDesc::sourceText, and XactReadOnly.

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

Variable Documentation

◆ ExecutorCheckPerms_hook

ExecutorCheckPerms_hook_type ExecutorCheckPerms_hook = NULL

Definition at line 72 of file execMain.c.

Referenced by _PG_init(), and ExecCheckPermissions().

◆ ExecutorEnd_hook

ExecutorEnd_hook_type ExecutorEnd_hook = NULL

Definition at line 69 of file execMain.c.

Referenced by _PG_init(), and ExecutorEnd().

◆ ExecutorFinish_hook

ExecutorFinish_hook_type ExecutorFinish_hook = NULL

Definition at line 68 of file execMain.c.

Referenced by _PG_init(), and ExecutorFinish().

◆ ExecutorRun_hook

ExecutorRun_hook_type ExecutorRun_hook = NULL

Definition at line 67 of file execMain.c.

Referenced by _PG_init(), and ExecutorRun().

◆ ExecutorStart_hook

ExecutorStart_hook_type ExecutorStart_hook = NULL

Definition at line 66 of file execMain.c.

Referenced by _PG_init(), and ExecutorStart().