PostgreSQL Source Code  git master
execMain.c File Reference
#include "postgres.h"
#include "access/heapam.h"
#include "access/htup_details.h"
#include "access/sysattr.h"
#include "access/tableam.h"
#include "access/transam.h"
#include "access/xact.h"
#include "catalog/namespace.h"
#include "catalog/pg_publication.h"
#include "commands/matview.h"
#include "commands/trigger.h"
#include "executor/execdebug.h"
#include "executor/nodeSubplan.h"
#include "foreign/fdwapi.h"
#include "jit/jit.h"
#include "mb/pg_wchar.h"
#include "miscadmin.h"
#include "parser/parsetree.h"
#include "storage/bufmgr.h"
#include "storage/lmgr.h"
#include "tcop/utility.h"
#include "utils/acl.h"
#include "utils/lsyscache.h"
#include "utils/memutils.h"
#include "utils/partcache.h"
#include "utils/rls.h"
#include "utils/ruleutils.h"
#include "utils/snapmgr.h"
Include dependency graph for execMain.c:

Go to the source code of this file.

Macros

#define GetInsertedColumns(relinfo, estate)   (exec_rt_fetch((relinfo)->ri_RangeTableIndex, estate)->insertedCols)
 
#define GetUpdatedColumns(relinfo, estate)   (exec_rt_fetch((relinfo)->ri_RangeTableIndex, estate)->updatedCols)
 
#define GetAllUpdatedColumns(relinfo, estate)
 

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 ExecCheckRTEPerms (RangeTblEntry *rte)
 
static bool ExecCheckRTEPermsModified (Oid relOid, Oid userid, Bitmapset *modifiedCols, AclMode requiredPerms)
 
static void ExecCheckXactReadOnly (PlannedStmt *plannedstmt)
 
static char * ExecBuildSlotValueDescription (Oid reloid, TupleTableSlot *slot, TupleDesc tupdesc, Bitmapset *modifiedCols, int maxfieldlen)
 
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 ExecCheckRTPerms (List *rangeTable, bool ereport_on_violation)
 
void CheckValidResultRel (ResultRelInfo *resultRelInfo, CmdType operation)
 
void InitResultRelInfo (ResultRelInfo *resultRelInfo, Relation resultRelationDesc, Index resultRelationIndex, Relation partition_root, int instrument_options)
 
ResultRelInfoExecGetTriggerResultRel (EState *estate, Oid relid)
 
void ExecCleanUpTriggerState (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)
 
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)
 
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

◆ GetAllUpdatedColumns

#define GetAllUpdatedColumns (   relinfo,
  estate 
)
Value:
(bms_union(exec_rt_fetch((relinfo)->ri_RangeTableIndex, estate)->updatedCols, \
exec_rt_fetch((relinfo)->ri_RangeTableIndex, estate)->extraUpdatedCols))
static RangeTblEntry * exec_rt_fetch(Index rti, EState *estate)
Definition: executor.h:543
Bitmapset * bms_union(const Bitmapset *a, const Bitmapset *b)
Definition: bitmapset.c:225

Definition at line 113 of file execMain.c.

Referenced by ExecUpdateLockMode().

◆ GetInsertedColumns

#define GetInsertedColumns (   relinfo,
  estate 
)    (exec_rt_fetch((relinfo)->ri_RangeTableIndex, estate)->insertedCols)

Definition at line 109 of file execMain.c.

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

◆ GetUpdatedColumns

#define GetUpdatedColumns (   relinfo,
  estate 
)    (exec_rt_fetch((relinfo)->ri_RangeTableIndex, estate)->updatedCols)

Definition at line 111 of file execMain.c.

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

Function Documentation

◆ CheckValidResultRel()

void CheckValidResultRel ( ResultRelInfo resultRelInfo,
CmdType  operation 
)

Definition at line 1076 of file execMain.c.

References CheckCmdReplicaIdentity(), CMD_DELETE, CMD_INSERT, CMD_UPDATE, elog, ereport, errcode(), errhint(), errmsg(), ERROR, FdwRoutine::ExecForeignDelete, FdwRoutine::ExecForeignInsert, FdwRoutine::ExecForeignUpdate, FdwRoutine::IsForeignRelUpdatable, MatViewIncrementalMaintenanceIsEnabled(), RelationData::rd_rel, RelationGetRelationName, ResultRelInfo::ri_FdwRoutine, ResultRelInfo::ri_RelationDesc, TriggerDesc::trig_delete_instead_row, TriggerDesc::trig_insert_instead_row, TriggerDesc::trig_update_instead_row, and RelationData::trigdesc.

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

1077 {
1078  Relation resultRel = resultRelInfo->ri_RelationDesc;
1079  TriggerDesc *trigDesc = resultRel->trigdesc;
1080  FdwRoutine *fdwroutine;
1081 
1082  switch (resultRel->rd_rel->relkind)
1083  {
1084  case RELKIND_RELATION:
1085  case RELKIND_PARTITIONED_TABLE:
1086  CheckCmdReplicaIdentity(resultRel, operation);
1087  break;
1088  case RELKIND_SEQUENCE:
1089  ereport(ERROR,
1090  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1091  errmsg("cannot change sequence \"%s\"",
1092  RelationGetRelationName(resultRel))));
1093  break;
1094  case RELKIND_TOASTVALUE:
1095  ereport(ERROR,
1096  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1097  errmsg("cannot change TOAST relation \"%s\"",
1098  RelationGetRelationName(resultRel))));
1099  break;
1100  case RELKIND_VIEW:
1101 
1102  /*
1103  * Okay only if there's a suitable INSTEAD OF trigger. Messages
1104  * here should match rewriteHandler.c's rewriteTargetView and
1105  * RewriteQuery, except that we omit errdetail because we haven't
1106  * got the information handy (and given that we really shouldn't
1107  * get here anyway, it's not worth great exertion to get).
1108  */
1109  switch (operation)
1110  {
1111  case CMD_INSERT:
1112  if (!trigDesc || !trigDesc->trig_insert_instead_row)
1113  ereport(ERROR,
1114  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
1115  errmsg("cannot insert into view \"%s\"",
1116  RelationGetRelationName(resultRel)),
1117  errhint("To enable inserting into the view, provide an INSTEAD OF INSERT trigger or an unconditional ON INSERT DO INSTEAD rule.")));
1118  break;
1119  case CMD_UPDATE:
1120  if (!trigDesc || !trigDesc->trig_update_instead_row)
1121  ereport(ERROR,
1122  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
1123  errmsg("cannot update view \"%s\"",
1124  RelationGetRelationName(resultRel)),
1125  errhint("To enable updating the view, provide an INSTEAD OF UPDATE trigger or an unconditional ON UPDATE DO INSTEAD rule.")));
1126  break;
1127  case CMD_DELETE:
1128  if (!trigDesc || !trigDesc->trig_delete_instead_row)
1129  ereport(ERROR,
1130  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
1131  errmsg("cannot delete from view \"%s\"",
1132  RelationGetRelationName(resultRel)),
1133  errhint("To enable deleting from the view, provide an INSTEAD OF DELETE trigger or an unconditional ON DELETE DO INSTEAD rule.")));
1134  break;
1135  default:
1136  elog(ERROR, "unrecognized CmdType: %d", (int) operation);
1137  break;
1138  }
1139  break;
1140  case RELKIND_MATVIEW:
1142  ereport(ERROR,
1143  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1144  errmsg("cannot change materialized view \"%s\"",
1145  RelationGetRelationName(resultRel))));
1146  break;
1147  case RELKIND_FOREIGN_TABLE:
1148  /* Okay only if the FDW supports it */
1149  fdwroutine = resultRelInfo->ri_FdwRoutine;
1150  switch (operation)
1151  {
1152  case CMD_INSERT:
1153  if (fdwroutine->ExecForeignInsert == NULL)
1154  ereport(ERROR,
1155  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1156  errmsg("cannot insert into foreign table \"%s\"",
1157  RelationGetRelationName(resultRel))));
1158  if (fdwroutine->IsForeignRelUpdatable != NULL &&
1159  (fdwroutine->IsForeignRelUpdatable(resultRel) & (1 << CMD_INSERT)) == 0)
1160  ereport(ERROR,
1161  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
1162  errmsg("foreign table \"%s\" does not allow inserts",
1163  RelationGetRelationName(resultRel))));
1164  break;
1165  case CMD_UPDATE:
1166  if (fdwroutine->ExecForeignUpdate == NULL)
1167  ereport(ERROR,
1168  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1169  errmsg("cannot update foreign table \"%s\"",
1170  RelationGetRelationName(resultRel))));
1171  if (fdwroutine->IsForeignRelUpdatable != NULL &&
1172  (fdwroutine->IsForeignRelUpdatable(resultRel) & (1 << CMD_UPDATE)) == 0)
1173  ereport(ERROR,
1174  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
1175  errmsg("foreign table \"%s\" does not allow updates",
1176  RelationGetRelationName(resultRel))));
1177  break;
1178  case CMD_DELETE:
1179  if (fdwroutine->ExecForeignDelete == NULL)
1180  ereport(ERROR,
1181  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1182  errmsg("cannot delete from foreign table \"%s\"",
1183  RelationGetRelationName(resultRel))));
1184  if (fdwroutine->IsForeignRelUpdatable != NULL &&
1185  (fdwroutine->IsForeignRelUpdatable(resultRel) & (1 << CMD_DELETE)) == 0)
1186  ereport(ERROR,
1187  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
1188  errmsg("foreign table \"%s\" does not allow deletes",
1189  RelationGetRelationName(resultRel))));
1190  break;
1191  default:
1192  elog(ERROR, "unrecognized CmdType: %d", (int) operation);
1193  break;
1194  }
1195  break;
1196  default:
1197  ereport(ERROR,
1198  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1199  errmsg("cannot change relation \"%s\"",
1200  RelationGetRelationName(resultRel))));
1201  break;
1202  }
1203 }
ExecForeignDelete_function ExecForeignDelete
Definition: fdwapi.h:213
Relation ri_RelationDesc
Definition: execnodes.h:413
int errhint(const char *fmt,...)
Definition: elog.c:1071
bool MatViewIncrementalMaintenanceIsEnabled(void)
Definition: matview.c:908
ExecForeignInsert_function ExecForeignInsert
Definition: fdwapi.h:211
int errcode(int sqlerrcode)
Definition: elog.c:610
Form_pg_class rd_rel
Definition: rel.h:109
bool trig_insert_instead_row
Definition: reltrigger.h:58
#define ERROR
Definition: elog.h:43
TriggerDesc * trigdesc
Definition: rel.h:115
#define RelationGetRelationName(relation)
Definition: rel.h:490
struct FdwRoutine * ri_FdwRoutine
Definition: execnodes.h:442
void CheckCmdReplicaIdentity(Relation rel, CmdType cmd)
bool trig_update_instead_row
Definition: reltrigger.h:63
bool trig_delete_instead_row
Definition: reltrigger.h:68
#define ereport(elevel,...)
Definition: elog.h:144
ExecForeignUpdate_function ExecForeignUpdate
Definition: fdwapi.h:212
int errmsg(const char *fmt,...)
Definition: elog.c:824
#define elog(elevel,...)
Definition: elog.h:214
IsForeignRelUpdatable_function IsForeignRelUpdatable
Definition: fdwapi.h:217

◆ CheckValidRowMarkRel()

static void CheckValidRowMarkRel ( Relation  rel,
RowMarkType  markType 
)
static

Definition at line 1212 of file execMain.c.

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

Referenced by InitPlan().

1213 {
1214  FdwRoutine *fdwroutine;
1215 
1216  switch (rel->rd_rel->relkind)
1217  {
1218  case RELKIND_RELATION:
1219  case RELKIND_PARTITIONED_TABLE:
1220  /* OK */
1221  break;
1222  case RELKIND_SEQUENCE:
1223  /* Must disallow this because we don't vacuum sequences */
1224  ereport(ERROR,
1225  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1226  errmsg("cannot lock rows in sequence \"%s\"",
1227  RelationGetRelationName(rel))));
1228  break;
1229  case RELKIND_TOASTVALUE:
1230  /* We could allow this, but there seems no good reason to */
1231  ereport(ERROR,
1232  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1233  errmsg("cannot lock rows in TOAST relation \"%s\"",
1234  RelationGetRelationName(rel))));
1235  break;
1236  case RELKIND_VIEW:
1237  /* Should not get here; planner should have expanded the view */
1238  ereport(ERROR,
1239  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1240  errmsg("cannot lock rows in view \"%s\"",
1241  RelationGetRelationName(rel))));
1242  break;
1243  case RELKIND_MATVIEW:
1244  /* Allow referencing a matview, but not actual locking clauses */
1245  if (markType != ROW_MARK_REFERENCE)
1246  ereport(ERROR,
1247  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1248  errmsg("cannot lock rows in materialized view \"%s\"",
1249  RelationGetRelationName(rel))));
1250  break;
1251  case RELKIND_FOREIGN_TABLE:
1252  /* Okay only if the FDW supports it */
1253  fdwroutine = GetFdwRoutineForRelation(rel, false);
1254  if (fdwroutine->RefetchForeignRow == NULL)
1255  ereport(ERROR,
1256  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1257  errmsg("cannot lock rows in foreign table \"%s\"",
1258  RelationGetRelationName(rel))));
1259  break;
1260  default:
1261  ereport(ERROR,
1262  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1263  errmsg("cannot lock rows in relation \"%s\"",
1264  RelationGetRelationName(rel))));
1265  break;
1266  }
1267 }
int errcode(int sqlerrcode)
Definition: elog.c:610
Form_pg_class rd_rel
Definition: rel.h:109
#define ERROR
Definition: elog.h:43
#define RelationGetRelationName(relation)
Definition: rel.h:490
#define ereport(elevel,...)
Definition: elog.h:144
int errmsg(const char *fmt,...)
Definition: elog.c:824
FdwRoutine * GetFdwRoutineForRelation(Relation relation, bool makecopy)
Definition: foreign.c:427
RefetchForeignRow_function RefetchForeignRow
Definition: fdwapi.h:225

◆ EvalPlanQual()

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

Definition at line 2421 of file execMain.c.

References Assert, EvalPlanQualBegin(), EvalPlanQualNext(), EvalPlanQualSlot(), ExecClearTuple(), ExecCopySlot(), ExecMaterializeSlot(), and TupIsNull.

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

2423 {
2424  TupleTableSlot *slot;
2425  TupleTableSlot *testslot;
2426 
2427  Assert(rti > 0);
2428 
2429  /*
2430  * Need to run a recheck subquery. Initialize or reinitialize EPQ state.
2431  */
2432  EvalPlanQualBegin(epqstate);
2433 
2434  /*
2435  * Callers will often use the EvalPlanQualSlot to store the tuple to avoid
2436  * an unnecessary copy.
2437  */
2438  testslot = EvalPlanQualSlot(epqstate, relation, rti);
2439  if (testslot != inputslot)
2440  ExecCopySlot(testslot, inputslot);
2441 
2442  /*
2443  * Run the EPQ query. We assume it will return at most one tuple.
2444  */
2445  slot = EvalPlanQualNext(epqstate);
2446 
2447  /*
2448  * If we got a tuple, force the slot to materialize the tuple so that it
2449  * is not dependent on any local state in the EPQ query (in particular,
2450  * it's highly likely that the slot contains references to any pass-by-ref
2451  * datums that may be present in copyTuple). As with the next step, this
2452  * is to guard against early re-use of the EPQ query.
2453  */
2454  if (!TupIsNull(slot))
2455  ExecMaterializeSlot(slot);
2456 
2457  /*
2458  * Clear out the test tuple. This is needed in case the EPQ query is
2459  * re-used to test a tuple for a different relation. (Not clear that can
2460  * really happen, but let's be safe.)
2461  */
2462  ExecClearTuple(testslot);
2463 
2464  return slot;
2465 }
static TupleTableSlot * ExecCopySlot(TupleTableSlot *dstslot, TupleTableSlot *srcslot)
Definition: tuptable.h:475
static TupleTableSlot * ExecClearTuple(TupleTableSlot *slot)
Definition: tuptable.h:425
TupleTableSlot * EvalPlanQualNext(EPQState *epqstate)
Definition: execMain.c:2667
TupleTableSlot * EvalPlanQualSlot(EPQState *epqstate, Relation relation, Index rti)
Definition: execMain.c:2530
#define TupIsNull(slot)
Definition: tuptable.h:292
static void ExecMaterializeSlot(TupleTableSlot *slot)
Definition: tuptable.h:443
#define Assert(condition)
Definition: c.h:745
void EvalPlanQualBegin(EPQState *epqstate)
Definition: execMain.c:2683

◆ EvalPlanQualBegin()

void EvalPlanQualBegin ( EPQState epqstate)

Definition at line 2683 of file execMain.c.

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(), MemSet, NIL, PlannedStmt::paramExecTypes, EPQState::parentestate, PlanState::plan, EPQState::plan, EPQState::recheckestate, EPQState::recheckplanstate, EPQState::relsubs_done, and ParamExecData::value.

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

2684 {
2685  EState *parentestate = epqstate->parentestate;
2686  EState *recheckestate = epqstate->recheckestate;
2687 
2688  if (recheckestate == NULL)
2689  {
2690  /* First time through, so create a child EState */
2691  EvalPlanQualStart(epqstate, epqstate->plan);
2692  }
2693  else
2694  {
2695  /*
2696  * We already have a suitable child EPQ tree, so just reset it.
2697  */
2698  Index rtsize = parentestate->es_range_table_size;
2699  PlanState *rcplanstate = epqstate->recheckplanstate;
2700 
2701  MemSet(epqstate->relsubs_done, 0, rtsize * sizeof(bool));
2702 
2703  /* Recopy current values of parent parameters */
2704  if (parentestate->es_plannedstmt->paramExecTypes != NIL)
2705  {
2706  int i;
2707 
2708  /*
2709  * Force evaluation of any InitPlan outputs that could be needed
2710  * by the subplan, just in case they got reset since
2711  * EvalPlanQualStart (see comments therein).
2712  */
2713  ExecSetParamPlanMulti(rcplanstate->plan->extParam,
2714  GetPerTupleExprContext(parentestate));
2715 
2716  i = list_length(parentestate->es_plannedstmt->paramExecTypes);
2717 
2718  while (--i >= 0)
2719  {
2720  /* copy value if any, but not execPlan link */
2721  recheckestate->es_param_exec_vals[i].value =
2722  parentestate->es_param_exec_vals[i].value;
2723  recheckestate->es_param_exec_vals[i].isnull =
2724  parentestate->es_param_exec_vals[i].isnull;
2725  }
2726  }
2727 
2728  /*
2729  * Mark child plan tree as needing rescan at all scan nodes. The
2730  * first ExecProcNode will take care of actually doing the rescan.
2731  */
2732  rcplanstate->chgParam = bms_add_member(rcplanstate->chgParam,
2733  epqstate->epqParam);
2734  }
2735 }
List * paramExecTypes
Definition: plannodes.h:90
#define NIL
Definition: pg_list.h:65
void ExecSetParamPlanMulti(const Bitmapset *params, ExprContext *econtext)
Definition: nodeSubplan.c:1245
PlannedStmt * es_plannedstmt
Definition: execnodes.h:513
#define MemSet(start, val, len)
Definition: c.h:949
EState * parentestate
Definition: execnodes.h:1080
#define GetPerTupleExprContext(estate)
Definition: executor.h:507
ParamExecData * es_param_exec_vals
Definition: execnodes.h:547
EState * recheckestate
Definition: execnodes.h:1110
bool isnull
Definition: params.h:150
static void EvalPlanQualStart(EPQState *epqstate, Plan *planTree)
Definition: execMain.c:2744
bool * relsubs_done
Definition: execnodes.h:1123
Bitmapset * chgParam
Definition: execnodes.h:976
Plan * plan
Definition: execnodes.h:1096
unsigned int Index
Definition: c.h:482
Plan * plan
Definition: execnodes.h:944
static int list_length(const List *l)
Definition: pg_list.h:169
Bitmapset * extParam
Definition: plannodes.h:160
Index es_range_table_size
Definition: execnodes.h:508
Bitmapset * bms_add_member(Bitmapset *a, int x)
Definition: bitmapset.c:736
int i
Datum value
Definition: params.h:149
int epqParam
Definition: execnodes.h:1081
PlanState * recheckplanstate
Definition: execnodes.h:1125

