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/partition.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/parse_relation.h"
#include "parser/parsetree.h"
#include "storage/bufmgr.h"
#include "storage/lmgr.h"
#include "tcop/utility.h"
#include "utils/acl.h"
#include "utils/backend_status.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.

Functions

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

Variables

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

Function Documentation

◆ CheckValidResultRel()

void CheckValidResultRel ( ResultRelInfo resultRelInfo,
CmdType  operation 
)

Definition at line 1024 of file execMain.c.

1025 {
1026  Relation resultRel = resultRelInfo->ri_RelationDesc;
1027  TriggerDesc *trigDesc = resultRel->trigdesc;
1028  FdwRoutine *fdwroutine;
1029 
1030  switch (resultRel->rd_rel->relkind)
1031  {
1032  case RELKIND_RELATION:
1033  case RELKIND_PARTITIONED_TABLE:
1034  CheckCmdReplicaIdentity(resultRel, operation);
1035  break;
1036  case RELKIND_SEQUENCE:
1037  ereport(ERROR,
1038  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1039  errmsg("cannot change sequence \"%s\"",
1040  RelationGetRelationName(resultRel))));
1041  break;
1042  case RELKIND_TOASTVALUE:
1043  ereport(ERROR,
1044  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1045  errmsg("cannot change TOAST relation \"%s\"",
1046  RelationGetRelationName(resultRel))));
1047  break;
1048  case RELKIND_VIEW:
1049 
1050  /*
1051  * Okay only if there's a suitable INSTEAD OF trigger. Messages
1052  * here should match rewriteHandler.c's rewriteTargetView and
1053  * RewriteQuery, except that we omit errdetail because we haven't
1054  * got the information handy (and given that we really shouldn't
1055  * get here anyway, it's not worth great exertion to get).
1056  */
1057  switch (operation)
1058  {
1059  case CMD_INSERT:
1060  if (!trigDesc || !trigDesc->trig_insert_instead_row)
1061  ereport(ERROR,
1062  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
1063  errmsg("cannot insert into view \"%s\"",
1064  RelationGetRelationName(resultRel)),
1065  errhint("To enable inserting into the view, provide an INSTEAD OF INSERT trigger or an unconditional ON INSERT DO INSTEAD rule.")));
1066  break;
1067  case CMD_UPDATE:
1068  if (!trigDesc || !trigDesc->trig_update_instead_row)
1069  ereport(ERROR,
1070  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
1071  errmsg("cannot update view \"%s\"",
1072  RelationGetRelationName(resultRel)),
1073  errhint("To enable updating the view, provide an INSTEAD OF UPDATE trigger or an unconditional ON UPDATE DO INSTEAD rule.")));
1074  break;
1075  case CMD_DELETE:
1076  if (!trigDesc || !trigDesc->trig_delete_instead_row)
1077  ereport(ERROR,
1078  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
1079  errmsg("cannot delete from view \"%s\"",
1080  RelationGetRelationName(resultRel)),
1081  errhint("To enable deleting from the view, provide an INSTEAD OF DELETE trigger or an unconditional ON DELETE DO INSTEAD rule.")));
1082  break;
1083  default:
1084  elog(ERROR, "unrecognized CmdType: %d", (int) operation);
1085  break;
1086  }
1087  break;
1088  case RELKIND_MATVIEW:
1090  ereport(ERROR,
1091  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1092  errmsg("cannot change materialized view \"%s\"",
1093  RelationGetRelationName(resultRel))));
1094  break;
1095  case RELKIND_FOREIGN_TABLE:
1096  /* Okay only if the FDW supports it */
1097  fdwroutine = resultRelInfo->ri_FdwRoutine;
1098  switch (operation)
1099  {
1100  case CMD_INSERT:
1101  if (fdwroutine->ExecForeignInsert == NULL)
1102  ereport(ERROR,
1103  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1104  errmsg("cannot insert into foreign table \"%s\"",
1105  RelationGetRelationName(resultRel))));
1106  if (fdwroutine->IsForeignRelUpdatable != NULL &&
1107  (fdwroutine->IsForeignRelUpdatable(resultRel) & (1 << CMD_INSERT)) == 0)
1108  ereport(ERROR,
1109  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
1110  errmsg("foreign table \"%s\" does not allow inserts",
1111  RelationGetRelationName(resultRel))));
1112  break;
1113  case CMD_UPDATE:
1114  if (fdwroutine->ExecForeignUpdate == NULL)
1115  ereport(ERROR,
1116  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1117  errmsg("cannot update foreign table \"%s\"",
1118  RelationGetRelationName(resultRel))));
1119  if (fdwroutine->IsForeignRelUpdatable != NULL &&
1120  (fdwroutine->IsForeignRelUpdatable(resultRel) & (1 << CMD_UPDATE)) == 0)
1121  ereport(ERROR,
1122  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
1123  errmsg("foreign table \"%s\" does not allow updates",
1124  RelationGetRelationName(resultRel))));
1125  break;
1126  case CMD_DELETE:
1127  if (fdwroutine->ExecForeignDelete == NULL)
1128  ereport(ERROR,
1129  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1130  errmsg("cannot delete from foreign table \"%s\"",
1131  RelationGetRelationName(resultRel))));
1132  if (fdwroutine->IsForeignRelUpdatable != NULL &&
1133  (fdwroutine->IsForeignRelUpdatable(resultRel) & (1 << CMD_DELETE)) == 0)
1134  ereport(ERROR,
1135  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
1136  errmsg("foreign table \"%s\" does not allow deletes",
1137  RelationGetRelationName(resultRel))));
1138  break;
1139  default:
1140  elog(ERROR, "unrecognized CmdType: %d", (int) operation);
1141  break;
1142  }
1143  break;
1144  default:
1145  ereport(ERROR,
1146  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1147  errmsg("cannot change relation \"%s\"",
1148  RelationGetRelationName(resultRel))));
1149  break;
1150  }
1151 }
int errhint(const char *fmt,...)
Definition: elog.c:1316
int errcode(int sqlerrcode)
Definition: elog.c:858
int errmsg(const char *fmt,...)
Definition: elog.c:1069
#define ERROR
Definition: elog.h:39
#define ereport(elevel,...)
Definition: elog.h:149
void CheckCmdReplicaIdentity(Relation rel, CmdType cmd)
bool MatViewIncrementalMaintenanceIsEnabled(void)
Definition: matview.c:917
@ CMD_INSERT
Definition: nodes.h:278
@ CMD_DELETE
Definition: nodes.h:279
@ CMD_UPDATE
Definition: nodes.h:277
#define RelationGetRelationName(relation)
Definition: rel.h:538
ExecForeignInsert_function ExecForeignInsert
Definition: fdwapi.h:232
ExecForeignUpdate_function ExecForeignUpdate
Definition: fdwapi.h:235
ExecForeignDelete_function ExecForeignDelete
Definition: fdwapi.h:236
IsForeignRelUpdatable_function IsForeignRelUpdatable
Definition: fdwapi.h:240
TriggerDesc * trigdesc
Definition: rel.h:117
Form_pg_class rd_rel
Definition: rel.h:111
Relation ri_RelationDesc
Definition: execnodes.h:450
struct FdwRoutine * ri_FdwRoutine
Definition: execnodes.h:497
bool trig_update_instead_row
Definition: reltrigger.h:63
bool trig_delete_instead_row
Definition: reltrigger.h:68
bool trig_insert_instead_row
Definition: reltrigger.h:58

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

◆ CheckValidRowMarkRel()

static void CheckValidRowMarkRel ( Relation  rel,
RowMarkType  markType 
)
static

Definition at line 1160 of file execMain.c.

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

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

Referenced by InitPlan().

◆ EvalPlanQual()

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

Definition at line 2494 of file execMain.c.

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

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

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

◆ EvalPlanQualBegin()

void EvalPlanQualBegin ( EPQState epqstate)

Definition at line 2775 of file execMain.c.

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

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

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

◆ EvalPlanQualEnd()

void EvalPlanQualEnd ( EPQState epqstate)

Definition at line 3006 of file execMain.c.

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

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

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

◆ EvalPlanQualFetchRowMark()

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

Definition at line 2650 of file execMain.c.

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

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

Referenced by ExecScanFetch().

◆ EvalPlanQualInit()

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

Definition at line 2563 of file execMain.c.

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

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

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

◆ EvalPlanQualNext()

TupleTableSlot* EvalPlanQualNext ( EPQState epqstate)

Definition at line 2759 of file execMain.c.

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

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

Referenced by EvalPlanQual(), and ExecLockRows().

◆ EvalPlanQualSetPlan()

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

Definition at line 2605 of file execMain.c.

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

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

Referenced by ExecInitModifyTable().

◆ EvalPlanQualSlot()

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