◆ EvalPlanQualEnd()

void EvalPlanQualEnd ( EPQState epqstate)

Definition at line 2921 of file execMain.c.

References EState::es_query_cxt, EState::es_range_table_size, EState::es_subplanstates, EState::es_tupleTable, ExecCleanUpTriggerState(), ExecEndNode(), ExecResetTupleTable(), FreeExecutorState(), lfirst, MemoryContextSwitchTo(), NIL, EPQState::origslot, EPQState::parentestate, EPQState::recheckestate, EPQState::recheckplanstate, 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(), and ExecEndModifyTable().

2922 {
2923  EState *estate = epqstate->recheckestate;
2924  Index rtsize;
2925  MemoryContext oldcontext;
2926  ListCell *l;
2927 
2928  rtsize = epqstate->parentestate->es_range_table_size;
2929 
2930  /*
2931  * We may have a tuple table, even if EPQ wasn't started, because we allow
2932  * use of EvalPlanQualSlot() without calling EvalPlanQualBegin().
2933  */
2934  if (epqstate->tuple_table != NIL)
2935  {
2936  memset(epqstate->relsubs_slot, 0,
2937  rtsize * sizeof(TupleTableSlot *));
2938  ExecResetTupleTable(epqstate->tuple_table, true);
2939  epqstate->tuple_table = NIL;
2940  }
2941 
2942  /* EPQ wasn't started, nothing further to do */
2943  if (estate == NULL)
2944  return;
2945 
2946  oldcontext = MemoryContextSwitchTo(estate->es_query_cxt);
2947 
2948  ExecEndNode(epqstate->recheckplanstate);
2949 
2950  foreach(l, estate->es_subplanstates)
2951  {
2952  PlanState *subplanstate = (PlanState *) lfirst(l);
2953 
2954  ExecEndNode(subplanstate);
2955  }
2956 
2957  /* throw away the per-estate tuple table, some node may have used it */
2958  ExecResetTupleTable(estate->es_tupleTable, false);
2959 
2960  /* close any trigger target relations attached to this EState */
2961  ExecCleanUpTriggerState(estate);
2962 
2963  MemoryContextSwitchTo(oldcontext);
2964 
2965  FreeExecutorState(estate);
2966 
2967  /* Mark EPQState idle */
2968  epqstate->origslot = NULL;
2969  epqstate->recheckestate = NULL;
2970  epqstate->recheckplanstate = NULL;
2971  epqstate->relsubs_rowmark = NULL;
2972  epqstate->relsubs_done = NULL;
2973 }
TupleTableSlot ** relsubs_slot
Definition: execnodes.h:1089
#define NIL
Definition: pg_list.h:65
void ExecEndNode(PlanState *node)
Definition: execProcnode.c:543
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:109
EState * parentestate
Definition: execnodes.h:1080
void FreeExecutorState(EState *estate)
Definition: execUtils.c:191
MemoryContext es_query_cxt
Definition: execnodes.h:552
EState * recheckestate
Definition: execnodes.h:1110
List * tuple_table
Definition: execnodes.h:1088
bool * relsubs_done
Definition: execnodes.h:1123
TupleTableSlot * origslot
Definition: execnodes.h:1105
List * es_tupleTable
Definition: execnodes.h:554
void ExecResetTupleTable(List *tupleTable, bool shouldFree)
Definition: execTuples.c:1161
unsigned int Index
Definition: c.h:482
#define lfirst(lc)
Definition: pg_list.h:190
Index es_range_table_size
Definition: execnodes.h:508
List * es_subplanstates
Definition: execnodes.h:564
void ExecCleanUpTriggerState(EState *estate)
Definition: execMain.c:1435
ExecAuxRowMark ** relsubs_rowmark
Definition: execnodes.h:1117
PlanState * recheckplanstate
Definition: execnodes.h:1125

◆ EvalPlanQualFetchRowMark()

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

Definition at line 2558 of file execMain.c.

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

2559 {
2560  ExecAuxRowMark *earm = epqstate->relsubs_rowmark[rti - 1];
2561  ExecRowMark *erm = earm->rowmark;
2562  Datum datum;
2563  bool isNull;
2564 
2565  Assert(earm != NULL);
2566  Assert(epqstate->origslot != NULL);
2567 
2569  elog(ERROR, "EvalPlanQual doesn't support locking rowmarks");
2570 
2571  /* if child rel, must check whether it produced this row */
2572  if (erm->rti != erm->prti)
2573  {
2574  Oid tableoid;
2575 
2576  datum = ExecGetJunkAttribute(epqstate->origslot,
2577  earm->toidAttNo,
2578  &isNull);
2579  /* non-locked rels could be on the inside of outer joins */
2580  if (isNull)
2581  return false;
2582 
2583  tableoid = DatumGetObjectId(datum);
2584 
2585  Assert(OidIsValid(erm->relid));
2586  if (tableoid != erm->relid)
2587  {
2588  /* this child is inactive right now */
2589  return false;
2590  }
2591  }
2592 
2593  if (erm->markType == ROW_MARK_REFERENCE)
2594  {
2595  Assert(erm->relation != NULL);
2596 
2597  /* fetch the tuple's ctid */
2598  datum = ExecGetJunkAttribute(epqstate->origslot,
2599  earm->ctidAttNo,
2600  &isNull);
2601  /* non-locked rels could be on the inside of outer joins */
2602  if (isNull)
2603  return false;
2604 
2605  /* fetch requests on foreign tables must be passed to their FDW */
2606  if (erm->relation->rd_rel->relkind == RELKIND_FOREIGN_TABLE)
2607  {
2608  FdwRoutine *fdwroutine;
2609  bool updated = false;
2610 
2611  fdwroutine = GetFdwRoutineForRelation(erm->relation, false);
2612  /* this should have been checked already, but let's be safe */
2613  if (fdwroutine->RefetchForeignRow == NULL)
2614  ereport(ERROR,
2615  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2616  errmsg("cannot lock rows in foreign table \"%s\"",
2618 
2619  fdwroutine->RefetchForeignRow(epqstate->recheckestate,
2620  erm,
2621  datum,
2622  slot,
2623  &updated);
2624  if (TupIsNull(slot))
2625  elog(ERROR, "failed to fetch tuple for EvalPlanQual recheck");
2626 
2627  /*
2628  * Ideally we'd insist on updated == false here, but that assumes
2629  * that FDWs can track that exactly, which they might not be able
2630  * to. So just ignore the flag.
2631  */
2632  return true;
2633  }
2634  else
2635  {
2636  /* ordinary table, fetch the tuple */
2638  (ItemPointer) DatumGetPointer(datum),
2639  SnapshotAny, slot))
2640  elog(ERROR, "failed to fetch tuple for EvalPlanQual recheck");
2641  return true;
2642  }
2643  }
2644  else
2645  {
2646  Assert(erm->markType == ROW_MARK_COPY);
2647 
2648  /* fetch the whole-row Var for the relation */
2649  datum = ExecGetJunkAttribute(epqstate->origslot,
2650  earm->wholeAttNo,
2651  &isNull);
2652  /* non-locked rels could be on the inside of outer joins */
2653  if (isNull)
2654  return false;
2655 
2656  ExecStoreHeapTupleDatum(datum, slot);
2657  return true;
2658  }
2659 }
Relation relation
Definition: execnodes.h:624
#define DatumGetObjectId(X)
Definition: postgres.h:500
int errcode(int sqlerrcode)
Definition: elog.c:610
Form_pg_class rd_rel
Definition: rel.h:109
unsigned int Oid
Definition: postgres_ext.h:31
#define OidIsValid(objectId)
Definition: c.h:651
#define RowMarkRequiresRowShareLock(marktype)
Definition: plannodes.h:1033
ExecRowMark * rowmark
Definition: execnodes.h:651
#define ERROR
Definition: elog.h:43
EState * recheckestate
Definition: execnodes.h:1110
Index rti
Definition: execnodes.h:626
AttrNumber wholeAttNo
Definition: execnodes.h:654
Index prti
Definition: execnodes.h:627
#define RelationGetRelationName(relation)
Definition: rel.h:490
#define TupIsNull(slot)
Definition: tuptable.h:292
TupleTableSlot * origslot
Definition: execnodes.h:1105
void ExecStoreHeapTupleDatum(Datum data, TupleTableSlot *slot)
Definition: execTuples.c:1576
static bool table_tuple_fetch_row_version(Relation rel, ItemPointer tid, Snapshot snapshot, TupleTableSlot *slot)
Definition: tableam.h:1071
uintptr_t Datum
Definition: postgres.h:367
#define ereport(elevel,...)
Definition: elog.h:144
#define Assert(condition)
Definition: c.h:745
RowMarkType markType
Definition: execnodes.h:629
AttrNumber toidAttNo
Definition: execnodes.h:653
#define SnapshotAny
Definition: snapmgr.h:68
#define DatumGetPointer(X)
Definition: postgres.h:549
int errmsg(const char *fmt,...)
Definition: elog.c:824
FdwRoutine * GetFdwRoutineForRelation(Relation relation, bool makecopy)
Definition: foreign.c:427
Datum ExecGetJunkAttribute(TupleTableSlot *slot, AttrNumber attno, bool *isNull)
Definition: execJunk.c:247
#define elog(elevel,...)
Definition: elog.h:214
ExecAuxRowMark ** relsubs_rowmark
Definition: execnodes.h:1117
AttrNumber ctidAttNo
Definition: execnodes.h:652
RefetchForeignRow_function RefetchForeignRow
Definition: fdwapi.h:225

◆ EvalPlanQualInit()

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

Definition at line 2475 of file execMain.c.

References EPQState::arowMarks, EPQState::epqParam, EState::es_range_table_size, NIL, EPQState::origslot, palloc0(), EPQState::parentestate, EPQState::plan, EPQState::recheckestate, EPQState::recheckplanstate, 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(), ExecInitLockRows(), and ExecInitModifyTable().

2477 {
2478  Index rtsize = parentestate->es_range_table_size;
2479 
2480  /* initialize data not changing over EPQState's lifetime */
2481  epqstate->parentestate = parentestate;
2482  epqstate->epqParam = epqParam;
2483 
2484  /*
2485  * Allocate space to reference a slot for each potential rti - do so now
2486  * rather than in EvalPlanQualBegin(), as done for other dynamically
2487  * allocated resources, so EvalPlanQualSlot() can be used to hold tuples
2488  * that *may* need EPQ later, without forcing the overhead of
2489  * EvalPlanQualBegin().
2490  */
2491  epqstate->tuple_table = NIL;
2492  epqstate->relsubs_slot = (TupleTableSlot **)
2493  palloc0(rtsize * sizeof(TupleTableSlot *));
2494 
2495  /* ... and remember data that EvalPlanQualBegin will need */
2496  epqstate->plan = subplan;
2497  epqstate->arowMarks = auxrowmarks;
2498 
2499  /* ... and mark the EPQ state inactive */
2500  epqstate->origslot = NULL;
2501  epqstate->recheckestate = NULL;
2502  epqstate->recheckplanstate = NULL;
2503  epqstate->relsubs_rowmark = NULL;
2504  epqstate->relsubs_done = NULL;
2505 }
TupleTableSlot ** relsubs_slot
Definition: execnodes.h:1089
#define NIL
Definition: pg_list.h:65
EState * parentestate
Definition: execnodes.h:1080
EState * recheckestate
Definition: execnodes.h:1110
List * arowMarks
Definition: execnodes.h:1097
List * tuple_table
Definition: execnodes.h:1088
bool * relsubs_done
Definition: execnodes.h:1123
TupleTableSlot * origslot
Definition: execnodes.h:1105
Plan * plan
Definition: execnodes.h:1096
void * palloc0(Size size)
Definition: mcxt.c:981
unsigned int Index
Definition: c.h:482
Index es_range_table_size
Definition: execnodes.h:508
int epqParam
Definition: execnodes.h:1081
ExecAuxRowMark ** relsubs_rowmark
Definition: execnodes.h:1117
PlanState * recheckplanstate
Definition: execnodes.h:1125

◆ EvalPlanQualNext()

TupleTableSlot* EvalPlanQualNext ( EPQState epqstate)

Definition at line 2667 of file execMain.c.

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

Referenced by EvalPlanQual(), and ExecLockRows().

2668 {
2669  MemoryContext oldcontext;
2670  TupleTableSlot *slot;
2671 
2672  oldcontext = MemoryContextSwitchTo(epqstate->recheckestate->es_query_cxt);
2673  slot = ExecProcNode(epqstate->recheckplanstate);
2674  MemoryContextSwitchTo(oldcontext);
2675 
2676  return slot;
2677 }
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:109
MemoryContext es_query_cxt
Definition: execnodes.h:552
EState * recheckestate
Definition: execnodes.h:1110
static TupleTableSlot * ExecProcNode(PlanState *node)
Definition: executor.h:240
PlanState * recheckplanstate
Definition: execnodes.h:1125

◆ EvalPlanQualSetPlan()

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

Definition at line 2513 of file execMain.c.

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

Referenced by ExecInitModifyTable(), and ExecModifyTable().

2514 {
2515  /* If we have a live EPQ query, shut it down */
2516  EvalPlanQualEnd(epqstate);
2517  /* And set/change the plan pointer */
2518  epqstate->plan = subplan;
2519  /* The rowmarks depend on the plan, too */
2520  epqstate->arowMarks = auxrowmarks;
2521 }
void EvalPlanQualEnd(EPQState *epqstate)
Definition: execMain.c:2921
List * arowMarks
Definition: execnodes.h:1097
Plan * plan
Definition: execnodes.h:1096

◆ EvalPlanQualSlot()

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

Definition at line 2530 of file execMain.c.

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

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

2532 {
2533  TupleTableSlot **slot;
2534 
2535  Assert(relation);
2536  Assert(rti > 0 && rti <= epqstate->parentestate->es_range_table_size);
2537  slot = &epqstate->relsubs_slot[rti - 1];
2538 
2539  if (*slot == NULL)
2540  {
2541  MemoryContext oldcontext;
2542 
2543  oldcontext = MemoryContextSwitchTo(epqstate->parentestate->es_query_cxt);
2544  *slot = table_slot_create(relation, &epqstate->tuple_table);
2545  MemoryContextSwitchTo(oldcontext);
2546  }
2547 
2548  return *slot;
2549 }
TupleTableSlot * table_slot_create(Relation relation, List **reglist)
Definition: tableam.c:91
TupleTableSlot ** relsubs_slot
Definition: execnodes.h:1089
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:109
EState * parentestate
Definition: execnodes.h:1080
MemoryContext es_query_cxt
Definition: execnodes.h:552
List * tuple_table
Definition: execnodes.h:1088
#define Assert(condition)
Definition: c.h:745

◆ EvalPlanQualStart()

static void EvalPlanQualStart ( EPQState epqstate,
Plan planTree 
)
static

Definition at line 2744 of file execMain.c.

References EPQState::arowMarks, Assert, CreateExecutorState(), EState::es_crosscheck_snapshot, EState::es_direction, EState::es_epq_active, EState::es_instrument, EState::es_junkFilter, EState::es_num_result_relations, EState::es_num_root_result_relations, 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_root_result_relations, EState::es_rowmarks, EState::es_snapshot, EState::es_subplanstates, EState::es_top_eflags, ExecInitNode(), ExecSetParamPlanMulti(), Plan::extParam, ForwardScanDirection, GetPerTupleExprContext, i, ParamExecData::isnull, lappend(), lfirst, list_length(), MemoryContextSwitchTo(), NIL, palloc(), palloc0(), PlannedStmt::paramExecTypes, EPQState::parentestate, EPQState::recheckestate, EPQState::recheckplanstate, EPQState::relsubs_done, EPQState::relsubs_rowmark, ExecAuxRowMark::rowmark, ExecRowMark::rti, PlannedStmt::subplans, and ParamExecData::value.

Referenced by EvalPlanQualBegin().