Definition at line 2622 of file execMain.c.

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

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

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

◆ EvalPlanQualStart()

static void EvalPlanQualStart ( EPQState epqstate,
Plan planTree 
)
static

Definition at line 2842 of file execMain.c.

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

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

Referenced by EvalPlanQualBegin().

◆ ExecBuildAuxRowMark()

ExecAuxRowMark* ExecBuildAuxRowMark ( ExecRowMark erm,
List targetlist 
)

Definition at line 2424 of file execMain.c.

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

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

Referenced by ExecInitLockRows(), and ExecInitModifyTable().

◆ ExecBuildSlotValueDescription()

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

Definition at line 2238 of file execMain.c.

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

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

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

◆ ExecCheckOneRelPerms()

static bool ExecCheckOneRelPerms ( RTEPermissionInfo perminfo)
static

Definition at line 645 of file execMain.c.

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

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

Referenced by ExecCheckPermissions().

◆ ExecCheckPermissions()

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

Definition at line 581 of file execMain.c.

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

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

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

◆ ExecCheckPermissionsModified()

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

Definition at line 754 of file execMain.c.

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

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

Referenced by ExecCheckOneRelPerms().

◆ ExecCheckXactReadOnly()

static void ExecCheckXactReadOnly ( PlannedStmt plannedstmt)
static

Definition at line 801 of file execMain.c.

802 {
803  ListCell *l;
804 
805  /*
806  * Fail if write permissions are requested in parallel mode for table
807  * (temp or non-temp), otherwise fail for any non-temp table.
808  */
809  foreach(l, plannedstmt->permInfos)
810  {
812 
813  if ((perminfo->requiredPerms & (~ACL_SELECT)) == 0)
814  continue;
815 
816  if (isTempNamespace(get_rel_namespace(perminfo->relid)))
817  continue;
818 
820  }
821 
822  if (plannedstmt->commandType != CMD_SELECT || plannedstmt->hasModifyingCTE)
824 }
Oid get_rel_namespace(Oid relid)
Definition: lsyscache.c:1956
bool isTempNamespace(Oid namespaceId)
Definition: namespace.c:3182
@ CMD_SELECT
Definition: nodes.h:276
Definition: nodes.h:129
bool hasModifyingCTE
Definition: plannodes.h:59
List * permInfos
Definition: plannodes.h:75
CmdType commandType
Definition: plannodes.h:53
void PreventCommandIfReadOnly(const char *cmdname)
Definition: utility.c:411
void PreventCommandIfParallelMode(const char *cmdname)
Definition: utility.c:429
static const char * CreateCommandName(Node *parsetree)
Definition: utility.h:103

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

Referenced by standard_ExecutorStart().

◆ ExecCloseRangeTableRelations()

void ExecCloseRangeTableRelations ( EState estate)

Definition at line 1601 of file execMain.c.

1602 {
1603  int i;
1604 
1605  for (i = 0; i < estate->es_range_table_size; i++)
1606  {
1607  if (estate->es_relations[i])
1608  table_close(estate->es_relations[i], NoLock);
1609  }
1610 }
#define NoLock
Definition: lockdefs.h:34
void table_close(Relation relation, LOCKMODE lockmode)
Definition: table.c:126

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

Referenced by CopyFrom(), and ExecEndPlan().

◆ ExecCloseResultRelations()

void ExecCloseResultRelations ( EState estate)

Definition at line 1541 of file execMain.c.

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

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

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

◆ ExecConstraints()

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

Definition at line 1940 of file execMain.c.

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

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

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

◆ ExecEndPlan()

static void ExecEndPlan ( PlanState planstate,
EState estate 
)
static

Definition at line 1502 of file execMain.c.

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

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

Referenced by standard_ExecutorEnd().

◆ ExecFindRowMark()

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

Definition at line 2401 of file execMain.c.

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

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

Referenced by ExecInitLockRows(), and ExecInitModifyTable().

◆ ExecGetAncestorResultRels()

List* ExecGetAncestorResultRels ( EState estate,
ResultRelInfo resultRelInfo 
)

Definition at line 1396 of file execMain.c.

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

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

Referenced by ExecCrossPartitionUpdateForeignKey().

◆ ExecGetTriggerResultRel()

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

Definition at line 1320 of file execMain.c.

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

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

Referenced by afterTriggerInvokeEvents().

◆ ExecPartitionCheck()

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

Definition at line 1816 of file execMain.c.

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

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

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

◆ ExecPartitionCheckEmitError()

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

Definition at line 1869 of file execMain.c.

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

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

Referenced by ExecCrossPartitionUpdate(), and ExecPartitionCheck().

◆ ExecPostprocessPlan()

static void ExecPostprocessPlan ( EState estate)
static

Definition at line 1456 of file execMain.c.

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

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

Referenced by standard_ExecutorFinish().

◆ ExecRelCheck()

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

Definition at line 1741 of file execMain.c.

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

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

Referenced by ExecConstraints().

◆ ExecUpdateLockMode()

LockTupleMode ExecUpdateLockMode ( EState estate,
ResultRelInfo relinfo 
)

Definition at line 2375 of file execMain.c.

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

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

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

◆ ExecutePlan()

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

Definition at line 1625 of file execMain.c.

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

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

Referenced by standard_ExecutorRun().

◆ ExecutorEnd()

void ExecutorEnd ( QueryDesc queryDesc)

Definition at line 469 of file execMain.c.

470 {
471  if (ExecutorEnd_hook)
472  (*ExecutorEnd_hook) (queryDesc);
473  else
474  standard_ExecutorEnd(queryDesc);
475 }
ExecutorEnd_hook_type ExecutorEnd_hook
Definition: execMain.c:76
void standard_ExecutorEnd(QueryDesc *queryDesc)
Definition: execMain.c:478

References ExecutorEnd_hook, and standard_ExecutorEnd().

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

◆ ExecutorFinish()

void ExecutorFinish ( QueryDesc queryDesc)

Definition at line 409 of file execMain.c.

410 {
412  (*ExecutorFinish_hook) (queryDesc);
413  else
414  standard_ExecutorFinish(queryDesc);
415 }
ExecutorFinish_hook_type ExecutorFinish_hook
Definition: execMain.c:75
void standard_ExecutorFinish(QueryDesc *queryDesc)
Definition: execMain.c:418

References ExecutorFinish_hook, and standard_ExecutorFinish().

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

◆ ExecutorRewind()

void ExecutorRewind ( QueryDesc queryDesc)

Definition at line 535 of file execMain.c.

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

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

Referenced by DoPortalRewind(), and PersistHoldablePortal().

◆ ExecutorRun()

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

Definition at line 302 of file execMain.c.

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

References ExecutorRun_hook, and standard_ExecutorRun().

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

◆ ExecutorStart()

void ExecutorStart ( QueryDesc queryDesc,
int  eflags 
)

Definition at line 132 of file execMain.c.

133 {
134  /*
135  * In some cases (e.g. an EXECUTE statement) a query execution will skip
136  * parse analysis, which means that the query_id won't be reported. Note
137  * that it's harmless to report the query_id multiple times, as the call
138  * will be ignored if the top level query_id has already been reported.
139  */
140  pgstat_report_query_id(queryDesc->plannedstmt->queryId, false);
141 
142  if (ExecutorStart_hook)
143  (*ExecutorStart_hook) (queryDesc, eflags);
144  else
145  standard_ExecutorStart(queryDesc, eflags);
146 }
void pgstat_report_query_id(uint64 query_id, bool force)
ExecutorStart_hook_type ExecutorStart_hook
Definition: execMain.c:73
void standard_ExecutorStart(QueryDesc *queryDesc, int eflags)
Definition: execMain.c:149
uint64 queryId
Definition: plannodes.h:55
PlannedStmt * plannedstmt
Definition: execdesc.h:37

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

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