2745 {
2746  EState *parentestate = epqstate->parentestate;
2747  Index rtsize = parentestate->es_range_table_size;
2748  EState *rcestate;
2749  MemoryContext oldcontext;
2750  ListCell *l;
2751 
2752  epqstate->recheckestate = rcestate = CreateExecutorState();
2753 
2754  oldcontext = MemoryContextSwitchTo(rcestate->es_query_cxt);
2755 
2756  /* signal that this is an EState for executing EPQ */
2757  rcestate->es_epq_active = epqstate;
2758 
2759  /*
2760  * Child EPQ EStates share the parent's copy of unchanging state such as
2761  * the snapshot, rangetable, result-rel info, and external Param info.
2762  * They need their own copies of local state, including a tuple table,
2763  * es_param_exec_vals, etc.
2764  *
2765  * The ResultRelInfo array management is trickier than it looks. We
2766  * create fresh arrays for the child but copy all the content from the
2767  * parent. This is because it's okay for the child to share any
2768  * per-relation state the parent has already created --- but if the child
2769  * sets up any ResultRelInfo fields, such as its own junkfilter, that
2770  * state must *not* propagate back to the parent. (For one thing, the
2771  * pointed-to data is in a memory context that won't last long enough.)
2772  */
2773  rcestate->es_direction = ForwardScanDirection;
2774  rcestate->es_snapshot = parentestate->es_snapshot;
2775  rcestate->es_crosscheck_snapshot = parentestate->es_crosscheck_snapshot;
2776  rcestate->es_range_table = parentestate->es_range_table;
2777  rcestate->es_range_table_size = parentestate->es_range_table_size;
2778  rcestate->es_relations = parentestate->es_relations;
2779  rcestate->es_queryEnv = parentestate->es_queryEnv;
2780  rcestate->es_rowmarks = parentestate->es_rowmarks;
2781  rcestate->es_plannedstmt = parentestate->es_plannedstmt;
2782  rcestate->es_junkFilter = parentestate->es_junkFilter;
2783  rcestate->es_output_cid = parentestate->es_output_cid;
2784  if (parentestate->es_num_result_relations > 0)
2785  {
2786  int numResultRelations = parentestate->es_num_result_relations;
2787  int numRootResultRels = parentestate->es_num_root_result_relations;
2788  ResultRelInfo *resultRelInfos;
2789 
2790  resultRelInfos = (ResultRelInfo *)
2791  palloc(numResultRelations * sizeof(ResultRelInfo));
2792  memcpy(resultRelInfos, parentestate->es_result_relations,
2793  numResultRelations * sizeof(ResultRelInfo));
2794  rcestate->es_result_relations = resultRelInfos;
2795  rcestate->es_num_result_relations = numResultRelations;
2796 
2797  /* Also transfer partitioned root result relations. */
2798  if (numRootResultRels > 0)
2799  {
2800  resultRelInfos = (ResultRelInfo *)
2801  palloc(numRootResultRels * sizeof(ResultRelInfo));
2802  memcpy(resultRelInfos, parentestate->es_root_result_relations,
2803  numRootResultRels * sizeof(ResultRelInfo));
2804  rcestate->es_root_result_relations = resultRelInfos;
2805  rcestate->es_num_root_result_relations = numRootResultRels;
2806  }
2807  }
2808  /* es_result_relation_info must NOT be copied */
2809  /* es_trig_target_relations must NOT be copied */
2810  rcestate->es_top_eflags = parentestate->es_top_eflags;
2811  rcestate->es_instrument = parentestate->es_instrument;
2812  /* es_auxmodifytables must NOT be copied */
2813 
2814  /*
2815  * The external param list is simply shared from parent. The internal
2816  * param workspace has to be local state, but we copy the initial values
2817  * from the parent, so as to have access to any param values that were
2818  * already set from other parts of the parent's plan tree.
2819  */
2820  rcestate->es_param_list_info = parentestate->es_param_list_info;
2821  if (parentestate->es_plannedstmt->paramExecTypes != NIL)
2822  {
2823  int i;
2824 
2825  /*
2826  * Force evaluation of any InitPlan outputs that could be needed by
2827  * the subplan. (With more complexity, maybe we could postpone this
2828  * till the subplan actually demands them, but it doesn't seem worth
2829  * the trouble; this is a corner case already, since usually the
2830  * InitPlans would have been evaluated before reaching EvalPlanQual.)
2831  *
2832  * This will not touch output params of InitPlans that occur somewhere
2833  * within the subplan tree, only those that are attached to the
2834  * ModifyTable node or above it and are referenced within the subplan.
2835  * That's OK though, because the planner would only attach such
2836  * InitPlans to a lower-level SubqueryScan node, and EPQ execution
2837  * will not descend into a SubqueryScan.
2838  *
2839  * The EState's per-output-tuple econtext is sufficiently short-lived
2840  * for this, since it should get reset before there is any chance of
2841  * doing EvalPlanQual again.
2842  */
2843  ExecSetParamPlanMulti(planTree->extParam,
2844  GetPerTupleExprContext(parentestate));
2845 
2846  /* now make the internal param workspace ... */
2847  i = list_length(parentestate->es_plannedstmt->paramExecTypes);
2848  rcestate->es_param_exec_vals = (ParamExecData *)
2849  palloc0(i * sizeof(ParamExecData));
2850  /* ... and copy down all values, whether really needed or not */
2851  while (--i >= 0)
2852  {
2853  /* copy value if any, but not execPlan link */
2854  rcestate->es_param_exec_vals[i].value =
2855  parentestate->es_param_exec_vals[i].value;
2856  rcestate->es_param_exec_vals[i].isnull =
2857  parentestate->es_param_exec_vals[i].isnull;
2858  }
2859  }
2860 
2861  /*
2862  * Initialize private state information for each SubPlan. We must do this
2863  * before running ExecInitNode on the main query tree, since
2864  * ExecInitSubPlan expects to be able to find these entries. Some of the
2865  * SubPlans might not be used in the part of the plan tree we intend to
2866  * run, but since it's not easy to tell which, we just initialize them
2867  * all.
2868  */
2869  Assert(rcestate->es_subplanstates == NIL);
2870  foreach(l, parentestate->es_plannedstmt->subplans)
2871  {
2872  Plan *subplan = (Plan *) lfirst(l);
2873  PlanState *subplanstate;
2874 
2875  subplanstate = ExecInitNode(subplan, rcestate, 0);
2876  rcestate->es_subplanstates = lappend(rcestate->es_subplanstates,
2877  subplanstate);
2878  }
2879 
2880  /*
2881  * Build an RTI indexed array of rowmarks, so that
2882  * EvalPlanQualFetchRowMark() can efficiently access the to be fetched
2883  * rowmark.
2884  */
2885  epqstate->relsubs_rowmark = (ExecAuxRowMark **)
2886  palloc0(rtsize * sizeof(ExecAuxRowMark *));
2887  foreach(l, epqstate->arowMarks)
2888  {
2889  ExecAuxRowMark *earm = (ExecAuxRowMark *) lfirst(l);
2890 
2891  epqstate->relsubs_rowmark[earm->rowmark->rti - 1] = earm;
2892  }
2893 
2894  /*
2895  * Initialize per-relation EPQ tuple states to not-fetched.
2896  */
2897  epqstate->relsubs_done = (bool *)
2898  palloc0(rtsize * sizeof(bool));
2899 
2900  /*
2901  * Initialize the private state information for all the nodes in the part
2902  * of the plan tree we need to run. This opens files, allocates storage
2903  * and leaves us ready to start processing tuples.
2904  */
2905  epqstate->recheckplanstate = ExecInitNode(planTree, rcestate, 0);
2906 
2907  MemoryContextSwitchTo(oldcontext);
2908 }
List * paramExecTypes
Definition: plannodes.h:90
#define NIL
Definition: pg_list.h:65
JunkFilter * es_junkFilter
Definition: execnodes.h:516
void ExecSetParamPlanMulti(const Bitmapset *params, ExprContext *econtext)
Definition: nodeSubplan.c:1245
CommandId es_output_cid
Definition: execnodes.h:519
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:109
PlannedStmt * es_plannedstmt
Definition: execnodes.h:513
Snapshot es_crosscheck_snapshot
Definition: execnodes.h:506
Snapshot es_snapshot
Definition: execnodes.h:505
List * es_range_table
Definition: execnodes.h:507
EState * parentestate
Definition: execnodes.h:1080
ScanDirection es_direction
Definition: execnodes.h:504
struct EPQState * es_epq_active
Definition: execnodes.h:581
ExecRowMark * rowmark
Definition: execnodes.h:651
struct ExecRowMark ** es_rowmarks
Definition: execnodes.h:511
#define GetPerTupleExprContext(estate)
Definition: executor.h:507
ParamExecData * es_param_exec_vals
Definition: execnodes.h:547
MemoryContext es_query_cxt
Definition: execnodes.h:552
EState * recheckestate
Definition: execnodes.h:1110
bool isnull
Definition: params.h:150
List * arowMarks
Definition: execnodes.h:1097
Index rti
Definition: execnodes.h:626
ResultRelInfo * es_result_relations
Definition: execnodes.h:522
bool * relsubs_done
Definition: execnodes.h:1123
int es_instrument
Definition: execnodes.h:559
EState * CreateExecutorState(void)
Definition: execUtils.c:89
List * lappend(List *list, void *datum)
Definition: list.c:321
QueryEnvironment * es_queryEnv
Definition: execnodes.h:549
int es_num_root_result_relations
Definition: execnodes.h:533
void * palloc0(Size size)
Definition: mcxt.c:981
int es_num_result_relations
Definition: execnodes.h:523
unsigned int Index
Definition: c.h:482
List * subplans
Definition: plannodes.h:79
#define Assert(condition)
Definition: c.h:745
#define lfirst(lc)
Definition: pg_list.h:190
Relation * es_relations
Definition: execnodes.h:509
static int list_length(const List *l)
Definition: pg_list.h:169
Bitmapset * extParam
Definition: plannodes.h:160
Index es_range_table_size
Definition: execnodes.h:508
List * es_subplanstates
Definition: execnodes.h:564
void * palloc(Size size)
Definition: mcxt.c:950
int es_top_eflags
Definition: execnodes.h:558
ResultRelInfo * es_root_result_relations
Definition: execnodes.h:532
int i
Datum value
Definition: params.h:149
ParamListInfo es_param_list_info
Definition: execnodes.h:546
PlanState * ExecInitNode(Plan *node, EState *estate, int eflags)
Definition: execProcnode.c:139
ExecAuxRowMark ** relsubs_rowmark
Definition: execnodes.h:1117
PlanState * recheckplanstate
Definition: execnodes.h:1125

◆ ExecBuildAuxRowMark()

ExecAuxRowMark* ExecBuildAuxRowMark ( ExecRowMark erm,
List targetlist 
)

Definition at line 2351 of file execMain.c.

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

2352 {
2353  ExecAuxRowMark *aerm = (ExecAuxRowMark *) palloc0(sizeof(ExecAuxRowMark));
2354  char resname[32];
2355 
2356  aerm->rowmark = erm;
2357 
2358  /* Look up the resjunk columns associated with this rowmark */
2359  if (erm->markType != ROW_MARK_COPY)
2360  {
2361  /* need ctid for all methods other than COPY */
2362  snprintf(resname, sizeof(resname), "ctid%u", erm->rowmarkId);
2363  aerm->ctidAttNo = ExecFindJunkAttributeInTlist(targetlist,
2364  resname);
2365  if (!AttributeNumberIsValid(aerm->ctidAttNo))
2366  elog(ERROR, "could not find junk %s column", resname);
2367  }
2368  else
2369  {
2370  /* need wholerow if COPY */
2371  snprintf(resname, sizeof(resname), "wholerow%u", erm->rowmarkId);
2372  aerm->wholeAttNo = ExecFindJunkAttributeInTlist(targetlist,
2373  resname);
2374  if (!AttributeNumberIsValid(aerm->wholeAttNo))
2375  elog(ERROR, "could not find junk %s column", resname);
2376  }
2377 
2378  /* if child rel, need tableoid */
2379  if (erm->rti != erm->prti)
2380  {
2381  snprintf(resname, sizeof(resname), "tableoid%u", erm->rowmarkId);
2382  aerm->toidAttNo = ExecFindJunkAttributeInTlist(targetlist,
2383  resname);
2384  if (!AttributeNumberIsValid(aerm->toidAttNo))
2385  elog(ERROR, "could not find junk %s column", resname);
2386  }
2387 
2388  return aerm;
2389 }
AttrNumber ExecFindJunkAttributeInTlist(List *targetlist, const char *attrName)
Definition: execJunk.c:220
ExecRowMark * rowmark
Definition: execnodes.h:651
#define ERROR
Definition: elog.h:43
Index rti
Definition: execnodes.h:626
AttrNumber wholeAttNo
Definition: execnodes.h:654
Index prti
Definition: execnodes.h:627
Index rowmarkId
Definition: execnodes.h:628
#define AttributeNumberIsValid(attributeNumber)
Definition: attnum.h:34
void * palloc0(Size size)
Definition: mcxt.c:981
RowMarkType markType
Definition: execnodes.h:629
AttrNumber toidAttNo
Definition: execnodes.h:653
#define elog(elevel,...)
Definition: elog.h:214
#define snprintf
Definition: port.h:193
AttrNumber ctidAttNo
Definition: execnodes.h:652

◆ ExecBuildSlotValueDescription()

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

Definition at line 2165 of file execMain.c.

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

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

2170 {
2172  StringInfoData collist;
2173  bool write_comma = false;
2174  bool write_comma_collist = false;
2175  int i;
2176  AclResult aclresult;
2177  bool table_perm = false;
2178  bool any_perm = false;
2179 
2180  /*
2181  * Check if RLS is enabled and should be active for the relation; if so,
2182  * then don't return anything. Otherwise, go through normal permission
2183  * checks.
2184  */
2185  if (check_enable_rls(reloid, InvalidOid, true) == RLS_ENABLED)
2186  return NULL;
2187 
2188  initStringInfo(&buf);
2189 
2190  appendStringInfoChar(&buf, '(');
2191 
2192  /*
2193  * Check if the user has permissions to see the row. Table-level SELECT
2194  * allows access to all columns. If the user does not have table-level
2195  * SELECT then we check each column and include those the user has SELECT
2196  * rights on. Additionally, we always include columns the user provided
2197  * data for.
2198  */
2199  aclresult = pg_class_aclcheck(reloid, GetUserId(), ACL_SELECT);
2200  if (aclresult != ACLCHECK_OK)
2201  {
2202  /* Set up the buffer for the column list */
2203  initStringInfo(&collist);
2204  appendStringInfoChar(&collist, '(');
2205  }
2206  else
2207  table_perm = any_perm = true;
2208 
2209  /* Make sure the tuple is fully deconstructed */
2210  slot_getallattrs(slot);
2211 
2212  for (i = 0; i < tupdesc->natts; i++)
2213  {
2214  bool column_perm = false;
2215  char *val;
2216  int vallen;
2217  Form_pg_attribute att = TupleDescAttr(tupdesc, i);
2218 
2219  /* ignore dropped columns */
2220  if (att->attisdropped)
2221  continue;
2222 
2223  if (!table_perm)
2224  {
2225  /*
2226  * No table-level SELECT, so need to make sure they either have
2227  * SELECT rights on the column or that they have provided the data
2228  * for the column. If not, omit this column from the error
2229  * message.
2230  */
2231  aclresult = pg_attribute_aclcheck(reloid, att->attnum,
2232  GetUserId(), ACL_SELECT);
2234  modifiedCols) || aclresult == ACLCHECK_OK)
2235  {
2236  column_perm = any_perm = true;
2237 
2238  if (write_comma_collist)
2239  appendStringInfoString(&collist, ", ");
2240  else
2241  write_comma_collist = true;
2242 
2243  appendStringInfoString(&collist, NameStr(att->attname));
2244  }
2245  }
2246 
2247  if (table_perm || column_perm)
2248  {
2249  if (slot->tts_isnull[i])
2250  val = "null";
2251  else
2252  {
2253  Oid foutoid;
2254  bool typisvarlena;
2255 
2256  getTypeOutputInfo(att->atttypid,
2257  &foutoid, &typisvarlena);
2258  val = OidOutputFunctionCall(foutoid, slot->tts_values[i]);
2259  }
2260 
2261  if (write_comma)
2262  appendStringInfoString(&buf, ", ");
2263  else
2264  write_comma = true;
2265 
2266  /* truncate if needed */
2267  vallen = strlen(val);
2268  if (vallen <= maxfieldlen)
2269  appendBinaryStringInfo(&buf, val, vallen);
2270  else
2271  {
2272  vallen = pg_mbcliplen(val, vallen, maxfieldlen);
2273  appendBinaryStringInfo(&buf, val, vallen);
2274  appendStringInfoString(&buf, "...");
2275  }
2276  }
2277  }
2278 
2279  /* If we end up with zero columns being returned, then return NULL. */
2280  if (!any_perm)
2281  return NULL;
2282 
2283  appendStringInfoChar(&buf, ')');
2284 
2285  if (!table_perm)
2286  {
2287  appendStringInfoString(&collist, ") = ");
2288  appendBinaryStringInfo(&collist, buf.data, buf.len);
2289 
2290  return collist.data;
2291  }
2292 
2293  return buf.data;
2294 }
void getTypeOutputInfo(Oid type, Oid *typOutput, bool *typIsVarlena)
Definition: lsyscache.c:2784
AclResult pg_attribute_aclcheck(Oid table_oid, AttrNumber attnum, Oid roleid, AclMode mode)
Definition: aclchk.c:4449
Oid GetUserId(void)
Definition: miscinit.c:476
#define TupleDescAttr(tupdesc, i)
Definition: tupdesc.h:92
Datum * tts_values
Definition: tuptable.h:126
#define FirstLowInvalidHeapAttributeNumber
Definition: sysattr.h:27
unsigned int Oid
Definition: postgres_ext.h:31
int pg_mbcliplen(const char *mbstr, int len, int limit)
Definition: mbutils.c:967
static void slot_getallattrs(TupleTableSlot *slot)
Definition: tuptable.h:354
void appendStringInfoString(StringInfo str, const char *s)
Definition: stringinfo.c:176
static char * buf
Definition: pg_test_fsync.c:67
bool * tts_isnull
Definition: tuptable.h:128
FormData_pg_attribute * Form_pg_attribute
Definition: pg_attribute.h:193
void appendStringInfoChar(StringInfo str, char ch)
Definition: stringinfo.c:188
void initStringInfo(StringInfo str)
Definition: stringinfo.c:59
AclResult
Definition: acl.h:177
#define ACL_SELECT
Definition: parsenodes.h:75
#define InvalidOid
Definition: postgres_ext.h:36
int check_enable_rls(Oid relid, Oid checkAsUser, bool noError)
Definition: rls.c:52
AclResult pg_class_aclcheck(Oid table_oid, Oid roleid, AclMode mode)
Definition: aclchk.c:4563
char * OidOutputFunctionCall(Oid functionId, Datum val)
Definition: fmgr.c:1657
int i
#define NameStr(name)
Definition: c.h:622
bool bms_is_member(int x, const Bitmapset *a)
Definition: bitmapset.c:427
void appendBinaryStringInfo(StringInfo str, const char *data, int datalen)
Definition: stringinfo.c:227
long val
Definition: informix.c:664

◆ ExecCheckRTEPerms()

static bool ExecCheckRTEPerms ( RangeTblEntry rte)
static

Definition at line 602 of file execMain.c.

References ACL_INSERT, ACL_SELECT, ACL_UPDATE, ACLCHECK_OK, ACLMASK_ALL, ACLMASK_ANY, bms_is_empty(), bms_next_member(), RangeTblEntry::checkAsUser, ExecCheckRTEPermsModified(), FirstLowInvalidHeapAttributeNumber, GetUserId(), RangeTblEntry::insertedCols, InvalidAttrNumber, pg_attribute_aclcheck(), pg_attribute_aclcheck_all(), pg_class_aclmask(), RangeTblEntry::relid, RangeTblEntry::requiredPerms, RTE_RELATION, RangeTblEntry::rtekind, RangeTblEntry::selectedCols, and RangeTblEntry::updatedCols.

Referenced by ExecCheckRTPerms().