◆ ExecWithCheckOptions()

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

Definition at line 2075 of file execMain.c.

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

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

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

◆ InitPlan()

static void InitPlan ( QueryDesc queryDesc,
int  eflags 
)
static

Definition at line 835 of file execMain.c.

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

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

Referenced by standard_ExecutorStart().

◆ InitResultRelInfo()

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

Definition at line 1225 of file execMain.c.

1230 {
1231  MemSet(resultRelInfo, 0, sizeof(ResultRelInfo));
1232  resultRelInfo->type = T_ResultRelInfo;
1233  resultRelInfo->ri_RangeTableIndex = resultRelationIndex;
1234  resultRelInfo->ri_RelationDesc = resultRelationDesc;
1235  resultRelInfo->ri_NumIndices = 0;
1236  resultRelInfo->ri_IndexRelationDescs = NULL;
1237  resultRelInfo->ri_IndexRelationInfo = NULL;
1238  /* make a copy so as not to depend on relcache info not changing... */
1239  resultRelInfo->ri_TrigDesc = CopyTriggerDesc(resultRelationDesc->trigdesc);
1240  if (resultRelInfo->ri_TrigDesc)
1241  {
1242  int n = resultRelInfo->ri_TrigDesc->numtriggers;
1243 
1244  resultRelInfo->ri_TrigFunctions = (FmgrInfo *)
1245  palloc0(n * sizeof(FmgrInfo));
1246  resultRelInfo->ri_TrigWhenExprs = (ExprState **)
1247  palloc0(n * sizeof(ExprState *));
1248  if (instrument_options)
1249  resultRelInfo->ri_TrigInstrument = InstrAlloc(n, instrument_options, false);
1250  }
1251  else
1252  {
1253  resultRelInfo->ri_TrigFunctions = NULL;
1254  resultRelInfo->ri_TrigWhenExprs = NULL;
1255  resultRelInfo->ri_TrigInstrument = NULL;
1256  }
1257  if (resultRelationDesc->rd_rel->relkind == RELKIND_FOREIGN_TABLE)
1258  resultRelInfo->ri_FdwRoutine = GetFdwRoutineForRelation(resultRelationDesc, true);
1259  else
1260  resultRelInfo->ri_FdwRoutine = NULL;
1261 
1262  /* The following fields are set later if needed */
1263  resultRelInfo->ri_RowIdAttNo = 0;
1264  resultRelInfo->ri_extraUpdatedCols = NULL;
1265  resultRelInfo->ri_projectNew = NULL;
1266  resultRelInfo->ri_newTupleSlot = NULL;
1267  resultRelInfo->ri_oldTupleSlot = NULL;
1268  resultRelInfo->ri_projectNewInfoValid = false;
1269  resultRelInfo->ri_FdwState = NULL;
1270  resultRelInfo->ri_usesFdwDirectModify = false;
1271  resultRelInfo->ri_ConstraintExprs = NULL;
1272  resultRelInfo->ri_GeneratedExprsI = NULL;
1273  resultRelInfo->ri_GeneratedExprsU = NULL;
1274  resultRelInfo->ri_projectReturning = NULL;
1275  resultRelInfo->ri_onConflictArbiterIndexes = NIL;
1276  resultRelInfo->ri_onConflict = NULL;
1277  resultRelInfo->ri_ReturningSlot = NULL;
1278  resultRelInfo->ri_TrigOldSlot = NULL;
1279  resultRelInfo->ri_TrigNewSlot = NULL;
1280  resultRelInfo->ri_matchedMergeAction = NIL;
1281  resultRelInfo->ri_notMatchedMergeAction = NIL;
1282 
1283  /*
1284  * Only ExecInitPartitionInfo() and ExecInitPartitionDispatchInfo() pass
1285  * non-NULL partition_root_rri. For child relations that are part of the
1286  * initial query rather than being dynamically added by tuple routing,
1287  * this field is filled in ExecInitModifyTable().
1288  */
1289  resultRelInfo->ri_RootResultRelInfo = partition_root_rri;
1290  /* Set by ExecGetRootToChildMap */
1291  resultRelInfo->ri_RootToChildMap = NULL;
1292  resultRelInfo->ri_RootToChildMapValid = false;
1293  /* Set by ExecInitRoutingInfo */
1294  resultRelInfo->ri_PartitionTupleSlot = NULL;
1295  resultRelInfo->ri_ChildToRootMap = NULL;
1296  resultRelInfo->ri_ChildToRootMapValid = false;
1297  resultRelInfo->ri_CopyMultiInsertBuffer = NULL;
1298 }
#define MemSet(start, val, len)
Definition: c.h:1009
Instrumentation * InstrAlloc(int n, int instrument_options, bool async_mode)
Definition: instrument.c:31
Definition: fmgr.h:57
TupleConversionMap * ri_RootToChildMap
Definition: execnodes.h:560
List * ri_matchedMergeAction
Definition: execnodes.h:542
TupleTableSlot * ri_PartitionTupleSlot
Definition: execnodes.h:575
List * ri_notMatchedMergeAction
Definition: execnodes.h:543
bool ri_projectNewInfoValid
Definition: execnodes.h:477
OnConflictSetState * ri_onConflict
Definition: execnodes.h:539
List * ri_onConflictArbiterIndexes
Definition: execnodes.h:536
Instrumentation * ri_TrigInstrument
Definition: execnodes.h:489
RelationPtr ri_IndexRelationDescs
Definition: execnodes.h:456
TupleTableSlot * ri_ReturningSlot
Definition: execnodes.h:492
TupleTableSlot * ri_oldTupleSlot
Definition: execnodes.h:475
bool ri_RootToChildMapValid
Definition: execnodes.h:561
struct CopyMultiInsertBuffer * ri_CopyMultiInsertBuffer
Definition: execnodes.h:578
TriggerDesc * ri_TrigDesc
Definition: execnodes.h:480
Bitmapset * ri_extraUpdatedCols
Definition: execnodes.h:468
ExprState ** ri_GeneratedExprsI
Definition: execnodes.h:522
TupleConversionMap * ri_ChildToRootMap
Definition: execnodes.h:554
void * ri_FdwState
Definition: execnodes.h:500
bool ri_ChildToRootMapValid
Definition: execnodes.h:555
TupleTableSlot * ri_newTupleSlot
Definition: execnodes.h:473
ProjectionInfo * ri_projectNew
Definition: execnodes.h:471
NodeTag type
Definition: execnodes.h:444
ProjectionInfo * ri_projectReturning
Definition: execnodes.h:533
ExprState ** ri_GeneratedExprsU
Definition: execnodes.h:523
ExprState ** ri_TrigWhenExprs
Definition: execnodes.h:486
FmgrInfo * ri_TrigFunctions
Definition: execnodes.h:483
bool ri_usesFdwDirectModify
Definition: execnodes.h:503
AttrNumber ri_RowIdAttNo
Definition: execnodes.h:465
IndexInfo ** ri_IndexRelationInfo
Definition: execnodes.h:459
TupleTableSlot * ri_TrigNewSlot
Definition: execnodes.h:494
TupleTableSlot * ri_TrigOldSlot
Definition: execnodes.h:493
int numtriggers
Definition: reltrigger.h:50
TriggerDesc * CopyTriggerDesc(TriggerDesc *trigdesc)
Definition: trigger.c:2091

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

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

◆ standard_ExecutorEnd()

void standard_ExecutorEnd ( QueryDesc queryDesc)

Definition at line 478 of file execMain.c.

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

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

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

◆ standard_ExecutorFinish()

void standard_ExecutorFinish ( QueryDesc queryDesc)

Definition at line 418 of file execMain.c.

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

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

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

◆ standard_ExecutorRun()

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

Definition at line 313 of file execMain.c.

315 {
316  EState *estate;
317  CmdType operation;
319  bool sendTuples;
320  MemoryContext oldcontext;
321 
322  /* sanity checks */
323  Assert(queryDesc != NULL);
324 
325  estate = queryDesc->estate;
326 
327  Assert(estate != NULL);
329 
330  /*
331  * Switch into per-query memory context
332  */
333  oldcontext = MemoryContextSwitchTo(estate->es_query_cxt);
334 
335  /* Allow instrumentation of Executor overall runtime */
336  if (queryDesc->totaltime)
337  InstrStartNode(queryDesc->totaltime);
338 
339  /*
340  * extract information from the query descriptor and the query feature.
341  */
342  operation = queryDesc->operation;
343  dest = queryDesc->dest;
344 
345  /*
346  * startup tuple receiver, if we will be emitting tuples
347  */
348  estate->es_processed = 0;
349 
350  sendTuples = (operation == CMD_SELECT ||
351  queryDesc->plannedstmt->hasReturning);
352 
353  if (sendTuples)
354  dest->rStartup(dest, operation, queryDesc->tupDesc);
355 
356  /*
357  * run plan
358  */
359  if (!ScanDirectionIsNoMovement(direction))
360  {
361  if (execute_once && queryDesc->already_executed)
362  elog(ERROR, "can't re-execute query flagged for single execution");
363  queryDesc->already_executed = true;
364 
365  ExecutePlan(estate,
366  queryDesc->planstate,
367  queryDesc->plannedstmt->parallelModeNeeded,
368  operation,
369  sendTuples,
370  count,
371  direction,
372  dest,
373  execute_once);
374  }
375 
376  /*
377  * Update es_total_processed to keep track of the number of tuples
378  * processed across multiple ExecutorRun() calls.
379  */
380  estate->es_total_processed += estate->es_processed;
381 
382  /*
383  * shutdown tuple receiver, if we started it
384  */
385  if (sendTuples)
386  dest->rShutdown(dest);
387 
388  if (queryDesc->totaltime)
389  InstrStopNode(queryDesc->totaltime, estate->es_processed);
390 
391  MemoryContextSwitchTo(oldcontext);
392 }
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:1625
#define ScanDirectionIsNoMovement(direction)
Definition: sdir.h:57
uint64 es_total_processed
Definition: execnodes.h:665
bool hasReturning
Definition: plannodes.h:57
bool parallelModeNeeded
Definition: plannodes.h:67
DestReceiver * dest
Definition: execdesc.h:41
bool already_executed
Definition: execdesc.h:52

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

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