603 {
604  AclMode requiredPerms;
605  AclMode relPerms;
606  AclMode remainingPerms;
607  Oid relOid;
608  Oid userid;
609 
610  /*
611  * Only plain-relation RTEs need to be checked here. Function RTEs are
612  * checked when the function is prepared for execution. Join, subquery,
613  * and special RTEs need no checks.
614  */
615  if (rte->rtekind != RTE_RELATION)
616  return true;
617 
618  /*
619  * No work if requiredPerms is empty.
620  */
621  requiredPerms = rte->requiredPerms;
622  if (requiredPerms == 0)
623  return true;
624 
625  relOid = rte->relid;
626 
627  /*
628  * userid to check as: current user unless we have a setuid indication.
629  *
630  * Note: GetUserId() is presently fast enough that there's no harm in
631  * calling it separately for each RTE. If that stops being true, we could
632  * call it once in ExecCheckRTPerms and pass the userid down from there.
633  * But for now, no need for the extra clutter.
634  */
635  userid = rte->checkAsUser ? rte->checkAsUser : GetUserId();
636 
637  /*
638  * We must have *all* the requiredPerms bits, but some of the bits can be
639  * satisfied from column-level rather than relation-level permissions.
640  * First, remove any bits that are satisfied by relation permissions.
641  */
642  relPerms = pg_class_aclmask(relOid, userid, requiredPerms, ACLMASK_ALL);
643  remainingPerms = requiredPerms & ~relPerms;
644  if (remainingPerms != 0)
645  {
646  int col = -1;
647 
648  /*
649  * If we lack any permissions that exist only as relation permissions,
650  * we can fail straight away.
651  */
652  if (remainingPerms & ~(ACL_SELECT | ACL_INSERT | ACL_UPDATE))
653  return false;
654 
655  /*
656  * Check to see if we have the needed privileges at column level.
657  *
658  * Note: failures just report a table-level error; it would be nicer
659  * to report a column-level error if we have some but not all of the
660  * column privileges.
661  */
662  if (remainingPerms & ACL_SELECT)
663  {
664  /*
665  * When the query doesn't explicitly reference any columns (for
666  * example, SELECT COUNT(*) FROM table), allow the query if we
667  * have SELECT on any column of the rel, as per SQL spec.
668  */
669  if (bms_is_empty(rte->selectedCols))
670  {
671  if (pg_attribute_aclcheck_all(relOid, userid, ACL_SELECT,
673  return false;
674  }
675 
676  while ((col = bms_next_member(rte->selectedCols, col)) >= 0)
677  {
678  /* bit #s are offset by FirstLowInvalidHeapAttributeNumber */
680 
681  if (attno == InvalidAttrNumber)
682  {
683  /* Whole-row reference, must have priv on all cols */
684  if (pg_attribute_aclcheck_all(relOid, userid, ACL_SELECT,
686  return false;
687  }
688  else
689  {
690  if (pg_attribute_aclcheck(relOid, attno, userid,
691  ACL_SELECT) != ACLCHECK_OK)
692  return false;
693  }
694  }
695  }
696 
697  /*
698  * Basically the same for the mod columns, for both INSERT and UPDATE
699  * privilege as specified by remainingPerms.
700  */
701  if (remainingPerms & ACL_INSERT && !ExecCheckRTEPermsModified(relOid,
702  userid,
703  rte->insertedCols,
704  ACL_INSERT))
705  return false;
706 
707  if (remainingPerms & ACL_UPDATE && !ExecCheckRTEPermsModified(relOid,
708  userid,
709  rte->updatedCols,
710  ACL_UPDATE))
711  return false;
712  }
713  return true;
714 }
AclResult pg_attribute_aclcheck(Oid table_oid, AttrNumber attnum, Oid roleid, AclMode mode)
Definition: aclchk.c:4449
Oid GetUserId(void)
Definition: miscinit.c:476
int bms_next_member(const Bitmapset *a, int prevbit)
Definition: bitmapset.c:1043
#define FirstLowInvalidHeapAttributeNumber
Definition: sysattr.h:27
AclMode requiredPerms
Definition: parsenodes.h:1120
unsigned int Oid
Definition: postgres_ext.h:31
AclMode pg_class_aclmask(Oid table_oid, Oid roleid, AclMode mask, AclMaskHow how)
Definition: aclchk.c:3772
uint32 AclMode
Definition: parsenodes.h:72
Bitmapset * selectedCols
Definition: parsenodes.h:1122
static bool ExecCheckRTEPermsModified(Oid relOid, Oid userid, Bitmapset *modifiedCols, AclMode requiredPerms)
Definition: execMain.c:722
bool bms_is_empty(const Bitmapset *a)
Definition: bitmapset.c:701
#define ACL_UPDATE
Definition: parsenodes.h:76
#define ACL_SELECT
Definition: parsenodes.h:75
Bitmapset * updatedCols
Definition: parsenodes.h:1124
#define ACL_INSERT
Definition: parsenodes.h:74
AclResult pg_attribute_aclcheck_all(Oid table_oid, Oid roleid, AclMode mode, AclMaskHow how)
Definition: aclchk.c:4478
#define InvalidAttrNumber
Definition: attnum.h:23
RTEKind rtekind
Definition: parsenodes.h:977
Bitmapset * insertedCols
Definition: parsenodes.h:1123
int16 AttrNumber
Definition: attnum.h:21

◆ ExecCheckRTEPermsModified()

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

Definition at line 722 of file execMain.c.

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

724 {
725  int col = -1;
726 
727  /*
728  * When the query doesn't explicitly update any columns, allow the query
729  * if we have permission on any column of the rel. This is to handle
730  * SELECT FOR UPDATE as well as possible corner cases in UPDATE.
731  */
732  if (bms_is_empty(modifiedCols))
733  {
734  if (pg_attribute_aclcheck_all(relOid, userid, requiredPerms,
736  return false;
737  }
738 
739  while ((col = bms_next_member(modifiedCols, col)) >= 0)
740  {
741  /* bit #s are offset by FirstLowInvalidHeapAttributeNumber */
743 
744  if (attno == InvalidAttrNumber)
745  {
746  /* whole-row reference can't happen here */
747  elog(ERROR, "whole-row update is not implemented");
748  }
749  else
750  {
751  if (pg_attribute_aclcheck(relOid, attno, userid,
752  requiredPerms) != ACLCHECK_OK)
753  return false;
754  }
755  }
756  return true;
757 }
AclResult pg_attribute_aclcheck(Oid table_oid, AttrNumber attnum, Oid roleid, AclMode mode)
Definition: aclchk.c:4449
int bms_next_member(const Bitmapset *a, int prevbit)
Definition: bitmapset.c:1043
#define FirstLowInvalidHeapAttributeNumber
Definition: sysattr.h:27
#define ERROR
Definition: elog.h:43
bool bms_is_empty(const Bitmapset *a)
Definition: bitmapset.c:701
AclResult pg_attribute_aclcheck_all(Oid table_oid, Oid roleid, AclMode mode, AclMaskHow how)
Definition: aclchk.c:4478
#define InvalidAttrNumber
Definition: attnum.h:23
#define elog(elevel,...)
Definition: elog.h:214
int16 AttrNumber
Definition: attnum.h:21

◆ ExecCheckRTPerms()

bool ExecCheckRTPerms ( List rangeTable,
bool  ereport_on_violation 
)

Definition at line 571 of file execMain.c.

References aclcheck_error(), ACLCHECK_NO_PRIV, Assert, ExecCheckRTEPerms(), ExecutorCheckPerms_hook, get_rel_name(), get_rel_relkind(), get_relkind_objtype(), lfirst, RangeTblEntry::relid, RTE_RELATION, and RangeTblEntry::rtekind.

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

572 {
573  ListCell *l;
574  bool result = true;
575 
576  foreach(l, rangeTable)
577  {
578  RangeTblEntry *rte = (RangeTblEntry *) lfirst(l);
579 
580  result = ExecCheckRTEPerms(rte);
581  if (!result)
582  {
583  Assert(rte->rtekind == RTE_RELATION);
584  if (ereport_on_violation)
586  get_rel_name(rte->relid));
587  return false;
588  }
589  }
590 
592  result = (*ExecutorCheckPerms_hook) (rangeTable,
593  ereport_on_violation);
594  return result;
595 }
char get_rel_relkind(Oid relid)
Definition: lsyscache.c:1915
void aclcheck_error(AclResult aclerr, ObjectType objtype, const char *objectname)
Definition: aclchk.c:3294
static bool ExecCheckRTEPerms(RangeTblEntry *rte)
Definition: execMain.c:602
ExecutorCheckPerms_hook_type ExecutorCheckPerms_hook
Definition: execMain.c:76
#define Assert(condition)
Definition: c.h:745
#define lfirst(lc)
Definition: pg_list.h:190
RTEKind rtekind
Definition: parsenodes.h:977
ObjectType get_relkind_objtype(char relkind)
char * get_rel_name(Oid relid)
Definition: lsyscache.c:1840

◆ ExecCheckXactReadOnly()

static void ExecCheckXactReadOnly ( PlannedStmt plannedstmt)
static

Definition at line 769 of file execMain.c.

References ACL_SELECT, CMD_SELECT, PlannedStmt::commandType, CreateCommandName(), get_rel_namespace(), PlannedStmt::hasModifyingCTE, isTempNamespace(), lfirst, PreventCommandIfParallelMode(), PreventCommandIfReadOnly(), RangeTblEntry::relid, RangeTblEntry::requiredPerms, PlannedStmt::rtable, RTE_RELATION, and RangeTblEntry::rtekind.

Referenced by standard_ExecutorStart().

770 {
771  ListCell *l;
772 
773  /*
774  * Fail if write permissions are requested in parallel mode for table
775  * (temp or non-temp), otherwise fail for any non-temp table.
776  */
777  foreach(l, plannedstmt->rtable)
778  {
779  RangeTblEntry *rte = (RangeTblEntry *) lfirst(l);
780 
781  if (rte->rtekind != RTE_RELATION)
782  continue;
783 
784  if ((rte->requiredPerms & (~ACL_SELECT)) == 0)
785  continue;
786 
788  continue;
789 
791  }
792 
793  if (plannedstmt->commandType != CMD_SELECT || plannedstmt->hasModifyingCTE)
795 }
void PreventCommandIfParallelMode(const char *cmdname)
Definition: utility.c:425
static const char * CreateCommandName(Node *parsetree)
Definition: utility.h:99
Oid get_rel_namespace(Oid relid)
Definition: lsyscache.c:1864
Definition: nodes.h:529
AclMode requiredPerms
Definition: parsenodes.h:1120
bool isTempNamespace(Oid namespaceId)
Definition: namespace.c:3156
CmdType commandType
Definition: plannodes.h:46
#define ACL_SELECT
Definition: parsenodes.h:75
#define lfirst(lc)
Definition: pg_list.h:190
bool hasModifyingCTE
Definition: plannodes.h:52
List * rtable
Definition: plannodes.h:66
void PreventCommandIfReadOnly(const char *cmdname)
Definition: utility.c:407
RTEKind rtekind
Definition: parsenodes.h:977

◆ ExecCleanUpTriggerState()

void ExecCleanUpTriggerState ( EState estate)

Definition at line 1435 of file execMain.c.

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

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

1436 {
1437  ListCell *l;
1438 
1439  foreach(l, estate->es_trig_target_relations)
1440  {
1441  ResultRelInfo *resultRelInfo = (ResultRelInfo *) lfirst(l);
1442 
1443  /*
1444  * Assert this is a "dummy" ResultRelInfo, see above. Otherwise we
1445  * might be issuing a duplicate close against a Relation opened by
1446  * ExecGetRangeTableRelation.
1447  */
1448  Assert(resultRelInfo->ri_RangeTableIndex == 0);
1449 
1450  /*
1451  * Since ExecGetTriggerResultRel doesn't call ExecOpenIndices for
1452  * these rels, we needn't call ExecCloseIndices either.
1453  */
1454  Assert(resultRelInfo->ri_NumIndices == 0);
1455 
1456  table_close(resultRelInfo->ri_RelationDesc, NoLock);
1457  }
1458 }
int ri_NumIndices
Definition: execnodes.h:416
Relation ri_RelationDesc
Definition: execnodes.h:413
void table_close(Relation relation, LOCKMODE lockmode)
Definition: table.c:167
Index ri_RangeTableIndex
Definition: execnodes.h:410
#define NoLock
Definition: lockdefs.h:34
List * es_trig_target_relations
Definition: execnodes.h:543
#define Assert(condition)
Definition: c.h:745
#define lfirst(lc)
Definition: pg_list.h:190

◆ ExecConstraints()

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

Definition at line 1886 of file execMain.c.

References Assert, bms_union(), build_attrmap_by_name_if_req(), TupleDescData::constr, ereport, errcode(), errdetail(), errmsg(), ERROR, errtablecol(), errtableconstraint(), ExecBuildSlotValueDescription(), ExecRelCheck(), execute_attr_map_slot(), GetInsertedColumns, GetUpdatedColumns, TupleConstr::has_not_null, MakeTupleTableSlot(), NameStr, TupleDescData::natts, TupleConstr::num_check, RelationGetDescr, RelationGetRelationName, RelationGetRelid, ResultRelInfo::ri_PartitionRoot, ResultRelInfo::ri_RelationDesc, slot_attisnull(), TTSOpsVirtual, and TupleDescAttr.

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

1888 {
1889  Relation rel = resultRelInfo->ri_RelationDesc;
1890  TupleDesc tupdesc = RelationGetDescr(rel);
1891  TupleConstr *constr = tupdesc->constr;
1892  Bitmapset *modifiedCols;
1893  Bitmapset *insertedCols;
1894  Bitmapset *updatedCols;
1895 
1896  Assert(constr); /* we should not be called otherwise */
1897 
1898  if (constr->has_not_null)
1899  {
1900  int natts = tupdesc->natts;
1901  int attrChk;
1902 
1903  for (attrChk = 1; attrChk <= natts; attrChk++)
1904  {
1905  Form_pg_attribute att = TupleDescAttr(tupdesc, attrChk - 1);
1906 
1907  if (att->attnotnull && slot_attisnull(slot, attrChk))
1908  {
1909  char *val_desc;
1910  Relation orig_rel = rel;
1911  TupleDesc orig_tupdesc = RelationGetDescr(rel);
1912 
1913  /*
1914  * If the tuple has been routed, it's been converted to the
1915  * partition's rowtype, which might differ from the root
1916  * table's. We must convert it back to the root table's
1917  * rowtype so that val_desc shown error message matches the
1918  * input tuple.
1919  */
1920  if (resultRelInfo->ri_PartitionRoot)
1921  {
1922  AttrMap *map;
1923 
1924  rel = resultRelInfo->ri_PartitionRoot;
1925  tupdesc = RelationGetDescr(rel);
1926  /* a reverse map */
1927  map = build_attrmap_by_name_if_req(orig_tupdesc,
1928  tupdesc);
1929 
1930  /*
1931  * Partition-specific slot's tupdesc can't be changed, so
1932  * allocate a new one.
1933  */
1934  if (map != NULL)
1935  slot = execute_attr_map_slot(map, slot,
1936  MakeTupleTableSlot(tupdesc, &TTSOpsVirtual));
1937  }
1938 
1939  insertedCols = GetInsertedColumns(resultRelInfo, estate);
1940  updatedCols = GetUpdatedColumns(resultRelInfo, estate);
1941  modifiedCols = bms_union(insertedCols, updatedCols);
1943  slot,
1944  tupdesc,
1945  modifiedCols,
1946  64);
1947 
1948  ereport(ERROR,
1949  (errcode(ERRCODE_NOT_NULL_VIOLATION),
1950  errmsg("null value in column \"%s\" of relation \"%s\" violates not-null constraint",
1951  NameStr(att->attname),
1952  RelationGetRelationName(orig_rel)),
1953  val_desc ? errdetail("Failing row contains %s.", val_desc) : 0,
1954  errtablecol(orig_rel, attrChk)));
1955  }
1956  }
1957  }
1958 
1959  if (constr->num_check > 0)
1960  {
1961  const char *failed;
1962 
1963  if ((failed = ExecRelCheck(resultRelInfo, slot, estate)) != NULL)
1964  {
1965  char *val_desc;
1966  Relation orig_rel = rel;
1967 
1968  /* See the comment above. */
1969  if (resultRelInfo->ri_PartitionRoot)
1970  {
1971  TupleDesc old_tupdesc = RelationGetDescr(rel);
1972  AttrMap *map;
1973 
1974  rel = resultRelInfo->ri_PartitionRoot;
1975  tupdesc = RelationGetDescr(rel);
1976  /* a reverse map */
1977  map = build_attrmap_by_name_if_req(old_tupdesc,
1978  tupdesc);
1979 
1980  /*
1981  * Partition-specific slot's tupdesc can't be changed, so
1982  * allocate a new one.
1983  */
1984  if (map != NULL)
1985  slot = execute_attr_map_slot(map, slot,
1986  MakeTupleTableSlot(tupdesc, &TTSOpsVirtual));
1987  }
1988 
1989  insertedCols = GetInsertedColumns(resultRelInfo, estate);
1990  updatedCols = GetUpdatedColumns(resultRelInfo, estate);
1991  modifiedCols = bms_union(insertedCols, updatedCols);
1993  slot,
1994  tupdesc,
1995  modifiedCols,
1996  64);
1997  ereport(ERROR,
1998  (errcode(ERRCODE_CHECK_VIOLATION),
1999  errmsg("new row for relation \"%s\" violates check constraint \"%s\"",
2000  RelationGetRelationName(orig_rel), failed),
2001  val_desc ? errdetail("Failing row contains %s.", val_desc) : 0,
2002  errtableconstraint(orig_rel, failed)));
2003  }
2004  }
2005 }
#define GetUpdatedColumns(relinfo, estate)
Definition: execMain.c:111
Relation ri_RelationDesc
Definition: execnodes.h:413
#define RelationGetDescr(relation)
Definition: rel.h:482
#define TupleDescAttr(tupdesc, i)
Definition: tupdesc.h:92
Relation ri_PartitionRoot
Definition: execnodes.h:484
const TupleTableSlotOps TTSOpsVirtual
Definition: execTuples.c:83
int errcode(int sqlerrcode)
Definition: elog.c:610
Definition: attmap.h:34
int errtableconstraint(Relation rel, const char *conname)
Definition: relcache.c:5551
AttrMap * build_attrmap_by_name_if_req(TupleDesc indesc, TupleDesc outdesc)
Definition: attmap.c:259
#define ERROR
Definition: elog.h:43
static char * ExecBuildSlotValueDescription(Oid reloid, TupleTableSlot *slot, TupleDesc tupdesc, Bitmapset *modifiedCols, int maxfieldlen)
Definition: execMain.c:2165
TupleConstr * constr
Definition: tupdesc.h:85
int errdetail(const char *fmt,...)
Definition: elog.c:957
#define RelationGetRelationName(relation)
Definition: rel.h:490
FormData_pg_attribute * Form_pg_attribute
Definition: pg_attribute.h:193
TupleTableSlot * MakeTupleTableSlot(TupleDesc tupleDesc, const TupleTableSlotOps *tts_ops)
Definition: execTuples.c:1082
uint16 num_check
Definition: tupdesc.h:43
static const char * ExecRelCheck(ResultRelInfo *resultRelInfo, TupleTableSlot *slot, EState *estate)
Definition: execMain.c:1698
#define ereport(elevel,...)
Definition: elog.h:144
TupleTableSlot * execute_attr_map_slot(AttrMap *attrMap, TupleTableSlot *in_slot, TupleTableSlot *out_slot)
Definition: tupconvert.c:177
#define Assert(condition)
Definition: c.h:745
int errtablecol(Relation rel, int attnum)
Definition: relcache.c:5514
Bitmapset * bms_union(const Bitmapset *a, const Bitmapset *b)
Definition: bitmapset.c:225
int errmsg(const char *fmt,...)
Definition: elog.c:824
#define NameStr(name)
Definition: c.h:622
bool has_not_null
Definition: tupdesc.h:44
static bool slot_attisnull(TupleTableSlot *slot, int attnum)
Definition: tuptable.h:367
#define RelationGetRelid(relation)
Definition: rel.h:456
#define GetInsertedColumns(relinfo, estate)
Definition: execMain.c:109

◆ ExecEndPlan()

static void ExecEndPlan ( PlanState planstate,
EState estate 
)
static

Definition at line 1513 of file execMain.c.

References EState::es_num_result_relations, EState::es_range_table_size, EState::es_relations, EState::es_result_relations, EState::es_subplanstates, EState::es_tupleTable, ExecCleanUpTriggerState(), ExecCloseIndices(), ExecEndNode(), ExecResetTupleTable(), i, lfirst, NoLock, and table_close().

Referenced by standard_ExecutorEnd().

1514 {
1515  ResultRelInfo *resultRelInfo;
1516  Index num_relations;
1517  Index i;
1518  ListCell *l;
1519 
1520  /*
1521  * shut down the node-type-specific query processing
1522  */
1523  ExecEndNode(planstate);
1524 
1525  /*
1526  * for subplans too
1527  */
1528  foreach(l, estate->es_subplanstates)
1529  {
1530  PlanState *subplanstate = (PlanState *) lfirst(l);
1531 
1532  ExecEndNode(subplanstate);
1533  }
1534 
1535  /*
1536  * destroy the executor's tuple table. Actually we only care about
1537  * releasing buffer pins and tupdesc refcounts; there's no need to pfree
1538  * the TupleTableSlots, since the containing memory context is about to go
1539  * away anyway.
1540  */
1541  ExecResetTupleTable(estate->es_tupleTable, false);
1542 
1543  /*
1544  * close indexes of result relation(s) if any. (Rels themselves get
1545  * closed next.)
1546  */
1547  resultRelInfo = estate->es_result_relations;
1548  for (i = estate->es_num_result_relations; i > 0; i--)
1549  {
1550  ExecCloseIndices(resultRelInfo);
1551  resultRelInfo++;
1552  }
1553 
1554  /*
1555  * close whatever rangetable Relations have been opened. We do not
1556  * release any locks we might hold on those rels.
1557  */
1558  num_relations = estate->es_range_table_size;
1559  for (i = 0; i < num_relations; i++)
1560  {
1561  if (estate->es_relations[i])
1562  table_close(estate->es_relations[i], NoLock);
1563  }
1564 
1565  /* likewise close any trigger target relations */
1566  ExecCleanUpTriggerState(estate);
1567 }
void table_close(Relation relation, LOCKMODE lockmode)
Definition: table.c:167
void ExecEndNode(PlanState *node)
Definition: execProcnode.c:543
#define NoLock
Definition: lockdefs.h:34
ResultRelInfo * es_result_relations
Definition: execnodes.h:522
List * es_tupleTable
Definition: execnodes.h:554
void ExecResetTupleTable(List *tupleTable, bool shouldFree)
Definition: execTuples.c:1161
int es_num_result_relations
Definition: execnodes.h:523
unsigned int Index
Definition: c.h:482
#define lfirst(lc)
Definition: pg_list.h:190
Relation * es_relations
Definition: execnodes.h:509
Index es_range_table_size
Definition: execnodes.h:508
List * es_subplanstates
Definition: execnodes.h:564
void ExecCleanUpTriggerState(EState *estate)
Definition: execMain.c:1435
int i
void ExecCloseIndices(ResultRelInfo *resultRelInfo)
Definition: execIndexing.c:226

◆ ExecFindRowMark()

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

Definition at line 2328 of file execMain.c.

References elog, ERROR, and EState::es_rowmarks.

Referenced by ExecInitLockRows(), and ExecInitModifyTable().

2329 {
2330  if (rti > 0 && rti <= estate->es_range_table_size &&
2331  estate->es_rowmarks != NULL)
2332  {
2333  ExecRowMark *erm = estate->es_rowmarks[rti - 1];
2334 
2335  if (erm)
2336  return erm;
2337  }
2338  if (!missing_ok)
2339  elog(ERROR, "failed to find ExecRowMark for rangetable index %u", rti);
2340  return NULL;
2341 }
struct ExecRowMark ** es_rowmarks
Definition: execnodes.h:511
#define ERROR
Definition: elog.h:43
#define elog(elevel,...)
Definition: elog.h:214

◆ ExecGetTriggerResultRel()

ResultRelInfo* ExecGetTriggerResultRel ( EState estate,
Oid  relid 
)

Definition at line 1352 of file execMain.c.

References EState::es_instrument, EState::es_num_result_relations, EState::es_num_root_result_relations, EState::es_query_cxt, EState::es_result_relations, EState::es_root_result_relations, 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().

1353 {
1354  ResultRelInfo *rInfo;
1355  int nr;
1356  ListCell *l;
1357  Relation rel;
1358  MemoryContext oldcontext;
1359 
1360  /* First, search through the query result relations */
1361  rInfo = estate->es_result_relations;
1362  nr = estate->es_num_result_relations;
1363  while (nr > 0)
1364  {
1365  if (RelationGetRelid(rInfo->ri_RelationDesc) == relid)
1366  return rInfo;
1367  rInfo++;
1368  nr--;
1369  }
1370  /* Second, search through the root result relations, if any */
1371  rInfo = estate->es_root_result_relations;
1372  nr = estate->es_num_root_result_relations;
1373  while (nr > 0)
1374  {
1375  if (RelationGetRelid(rInfo->ri_RelationDesc) == relid)
1376  return rInfo;
1377  rInfo++;
1378  nr--;
1379  }
1380 
1381  /*
1382  * Third, search through the result relations that were created during
1383  * tuple routing, if any.
1384  */
1385  foreach(l, estate->es_tuple_routing_result_relations)
1386  {
1387  rInfo = (ResultRelInfo *) lfirst(l);
1388  if (RelationGetRelid(rInfo->ri_RelationDesc) == relid)
1389  return rInfo;
1390  }
1391 
1392  /* Nope, but maybe we already made an extra ResultRelInfo for it */
1393  foreach(l, estate->es_trig_target_relations)
1394  {
1395  rInfo = (ResultRelInfo *) lfirst(l);
1396  if (RelationGetRelid(rInfo->ri_RelationDesc) == relid)
1397  return rInfo;
1398  }
1399  /* Nope, so we need a new one */
1400 
1401  /*
1402  * Open the target relation's relcache entry. We assume that an
1403  * appropriate lock is still held by the backend from whenever the trigger
1404  * event got queued, so we need take no new lock here. Also, we need not
1405  * recheck the relkind, so no need for CheckValidResultRel.
1406  */
1407  rel = table_open(relid, NoLock);
1408 
1409  /*
1410  * Make the new entry in the right context.
1411  */
1412  oldcontext = MemoryContextSwitchTo(estate->es_query_cxt);
1413  rInfo = makeNode(ResultRelInfo);
1414  InitResultRelInfo(rInfo,
1415  rel,
1416  0, /* dummy rangetable index */
1417  NULL,
1418  estate->es_instrument);
1419  estate->es_trig_target_relations =
1420  lappend(estate->es_trig_target_relations, rInfo);
1421  MemoryContextSwitchTo(oldcontext);
1422 
1423  /*
1424  * Currently, we don't need any index information in ResultRelInfos used
1425  * only for triggers, so no need to call ExecOpenIndices.
1426  */
1427 
1428  return rInfo;
1429 }
void InitResultRelInfo(ResultRelInfo *resultRelInfo, Relation resultRelationDesc, Index resultRelationIndex, Relation partition_root, int instrument_options)
Definition: execMain.c:1277
Relation ri_RelationDesc
Definition: execnodes.h:413
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:109
MemoryContext es_query_cxt
Definition: execnodes.h:552
#define NoLock
Definition: lockdefs.h:34
ResultRelInfo * es_result_relations
Definition: execnodes.h:522
int es_instrument
Definition: execnodes.h:559
List * lappend(List *list, void *datum)
Definition: list.c:321
int es_num_root_result_relations
Definition: execnodes.h:533
List * es_trig_target_relations
Definition: execnodes.h:543
int es_num_result_relations
Definition: execnodes.h:523
List * es_tuple_routing_result_relations
Definition: execnodes.h:540
#define makeNode(_type_)
Definition: nodes.h:577
#define lfirst(lc)
Definition: pg_list.h:190
ResultRelInfo * es_root_result_relations
Definition: execnodes.h:532
Relation table_open(Oid relationId, LOCKMODE lockmode)
Definition: table.c:39
#define RelationGetRelid(relation)
Definition: rel.h:456

◆ ExecPartitionCheck()

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

Definition at line 1764 of file execMain.c.

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(), ExecBRUpdateTriggers(), ExecFindPartition(), ExecInsert(), ExecSimpleRelationInsert(), ExecSimpleRelationUpdate(), and ExecUpdate().

1766 {
1767  ExprContext *econtext;
1768  bool success;
1769 
1770  /*
1771  * If first time through, build expression state tree for the partition
1772  * check expression. (In the corner case where the partition check
1773  * expression is empty, ie there's a default partition and nothing else,
1774  * we'll be fooled into executing this code each time through. But it's
1775  * pretty darn cheap in that case, so we don't worry about it.)
1776  */
1777  if (resultRelInfo->ri_PartitionCheckExpr == NULL)
1778  {
1779  /*
1780  * Ensure that the qual tree and prepared expression are in the
1781  * query-lifespan context.
1782  */
1784  List *qual = RelationGetPartitionQual(resultRelInfo->ri_RelationDesc);
1785 
1786  resultRelInfo->ri_PartitionCheckExpr = ExecPrepareCheck(qual, estate);
1787  MemoryContextSwitchTo(oldcxt);
1788  }
1789 
1790  /*
1791  * We will use the EState's per-tuple context for evaluating constraint
1792  * expressions (creating it if it's not already there).
1793  */
1794  econtext = GetPerTupleExprContext(estate);
1795 
1796  /* Arrange for econtext's scan tuple to be the tuple under test */
1797  econtext->ecxt_scantuple = slot;
1798 
1799  /*
1800  * As in case of the catalogued constraints, we treat a NULL result as
1801  * success here, not a failure.
1802  */
1803  success = ExecCheck(resultRelInfo->ri_PartitionCheckExpr, econtext);
1804 
1805  /* if asked to emit error, don't actually return on failure */
1806  if (!success && emitError)
1807  ExecPartitionCheckEmitError(resultRelInfo, slot, estate);
1808 
1809  return success;
1810 }
Relation ri_RelationDesc
Definition: execnodes.h:413
ExprState * ExecPrepareCheck(List *qual, EState *estate)
Definition: execExpr.c:543
ExprState * ri_PartitionCheckExpr
Definition: execnodes.h:481
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:109
#define GetPerTupleExprContext(estate)
Definition: executor.h:507
MemoryContext es_query_cxt
Definition: execnodes.h:552
void ExecPartitionCheckEmitError(ResultRelInfo *resultRelInfo, TupleTableSlot *slot, EState *estate)
Definition: execMain.c:1817
TupleTableSlot * ecxt_scantuple
Definition: execnodes.h:226
List * RelationGetPartitionQual(Relation rel)
Definition: partcache.c:276
bool ExecCheck(ExprState *state, ExprContext *econtext)
Definition: execExpr.c:599
static bool success
Definition: initdb.c:162
Definition: pg_list.h:50

◆ ExecPartitionCheckEmitError()

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

Definition at line 1817 of file execMain.c.

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

Referenced by ExecPartitionCheck(), and ExecUpdate().

1820 {
1821  Oid root_relid;
1822  TupleDesc tupdesc;
1823  char *val_desc;
1824  Bitmapset *modifiedCols;
1825 
1826  /*
1827  * If the tuple has been routed, it's been converted to the partition's
1828  * rowtype, which might differ from the root table's. We must convert it
1829  * back to the root table's rowtype so that val_desc in the error message
1830  * matches the input tuple.
1831  */
1832  if (resultRelInfo->ri_PartitionRoot)
1833  {
1834  TupleDesc old_tupdesc;
1835  AttrMap *map;
1836 
1837  root_relid = RelationGetRelid(resultRelInfo->ri_PartitionRoot);
1838  tupdesc = RelationGetDescr(resultRelInfo->ri_PartitionRoot);
1839 
1840  old_tupdesc = RelationGetDescr(resultRelInfo->ri_RelationDesc);
1841  /* a reverse map */
1842  map = build_attrmap_by_name_if_req(old_tupdesc, tupdesc);
1843 
1844  /*
1845  * Partition-specific slot's tupdesc can't be changed, so allocate a
1846  * new one.
1847  */
1848  if (map != NULL)
1849  slot = execute_attr_map_slot(map, slot,
1850  MakeTupleTableSlot(tupdesc, &TTSOpsVirtual));
1851  }
1852  else
1853  {
1854  root_relid = RelationGetRelid(resultRelInfo->ri_RelationDesc);
1855  tupdesc = RelationGetDescr(resultRelInfo->ri_RelationDesc);
1856  }
1857 
1858  modifiedCols = bms_union(GetInsertedColumns(resultRelInfo, estate),
1859  GetUpdatedColumns(resultRelInfo, estate));
1860 
1861  val_desc = ExecBuildSlotValueDescription(root_relid,
1862  slot,
1863  tupdesc,
1864  modifiedCols,
1865  64);
1866  ereport(ERROR,
1867  (errcode(ERRCODE_CHECK_VIOLATION),
1868  errmsg("new row for relation \"%s\" violates partition constraint",
1869  RelationGetRelationName(resultRelInfo->ri_RelationDesc)),
1870  val_desc ? errdetail("Failing row contains %s.", val_desc) : 0,
1871  errtable(resultRelInfo->ri_RelationDesc)));
1872 }
#define GetUpdatedColumns(relinfo, estate)
Definition: execMain.c:111
Relation ri_RelationDesc
Definition: execnodes.h:413
#define RelationGetDescr(relation)
Definition: rel.h:482
Relation ri_PartitionRoot
Definition: execnodes.h:484
const TupleTableSlotOps TTSOpsVirtual
Definition: execTuples.c:83
int errcode(int sqlerrcode)
Definition: elog.c:610
unsigned int Oid
Definition: postgres_ext.h:31
Definition: attmap.h:34
AttrMap * build_attrmap_by_name_if_req(TupleDesc indesc, TupleDesc outdesc)
Definition: attmap.c:259
#define ERROR
Definition: elog.h:43
static char * ExecBuildSlotValueDescription(Oid reloid, TupleTableSlot *slot, TupleDesc tupdesc, Bitmapset *modifiedCols, int maxfieldlen)
Definition: execMain.c:2165
int errdetail(const char *fmt,...)
Definition: elog.c:957
#define RelationGetRelationName(relation)
Definition: rel.h:490
TupleTableSlot * MakeTupleTableSlot(TupleDesc tupleDesc, const TupleTableSlotOps *tts_ops)
Definition: execTuples.c:1082
#define ereport(elevel,...)
Definition: elog.h:144
TupleTableSlot * execute_attr_map_slot(AttrMap *attrMap, TupleTableSlot *in_slot, TupleTableSlot *out_slot)
Definition: tupconvert.c:177
Bitmapset * bms_union(const Bitmapset *a, const Bitmapset *b)
Definition: bitmapset.c:225
int errmsg(const char *fmt,...)
Definition: elog.c:824
int errtable(Relation rel)
Definition: relcache.c:5497
#define RelationGetRelid(relation)
Definition: rel.h:456
#define GetInsertedColumns(relinfo, estate)
Definition: execMain.c:109

◆ ExecPostprocessPlan()

static void ExecPostprocessPlan ( EState estate)
static

Definition at line 1467 of file execMain.c.

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

Referenced by standard_ExecutorFinish().

1468 {
1469  ListCell *lc;
1470 
1471  /*
1472  * Make sure nodes run forward.
1473  */
1475 
1476  /*
1477  * Run any secondary ModifyTable nodes to completion, in case the main
1478  * query did not fetch all rows from them. (We do this to ensure that
1479  * such nodes have predictable results.)
1480  */
1481  foreach(lc, estate->es_auxmodifytables)
1482  {
1483  PlanState *ps = (PlanState *) lfirst(lc);
1484 
1485  for (;;)
1486  {
1487  TupleTableSlot *slot;
1488 
1489  /* Reset the per-output-tuple exprcontext each time */
1490  ResetPerTupleExprContext(estate);
1491 
1492  slot = ExecProcNode(ps);
1493 
1494  if (TupIsNull(slot))
1495  break;
1496  }
1497  }
1498 }
#define ResetPerTupleExprContext(estate)
Definition: executor.h:516
ScanDirection es_direction
Definition: execnodes.h:504
#define TupIsNull(slot)
Definition: tuptable.h:292
List * es_auxmodifytables
Definition: execnodes.h:566
static TupleTableSlot * ExecProcNode(PlanState *node)
Definition: executor.h:240
#define lfirst(lc)
Definition: pg_list.h:190

◆ ExecRelCheck()

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

Definition at line 1698 of file execMain.c.

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

Referenced by ExecConstraints().

1700 {
1701  Relation rel = resultRelInfo->ri_RelationDesc;
1702  int ncheck = rel->rd_att->constr->num_check;
1703  ConstrCheck *check = rel->rd_att->constr->check;
1704  ExprContext *econtext;
1705  MemoryContext oldContext;
1706  int i;
1707 
1708  /*
1709  * If first time through for this result relation, build expression
1710  * nodetrees for rel's constraint expressions. Keep them in the per-query
1711  * memory context so they'll survive throughout the query.
1712  */
1713  if (resultRelInfo->ri_ConstraintExprs == NULL)
1714  {
1715  oldContext = MemoryContextSwitchTo(estate->es_query_cxt);
1716  resultRelInfo->ri_ConstraintExprs =
1717  (ExprState **) palloc(ncheck * sizeof(ExprState *));
1718  for (i = 0; i < ncheck; i++)
1719  {
1720  Expr *checkconstr;
1721 
1722  checkconstr = stringToNode(check[i].ccbin);
1723  resultRelInfo->ri_ConstraintExprs[i] =
1724  ExecPrepareExpr(checkconstr, estate);
1725  }
1726  MemoryContextSwitchTo(oldContext);
1727  }
1728 
1729  /*
1730  * We will use the EState's per-tuple context for evaluating constraint
1731  * expressions (creating it if it's not already there).
1732  */
1733  econtext = GetPerTupleExprContext(estate);
1734 
1735  /* Arrange for econtext's scan tuple to be the tuple under test */
1736  econtext->ecxt_scantuple = slot;
1737 
1738  /* And evaluate the constraints */
1739  for (i = 0; i < ncheck; i++)
1740  {
1741  ExprState *checkconstr = resultRelInfo->ri_ConstraintExprs[i];
1742 
1743  /*
1744  * NOTE: SQL specifies that a NULL result from a constraint expression
1745  * is not to be treated as a failure. Therefore, use ExecCheck not
1746  * ExecQual.
1747  */
1748  if (!ExecCheck(checkconstr, econtext))
1749  return check[i].ccname;
1750  }
1751 
1752  /* NULL result means no error */
1753  return NULL;
1754 }
Relation ri_RelationDesc
Definition: execnodes.h:413
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:109
void * stringToNode(const char *str)
Definition: read.c:89
ExprState * ExecPrepareExpr(Expr *node, EState *estate)
Definition: execExpr.c:492
#define GetPerTupleExprContext(estate)
Definition: executor.h:507
MemoryContext es_query_cxt
Definition: execnodes.h:552
TupleConstr * constr
Definition: tupdesc.h:85
char * ccname
Definition: tupdesc.h:30
ExprState ** ri_ConstraintExprs
Definition: execnodes.h:457
TupleDesc rd_att
Definition: rel.h:110
uint16 num_check
Definition: tupdesc.h:43
TupleTableSlot * ecxt_scantuple
Definition: execnodes.h:226
void * palloc(Size size)
Definition: mcxt.c:950
int i
bool ExecCheck(ExprState *state, ExprContext *econtext)
Definition: execExpr.c:599
ConstrCheck * check
Definition: tupdesc.h:40

◆ ExecUpdateLockMode()

LockTupleMode ExecUpdateLockMode ( EState estate,
ResultRelInfo relinfo 
)

Definition at line 2302 of file execMain.c.

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

Referenced by ExecBRUpdateTriggers(), and ExecOnConflictUpdate().

2303 {
2304  Bitmapset *keyCols;
2305  Bitmapset *updatedCols;
2306 
2307  /*
2308  * Compute lock mode to use. If columns that are part of the key have not
2309  * been modified, then we can use a weaker lock, allowing for better
2310  * concurrency.
2311  */
2312  updatedCols = GetAllUpdatedColumns(relinfo, estate);
2313  keyCols = RelationGetIndexAttrBitmap(relinfo->ri_RelationDesc,
2315 
2316  if (bms_overlap(keyCols, updatedCols))
2317  return LockTupleExclusive;
2318 
2319  return LockTupleNoKeyExclusive;
2320 }
Relation ri_RelationDesc
Definition: execnodes.h:413
#define GetAllUpdatedColumns(relinfo, estate)
Definition: execMain.c:113
bool bms_overlap(const Bitmapset *a, const Bitmapset *b)
Definition: bitmapset.c:494
Bitmapset * RelationGetIndexAttrBitmap(Relation relation, IndexAttrBitmapKind attrKind)
Definition: relcache.c:4944

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

References CMD_SELECT, 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(), _DestReceiver::receiveSlot, ResetPerTupleExprContext, and TupIsNull.

Referenced by standard_ExecutorRun().

1591 {
1592  TupleTableSlot *slot;
1593  uint64 current_tuple_count;
1594 
1595  /*
1596  * initialize local variables
1597  */
1598  current_tuple_count = 0;
1599 
1600  /*
1601  * Set the direction.
1602  */
1603  estate->es_direction = direction;
1604 
1605  /*
1606  * If the plan might potentially be executed multiple times, we must force
1607  * it to run without parallelism, because we might exit early.
1608  */
1609  if (!execute_once)
1610  use_parallel_mode = false;
1611 
1612  estate->es_use_parallel_mode = use_parallel_mode;
1613  if (use_parallel_mode)
1615 
1616  /*
1617  * Loop until we've processed the proper number of tuples from the plan.
1618  */
1619  for (;;)
1620  {
1621  /* Reset the per-output-tuple exprcontext */
1622  ResetPerTupleExprContext(estate);
1623 
1624  /*
1625  * Execute the plan and obtain a tuple
1626  */
1627  slot = ExecProcNode(planstate);
1628 
1629  /*
1630  * if the tuple is null, then we assume there is nothing more to
1631  * process so we just end the loop...
1632  */
1633  if (TupIsNull(slot))
1634  break;
1635 
1636  /*
1637  * If we have a junk filter, then project a new tuple with the junk
1638  * removed.
1639  *
1640  * Store this new "clean" tuple in the junkfilter's resultSlot.
1641  * (Formerly, we stored it back over the "dirty" tuple, which is WRONG
1642  * because that tuple slot has the wrong descriptor.)
1643  */
1644  if (estate->es_junkFilter != NULL)
1645  slot = ExecFilterJunk(estate->es_junkFilter, slot);
1646 
1647  /*
1648  * If we are supposed to send the tuple somewhere, do so. (In
1649  * practice, this is probably always the case at this point.)
1650  */
1651  if (sendTuples)
1652  {
1653  /*
1654  * If we are not able to send the tuple, we assume the destination
1655  * has closed and no more tuples can be sent. If that's the case,
1656  * end the loop.
1657  */
1658  if (!dest->receiveSlot(slot, dest))
1659  break;
1660  }
1661 
1662  /*
1663  * Count tuples processed, if this is a SELECT. (For other operation
1664  * types, the ModifyTable plan node must count the appropriate
1665  * events.)
1666  */
1667  if (operation == CMD_SELECT)
1668  (estate->es_processed)++;
1669 
1670  /*
1671  * check our tuple count.. if we've processed the proper number then
1672  * quit, else loop again and process more tuples. Zero numberTuples
1673  * means no limit.
1674  */
1675  current_tuple_count++;
1676  if (numberTuples && numberTuples == current_tuple_count)
1677  break;
1678  }
1679 
1680  /*
1681  * If we know we won't need to back up, we can release resources at this
1682  * point.
1683  */
1684  if (!(estate->es_top_eflags & EXEC_FLAG_BACKWARD))
1685  (void) ExecShutdownNode(planstate);
1686 
1687  if (use_parallel_mode)
1688  ExitParallelMode();
1689 }
bool(* receiveSlot)(TupleTableSlot *slot, DestReceiver *self)
Definition: dest.h:119
JunkFilter * es_junkFilter
Definition: execnodes.h:516
#define ResetPerTupleExprContext(estate)
Definition: executor.h:516
bool ExecShutdownNode(PlanState *node)
Definition: execProcnode.c:751
ScanDirection es_direction
Definition: execnodes.h:504
bool es_use_parallel_mode
Definition: execnodes.h:583
void ExitParallelMode(void)
Definition: xact.c:992
#define EXEC_FLAG_BACKWARD
Definition: executor.h:58
#define TupIsNull(slot)
Definition: tuptable.h:292
TupleTableSlot * ExecFilterJunk(JunkFilter *junkfilter, TupleTableSlot *slot)
Definition: execJunk.c:261
static TupleTableSlot * ExecProcNode(PlanState *node)
Definition: executor.h:240
uint64 es_processed
Definition: execnodes.h:556
void EnterParallelMode(void)
Definition: xact.c:979
int es_top_eflags
Definition: execnodes.h:558

◆ ExecutorEnd()

void ExecutorEnd ( QueryDesc queryDesc)

Definition at line 462 of file execMain.c.

References ExecutorEnd_hook, and standard_ExecutorEnd().

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

463 {
464  if (ExecutorEnd_hook)
465  (*ExecutorEnd_hook) (queryDesc);
466  else
467  standard_ExecutorEnd(queryDesc);
468 }
void standard_ExecutorEnd(QueryDesc *queryDesc)
Definition: execMain.c:471
ExecutorEnd_hook_type ExecutorEnd_hook
Definition: execMain.c:73

◆ ExecutorFinish()

void ExecutorFinish ( QueryDesc queryDesc)

Definition at line 402 of file execMain.c.

References ExecutorFinish_hook, and standard_ExecutorFinish().

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

403 {
405  (*ExecutorFinish_hook) (queryDesc);
406  else
407  standard_ExecutorFinish(queryDesc);
408 }
void standard_ExecutorFinish(QueryDesc *queryDesc)
Definition: execMain.c:411
ExecutorFinish_hook_type ExecutorFinish_hook
Definition: execMain.c:72

◆ ExecutorRewind()

void ExecutorRewind ( QueryDesc queryDesc)

Definition at line 528 of file execMain.c.

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

Referenced by DoPortalRewind(), and PersistHoldablePortal().

529 {
530  EState *estate;
531  MemoryContext oldcontext;
532 
533  /* sanity checks */
534  Assert(queryDesc != NULL);
535 
536  estate = queryDesc->estate;
537 
538  Assert(estate != NULL);
539 
540  /* It's probably not sensible to rescan updating queries */
541  Assert(queryDesc->operation == CMD_SELECT);
542 
543  /*
544  * Switch into per-query memory context
545  */
546  oldcontext = MemoryContextSwitchTo(estate->es_query_cxt);
547 
548  /*
549  * rescan plan
550  */
551  ExecReScan(queryDesc->planstate);
552 
553  MemoryContextSwitchTo(oldcontext);
554 }
EState * estate
Definition: execdesc.h:48
void ExecReScan(PlanState *node)
Definition: execAmi.c:76
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:109
MemoryContext es_query_cxt
Definition: execnodes.h:552
PlanState * planstate
Definition: execdesc.h:49
CmdType operation
Definition: execdesc.h:36
#define Assert(condition)
Definition: c.h:745

◆ ExecutorRun()

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

Definition at line 301 of file execMain.c.

References ExecutorRun_hook, and standard_ExecutorRun().

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

304 {
305  if (ExecutorRun_hook)
306  (*ExecutorRun_hook) (queryDesc, direction, count, execute_once);
307  else
308  standard_ExecutorRun(queryDesc, direction, count, execute_once);
309 }
void standard_ExecutorRun(QueryDesc *queryDesc, ScanDirection direction, uint64 count, bool execute_once)
Definition: execMain.c:312
ExecutorRun_hook_type ExecutorRun_hook
Definition: execMain.c:71

◆ ExecutorStart()

void ExecutorStart ( QueryDesc queryDesc,
int  eflags 
)

Definition at line 143 of file execMain.c.

References ExecutorStart_hook, and standard_ExecutorStart().

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

144 {
145  if (ExecutorStart_hook)
146  (*ExecutorStart_hook) (queryDesc, eflags);
147  else
148  standard_ExecutorStart(queryDesc, eflags);
149 }
void standard_ExecutorStart(QueryDesc *queryDesc, int eflags)
Definition: execMain.c:152
ExecutorStart_hook_type ExecutorStart_hook
Definition: execMain.c:70

◆ ExecWithCheckOptions()

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

Definition at line 2017 of file execMain.c.

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

Referenced by ExecInsert(), ExecOnConflictUpdate(), and ExecUpdate().

2019 {
2020  Relation rel = resultRelInfo->ri_RelationDesc;
2021  TupleDesc tupdesc = RelationGetDescr(rel);
2022  ExprContext *econtext;
2023  ListCell *l1,
2024  *l2;
2025 
2026  /*
2027  * We will use the EState's per-tuple context for evaluating constraint
2028  * expressions (creating it if it's not already there).
2029  */
2030  econtext = GetPerTupleExprContext(estate);
2031 
2032  /* Arrange for econtext's scan tuple to be the tuple under test */
2033  econtext->ecxt_scantuple = slot;
2034 
2035  /* Check each of the constraints */
2036  forboth(l1, resultRelInfo->ri_WithCheckOptions,
2037  l2, resultRelInfo->ri_WithCheckOptionExprs)
2038  {
2039  WithCheckOption *wco = (WithCheckOption *) lfirst(l1);
2040  ExprState *wcoExpr = (ExprState *) lfirst(l2);
2041 
2042  /*
2043  * Skip any WCOs which are not the kind we are looking for at this
2044  * time.
2045  */
2046  if (wco->kind != kind)
2047  continue;
2048 
2049  /*
2050  * WITH CHECK OPTION checks are intended to ensure that the new tuple
2051  * is visible (in the case of a view) or that it passes the
2052  * 'with-check' policy (in the case of row security). If the qual
2053  * evaluates to NULL or FALSE, then the new tuple won't be included in
2054  * the view or doesn't pass the 'with-check' policy for the table.
2055  */
2056  if (!ExecQual(wcoExpr, econtext))
2057  {
2058  char *val_desc;
2059  Bitmapset *modifiedCols;
2060  Bitmapset *insertedCols;
2061  Bitmapset *updatedCols;
2062 
2063  switch (wco->kind)
2064  {
2065  /*
2066  * For WITH CHECK OPTIONs coming from views, we might be
2067  * able to provide the details on the row, depending on
2068  * the permissions on the relation (that is, if the user
2069  * could view it directly anyway). For RLS violations, we
2070  * don't include the data since we don't know if the user
2071  * should be able to view the tuple as that depends on the
2072  * USING policy.
2073  */
2074  case WCO_VIEW_CHECK:
2075  /* See the comment in ExecConstraints(). */
2076  if (resultRelInfo->ri_PartitionRoot)
2077  {
2078  TupleDesc old_tupdesc = RelationGetDescr(rel);
2079  AttrMap *map;
2080 
2081  rel = resultRelInfo->ri_PartitionRoot;
2082  tupdesc = RelationGetDescr(rel);
2083  /* a reverse map */
2084  map = build_attrmap_by_name_if_req(old_tupdesc,
2085  tupdesc);
2086 
2087  /*
2088  * Partition-specific slot's tupdesc can't be changed,
2089  * so allocate a new one.
2090  */
2091  if (map != NULL)
2092  slot = execute_attr_map_slot(map, slot,
2093  MakeTupleTableSlot(tupdesc, &TTSOpsVirtual));
2094  }
2095 
2096  insertedCols = GetInsertedColumns(resultRelInfo, estate);
2097  updatedCols = GetUpdatedColumns(resultRelInfo, estate);
2098  modifiedCols = bms_union(insertedCols, updatedCols);
2100  slot,
2101  tupdesc,
2102  modifiedCols,
2103  64);
2104 
2105  ereport(ERROR,
2106  (errcode(ERRCODE_WITH_CHECK_OPTION_VIOLATION),
2107  errmsg("new row violates check option for view \"%s\"",
2108  wco->relname),
2109  val_desc ? errdetail("Failing row contains %s.",
2110  val_desc) : 0));
2111  break;
2112  case WCO_RLS_INSERT_CHECK:
2113  case WCO_RLS_UPDATE_CHECK:
2114  if (wco->polname != NULL)
2115  ereport(ERROR,
2116  (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
2117  errmsg("new row violates row-level security policy \"%s\" for table \"%s\"",
2118  wco->polname, wco->relname)));
2119  else
2120  ereport(ERROR,
2121  (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
2122  errmsg("new row violates row-level security policy for table \"%s\"",
2123  wco->relname)));
2124  break;
2126  if (wco->polname != NULL)
2127  ereport(ERROR,
2128  (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
2129  errmsg("new row violates row-level security policy \"%s\" (USING expression) for table \"%s\"",
2130  wco->polname, wco->relname)));
2131  else
2132  ereport(ERROR,
2133  (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
2134  errmsg("new row violates row-level security policy (USING expression) for table \"%s\"",
2135  wco->relname)));
2136  break;
2137  default:
2138  elog(ERROR, "unrecognized WCO kind: %u", wco->kind);
2139  break;
2140  }
2141  }
2142  }
2143 }
#define GetUpdatedColumns(relinfo, estate)
Definition: execMain.c:111
Relation ri_RelationDesc
Definition: execnodes.h:413
#define forboth(cell1, list1, cell2, list2)
Definition: pg_list.h:419
#define RelationGetDescr(relation)
Definition: rel.h:482
Relation ri_PartitionRoot
Definition: execnodes.h:484
const TupleTableSlotOps TTSOpsVirtual
Definition: execTuples.c:83
int errcode(int sqlerrcode)
Definition: elog.c:610
static bool ExecQual(ExprState *state, ExprContext *econtext)
Definition: executor.h:370
Definition: attmap.h:34
List * ri_WithCheckOptionExprs
Definition: execnodes.h:454
#define GetPerTupleExprContext(estate)
Definition: executor.h:507
AttrMap * build_attrmap_by_name_if_req(TupleDesc indesc, TupleDesc outdesc)
Definition: attmap.c:259
#define ERROR
Definition: elog.h:43
static char * ExecBuildSlotValueDescription(Oid reloid, TupleTableSlot *slot, TupleDesc tupdesc, Bitmapset *modifiedCols, int maxfieldlen)
Definition: execMain.c:2165
int errdetail(const char *fmt,...)
Definition: elog.c:957
List * ri_WithCheckOptions
Definition: execnodes.h:451
TupleTableSlot * MakeTupleTableSlot(TupleDesc tupleDesc, const TupleTableSlotOps *tts_ops)
Definition: execTuples.c:1082
#define ereport(elevel,...)
Definition: elog.h:144
TupleTableSlot * execute_attr_map_slot(AttrMap *attrMap, TupleTableSlot *in_slot, TupleTableSlot *out_slot)
Definition: tupconvert.c:177
#define lfirst(lc)
Definition: pg_list.h:190
Bitmapset * bms_union(const Bitmapset *a, const Bitmapset *b)
Definition: bitmapset.c:225
TupleTableSlot * ecxt_scantuple
Definition: execnodes.h:226
int errmsg(const char *fmt,...)
Definition: elog.c:824
#define elog(elevel,...)
Definition: elog.h:214
#define RelationGetRelid(relation)
Definition: rel.h:456
#define GetInsertedColumns(relinfo, estate)
Definition: execMain.c:109

◆ InitPlan()

static void InitPlan ( QueryDesc queryDesc,
int  eflags 
)
static

Definition at line 806 of file execMain.c.

References Assert, bms_is_member(), CheckValidRowMarkRel(), CMD_SELECT, ExecRowMark::curCtid, elog, ExecRowMark::ermActive, ExecRowMark::ermExtra, ERROR, EState::es_epq_active, EState::es_instrument, EState::es_junkFilter, EState::es_num_result_relations, EState::es_num_root_result_relations, EState::es_plannedstmt, EState::es_range_table_size, EState::es_result_relation_info, EState::es_result_relations, EState::es_root_result_relations, EState::es_rowmarks, EState::es_subplanstates, EState::es_tupleTable, QueryDesc::estate, EXEC_FLAG_EXPLAIN_ONLY, EXEC_FLAG_REWIND, EXEC_FLAG_WITH_NO_DATA, exec_rt_fetch(), ExecCheckRTPerms(), ExecGetRangeTableRelation(), ExecGetResultType(), ExecInitExtraTupleSlot(), ExecInitJunkFilter(), ExecInitNode(), ExecInitRangeTable(), i, InitResultRelInfo(), PlanRowMark::isParent, ItemPointerSetInvalid, JunkFilter::jf_cleanTupType, lappend(), lfirst, lfirst_int, list_length(), ExecRowMark::markType, PlanRowMark::markType, NIL, QueryDesc::operation, palloc(), palloc0(), PlanState::plan, QueryDesc::plannedstmt, QueryDesc::planstate, PlannedStmt::planTree, ExecRowMark::prti, PlanRowMark::prti, ExecRowMark::relation, ExecRowMark::relid, RangeTblEntry::relid, TargetEntry::resjunk, PlannedStmt::resultRelations, PlannedStmt::rewindPlanIDs, PlannedStmt::rootResultRelations, 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().

807 {
808  CmdType operation = queryDesc->operation;
809  PlannedStmt *plannedstmt = queryDesc->plannedstmt;
810  Plan *plan = plannedstmt->planTree;
811  List *rangeTable = plannedstmt->rtable;
812  EState *estate = queryDesc->estate;
813  PlanState *planstate;
814  TupleDesc tupType;
815  ListCell *l;
816  int i;
817 
818  /*
819  * Do permissions checks
820  */
821  ExecCheckRTPerms(rangeTable, true);
822 
823  /*
824  * initialize the node's execution state
825  */
826  ExecInitRangeTable(estate, rangeTable);
827 
828  estate->es_plannedstmt = plannedstmt;
829 
830  /*
831  * Initialize ResultRelInfo data structures, and open the result rels.
832  */
833  if (plannedstmt->resultRelations)
834  {
835  List *resultRelations = plannedstmt->resultRelations;
836  int numResultRelations = list_length(resultRelations);
837  ResultRelInfo *resultRelInfos;
838  ResultRelInfo *resultRelInfo;
839 
840  resultRelInfos = (ResultRelInfo *)
841  palloc(numResultRelations * sizeof(ResultRelInfo));
842  resultRelInfo = resultRelInfos;
843  foreach(l, resultRelations)
844  {
845  Index resultRelationIndex = lfirst_int(l);
846  Relation resultRelation;
847 
848  resultRelation = ExecGetRangeTableRelation(estate,
849  resultRelationIndex);
850  InitResultRelInfo(resultRelInfo,
851  resultRelation,
852  resultRelationIndex,
853  NULL,
854  estate->es_instrument);
855  resultRelInfo++;
856  }
857  estate->es_result_relations = resultRelInfos;
858  estate->es_num_result_relations = numResultRelations;
859 
860  /* es_result_relation_info is NULL except when within ModifyTable */
861  estate->es_result_relation_info = NULL;
862 
863  /*
864  * In the partitioned result relation case, also build ResultRelInfos
865  * for all the partitioned table roots, because we will need them to
866  * fire statement-level triggers, if any.
867  */
868  if (plannedstmt->rootResultRelations)
869  {
870  int num_roots = list_length(plannedstmt->rootResultRelations);
871 
872  resultRelInfos = (ResultRelInfo *)
873  palloc(num_roots * sizeof(ResultRelInfo));
874  resultRelInfo = resultRelInfos;
875  foreach(l, plannedstmt->rootResultRelations)
876  {
877  Index resultRelIndex = lfirst_int(l);
878  Relation resultRelDesc;
879 
880  resultRelDesc = ExecGetRangeTableRelation(estate,
881  resultRelIndex);
882  InitResultRelInfo(resultRelInfo,
883  resultRelDesc,
884  resultRelIndex,
885  NULL,
886  estate->es_instrument);
887  resultRelInfo++;
888  }
889 
890  estate->es_root_result_relations = resultRelInfos;
891  estate->es_num_root_result_relations = num_roots;
892  }
893  else
894  {
895  estate->es_root_result_relations = NULL;
896  estate->es_num_root_result_relations = 0;
897  }
898  }
899  else
900  {
901  /*
902  * if no result relation, then set state appropriately
903  */
904  estate->es_result_relations = NULL;
905  estate->es_num_result_relations = 0;
906  estate->es_result_relation_info = NULL;
907  estate->es_root_result_relations = NULL;
908  estate->es_num_root_result_relations = 0;
909  }
910 
911  /*
912  * Next, build the ExecRowMark array from the PlanRowMark(s), if any.
913  */
914  if (plannedstmt->rowMarks)
915  {
916  estate->es_rowmarks = (ExecRowMark **)
917  palloc0(estate->es_range_table_size * sizeof(ExecRowMark *));
918  foreach(l, plannedstmt->rowMarks)
919  {
920  PlanRowMark *rc = (PlanRowMark *) lfirst(l);
921  Oid relid;
922  Relation relation;
923  ExecRowMark *erm;
924 
925  /* ignore "parent" rowmarks; they are irrelevant at runtime */
926  if (rc->isParent)
927  continue;
928 
929  /* get relation's OID (will produce InvalidOid if subquery) */
930  relid = exec_rt_fetch(rc->rti, estate)->relid;
931 
932  /* open relation, if we need to access it for this mark type */
933  switch (rc->markType)
934  {
935  case ROW_MARK_EXCLUSIVE:
937  case ROW_MARK_SHARE:
938  case ROW_MARK_KEYSHARE:
939  case ROW_MARK_REFERENCE:
940  relation = ExecGetRangeTableRelation(estate, rc->rti);
941  break;
942  case ROW_MARK_COPY:
943  /* no physical table access is required */
944  relation = NULL;
945  break;
946  default:
947  elog(ERROR, "unrecognized markType: %d", rc->markType);
948  relation = NULL; /* keep compiler quiet */
949  break;
950  }
951 
952  /* Check that relation is a legal target for marking */
953  if (relation)
954  CheckValidRowMarkRel(relation, rc->markType);
955 
956  erm = (ExecRowMark *) palloc(sizeof(ExecRowMark));
957  erm->relation = relation;
958  erm->relid = relid;
959  erm->rti = rc->rti;
960  erm->prti = rc->prti;
961  erm->rowmarkId = rc->rowmarkId;
962  erm->markType = rc->markType;
963  erm->strength = rc->strength;
964  erm->waitPolicy = rc->waitPolicy;
965  erm->ermActive = false;
967  erm->ermExtra = NULL;
968 
969  Assert(erm->rti > 0 && erm->rti <= estate->es_range_table_size &&
970  estate->es_rowmarks[erm->rti - 1] == NULL);
971 
972  estate->es_rowmarks[erm->rti - 1] = erm;
973  }
974  }
975 
976  /*
977  * Initialize the executor's tuple table to empty.
978  */
979  estate->es_tupleTable = NIL;
980 
981  /* signal that this EState is not used for EPQ */
982  estate->es_epq_active = NULL;
983 
984  /*
985  * Initialize private state information for each SubPlan. We must do this
986  * before running ExecInitNode on the main query tree, since
987  * ExecInitSubPlan expects to be able to find these entries.
988  */
989  Assert(estate->es_subplanstates == NIL);
990  i = 1; /* subplan indices count from 1 */
991  foreach(l, plannedstmt->subplans)
992  {
993  Plan *subplan = (Plan *) lfirst(l);
994  PlanState *subplanstate;
995  int sp_eflags;
996 
997  /*
998  * A subplan will never need to do BACKWARD scan nor MARK/RESTORE. If
999  * it is a parameterless subplan (not initplan), we suggest that it be
1000  * prepared to handle REWIND efficiently; otherwise there is no need.
1001  */
1002  sp_eflags = eflags
1004  if (bms_is_member(i, plannedstmt->rewindPlanIDs))
1005  sp_eflags |= EXEC_FLAG_REWIND;
1006 
1007  subplanstate = ExecInitNode(subplan, estate, sp_eflags);
1008 
1009  estate->es_subplanstates = lappend(estate->es_subplanstates,
1010  subplanstate);
1011 
1012  i++;
1013  }
1014 
1015  /*
1016  * Initialize the private state information for all the nodes in the query
1017  * tree. This opens files, allocates storage and leaves us ready to start
1018  * processing tuples.
1019  */
1020  planstate = ExecInitNode(plan, estate, eflags);
1021 
1022  /*
1023  * Get the tuple descriptor describing the type of tuples to return.
1024  */
1025  tupType = ExecGetResultType(planstate);
1026 
1027  /*
1028  * Initialize the junk filter if needed. SELECT queries need a filter if
1029  * there are any junk attrs in the top-level tlist.
1030  */
1031  if (operation == CMD_SELECT)
1032  {
1033  bool junk_filter_needed = false;
1034  ListCell *tlist;
1035 
1036  foreach(tlist, plan->targetlist)
1037  {
1038  TargetEntry *tle = (TargetEntry *) lfirst(tlist);
1039 
1040  if (tle->resjunk)
1041  {
1042  junk_filter_needed = true;
1043  break;
1044  }
1045  }
1046 
1047  if (junk_filter_needed)
1048  {
1049  JunkFilter *j;
1050  TupleTableSlot *slot;
1051 
1052  slot = ExecInitExtraTupleSlot(estate, NULL, &TTSOpsVirtual);
1053  j = ExecInitJunkFilter(planstate->plan->targetlist,
1054  slot);
1055  estate->es_junkFilter = j;
1056 
1057  /* Want to return the cleaned tuple type */
1058  tupType = j->jf_cleanTupType;
1059  }
1060  }
1061 
1062  queryDesc->tupDesc = tupType;
1063  queryDesc->planstate = planstate;
1064 }
#define NIL
Definition: pg_list.h:65
void ExecInitRangeTable(EState *estate, List *rangeTable)
Definition: execUtils.c:765
JunkFilter * es_junkFilter
Definition: execnodes.h:516
void InitResultRelInfo(ResultRelInfo *resultRelInfo, Relation resultRelationDesc, Index resultRelationIndex, Relation partition_root, int instrument_options)
Definition: execMain.c:1277
RowMarkType markType
Definition: plannodes.h:1080
TupleTableSlot * ExecInitExtraTupleSlot(EState *estate, TupleDesc tupledesc, const TupleTableSlotOps *tts_ops)
Definition: execTuples.c:1801
EState * estate
Definition: execdesc.h:48
Relation relation
Definition: execnodes.h:624
const TupleTableSlotOps TTSOpsVirtual
Definition: execTuples.c:83
PlannedStmt * es_plannedstmt
Definition: execnodes.h:513
bool ermActive
Definition: execnodes.h:632
Index prti
Definition: plannodes.h:1078
LockWaitPolicy waitPolicy
Definition: execnodes.h:631
#define EXEC_FLAG_WITH_NO_DATA
Definition: executor.h:61
LockClauseStrength strength
Definition: execnodes.h:630
unsigned int Oid
Definition: postgres_ext.h:31
Index rowmarkId
Definition: plannodes.h:1079
LockWaitPolicy waitPolicy
Definition: plannodes.h:1083
static void CheckValidRowMarkRel(Relation rel, RowMarkType markType)
Definition: execMain.c:1212
struct EPQState * es_epq_active
Definition: execnodes.h:581
struct Plan * planTree
Definition: plannodes.h:64
ItemPointerData curCtid
Definition: execnodes.h:633
struct ExecRowMark ** es_rowmarks
Definition: execnodes.h:511
bool resjunk
Definition: primnodes.h:1414
#define ERROR
Definition: elog.h:43
PlanState * planstate
Definition: execdesc.h:49
#define lfirst_int(lc)
Definition: pg_list.h:191
Index rti
Definition: execnodes.h:626
void * ermExtra
Definition: execnodes.h:634
TupleDesc jf_cleanTupType
Definition: execnodes.h:370
ResultRelInfo * es_result_relations
Definition: execnodes.h:522
Index prti
Definition: execnodes.h:627
List * rootResultRelations
Definition: plannodes.h:75
static RangeTblEntry * exec_rt_fetch(Index rti, EState *estate)
Definition: executor.h:543
int es_instrument
Definition: execnodes.h:559
#define EXEC_FLAG_REWIND
Definition: executor.h:57
Index rowmarkId
Definition: execnodes.h:628
List * lappend(List *list, void *datum)
Definition: list.c:321
int es_num_root_result_relations
Definition: execnodes.h:533
TupleDesc tupDesc
Definition: execdesc.h:47
CmdType operation
Definition: execdesc.h:36
List * es_tupleTable
Definition: execnodes.h:554
void * palloc0(Size size)
Definition: mcxt.c:981
int es_num_result_relations
Definition: execnodes.h:523
unsigned int Index
Definition: c.h:482
List * rowMarks
Definition: plannodes.h:84
Plan * plan
Definition: execnodes.h:944
Relation ExecGetRangeTableRelation(EState *estate, Index rti)
Definition: execUtils.c:795
List * subplans
Definition: plannodes.h:79
#define Assert(condition)
Definition: c.h:745
#define lfirst(lc)
Definition: pg_list.h:190
Bitmapset * rewindPlanIDs
Definition: plannodes.h:82
RowMarkType markType
Definition: execnodes.h:629
LockClauseStrength strength
Definition: plannodes.h:1082
static int list_length(const List *l)
Definition: pg_list.h:169
Index es_range_table_size
Definition: execnodes.h:508
List * es_subplanstates
Definition: execnodes.h:564
List * rtable
Definition: plannodes.h:66
TupleDesc ExecGetResultType(PlanState *planstate)
Definition: execUtils.c:495
List * targetlist
Definition: plannodes.h:142
#define ItemPointerSetInvalid(pointer)
Definition: itemptr.h:172
void * palloc(Size size)
Definition: mcxt.c:950
List * resultRelations
Definition: plannodes.h:69
ResultRelInfo * es_root_result_relations
Definition: execnodes.h:532
#define elog(elevel,...)
Definition: elog.h:214
int i
bool ExecCheckRTPerms(List *rangeTable, bool ereport_on_violation)
Definition: execMain.c:571
bool isParent
Definition: plannodes.h:1084
PlannedStmt * plannedstmt
Definition: execdesc.h:37
PlanState * ExecInitNode(Plan *node, EState *estate, int eflags)
Definition: execProcnode.c:139
Definition: pg_list.h:50
bool bms_is_member(int x, const Bitmapset *a)
Definition: bitmapset.c:427
#define EXEC_FLAG_EXPLAIN_ONLY
Definition: executor.h:56
JunkFilter * ExecInitJunkFilter(List *targetList, TupleTableSlot *slot)
Definition: execJunk.c:60
CmdType
Definition: nodes.h:672
ResultRelInfo * es_result_relation_info
Definition: execnodes.h:524

◆ InitResultRelInfo()

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

Definition at line 1277 of file execMain.c.

References CopyTriggerDesc(), GetFdwRoutineForRelation(), InstrAlloc(), MemSet, NIL, TriggerDesc::numtriggers, palloc0(), RelationData::rd_rel, ResultRelInfo::ri_ConstraintExprs, ResultRelInfo::ri_CopyMultiInsertBuffer, ResultRelInfo::ri_FdwRoutine, ResultRelInfo::ri_FdwState, ResultRelInfo::ri_GeneratedExprs, ResultRelInfo::ri_IndexRelationDescs, ResultRelInfo::ri_IndexRelationInfo, ResultRelInfo::ri_junkFilter, ResultRelInfo::ri_NumIndices, ResultRelInfo::ri_onConflict, ResultRelInfo::ri_onConflictArbiterIndexes, ResultRelInfo::ri_PartitionInfo, ResultRelInfo::ri_PartitionRoot, ResultRelInfo::ri_projectReturning, ResultRelInfo::ri_RangeTableIndex, ResultRelInfo::ri_RelationDesc, ResultRelInfo::ri_ReturningSlot, ResultRelInfo::ri_TrigDesc, ResultRelInfo::ri_TrigFunctions, ResultRelInfo::ri_TrigInstrument, ResultRelInfo::ri_TrigNewSlot, ResultRelInfo::ri_TrigOldSlot, ResultRelInfo::ri_TrigWhenExprs, ResultRelInfo::ri_usesFdwDirectModify, T_ResultRelInfo, RelationData::trigdesc, and ResultRelInfo::type.

Referenced by CopyFrom(), create_estate_for_relation(), ExecGetTriggerResultRel(), ExecInitPartitionDispatchInfo(), ExecInitPartitionInfo(), ExecuteTruncateGuts(), and InitPlan().

1282 {
1283  MemSet(resultRelInfo, 0, sizeof(ResultRelInfo));
1284  resultRelInfo->type = T_ResultRelInfo;
1285  resultRelInfo->ri_RangeTableIndex = resultRelationIndex;
1286  resultRelInfo->ri_RelationDesc = resultRelationDesc;
1287  resultRelInfo->ri_NumIndices = 0;
1288  resultRelInfo->ri_IndexRelationDescs = NULL;
1289  resultRelInfo->ri_IndexRelationInfo = NULL;
1290  /* make a copy so as not to depend on relcache info not changing... */
1291  resultRelInfo->ri_TrigDesc = CopyTriggerDesc(resultRelationDesc->trigdesc);
1292  if (resultRelInfo->ri_TrigDesc)
1293  {
1294  int n = resultRelInfo->ri_TrigDesc->numtriggers;
1295 
1296  resultRelInfo->ri_TrigFunctions = (FmgrInfo *)
1297  palloc0(n * sizeof(FmgrInfo));
1298  resultRelInfo->ri_TrigWhenExprs = (ExprState **)
1299  palloc0(n * sizeof(ExprState *));
1300  if (instrument_options)
1301  resultRelInfo->ri_TrigInstrument = InstrAlloc(n, instrument_options);
1302  }
1303  else
1304  {
1305  resultRelInfo->ri_TrigFunctions = NULL;
1306  resultRelInfo->ri_TrigWhenExprs = NULL;
1307  resultRelInfo->ri_TrigInstrument = NULL;
1308  }
1309  if (resultRelationDesc->rd_rel->relkind == RELKIND_FOREIGN_TABLE)
1310  resultRelInfo->ri_FdwRoutine = GetFdwRoutineForRelation(resultRelationDesc, true);
1311  else
1312  resultRelInfo->ri_FdwRoutine = NULL;
1313 
1314  /* The following fields are set later if needed */
1315  resultRelInfo->ri_FdwState = NULL;
1316  resultRelInfo->ri_usesFdwDirectModify = false;
1317  resultRelInfo->ri_ConstraintExprs = NULL;
1318  resultRelInfo->ri_GeneratedExprs = NULL;
1319  resultRelInfo->ri_junkFilter = NULL;
1320  resultRelInfo->ri_projectReturning = NULL;
1321  resultRelInfo->ri_onConflictArbiterIndexes = NIL;
1322  resultRelInfo->ri_onConflict = NULL;
1323  resultRelInfo->ri_ReturningSlot = NULL;
1324  resultRelInfo->ri_TrigOldSlot = NULL;
1325  resultRelInfo->ri_TrigNewSlot = NULL;
1326  resultRelInfo->ri_PartitionRoot = partition_root;
1327  resultRelInfo->ri_PartitionInfo = NULL; /* may be set later */
1328  resultRelInfo->ri_CopyMultiInsertBuffer = NULL;
1329 }
int ri_NumIndices
Definition: execnodes.h:416
#define NIL
Definition: pg_list.h:65
JunkFilter * ri_junkFilter
Definition: execnodes.h:466
Definition: fmgr.h:56
Relation ri_RelationDesc
Definition: execnodes.h:413
struct CopyMultiInsertBuffer * ri_CopyMultiInsertBuffer
Definition: execnodes.h:490
struct PartitionRoutingInfo * ri_PartitionInfo
Definition: execnodes.h:487
Relation ri_PartitionRoot
Definition: execnodes.h:484
Instrumentation * ri_TrigInstrument
Definition: execnodes.h:434
Instrumentation * InstrAlloc(int n, int instrument_options)
Definition: instrument.c:31
#define MemSet(start, val, len)
Definition: c.h:949
Form_pg_class rd_rel
Definition: rel.h:109
TupleTableSlot * ri_TrigNewSlot
Definition: execnodes.h:439
Index ri_RangeTableIndex
Definition: execnodes.h:410
NodeTag type
Definition: execnodes.h:407
TriggerDesc * trigdesc
Definition: rel.h:115
bool ri_usesFdwDirectModify
Definition: execnodes.h:448
ExprState ** ri_TrigWhenExprs
Definition: execnodes.h:431
TupleTableSlot * ri_ReturningSlot
Definition: execnodes.h:437
ExprState ** ri_GeneratedExprs
Definition: execnodes.h:460
ProjectionInfo * ri_projectReturning
Definition: execnodes.h:472
struct FdwRoutine * ri_FdwRoutine
Definition: execnodes.h:442
ExprState ** ri_ConstraintExprs
Definition: execnodes.h:457
TriggerDesc * ri_TrigDesc
Definition: execnodes.h:425
int numtriggers
Definition: reltrigger.h:50
OnConflictSetState * ri_onConflict
Definition: execnodes.h:478
void * palloc0(Size size)
Definition: mcxt.c:981
void * ri_FdwState
Definition: execnodes.h:445
TupleTableSlot * ri_TrigOldSlot
Definition: execnodes.h:438
TriggerDesc * CopyTriggerDesc(TriggerDesc *trigdesc)
Definition: trigger.c:1821
FdwRoutine * GetFdwRoutineForRelation(Relation relation, bool makecopy)
Definition: foreign.c:427
IndexInfo ** ri_IndexRelationInfo
Definition: execnodes.h:422
List * ri_onConflictArbiterIndexes
Definition: execnodes.h:475
RelationPtr ri_IndexRelationDescs
Definition: execnodes.h:419
FmgrInfo * ri_TrigFunctions
Definition: execnodes.h:428

◆ standard_ExecutorEnd()

void standard_ExecutorEnd ( QueryDesc queryDesc)

Definition at line 471 of file execMain.c.

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

472 {
473  EState *estate;
474  MemoryContext oldcontext;
475 
476  /* sanity checks */
477  Assert(queryDesc != NULL);
478 
479  estate = queryDesc->estate;
480 
481  Assert(estate != NULL);
482 
483  /*
484  * Check that ExecutorFinish was called, unless in EXPLAIN-only mode. This
485  * Assert is needed because ExecutorFinish is new as of 9.1, and callers
486  * might forget to call it.
487  */
488  Assert(estate->es_finished ||
490 
491  /*
492  * Switch into per-query memory context to run ExecEndPlan
493  */
494  oldcontext = MemoryContextSwitchTo(estate->es_query_cxt);
495 
496  ExecEndPlan(queryDesc->planstate, estate);
497 
498  /* do away with our snapshots */
501 
502  /*
503  * Must switch out of context before destroying it
504  */
505  MemoryContextSwitchTo(oldcontext);
506 
507  /*
508  * Release EState and per-query memory context. This should release
509  * everything the executor has allocated.
510  */
511  FreeExecutorState(estate);
512 
513  /* Reset queryDesc fields that no longer point to anything */
514  queryDesc->tupDesc = NULL;
515  queryDesc->estate = NULL;
516  queryDesc->planstate = NULL;
517  queryDesc->totaltime = NULL;
518 }
EState * estate
Definition: execdesc.h:48
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:109
Snapshot es_crosscheck_snapshot
Definition: execnodes.h:506
Snapshot es_snapshot
Definition: execnodes.h:505
void FreeExecutorState(EState *estate)
Definition: execUtils.c:191
MemoryContext es_query_cxt
Definition: execnodes.h:552
PlanState * planstate
Definition: execdesc.h:49
void UnregisterSnapshot(Snapshot snapshot)
Definition: snapmgr.c:852
TupleDesc tupDesc
Definition: execdesc.h:47
bool es_finished
Definition: execnodes.h:560
struct Instrumentation * totaltime
Definition: execdesc.h:55
#define Assert(condition)
Definition: c.h:745
static void ExecEndPlan(PlanState *planstate, EState *estate)
Definition: execMain.c:1513
int es_top_eflags
Definition: execnodes.h:558
#define EXEC_FLAG_EXPLAIN_ONLY
Definition: executor.h:56

◆ standard_ExecutorFinish()

void standard_ExecutorFinish ( QueryDesc queryDesc)

Definition at line 411 of file execMain.c.

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

412 {
413  EState *estate;
414  MemoryContext oldcontext;
415 
416  /* sanity checks */
417  Assert(queryDesc != NULL);
418 
419  estate = queryDesc->estate;
420 
421  Assert(estate != NULL);
423 
424  /* This should be run once and only once per Executor instance */
425  Assert(!estate->es_finished);
426 
427  /* Switch into per-query memory context */
428  oldcontext = MemoryContextSwitchTo(estate->es_query_cxt);
429 
430  /* Allow instrumentation of Executor overall runtime */
431  if (queryDesc->totaltime)
432  InstrStartNode(queryDesc->totaltime);
433 
434  /* Run ModifyTable nodes to completion */
435  ExecPostprocessPlan(estate);
436 
437  /* Execute queued AFTER triggers, unless told not to */
438  if (!(estate->es_top_eflags & EXEC_FLAG_SKIP_TRIGGERS))
439  AfterTriggerEndQuery(estate);
440 
441  if (queryDesc->totaltime)
442  InstrStopNode(queryDesc->totaltime, 0);
443 
444  MemoryContextSwitchTo(oldcontext);
445 
446  estate->es_finished = true;
447 }
void InstrStopNode(Instrumentation *instr, double nTuples)
Definition: instrument.c:83
static void ExecPostprocessPlan(EState *estate)
Definition: execMain.c:1467
EState * estate
Definition: execdesc.h:48
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:109
MemoryContext es_query_cxt
Definition: execnodes.h:552
void InstrStartNode(Instrumentation *instr)
Definition: instrument.c:67
bool es_finished
Definition: execnodes.h:560
struct Instrumentation * totaltime
Definition: execdesc.h:55
#define Assert(condition)
Definition: c.h:745
#define EXEC_FLAG_SKIP_TRIGGERS
Definition: executor.h:60
void AfterTriggerEndQuery(EState *estate)
Definition: trigger.c:4452
int es_top_eflags
Definition: execnodes.h:558
#define EXEC_FLAG_EXPLAIN_ONLY
Definition: executor.h:56

◆ standard_ExecutorRun()

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

Definition at line 312 of file execMain.c.

References QueryDesc::already_executed, Assert, CMD_SELECT, QueryDesc::dest, generate_unaccent_rules::dest, elog, ERROR, EState::es_processed, EState::es_query_cxt, EState::es_top_eflags, QueryDesc::estate, EXEC_FLAG_EXPLAIN_ONLY, ExecutePlan(), PlannedStmt::hasReturning, InstrStartNode(), InstrStopNode(), MemoryContextSwitchTo(), QueryDesc::operation, PlannedStmt::parallelModeNeeded, QueryDesc::plannedstmt, QueryDesc::planstate, _DestReceiver::rShutdown, _DestReceiver::rStartup, ScanDirectionIsNoMovement, QueryDesc::totaltime, and QueryDesc::tupDesc.

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

314 {
315  EState *estate;
316  CmdType operation;
318  bool sendTuples;
319  MemoryContext oldcontext;
320 
321  /* sanity checks */
322  Assert(queryDesc != NULL);
323 
324  estate = queryDesc->estate;
325 
326  Assert(estate != NULL);
328 
329  /*
330  * Switch into per-query memory context
331  */
332  oldcontext = MemoryContextSwitchTo(estate->es_query_cxt);
333 
334  /* Allow instrumentation of Executor overall runtime */
335  if (queryDesc->totaltime)
336  InstrStartNode(queryDesc->totaltime);
337 
338  /*
339  * extract information from the query descriptor and the query feature.
340  */
341  operation = queryDesc->operation;
342  dest = queryDesc->dest;
343 
344  /*
345  * startup tuple receiver, if we will be emitting tuples
346  */
347  estate->es_processed = 0;
348 
349  sendTuples = (operation == CMD_SELECT ||
350  queryDesc->plannedstmt->hasReturning);
351 
352  if (sendTuples)
353  dest->rStartup(dest, operation, queryDesc->tupDesc);
354 
355  /*
356  * run plan
357  */
358  if (!ScanDirectionIsNoMovement(direction))
359  {
360  if (execute_once && queryDesc->already_executed)
361  elog(ERROR, "can't re-execute query flagged for single execution");
362  queryDesc->already_executed = true;
363 
364  ExecutePlan(estate,
365  queryDesc->planstate,
366  queryDesc->plannedstmt->parallelModeNeeded,
367  operation,
368  sendTuples,
369  count,
370  direction,
371  dest,
372  execute_once);
373  }
374 
375  /*
376  * shutdown tuple receiver, if we started it
377  */
378  if (sendTuples)
379  dest->rShutdown(dest);
380 
381  if (queryDesc->totaltime)
382  InstrStopNode(queryDesc->totaltime, estate->es_processed);
383 
384  MemoryContextSwitchTo(oldcontext);
385 }
void InstrStopNode(Instrumentation *instr, double nTuples)
Definition: instrument.c:83
EState * estate
Definition: execdesc.h:48
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:109
#define ScanDirectionIsNoMovement(direction)
Definition: sdir.h:48
MemoryContext es_query_cxt
Definition: execnodes.h:552
#define ERROR
Definition: elog.h:43
PlanState * planstate
Definition: execdesc.h:49
void InstrStartNode(Instrumentation *instr)
Definition: instrument.c:67
void(* rStartup)(DestReceiver *self, int operation, TupleDesc typeinfo)
Definition: dest.h:122
bool hasReturning
Definition: plannodes.h:50
TupleDesc tupDesc
Definition: execdesc.h:47
CmdType operation
Definition: execdesc.h:36
bool already_executed
Definition: execdesc.h:52
struct Instrumentation * totaltime
Definition: execdesc.h:55
#define Assert(condition)
Definition: c.h:745
uint64 es_processed
Definition: execnodes.h:556
void(* rShutdown)(DestReceiver *self)
Definition: dest.h:125
DestReceiver * dest
Definition: execdesc.h:41
int es_top_eflags
Definition: execnodes.h:558
bool parallelModeNeeded
Definition: plannodes.h:60
#define elog(elevel,...)
Definition: elog.h:214
PlannedStmt * plannedstmt
Definition: execdesc.h:37
#define EXEC_FLAG_EXPLAIN_ONLY
Definition: executor.h:56
CmdType
Definition: nodes.h:672
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:1582

◆ standard_ExecutorStart()

void standard_ExecutorStart ( QueryDesc queryDesc,
int  eflags 
)

Definition at line 152 of file execMain.c.

References AfterTriggerBeginQuery(), Assert, CMD_DELETE, CMD_INSERT, 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(), 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().

153 {
154  EState *estate;
155  MemoryContext oldcontext;
156 
157  /* sanity checks: queryDesc must not be started already */
158  Assert(queryDesc != NULL);
159  Assert(queryDesc->estate == NULL);
160 
161  /*
162  * If the transaction is read-only, we need to check if any writes are
163  * planned to non-temporary tables. EXPLAIN is considered read-only.
164  *
165  * Don't allow writes in parallel mode. Supporting UPDATE and DELETE
166  * would require (a) storing the combocid hash in shared memory, rather
167  * than synchronizing it just once at the start of parallelism, and (b) an
168  * alternative to heap_update()'s reliance on xmax for mutual exclusion.
169  * INSERT may have no such troubles, but we forbid it to simplify the
170  * checks.
171  *
172  * We have lower-level defenses in CommandCounterIncrement and elsewhere
173  * against performing unsafe operations in parallel mode, but this gives a
174  * more user-friendly error message.
175  */
176  if ((XactReadOnly || IsInParallelMode()) &&
177  !(eflags & EXEC_FLAG_EXPLAIN_ONLY))
179 
180  /*
181  * Build EState, switch into per-query memory context for startup.
182  */
183  estate = CreateExecutorState();
184  queryDesc->estate = estate;
185 
186  oldcontext = MemoryContextSwitchTo(estate->es_query_cxt);
187 
188  /*
189  * Fill in external parameters, if any, from queryDesc; and allocate
190  * workspace for internal parameters
191  */
192  estate->es_param_list_info = queryDesc->params;
193 
194  if (queryDesc->plannedstmt->paramExecTypes != NIL)
195  {
196  int nParamExec;
197 
198  nParamExec = list_length(queryDesc->plannedstmt->paramExecTypes);
199  estate->es_param_exec_vals = (ParamExecData *)
200  palloc0(nParamExec * sizeof(ParamExecData));
201  }
202 
203  estate->es_sourceText = queryDesc->sourceText;
204 
205  /*
206  * Fill in the query environment, if any, from queryDesc.
207  */
208  estate->es_queryEnv = queryDesc->queryEnv;
209 
210  /*
211  * If non-read-only query, set the command ID to mark output tuples with
212  */
213  switch (queryDesc->operation)
214  {
215  case CMD_SELECT:
216 
217  /*
218  * SELECT FOR [KEY] UPDATE/SHARE and modifying CTEs need to mark
219  * tuples
220  */
221  if (queryDesc->plannedstmt->rowMarks != NIL ||
222  queryDesc->plannedstmt->hasModifyingCTE)
223  estate->es_output_cid = GetCurrentCommandId(true);
224 
225  /*
226  * A SELECT without modifying CTEs can't possibly queue triggers,
227  * so force skip-triggers mode. This is just a marginal efficiency
228  * hack, since AfterTriggerBeginQuery/AfterTriggerEndQuery aren't
229  * all that expensive, but we might as well do it.
230  */
231  if (!queryDesc->plannedstmt->hasModifyingCTE)
232  eflags |= EXEC_FLAG_SKIP_TRIGGERS;
233  break;
234 
235  case CMD_INSERT:
236  case CMD_DELETE:
237  case CMD_UPDATE:
238  estate->es_output_cid = GetCurrentCommandId(true);
239  break;
240 
241  default:
242  elog(ERROR, "unrecognized operation code: %d",
243  (int) queryDesc->operation);
244  break;
245  }
246 
247  /*
248  * Copy other important information into the EState
249  */
250  estate->es_snapshot = RegisterSnapshot(queryDesc->snapshot);
252  estate->es_top_eflags = eflags;
253  estate->es_instrument = queryDesc->instrument_options;
254  estate->es_jit_flags = queryDesc->plannedstmt->jitFlags;
255 
256  /*
257  * Set up an AFTER-trigger statement context, unless told not to, or
258  * unless it's EXPLAIN-only mode (when ExecutorFinish won't be called).
259  */
260  if (!(eflags & (EXEC_FLAG_SKIP_TRIGGERS | EXEC_FLAG_EXPLAIN_ONLY)))
262 
263  /*
264  * Initialize the plan state tree
265  */
266  InitPlan(queryDesc, eflags);
267 
268  MemoryContextSwitchTo(oldcontext);
269 }
List * paramExecTypes
Definition: plannodes.h:90
#define NIL
Definition: pg_list.h:65
EState * estate
Definition: execdesc.h:48
CommandId es_output_cid
Definition: execnodes.h:519
Snapshot RegisterSnapshot(Snapshot snapshot)
Definition: snapmgr.c:810
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:109
Snapshot es_crosscheck_snapshot
Definition: execnodes.h:506
Snapshot es_snapshot
Definition: execnodes.h:505
Snapshot snapshot
Definition: execdesc.h:39
int instrument_options
Definition: execdesc.h:44
const char * es_sourceText
Definition: execnodes.h:514
ParamExecData * es_param_exec_vals
Definition: execnodes.h:547
QueryEnvironment * queryEnv
Definition: execdesc.h:43
MemoryContext es_query_cxt
Definition: execnodes.h:552
bool IsInParallelMode(void)
Definition: xact.c:1012
#define ERROR
Definition: elog.h:43
int es_jit_flags
Definition: execnodes.h:597
ParamListInfo params
Definition: execdesc.h:42
int jitFlags
Definition: plannodes.h:62
int es_instrument
Definition: execnodes.h:559
EState * CreateExecutorState(void)
Definition: execUtils.c:89
QueryEnvironment * es_queryEnv
Definition: execnodes.h:549
CmdType operation
Definition: execdesc.h:36
static void ExecCheckXactReadOnly(PlannedStmt *plannedstmt)
Definition: execMain.c:769
void * palloc0(Size size)
Definition: mcxt.c:981
Snapshot crosscheck_snapshot
Definition: execdesc.h:40
List * rowMarks
Definition: plannodes.h:84
bool XactReadOnly
Definition: xact.c:78
void AfterTriggerBeginQuery(void)
Definition: trigger.c:4432
#define Assert(condition)
Definition: c.h:745
bool hasModifyingCTE
Definition: plannodes.h:52
static int list_length(const List *l)
Definition: pg_list.h:169
#define EXEC_FLAG_SKIP_TRIGGERS
Definition: executor.h:60
const char * sourceText
Definition: execdesc.h:38
int es_top_eflags
Definition: execnodes.h:558
#define elog(elevel,...)
Definition: elog.h:214
ParamListInfo es_param_list_info
Definition: execnodes.h:546
CommandId GetCurrentCommandId(bool used)
Definition: xact.c:761
PlannedStmt * plannedstmt
Definition: execdesc.h:37
#define EXEC_FLAG_EXPLAIN_ONLY
Definition: executor.h:56
static void InitPlan(QueryDesc *queryDesc, int eflags)
Definition: execMain.c:806

Variable Documentation

◆ ExecutorCheckPerms_hook

ExecutorCheckPerms_hook_type ExecutorCheckPerms_hook = NULL

Definition at line 76 of file execMain.c.

Referenced by _PG_init(), and ExecCheckRTPerms().

◆ ExecutorEnd_hook

ExecutorEnd_hook_type ExecutorEnd_hook = NULL

Definition at line 73 of file execMain.c.

Referenced by _PG_fini(), _PG_init(), and ExecutorEnd().

◆ ExecutorFinish_hook

ExecutorFinish_hook_type ExecutorFinish_hook = NULL

Definition at line 72 of file execMain.c.

Referenced by _PG_fini(), _PG_init(), and ExecutorFinish().

◆ ExecutorRun_hook

ExecutorRun_hook_type ExecutorRun_hook = NULL

Definition at line 71 of file execMain.c.

Referenced by _PG_fini(), _PG_init(), and ExecutorRun().

◆ ExecutorStart_hook

ExecutorStart_hook_type ExecutorStart_hook = NULL

Definition at line 70 of file execMain.c.

Referenced by _PG_fini(), _PG_init(), and ExecutorStart().