◆ standard_ExecutorStart()

void standard_ExecutorStart ( QueryDesc queryDesc,
int  eflags 
)

Definition at line 149 of file execMain.c.

150 {
151  EState *estate;
152  MemoryContext oldcontext;
153 
154  /* sanity checks: queryDesc must not be started already */
155  Assert(queryDesc != NULL);
156  Assert(queryDesc->estate == NULL);
157 
158  /*
159  * If the transaction is read-only, we need to check if any writes are
160  * planned to non-temporary tables. EXPLAIN is considered read-only.
161  *
162  * Don't allow writes in parallel mode. Supporting UPDATE and DELETE
163  * would require (a) storing the combo CID hash in shared memory, rather
164  * than synchronizing it just once at the start of parallelism, and (b) an
165  * alternative to heap_update()'s reliance on xmax for mutual exclusion.
166  * INSERT may have no such troubles, but we forbid it to simplify the
167  * checks.
168  *
169  * We have lower-level defenses in CommandCounterIncrement and elsewhere
170  * against performing unsafe operations in parallel mode, but this gives a
171  * more user-friendly error message.
172  */
173  if ((XactReadOnly || IsInParallelMode()) &&
174  !(eflags & EXEC_FLAG_EXPLAIN_ONLY))
176 
177  /*
178  * Build EState, switch into per-query memory context for startup.
179  */
180  estate = CreateExecutorState();
181  queryDesc->estate = estate;
182 
183  oldcontext = MemoryContextSwitchTo(estate->es_query_cxt);
184 
185  /*
186  * Fill in external parameters, if any, from queryDesc; and allocate
187  * workspace for internal parameters
188  */
189  estate->es_param_list_info = queryDesc->params;
190 
191  if (queryDesc->plannedstmt->paramExecTypes != NIL)
192  {
193  int nParamExec;
194 
195  nParamExec = list_length(queryDesc->plannedstmt->paramExecTypes);
196  estate->es_param_exec_vals = (ParamExecData *)
197  palloc0(nParamExec * sizeof(ParamExecData));
198  }
199 
200  /* We now require all callers to provide sourceText */
201  Assert(queryDesc->sourceText != NULL);
202  estate->es_sourceText = queryDesc->sourceText;
203 
204  /*
205  * Fill in the query environment, if any, from queryDesc.
206  */
207  estate->es_queryEnv = queryDesc->queryEnv;
208 
209  /*
210  * If non-read-only query, set the command ID to mark output tuples with
211  */
212  switch (queryDesc->operation)
213  {
214  case CMD_SELECT:
215 
216  /*
217  * SELECT FOR [KEY] UPDATE/SHARE and modifying CTEs need to mark
218  * tuples
219  */
220  if (queryDesc->plannedstmt->rowMarks != NIL ||
221  queryDesc->plannedstmt->hasModifyingCTE)
222  estate->es_output_cid = GetCurrentCommandId(true);
223 
224  /*
225  * A SELECT without modifying CTEs can't possibly queue triggers,
226  * so force skip-triggers mode. This is just a marginal efficiency
227  * hack, since AfterTriggerBeginQuery/AfterTriggerEndQuery aren't
228  * all that expensive, but we might as well do it.
229  */
230  if (!queryDesc->plannedstmt->hasModifyingCTE)
231  eflags |= EXEC_FLAG_SKIP_TRIGGERS;
232  break;
233 
234  case CMD_INSERT:
235  case CMD_DELETE:
236  case CMD_UPDATE:
237  case CMD_MERGE:
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  */
262 
263  /*
264  * Initialize the plan state tree
265  */
266  InitPlan(queryDesc, eflags);
267 
268  MemoryContextSwitchTo(oldcontext);
269 }
static void ExecCheckXactReadOnly(PlannedStmt *plannedstmt)
Definition: execMain.c:801
static void InitPlan(QueryDesc *queryDesc, int eflags)
Definition: execMain.c:835
@ CMD_MERGE
Definition: nodes.h:280
Snapshot RegisterSnapshot(Snapshot snapshot)
Definition: snapmgr.c:775
int es_jit_flags
Definition: execnodes.h:707
const char * es_sourceText
Definition: execnodes.h:626
int jitFlags
Definition: plannodes.h:69
const char * sourceText
Definition: execdesc.h:38
ParamListInfo params
Definition: execdesc.h:42
int instrument_options
Definition: execdesc.h:44
Snapshot snapshot
Definition: execdesc.h:39
QueryEnvironment * queryEnv
Definition: execdesc.h:43
Snapshot crosscheck_snapshot
Definition: execdesc.h:40
void AfterTriggerBeginQuery(void)
Definition: trigger.c:5006
bool XactReadOnly
Definition: xact.c:82
bool IsInParallelMode(void)
Definition: xact.c:1069
CommandId GetCurrentCommandId(bool used)
Definition: xact.c:818

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

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

Variable Documentation

◆ ExecutorCheckPerms_hook

ExecutorCheckPerms_hook_type ExecutorCheckPerms_hook = NULL

Definition at line 79 of file execMain.c.

Referenced by _PG_init(), and ExecCheckPermissions().

◆ ExecutorEnd_hook

ExecutorEnd_hook_type ExecutorEnd_hook = NULL

Definition at line 76 of file execMain.c.

Referenced by _PG_init(), and ExecutorEnd().

◆ ExecutorFinish_hook

ExecutorFinish_hook_type ExecutorFinish_hook = NULL

Definition at line 75 of file execMain.c.

Referenced by _PG_init(), and ExecutorFinish().

◆ ExecutorRun_hook

ExecutorRun_hook_type ExecutorRun_hook = NULL

Definition at line 74 of file execMain.c.

Referenced by _PG_init(), and ExecutorRun().

◆ ExecutorStart_hook

ExecutorStart_hook_type ExecutorStart_hook = NULL

Definition at line 73 of file execMain.c.

Referenced by _PG_init(), and ExecutorStart().