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

988 {
989  Relation resultRel = resultRelInfo->ri_RelationDesc;
990  TriggerDesc *trigDesc = resultRel->trigdesc;
991  FdwRoutine *fdwroutine;
992 
993  switch (resultRel->rd_rel->relkind)
994  {
995  case RELKIND_RELATION:
996  case RELKIND_PARTITIONED_TABLE:
997  CheckCmdReplicaIdentity(resultRel, operation);
998  break;
999  case RELKIND_SEQUENCE:
1000  ereport(ERROR,
1001  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1002  errmsg("cannot change sequence \"%s\"",
1003  RelationGetRelationName(resultRel))));
1004  break;
1005  case RELKIND_TOASTVALUE:
1006  ereport(ERROR,
1007  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1008  errmsg("cannot change TOAST relation \"%s\"",
1009  RelationGetRelationName(resultRel))));
1010  break;
1011  case RELKIND_VIEW:
1012 
1013  /*
1014  * Okay only if there's a suitable INSTEAD OF trigger. Messages
1015  * here should match rewriteHandler.c's rewriteTargetView and
1016  * RewriteQuery, except that we omit errdetail because we haven't
1017  * got the information handy (and given that we really shouldn't
1018  * get here anyway, it's not worth great exertion to get).
1019  */
1020  switch (operation)
1021  {
1022  case CMD_INSERT:
1023  if (!trigDesc || !trigDesc->trig_insert_instead_row)
1024  ereport(ERROR,
1025  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
1026  errmsg("cannot insert into view \"%s\"",
1027  RelationGetRelationName(resultRel)),
1028  errhint("To enable inserting into the view, provide an INSTEAD OF INSERT trigger or an unconditional ON INSERT DO INSTEAD rule.")));
1029  break;
1030  case CMD_UPDATE:
1031  if (!trigDesc || !trigDesc->trig_update_instead_row)
1032  ereport(ERROR,
1033  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
1034  errmsg("cannot update view \"%s\"",
1035  RelationGetRelationName(resultRel)),
1036  errhint("To enable updating the view, provide an INSTEAD OF UPDATE trigger or an unconditional ON UPDATE DO INSTEAD rule.")));
1037  break;
1038  case CMD_DELETE:
1039  if (!trigDesc || !trigDesc->trig_delete_instead_row)
1040  ereport(ERROR,
1041  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
1042  errmsg("cannot delete from view \"%s\"",
1043  RelationGetRelationName(resultRel)),
1044  errhint("To enable deleting from the view, provide an INSTEAD OF DELETE trigger or an unconditional ON DELETE DO INSTEAD rule.")));
1045  break;
1046  default:
1047  elog(ERROR, "unrecognized CmdType: %d", (int) operation);
1048  break;
1049  }
1050  break;
1051  case RELKIND_MATVIEW:
1053  ereport(ERROR,
1054  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1055  errmsg("cannot change materialized view \"%s\"",
1056  RelationGetRelationName(resultRel))));
1057  break;
1058  case RELKIND_FOREIGN_TABLE:
1059  /* Okay only if the FDW supports it */
1060  fdwroutine = resultRelInfo->ri_FdwRoutine;
1061  switch (operation)
1062  {
1063  case CMD_INSERT:
1064  if (fdwroutine->ExecForeignInsert == NULL)
1065  ereport(ERROR,
1066  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1067  errmsg("cannot insert into foreign table \"%s\"",
1068  RelationGetRelationName(resultRel))));
1069  if (fdwroutine->IsForeignRelUpdatable != NULL &&
1070  (fdwroutine->IsForeignRelUpdatable(resultRel) & (1 << CMD_INSERT)) == 0)
1071  ereport(ERROR,
1072  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
1073  errmsg("foreign table \"%s\" does not allow inserts",
1074  RelationGetRelationName(resultRel))));
1075  break;
1076  case CMD_UPDATE:
1077  if (fdwroutine->ExecForeignUpdate == NULL)
1078  ereport(ERROR,
1079  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1080  errmsg("cannot update foreign table \"%s\"",
1081  RelationGetRelationName(resultRel))));
1082  if (fdwroutine->IsForeignRelUpdatable != NULL &&
1083  (fdwroutine->IsForeignRelUpdatable(resultRel) & (1 << CMD_UPDATE)) == 0)
1084  ereport(ERROR,
1085  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
1086  errmsg("foreign table \"%s\" does not allow updates",
1087  RelationGetRelationName(resultRel))));
1088  break;
1089  case CMD_DELETE:
1090  if (fdwroutine->ExecForeignDelete == NULL)
1091  ereport(ERROR,
1092  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1093  errmsg("cannot delete from foreign table \"%s\"",
1094  RelationGetRelationName(resultRel))));
1095  if (fdwroutine->IsForeignRelUpdatable != NULL &&
1096  (fdwroutine->IsForeignRelUpdatable(resultRel) & (1 << CMD_DELETE)) == 0)
1097  ereport(ERROR,
1098  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
1099  errmsg("foreign table \"%s\" does not allow deletes",
1100  RelationGetRelationName(resultRel))));
1101  break;
1102  default:
1103  elog(ERROR, "unrecognized CmdType: %d", (int) operation);
1104  break;
1105  }
1106  break;
1107  default:
1108  ereport(ERROR,
1109  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1110  errmsg("cannot change relation \"%s\"",
1111  RelationGetRelationName(resultRel))));
1112  break;
1113  }
1114 }
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:921
@ CMD_INSERT
Definition: nodes.h:278
@ CMD_DELETE
Definition: nodes.h:279
@ CMD_UPDATE
Definition: nodes.h:277
#define RelationGetRelationName(relation)
Definition: rel.h:537
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:116
Form_pg_class rd_rel
Definition: rel.h:110
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 1123 of file execMain.c.

1124 {
1125  FdwRoutine *fdwroutine;
1126 
1127  switch (rel->rd_rel->relkind)
1128  {
1129  case RELKIND_RELATION:
1130  case RELKIND_PARTITIONED_TABLE:
1131  /* OK */
1132  break;
1133  case RELKIND_SEQUENCE:
1134  /* Must disallow this because we don't vacuum sequences */
1135  ereport(ERROR,
1136  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1137  errmsg("cannot lock rows in sequence \"%s\"",
1138  RelationGetRelationName(rel))));
1139  break;
1140  case RELKIND_TOASTVALUE:
1141  /* We could allow this, but there seems no good reason to */
1142  ereport(ERROR,
1143  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1144  errmsg("cannot lock rows in TOAST relation \"%s\"",
1145  RelationGetRelationName(rel))));
1146  break;
1147  case RELKIND_VIEW:
1148  /* Should not get here; planner should have expanded the view */
1149  ereport(ERROR,
1150  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1151  errmsg("cannot lock rows in view \"%s\"",
1152  RelationGetRelationName(rel))));
1153  break;
1154  case RELKIND_MATVIEW:
1155  /* Allow referencing a matview, but not actual locking clauses */
1156  if (markType != ROW_MARK_REFERENCE)
1157  ereport(ERROR,
1158  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1159  errmsg("cannot lock rows in materialized view \"%s\"",
1160  RelationGetRelationName(rel))));
1161  break;
1162  case RELKIND_FOREIGN_TABLE:
1163  /* Okay only if the FDW supports it */
1164  fdwroutine = GetFdwRoutineForRelation(rel, false);
1165  if (fdwroutine->RefetchForeignRow == NULL)
1166  ereport(ERROR,
1167  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1168  errmsg("cannot lock rows in foreign table \"%s\"",
1169  RelationGetRelationName(rel))));
1170  break;
1171  default:
1172  ereport(ERROR,
1173  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1174  errmsg("cannot lock rows in relation \"%s\"",
1175  RelationGetRelationName(rel))));
1176  break;
1177  }
1178 }
FdwRoutine * GetFdwRoutineForRelation(Relation relation, bool makecopy)
Definition: foreign.c:429
@ ROW_MARK_REFERENCE
Definition: plannodes.h:1334
RefetchForeignRow_function RefetchForeignRow
Definition: fdwapi.h:248

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

Referenced by InitPlan().

◆ EvalPlanQual()

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

Definition at line 2457 of file execMain.c.

2459 {
2460  TupleTableSlot *slot;
2461  TupleTableSlot *testslot;
2462 
2463  Assert(rti > 0);
2464 
2465  /*
2466  * Need to run a recheck subquery. Initialize or reinitialize EPQ state.
2467  */
2468  EvalPlanQualBegin(epqstate);
2469 
2470  /*
2471  * Callers will often use the EvalPlanQualSlot to store the tuple to avoid
2472  * an unnecessary copy.
2473  */
2474  testslot = EvalPlanQualSlot(epqstate, relation, rti);
2475  if (testslot != inputslot)
2476  ExecCopySlot(testslot, inputslot);
2477 
2478  /*
2479  * Run the EPQ query. We assume it will return at most one tuple.
2480  */
2481  slot = EvalPlanQualNext(epqstate);
2482 
2483  /*
2484  * If we got a tuple, force the slot to materialize the tuple so that it
2485  * is not dependent on any local state in the EPQ query (in particular,
2486  * it's highly likely that the slot contains references to any pass-by-ref
2487  * datums that may be present in copyTuple). As with the next step, this
2488  * is to guard against early re-use of the EPQ query.
2489  */
2490  if (!TupIsNull(slot))
2491  ExecMaterializeSlot(slot);
2492 
2493  /*
2494  * Clear out the test tuple. This is needed in case the EPQ query is
2495  * re-used to test a tuple for a different relation. (Not clear that can
2496  * really happen, but let's be safe.)
2497  */
2498  ExecClearTuple(testslot);
2499 
2500  return slot;
2501 }
void EvalPlanQualBegin(EPQState *epqstate)
Definition: execMain.c:2720
TupleTableSlot * EvalPlanQualNext(EPQState *epqstate)
Definition: execMain.c:2704
TupleTableSlot * EvalPlanQualSlot(EPQState *epqstate, Relation relation, Index rti)
Definition: execMain.c:2567
Assert(fmt[strlen(fmt) - 1] !='\n')
static TupleTableSlot * ExecClearTuple(TupleTableSlot *slot)
Definition: tuptable.h:433
static TupleTableSlot * ExecCopySlot(TupleTableSlot *dstslot, TupleTableSlot *srcslot)
Definition: tuptable.h:483
#define TupIsNull(slot)
Definition: tuptable.h:300
static void ExecMaterializeSlot(TupleTableSlot *slot)
Definition: tuptable.h:451

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

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

◆ EvalPlanQualBegin()

void EvalPlanQualBegin ( EPQState epqstate)

Definition at line 2720 of file execMain.c.

2721 {
2722  EState *parentestate = epqstate->parentestate;
2723  EState *recheckestate = epqstate->recheckestate;
2724 
2725  if (recheckestate == NULL)
2726  {
2727  /* First time through, so create a child EState */
2728  EvalPlanQualStart(epqstate, epqstate->plan);
2729  }
2730  else
2731  {
2732  /*
2733  * We already have a suitable child EPQ tree, so just reset it.
2734  */
2735  Index rtsize = parentestate->es_range_table_size;
2736  PlanState *rcplanstate = epqstate->recheckplanstate;
2737 
2738  MemSet(epqstate->relsubs_done, 0, rtsize * sizeof(bool));
2739 
2740  /* Recopy current values of parent parameters */
2741  if (parentestate->es_plannedstmt->paramExecTypes != NIL)
2742  {
2743  int i;
2744 
2745  /*
2746  * Force evaluation of any InitPlan outputs that could be needed
2747  * by the subplan, just in case they got reset since
2748  * EvalPlanQualStart (see comments therein).
2749  */
2750  ExecSetParamPlanMulti(rcplanstate->plan->extParam,
2751  GetPerTupleExprContext(parentestate));
2752 
2753  i = list_length(parentestate->es_plannedstmt->paramExecTypes);
2754 
2755  while (--i >= 0)
2756  {
2757  /* copy value if any, but not execPlan link */
2758  recheckestate->es_param_exec_vals[i].value =
2759  parentestate->es_param_exec_vals[i].value;
2760  recheckestate->es_param_exec_vals[i].isnull =
2761  parentestate->es_param_exec_vals[i].isnull;
2762  }
2763  }
2764 
2765  /*
2766  * Mark child plan tree as needing rescan at all scan nodes. The
2767  * first ExecProcNode will take care of actually doing the rescan.
2768  */
2769  rcplanstate->chgParam = bms_add_member(rcplanstate->chgParam,
2770  epqstate->epqParam);
2771  }
2772 }
Bitmapset * bms_add_member(Bitmapset *a, int x)
Definition: bitmapset.c:755
unsigned int Index
Definition: c.h:598
#define MemSet(start, val, len)
Definition: c.h:1004
static void EvalPlanQualStart(EPQState *epqstate, Plan *planTree)
Definition: execMain.c:2781
#define GetPerTupleExprContext(estate)
Definition: executor.h:538
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:1188
int epqParam
Definition: execnodes.h:1173
EState * parentestate
Definition: execnodes.h:1172
EState * recheckestate
Definition: execnodes.h:1202
PlanState * recheckplanstate
Definition: execnodes.h:1217
bool * relsubs_done
Definition: execnodes.h:1215
PlannedStmt * es_plannedstmt
Definition: execnodes.h:625
ParamExecData * es_param_exec_vals
Definition: execnodes.h:655
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:1035
Bitmapset * chgParam
Definition: execnodes.h:1067
Bitmapset * extParam
Definition: plannodes.h:174
List * paramExecTypes
Definition: plannodes.h:97

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

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

◆ EvalPlanQualEnd()

void EvalPlanQualEnd ( EPQState epqstate)

Definition at line 2933 of file execMain.c.

2934 {
2935  EState *estate = epqstate->recheckestate;
2936  Index rtsize;
2937  MemoryContext oldcontext;
2938  ListCell *l;
2939 
2940  rtsize = epqstate->parentestate->es_range_table_size;
2941 
2942  /*
2943  * We may have a tuple table, even if EPQ wasn't started, because we allow
2944  * use of EvalPlanQualSlot() without calling EvalPlanQualBegin().
2945  */
2946  if (epqstate->tuple_table != NIL)
2947  {
2948  memset(epqstate->relsubs_slot, 0,
2949  rtsize * sizeof(TupleTableSlot *));
2950  ExecResetTupleTable(epqstate->tuple_table, true);
2951  epqstate->tuple_table = NIL;
2952  }
2953 
2954  /* EPQ wasn't started, nothing further to do */
2955  if (estate == NULL)
2956  return;
2957 
2958  oldcontext = MemoryContextSwitchTo(estate->es_query_cxt);
2959 
2960  ExecEndNode(epqstate->recheckplanstate);
2961 
2962  foreach(l, estate->es_subplanstates)
2963  {
2964  PlanState *subplanstate = (PlanState *) lfirst(l);
2965 
2966  ExecEndNode(subplanstate);
2967  }
2968 
2969  /* throw away the per-estate tuple table, some node may have used it */
2970  ExecResetTupleTable(estate->es_tupleTable, false);
2971 
2972  /* Close any result and trigger target relations attached to this EState */
2973  ExecCloseResultRelations(estate);
2974 
2975  MemoryContextSwitchTo(oldcontext);
2976 
2977  FreeExecutorState(estate);
2978 
2979  /* Mark EPQState idle */
2980  epqstate->origslot = NULL;
2981  epqstate->recheckestate = NULL;
2982  epqstate->recheckplanstate = NULL;
2983  epqstate->relsubs_rowmark = NULL;
2984  epqstate->relsubs_done = NULL;
2985 }
void ExecCloseResultRelations(EState *estate)
Definition: execMain.c:1504
void ExecEndNode(PlanState *node)
Definition: execProcnode.c:557
void ExecResetTupleTable(List *tupleTable, bool shouldFree)
Definition: execTuples.c:1191
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:1209
TupleTableSlot * origslot
Definition: execnodes.h:1197
TupleTableSlot ** relsubs_slot
Definition: execnodes.h:1181
List * tuple_table
Definition: execnodes.h:1180
MemoryContext es_query_cxt
Definition: execnodes.h:660
List * es_tupleTable
Definition: execnodes.h:662
List * es_subplanstates
Definition: execnodes.h:672

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

2596 {
2597  ExecAuxRowMark *earm = epqstate->relsubs_rowmark[rti - 1];
2598  ExecRowMark *erm = earm->rowmark;
2599  Datum datum;
2600  bool isNull;
2601 
2602  Assert(earm != NULL);
2603  Assert(epqstate->origslot != NULL);
2604 
2606  elog(ERROR, "EvalPlanQual doesn't support locking rowmarks");
2607 
2608  /* if child rel, must check whether it produced this row */
2609  if (erm->rti != erm->prti)
2610  {
2611  Oid tableoid;
2612 
2613  datum = ExecGetJunkAttribute(epqstate->origslot,
2614  earm->toidAttNo,
2615  &isNull);
2616  /* non-locked rels could be on the inside of outer joins */
2617  if (isNull)
2618  return false;
2619 
2620  tableoid = DatumGetObjectId(datum);
2621 
2622  Assert(OidIsValid(erm->relid));
2623  if (tableoid != erm->relid)
2624  {
2625  /* this child is inactive right now */
2626  return false;
2627  }
2628  }
2629 
2630  if (erm->markType == ROW_MARK_REFERENCE)
2631  {
2632  Assert(erm->relation != NULL);
2633 
2634  /* fetch the tuple's ctid */
2635  datum = ExecGetJunkAttribute(epqstate->origslot,
2636  earm->ctidAttNo,
2637  &isNull);
2638  /* non-locked rels could be on the inside of outer joins */
2639  if (isNull)
2640  return false;
2641 
2642  /* fetch requests on foreign tables must be passed to their FDW */
2643  if (erm->relation->rd_rel->relkind == RELKIND_FOREIGN_TABLE)
2644  {
2645  FdwRoutine *fdwroutine;
2646  bool updated = false;
2647 
2648  fdwroutine = GetFdwRoutineForRelation(erm->relation, false);
2649  /* this should have been checked already, but let's be safe */
2650  if (fdwroutine->RefetchForeignRow == NULL)
2651  ereport(ERROR,
2652  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2653  errmsg("cannot lock rows in foreign table \"%s\"",
2655 
2656  fdwroutine->RefetchForeignRow(epqstate->recheckestate,
2657  erm,
2658  datum,
2659  slot,
2660  &updated);
2661  if (TupIsNull(slot))
2662  elog(ERROR, "failed to fetch tuple for EvalPlanQual recheck");
2663 
2664  /*
2665  * Ideally we'd insist on updated == false here, but that assumes
2666  * that FDWs can track that exactly, which they might not be able
2667  * to. So just ignore the flag.
2668  */
2669  return true;
2670  }
2671  else
2672  {
2673  /* ordinary table, fetch the tuple */
2675  (ItemPointer) DatumGetPointer(datum),
2676  SnapshotAny, slot))
2677  elog(ERROR, "failed to fetch tuple for EvalPlanQual recheck");
2678  return true;
2679  }
2680  }
2681  else
2682  {
2683  Assert(erm->markType == ROW_MARK_COPY);
2684 
2685  /* fetch the whole-row Var for the relation */
2686  datum = ExecGetJunkAttribute(epqstate->origslot,
2687  earm->wholeAttNo,
2688  &isNull);
2689  /* non-locked rels could be on the inside of outer joins */
2690  if (isNull)
2691  return false;
2692 
2693  ExecStoreHeapTupleDatum(datum, slot);
2694  return true;
2695  }
2696 }
#define OidIsValid(objectId)
Definition: c.h:759
void ExecStoreHeapTupleDatum(Datum data, TupleTableSlot *slot)
Definition: execTuples.c:1606
static Datum ExecGetJunkAttribute(TupleTableSlot *slot, AttrNumber attno, bool *isNull)
Definition: executor.h:180
#define RowMarkRequiresRowShareLock(marktype)
Definition: plannodes.h:1338
@ ROW_MARK_COPY
Definition: plannodes.h:1335
uintptr_t Datum
Definition: postgres.h:64
static Oid DatumGetObjectId(Datum X)
Definition: postgres.h:242
static Pointer DatumGetPointer(Datum X)
Definition: postgres.h:312
unsigned int Oid
Definition: postgres_ext.h:31
#define SnapshotAny
Definition: snapmgr.h:67
AttrNumber wholeAttNo
Definition: execnodes.h:766
ExecRowMark * rowmark
Definition: execnodes.h:763
AttrNumber toidAttNo
Definition: execnodes.h:765
AttrNumber ctidAttNo
Definition: execnodes.h:764
Index rti
Definition: execnodes.h:741
Index prti
Definition: execnodes.h:742
Relation relation
Definition: execnodes.h:739
RowMarkType markType
Definition: execnodes.h:744
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 
)

Definition at line 2511 of file execMain.c.

2513 {
2514  Index rtsize = parentestate->es_range_table_size;
2515 
2516  /* initialize data not changing over EPQState's lifetime */
2517  epqstate->parentestate = parentestate;
2518  epqstate->epqParam = epqParam;
2519 
2520  /*
2521  * Allocate space to reference a slot for each potential rti - do so now
2522  * rather than in EvalPlanQualBegin(), as done for other dynamically
2523  * allocated resources, so EvalPlanQualSlot() can be used to hold tuples
2524  * that *may* need EPQ later, without forcing the overhead of
2525  * EvalPlanQualBegin().
2526  */
2527  epqstate->tuple_table = NIL;
2528  epqstate->relsubs_slot = (TupleTableSlot **)
2529  palloc0(rtsize * sizeof(TupleTableSlot *));
2530 
2531  /* ... and remember data that EvalPlanQualBegin will need */
2532  epqstate->plan = subplan;
2533  epqstate->arowMarks = auxrowmarks;
2534 
2535  /* ... and mark the EPQ state inactive */
2536  epqstate->origslot = NULL;
2537  epqstate->recheckestate = NULL;
2538  epqstate->recheckplanstate = NULL;
2539  epqstate->relsubs_rowmark = NULL;
2540  epqstate->relsubs_done = NULL;
2541 }
void * palloc0(Size size)
Definition: mcxt.c:1241
List * arowMarks
Definition: execnodes.h:1189

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

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

◆ EvalPlanQualNext()

TupleTableSlot* EvalPlanQualNext ( EPQState epqstate)

Definition at line 2704 of file execMain.c.

2705 {
2706  MemoryContext oldcontext;
2707  TupleTableSlot *slot;
2708 
2709  oldcontext = MemoryContextSwitchTo(epqstate->recheckestate->es_query_cxt);
2710  slot = ExecProcNode(epqstate->recheckplanstate);
2711  MemoryContextSwitchTo(oldcontext);
2712 
2713  return slot;
2714 }
static TupleTableSlot * ExecProcNode(PlanState *node)
Definition: executor.h:257

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

2551 {
2552  /* If we have a live EPQ query, shut it down */
2553  EvalPlanQualEnd(epqstate);
2554  /* And set/change the plan pointer */
2555  epqstate->plan = subplan;
2556  /* The rowmarks depend on the plan, too */
2557  epqstate->arowMarks = auxrowmarks;
2558 }
void EvalPlanQualEnd(EPQState *epqstate)
Definition: execMain.c:2933

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

Referenced by ExecInitModifyTable().

◆ EvalPlanQualSlot()

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

Definition at line 2567 of file execMain.c.

2569 {
2570  TupleTableSlot **slot;
2571 
2572  Assert(relation);
2573  Assert(rti > 0 && rti <= epqstate->parentestate->es_range_table_size);
2574  slot = &epqstate->relsubs_slot[rti - 1];
2575 
2576  if (*slot == NULL)
2577  {
2578  MemoryContext oldcontext;
2579 
2580  oldcontext = MemoryContextSwitchTo(epqstate->parentestate->es_query_cxt);
2581  *slot = table_slot_create(relation, &epqstate->tuple_table);
2582  MemoryContextSwitchTo(oldcontext);
2583  }
2584 
2585  return *slot;
2586 }
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 2781 of file execMain.c.

2782 {
2783  EState *parentestate = epqstate->parentestate;
2784  Index rtsize = parentestate->es_range_table_size;
2785  EState *rcestate;
2786  MemoryContext oldcontext;
2787  ListCell *l;
2788 
2789  epqstate->recheckestate = rcestate = CreateExecutorState();
2790 
2791  oldcontext = MemoryContextSwitchTo(rcestate->es_query_cxt);
2792 
2793  /* signal that this is an EState for executing EPQ */
2794  rcestate->es_epq_active = epqstate;
2795 
2796  /*
2797  * Child EPQ EStates share the parent's copy of unchanging state such as
2798  * the snapshot, rangetable, and external Param info. They need their own
2799  * copies of local state, including a tuple table, es_param_exec_vals,
2800  * result-rel info, etc.
2801  */
2802  rcestate->es_direction = ForwardScanDirection;
2803  rcestate->es_snapshot = parentestate->es_snapshot;
2804  rcestate->es_crosscheck_snapshot = parentestate->es_crosscheck_snapshot;
2805  rcestate->es_range_table = parentestate->es_range_table;
2806  rcestate->es_range_table_size = parentestate->es_range_table_size;
2807  rcestate->es_relations = parentestate->es_relations;
2808  rcestate->es_rowmarks = parentestate->es_rowmarks;
2809  rcestate->es_rteperminfos = parentestate->es_rteperminfos;
2810  rcestate->es_plannedstmt = parentestate->es_plannedstmt;
2811  rcestate->es_junkFilter = parentestate->es_junkFilter;
2812  rcestate->es_output_cid = parentestate->es_output_cid;
2813  rcestate->es_queryEnv = parentestate->es_queryEnv;
2814 
2815  /*
2816  * ResultRelInfos needed by subplans are initialized from scratch when the
2817  * subplans themselves are initialized.
2818  */
2819  rcestate->es_result_relations = NULL;
2820  /* es_trig_target_relations must NOT be copied */
2821  rcestate->es_top_eflags = parentestate->es_top_eflags;
2822  rcestate->es_instrument = parentestate->es_instrument;
2823  /* es_auxmodifytables must NOT be copied */
2824 
2825  /*
2826  * The external param list is simply shared from parent. The internal
2827  * param workspace has to be local state, but we copy the initial values
2828  * from the parent, so as to have access to any param values that were
2829  * already set from other parts of the parent's plan tree.
2830  */
2831  rcestate->es_param_list_info = parentestate->es_param_list_info;
2832  if (parentestate->es_plannedstmt->paramExecTypes != NIL)
2833  {
2834  int i;
2835 
2836  /*
2837  * Force evaluation of any InitPlan outputs that could be needed by
2838  * the subplan. (With more complexity, maybe we could postpone this
2839  * till the subplan actually demands them, but it doesn't seem worth
2840  * the trouble; this is a corner case already, since usually the
2841  * InitPlans would have been evaluated before reaching EvalPlanQual.)
2842  *
2843  * This will not touch output params of InitPlans that occur somewhere
2844  * within the subplan tree, only those that are attached to the
2845  * ModifyTable node or above it and are referenced within the subplan.
2846  * That's OK though, because the planner would only attach such
2847  * InitPlans to a lower-level SubqueryScan node, and EPQ execution
2848  * will not descend into a SubqueryScan.
2849  *
2850  * The EState's per-output-tuple econtext is sufficiently short-lived
2851  * for this, since it should get reset before there is any chance of
2852  * doing EvalPlanQual again.
2853  */
2854  ExecSetParamPlanMulti(planTree->extParam,
2855  GetPerTupleExprContext(parentestate));
2856 
2857  /* now make the internal param workspace ... */
2858  i = list_length(parentestate->es_plannedstmt->paramExecTypes);
2859  rcestate->es_param_exec_vals = (ParamExecData *)
2860  palloc0(i * sizeof(ParamExecData));
2861  /* ... and copy down all values, whether really needed or not */
2862  while (--i >= 0)
2863  {
2864  /* copy value if any, but not execPlan link */
2865  rcestate->es_param_exec_vals[i].value =
2866  parentestate->es_param_exec_vals[i].value;
2867  rcestate->es_param_exec_vals[i].isnull =
2868  parentestate->es_param_exec_vals[i].isnull;
2869  }
2870  }
2871 
2872  /*
2873  * Initialize private state information for each SubPlan. We must do this
2874  * before running ExecInitNode on the main query tree, since
2875  * ExecInitSubPlan expects to be able to find these entries. Some of the
2876  * SubPlans might not be used in the part of the plan tree we intend to
2877  * run, but since it's not easy to tell which, we just initialize them
2878  * all.
2879  */
2880  Assert(rcestate->es_subplanstates == NIL);
2881  foreach(l, parentestate->es_plannedstmt->subplans)
2882  {
2883  Plan *subplan = (Plan *) lfirst(l);
2884  PlanState *subplanstate;
2885 
2886  subplanstate = ExecInitNode(subplan, rcestate, 0);
2887  rcestate->es_subplanstates = lappend(rcestate->es_subplanstates,
2888  subplanstate);
2889  }
2890 
2891  /*
2892  * Build an RTI indexed array of rowmarks, so that
2893  * EvalPlanQualFetchRowMark() can efficiently access the to be fetched
2894  * rowmark.
2895  */
2896  epqstate->relsubs_rowmark = (ExecAuxRowMark **)
2897  palloc0(rtsize * sizeof(ExecAuxRowMark *));
2898  foreach(l, epqstate->arowMarks)
2899  {
2900  ExecAuxRowMark *earm = (ExecAuxRowMark *) lfirst(l);
2901 
2902  epqstate->relsubs_rowmark[earm->rowmark->rti - 1] = earm;
2903  }
2904 
2905  /*
2906  * Initialize per-relation EPQ tuple states to not-fetched.
2907  */
2908  epqstate->relsubs_done = (bool *)
2909  palloc0(rtsize * sizeof(bool));
2910 
2911  /*
2912  * Initialize the private state information for all the nodes in the part
2913  * of the plan tree we need to run. This opens files, allocates storage
2914  * and leaves us ready to start processing tuples.
2915  */
2916  epqstate->recheckplanstate = ExecInitNode(planTree, rcestate, 0);
2917 
2918  MemoryContextSwitchTo(oldcontext);
2919 }
PlanState * ExecInitNode(Plan *node, EState *estate, int eflags)
Definition: execProcnode.c:142
EState * CreateExecutorState(void)
Definition: execUtils.c:93
List * lappend(List *list, void *datum)
Definition: list.c:338
@ ForwardScanDirection
Definition: sdir.h:28
struct ExecRowMark ** es_rowmarks
Definition: execnodes.h:622
int es_top_eflags
Definition: execnodes.h:666
int es_instrument
Definition: execnodes.h:667
QueryEnvironment * es_queryEnv
Definition: execnodes.h:657
ResultRelInfo ** es_result_relations
Definition: execnodes.h:635
List * es_range_table
Definition: execnodes.h:618
List * es_rteperminfos
Definition: execnodes.h:624
ParamListInfo es_param_list_info
Definition: execnodes.h:654
ScanDirection es_direction
Definition: execnodes.h:615
struct EPQState * es_epq_active
Definition: execnodes.h:689
Relation * es_relations
Definition: execnodes.h:620
CommandId es_output_cid
Definition: execnodes.h:632
Snapshot es_snapshot
Definition: execnodes.h:616
JunkFilter * es_junkFilter
Definition: execnodes.h:629
Snapshot es_crosscheck_snapshot
Definition: execnodes.h:617
List * subplans
Definition: plannodes.h:86

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, list_length(), MemoryContextSwitchTo(), NIL, palloc0(), PlannedStmt::paramExecTypes, EPQState::parentestate, EPQState::recheckestate, EPQState::recheckplanstate, EPQState::relsubs_done, EPQState::relsubs_rowmark, ExecAuxRowMark::rowmark, ExecRowMark::rti, PlannedStmt::subplans, and ParamExecData::value.

Referenced by EvalPlanQualBegin().

◆ ExecBuildAuxRowMark()

ExecAuxRowMark* ExecBuildAuxRowMark ( ExecRowMark erm,
List targetlist 
)

Definition at line 2387 of file execMain.c.

2388 {
2389  ExecAuxRowMark *aerm = (ExecAuxRowMark *) palloc0(sizeof(ExecAuxRowMark));
2390  char resname[32];
2391 
2392  aerm->rowmark = erm;
2393 
2394  /* Look up the resjunk columns associated with this rowmark */
2395  if (erm->markType != ROW_MARK_COPY)
2396  {
2397  /* need ctid for all methods other than COPY */
2398  snprintf(resname, sizeof(resname), "ctid%u", erm->rowmarkId);
2399  aerm->ctidAttNo = ExecFindJunkAttributeInTlist(targetlist,
2400  resname);
2401  if (!AttributeNumberIsValid(aerm->ctidAttNo))
2402  elog(ERROR, "could not find junk %s column", resname);
2403  }
2404  else
2405  {
2406  /* need wholerow if COPY */
2407  snprintf(resname, sizeof(resname), "wholerow%u", erm->rowmarkId);
2408  aerm->wholeAttNo = ExecFindJunkAttributeInTlist(targetlist,
2409  resname);
2410  if (!AttributeNumberIsValid(aerm->wholeAttNo))
2411  elog(ERROR, "could not find junk %s column", resname);
2412  }
2413 
2414  /* if child rel, need tableoid */
2415  if (erm->rti != erm->prti)
2416  {
2417  snprintf(resname, sizeof(resname), "tableoid%u", erm->rowmarkId);
2418  aerm->toidAttNo = ExecFindJunkAttributeInTlist(targetlist,
2419  resname);
2420  if (!AttributeNumberIsValid(aerm->toidAttNo))
2421  elog(ERROR, "could not find junk %s column", resname);
2422  }
2423 
2424  return aerm;
2425 }
#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:743

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

2206 {
2208  StringInfoData collist;
2209  bool write_comma = false;
2210  bool write_comma_collist = false;
2211  int i;
2212  AclResult aclresult;
2213  bool table_perm = false;
2214  bool any_perm = false;
2215 
2216  /*
2217  * Check if RLS is enabled and should be active for the relation; if so,
2218  * then don't return anything. Otherwise, go through normal permission
2219  * checks.
2220  */
2221  if (check_enable_rls(reloid, InvalidOid, true) == RLS_ENABLED)
2222  return NULL;
2223 
2224  initStringInfo(&buf);
2225 
2226  appendStringInfoChar(&buf, '(');
2227 
2228  /*
2229  * Check if the user has permissions to see the row. Table-level SELECT
2230  * allows access to all columns. If the user does not have table-level
2231  * SELECT then we check each column and include those the user has SELECT
2232  * rights on. Additionally, we always include columns the user provided
2233  * data for.
2234  */
2235  aclresult = pg_class_aclcheck(reloid, GetUserId(), ACL_SELECT);
2236  if (aclresult != ACLCHECK_OK)
2237  {
2238  /* Set up the buffer for the column list */
2239  initStringInfo(&collist);
2240  appendStringInfoChar(&collist, '(');
2241  }
2242  else
2243  table_perm = any_perm = true;
2244 
2245  /* Make sure the tuple is fully deconstructed */
2246  slot_getallattrs(slot);
2247 
2248  for (i = 0; i < tupdesc->natts; i++)
2249  {
2250  bool column_perm = false;
2251  char *val;
2252  int vallen;
2253  Form_pg_attribute att = TupleDescAttr(tupdesc, i);
2254 
2255  /* ignore dropped columns */
2256  if (att->attisdropped)
2257  continue;
2258 
2259  if (!table_perm)
2260  {
2261  /*
2262  * No table-level SELECT, so need to make sure they either have
2263  * SELECT rights on the column or that they have provided the data
2264  * for the column. If not, omit this column from the error
2265  * message.
2266  */
2267  aclresult = pg_attribute_aclcheck(reloid, att->attnum,
2268  GetUserId(), ACL_SELECT);
2270  modifiedCols) || aclresult == ACLCHECK_OK)
2271  {
2272  column_perm = any_perm = true;
2273 
2274  if (write_comma_collist)
2275  appendStringInfoString(&collist, ", ");
2276  else
2277  write_comma_collist = true;
2278 
2279  appendStringInfoString(&collist, NameStr(att->attname));
2280  }
2281  }
2282 
2283  if (table_perm || column_perm)
2284  {
2285  if (slot->tts_isnull[i])
2286  val = "null";
2287  else
2288  {
2289  Oid foutoid;
2290  bool typisvarlena;
2291 
2292  getTypeOutputInfo(att->atttypid,
2293  &foutoid, &typisvarlena);
2294  val = OidOutputFunctionCall(foutoid, slot->tts_values[i]);
2295  }
2296 
2297  if (write_comma)
2298  appendStringInfoString(&buf, ", ");
2299  else
2300  write_comma = true;
2301 
2302  /* truncate if needed */
2303  vallen = strlen(val);
2304  if (vallen <= maxfieldlen)
2305  appendBinaryStringInfo(&buf, val, vallen);
2306  else
2307  {
2308  vallen = pg_mbcliplen(val, vallen, maxfieldlen);
2309  appendBinaryStringInfo(&buf, val, vallen);
2310  appendStringInfoString(&buf, "...");
2311  }
2312  }
2313  }
2314 
2315  /* If we end up with zero columns being returned, then return NULL. */
2316  if (!any_perm)
2317  return NULL;
2318 
2319  appendStringInfoChar(&buf, ')');
2320 
2321  if (!table_perm)
2322  {
2323  appendStringInfoString(&collist, ") = ");
2324  appendBinaryStringInfo(&collist, buf.data, buf.len);
2325 
2326  return collist.data;
2327  }
2328 
2329  return buf.data;
2330 }
AclResult
Definition: acl.h:182
@ ACLCHECK_OK
Definition: acl.h:183
AclResult pg_attribute_aclcheck(Oid table_oid, AttrNumber attnum, Oid roleid, AclMode mode)
Definition: aclchk.c:3802
AclResult pg_class_aclcheck(Oid table_oid, Oid roleid, AclMode mode)
Definition: aclchk.c:3931
bool bms_is_member(int x, const Bitmapset *a)
Definition: bitmapset.c:444
#define NameStr(name)
Definition: c.h:730
char * OidOutputFunctionCall(Oid functionId, Datum val)
Definition: fmgr.c:1750
long val
Definition: informix.c:664
void getTypeOutputInfo(Oid type, Oid *typOutput, bool *typIsVarlena)
Definition: lsyscache.c:2865
int pg_mbcliplen(const char *mbstr, int len, int limit)
Definition: mbutils.c:1084
Oid GetUserId(void)
Definition: miscinit.c:510
#define ACL_SELECT
Definition: parsenodes.h:84
FormData_pg_attribute * Form_pg_attribute
Definition: pg_attribute.h:207
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:128
Datum * tts_values
Definition: tuptable.h:126
#define FirstLowInvalidHeapAttributeNumber
Definition: sysattr.h:27
#define TupleDescAttr(tupdesc, i)
Definition: tupdesc.h:92
static void slot_getallattrs(TupleTableSlot *slot)
Definition: tuptable.h:362

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

608 {
609  AclMode requiredPerms;
610  AclMode relPerms;
611  AclMode remainingPerms;
612  Oid userid;
613  Oid relOid = perminfo->relid;
614 
615  requiredPerms = perminfo->requiredPerms;
616  Assert(requiredPerms != 0);
617 
618  /*
619  * userid to check as: current user unless we have a setuid indication.
620  *
621  * Note: GetUserId() is presently fast enough that there's no harm in
622  * calling it separately for each relation. If that stops being true, we
623  * could call it once in ExecCheckPermissions and pass the userid down
624  * from there. But for now, no need for the extra clutter.
625  */
626  userid = OidIsValid(perminfo->checkAsUser) ?
627  perminfo->checkAsUser : GetUserId();
628 
629  /*
630  * We must have *all* the requiredPerms bits, but some of the bits can be
631  * satisfied from column-level rather than relation-level permissions.
632  * First, remove any bits that are satisfied by relation permissions.
633  */
634  relPerms = pg_class_aclmask(relOid, userid, requiredPerms, ACLMASK_ALL);
635  remainingPerms = requiredPerms & ~relPerms;
636  if (remainingPerms != 0)
637  {
638  int col = -1;
639 
640  /*
641  * If we lack any permissions that exist only as relation permissions,
642  * we can fail straight away.
643  */
644  if (remainingPerms & ~(ACL_SELECT | ACL_INSERT | ACL_UPDATE))
645  return false;
646 
647  /*
648  * Check to see if we have the needed privileges at column level.
649  *
650  * Note: failures just report a table-level error; it would be nicer
651  * to report a column-level error if we have some but not all of the
652  * column privileges.
653  */
654  if (remainingPerms & ACL_SELECT)
655  {
656  /*
657  * When the query doesn't explicitly reference any columns (for
658  * example, SELECT COUNT(*) FROM table), allow the query if we
659  * have SELECT on any column of the rel, as per SQL spec.
660  */
661  if (bms_is_empty(perminfo->selectedCols))
662  {
663  if (pg_attribute_aclcheck_all(relOid, userid, ACL_SELECT,
665  return false;
666  }
667 
668  while ((col = bms_next_member(perminfo->selectedCols, col)) >= 0)
669  {
670  /* bit #s are offset by FirstLowInvalidHeapAttributeNumber */
672 
673  if (attno == InvalidAttrNumber)
674  {
675  /* Whole-row reference, must have priv on all cols */
676  if (pg_attribute_aclcheck_all(relOid, userid, ACL_SELECT,
678  return false;
679  }
680  else
681  {
682  if (pg_attribute_aclcheck(relOid, attno, userid,
684  return false;
685  }
686  }
687  }
688 
689  /*
690  * Basically the same for the mod columns, for both INSERT and UPDATE
691  * privilege as specified by remainingPerms.
692  */
693  if (remainingPerms & ACL_INSERT &&
695  userid,
696  perminfo->insertedCols,
697  ACL_INSERT))
698  return false;
699 
700  if (remainingPerms & ACL_UPDATE &&
702  userid,
703  perminfo->updatedCols,
704  ACL_UPDATE))
705  return false;
706  }
707  return true;
708 }
@ ACLMASK_ANY
Definition: acl.h:177
@ ACLMASK_ALL
Definition: acl.h:176
AclResult pg_attribute_aclcheck_all(Oid table_oid, Oid roleid, AclMode mode, AclMaskHow how)
Definition: aclchk.c:3846
AclMode pg_class_aclmask(Oid table_oid, Oid roleid, AclMode mask, AclMaskHow how)
Definition: aclchk.c:3275
int16 AttrNumber
Definition: attnum.h:21
#define InvalidAttrNumber
Definition: attnum.h:23
int bms_next_member(const Bitmapset *a, int prevbit)
Definition: bitmapset.c:1039
#define bms_is_empty(a)
Definition: bitmapset.h:105
static bool ExecCheckPermissionsModified(Oid relOid, Oid userid, Bitmapset *modifiedCols, AclMode requiredPerms)
Definition: execMain.c:716
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:1248
AclMode requiredPerms
Definition: parsenodes.h:1246
Bitmapset * insertedCols
Definition: parsenodes.h:1249
Bitmapset * updatedCols
Definition: parsenodes.h:1250

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

576 {
577  ListCell *l;
578  bool result = true;
579 
580  foreach(l, rteperminfos)
581  {
583 
584  Assert(OidIsValid(perminfo->relid));
585  result = ExecCheckOneRelPerms(perminfo);
586  if (!result)
587  {
588  if (ereport_on_violation)
591  get_rel_name(perminfo->relid));
592  return false;
593  }
594  }
595 
597  result = (*ExecutorCheckPerms_hook) (rangeTable, rteperminfos,
598  ereport_on_violation);
599  return result;
600 }
@ ACLCHECK_NO_PRIV
Definition: acl.h:184
void aclcheck_error(AclResult aclerr, ObjectType objtype, const char *objectname)
Definition: aclchk.c:2679
static bool ExecCheckOneRelPerms(RTEPermissionInfo *perminfo)
Definition: execMain.c:607
ExecutorCheckPerms_hook_type ExecutorCheckPerms_hook
Definition: execMain.c:79
char get_rel_relkind(Oid relid)
Definition: lsyscache.c:1985
char * get_rel_name(Oid relid)
Definition: lsyscache.c:1910
ObjectType get_relkind_objtype(char relkind)
#define lfirst_node(type, lc)
Definition: pg_list.h:176

References aclcheck_error(), ACLCHECK_NO_PRIV, Assert(), ExecCheckOneRelPerms(), ExecutorCheckPerms_hook, get_rel_name(), get_rel_relkind(), get_relkind_objtype(), lfirst_node, OidIsValid, and RTEPermissionInfo::relid.

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

◆ ExecCheckPermissionsModified()

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

Definition at line 716 of file execMain.c.

718 {
719  int col = -1;
720 
721  /*
722  * When the query doesn't explicitly update any columns, allow the query
723  * if we have permission on any column of the rel. This is to handle
724  * SELECT FOR UPDATE as well as possible corner cases in UPDATE.
725  */
726  if (bms_is_empty(modifiedCols))
727  {
728  if (pg_attribute_aclcheck_all(relOid, userid, requiredPerms,
730  return false;
731  }
732 
733  while ((col = bms_next_member(modifiedCols, col)) >= 0)
734  {
735  /* bit #s are offset by FirstLowInvalidHeapAttributeNumber */
737 
738  if (attno == InvalidAttrNumber)
739  {
740  /* whole-row reference can't happen here */
741  elog(ERROR, "whole-row update is not implemented");
742  }
743  else
744  {
745  if (pg_attribute_aclcheck(relOid, attno, userid,
746  requiredPerms) != ACLCHECK_OK)
747  return false;
748  }
749  }
750  return true;
751 }

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

764 {
765  ListCell *l;
766 
767  /*
768  * Fail if write permissions are requested in parallel mode for table
769  * (temp or non-temp), otherwise fail for any non-temp table.
770  */
771  foreach(l, plannedstmt->permInfos)
772  {
774 
775  if ((perminfo->requiredPerms & (~ACL_SELECT)) == 0)
776  continue;
777 
778  if (isTempNamespace(get_rel_namespace(perminfo->relid)))
779  continue;
780 
782  }
783 
784  if (plannedstmt->commandType != CMD_SELECT || plannedstmt->hasModifyingCTE)
786 }
Oid get_rel_namespace(Oid relid)
Definition: lsyscache.c:1934
bool isTempNamespace(Oid namespaceId)
Definition: namespace.c:3200
@ CMD_SELECT
Definition: nodes.h:276
Definition: nodes.h:129
bool hasModifyingCTE
Definition: plannodes.h:59
List * permInfos
Definition: plannodes.h:78
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 1564 of file execMain.c.

1565 {
1566  int i;
1567 
1568  for (i = 0; i < estate->es_range_table_size; i++)
1569  {
1570  if (estate->es_relations[i])
1571  table_close(estate->es_relations[i], NoLock);
1572  }
1573 }
#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 1504 of file execMain.c.

1505 {
1506  ListCell *l;
1507 
1508  /*
1509  * close indexes of result relation(s) if any. (Rels themselves are
1510  * closed in ExecCloseRangeTableRelations())
1511  *
1512  * In addition, close the stub RTs that may be in each resultrel's
1513  * ri_ancestorResultRels.
1514  */
1515  foreach(l, estate->es_opened_result_relations)
1516  {
1517  ResultRelInfo *resultRelInfo = lfirst(l);
1518  ListCell *lc;
1519 
1520  ExecCloseIndices(resultRelInfo);
1521  foreach(lc, resultRelInfo->ri_ancestorResultRels)
1522  {
1523  ResultRelInfo *rInfo = lfirst(lc);
1524 
1525  /*
1526  * Ancestors with RTI > 0 (should only be the root ancestor) are
1527  * closed by ExecCloseRangeTableRelations.
1528  */
1529  if (rInfo->ri_RangeTableIndex > 0)
1530  continue;
1531 
1533  }
1534  }
1535 
1536  /* Close any relations that have been opened by ExecGetTriggerResultRel(). */
1537  foreach(l, estate->es_trig_target_relations)
1538  {
1539  ResultRelInfo *resultRelInfo = (ResultRelInfo *) lfirst(l);
1540 
1541  /*
1542  * Assert this is a "dummy" ResultRelInfo, see above. Otherwise we
1543  * might be issuing a duplicate close against a Relation opened by
1544  * ExecGetRangeTableRelation.
1545  */
1546  Assert(resultRelInfo->ri_RangeTableIndex == 0);
1547 
1548  /*
1549  * Since ExecGetTriggerResultRel doesn't call ExecOpenIndices for
1550  * these rels, we needn't call ExecCloseIndices either.
1551  */
1552  Assert(resultRelInfo->ri_NumIndices == 0);
1553 
1554  table_close(resultRelInfo->ri_RelationDesc, NoLock);
1555  }
1556 }
void ExecCloseIndices(ResultRelInfo *resultRelInfo)
Definition: execIndexing.c:231
List * es_trig_target_relations
Definition: execnodes.h:651
List * es_opened_result_relations
Definition: execnodes.h:638
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 1903 of file execMain.c.

1905 {
1906  Relation rel = resultRelInfo->ri_RelationDesc;
1907  TupleDesc tupdesc = RelationGetDescr(rel);
1908  TupleConstr *constr = tupdesc->constr;
1909  Bitmapset *modifiedCols;
1910 
1911  Assert(constr); /* we should not be called otherwise */
1912 
1913  if (constr->has_not_null)
1914  {
1915  int natts = tupdesc->natts;
1916  int attrChk;
1917 
1918  for (attrChk = 1; attrChk <= natts; attrChk++)
1919  {
1920  Form_pg_attribute att = TupleDescAttr(tupdesc, attrChk - 1);
1921 
1922  if (att->attnotnull && slot_attisnull(slot, attrChk))
1923  {
1924  char *val_desc;
1925  Relation orig_rel = rel;
1926  TupleDesc orig_tupdesc = RelationGetDescr(rel);
1927 
1928  /*
1929  * If the tuple has been routed, it's been converted to the
1930  * partition's rowtype, which might differ from the root
1931  * table's. We must convert it back to the root table's
1932  * rowtype so that val_desc shown error message matches the
1933  * input tuple.
1934  */
1935  if (resultRelInfo->ri_RootResultRelInfo)
1936  {
1937  ResultRelInfo *rootrel = resultRelInfo->ri_RootResultRelInfo;
1938  AttrMap *map;
1939 
1940  tupdesc = RelationGetDescr(rootrel->ri_RelationDesc);
1941  /* a reverse map */
1942  map = build_attrmap_by_name_if_req(orig_tupdesc,
1943  tupdesc,
1944  false);
1945 
1946  /*
1947  * Partition-specific slot's tupdesc can't be changed, so
1948  * allocate a new one.
1949  */
1950  if (map != NULL)
1951  slot = execute_attr_map_slot(map, slot,
1952  MakeTupleTableSlot(tupdesc, &TTSOpsVirtual));
1953  modifiedCols = bms_union(ExecGetInsertedCols(rootrel, estate),
1954  ExecGetUpdatedCols(rootrel, estate));
1955  rel = rootrel->ri_RelationDesc;
1956  }
1957  else
1958  modifiedCols = bms_union(ExecGetInsertedCols(resultRelInfo, estate),
1959  ExecGetUpdatedCols(resultRelInfo, estate));
1961  slot,
1962  tupdesc,
1963  modifiedCols,
1964  64);
1965 
1966  ereport(ERROR,
1967  (errcode(ERRCODE_NOT_NULL_VIOLATION),
1968  errmsg("null value in column \"%s\" of relation \"%s\" violates not-null constraint",
1969  NameStr(att->attname),
1970  RelationGetRelationName(orig_rel)),
1971  val_desc ? errdetail("Failing row contains %s.", val_desc) : 0,
1972  errtablecol(orig_rel, attrChk)));
1973  }
1974  }
1975  }
1976 
1977  if (rel->rd_rel->relchecks > 0)
1978  {
1979  const char *failed;
1980 
1981  if ((failed = ExecRelCheck(resultRelInfo, slot, estate)) != NULL)
1982  {
1983  char *val_desc;
1984  Relation orig_rel = rel;
1985 
1986  /* See the comment above. */
1987  if (resultRelInfo->ri_RootResultRelInfo)
1988  {
1989  ResultRelInfo *rootrel = resultRelInfo->ri_RootResultRelInfo;
1990  TupleDesc old_tupdesc = RelationGetDescr(rel);
1991  AttrMap *map;
1992 
1993  tupdesc = RelationGetDescr(rootrel->ri_RelationDesc);
1994  /* a reverse map */
1995  map = build_attrmap_by_name_if_req(old_tupdesc,
1996  tupdesc,
1997  false);
1998 
1999  /*
2000  * Partition-specific slot's tupdesc can't be changed, so
2001  * allocate a new one.
2002  */
2003  if (map != NULL)
2004  slot = execute_attr_map_slot(map, slot,
2005  MakeTupleTableSlot(tupdesc, &TTSOpsVirtual));
2006  modifiedCols = bms_union(ExecGetInsertedCols(rootrel, estate),
2007  ExecGetUpdatedCols(rootrel, estate));
2008  rel = rootrel->ri_RelationDesc;
2009  }
2010  else
2011  modifiedCols = bms_union(ExecGetInsertedCols(resultRelInfo, estate),
2012  ExecGetUpdatedCols(resultRelInfo, estate));
2014  slot,
2015  tupdesc,
2016  modifiedCols,
2017  64);
2018  ereport(ERROR,
2019  (errcode(ERRCODE_CHECK_VIOLATION),
2020  errmsg("new row for relation \"%s\" violates check constraint \"%s\"",
2021  RelationGetRelationName(orig_rel), failed),
2022  val_desc ? errdetail("Failing row contains %s.", val_desc) : 0,
2023  errtableconstraint(orig_rel, failed)));
2024  }
2025  }
2026 }
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:226
int errdetail(const char *fmt,...)
Definition: elog.c:1202
static const char * ExecRelCheck(ResultRelInfo *resultRelInfo, TupleTableSlot *slot, EState *estate)
Definition: execMain.c:1704
static char * ExecBuildSlotValueDescription(Oid reloid, TupleTableSlot *slot, TupleDesc tupdesc, Bitmapset *modifiedCols, int maxfieldlen)
Definition: execMain.c:2201
TupleTableSlot * MakeTupleTableSlot(TupleDesc tupleDesc, const TupleTableSlotOps *tts_ops)
Definition: execTuples.c:1112
const TupleTableSlotOps TTSOpsVirtual
Definition: execTuples.c:83
Bitmapset * ExecGetUpdatedCols(ResultRelInfo *relinfo, EState *estate)
Definition: execUtils.c:1319
Bitmapset * ExecGetInsertedCols(ResultRelInfo *relinfo, EState *estate)
Definition: execUtils.c:1298
#define RelationGetRelid(relation)
Definition: rel.h:503
#define RelationGetDescr(relation)
Definition: rel.h:529
int errtableconstraint(Relation rel, const char *conname)
Definition: relcache.c:5960
int errtablecol(Relation rel, int attnum)
Definition: relcache.c:5923
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:375

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

1466 {
1467  ListCell *l;
1468 
1469  /*
1470  * shut down the node-type-specific query processing
1471  */
1472  ExecEndNode(planstate);
1473 
1474  /*
1475  * for subplans too
1476  */
1477  foreach(l, estate->es_subplanstates)
1478  {
1479  PlanState *subplanstate = (PlanState *) lfirst(l);
1480 
1481  ExecEndNode(subplanstate);
1482  }
1483 
1484  /*
1485  * destroy the executor's tuple table. Actually we only care about
1486  * releasing buffer pins and tupdesc refcounts; there's no need to pfree
1487  * the TupleTableSlots, since the containing memory context is about to go
1488  * away anyway.
1489  */
1490  ExecResetTupleTable(estate->es_tupleTable, false);
1491 
1492  /*
1493  * Close any Relations that have been opened for range table entries or
1494  * result relations.
1495  */
1496  ExecCloseResultRelations(estate);
1498 }
void ExecCloseRangeTableRelations(EState *estate)
Definition: execMain.c:1564

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

2365 {
2366  if (rti > 0 && rti <= estate->es_range_table_size &&
2367  estate->es_rowmarks != NULL)
2368  {
2369  ExecRowMark *erm = estate->es_rowmarks[rti - 1];
2370 
2371  if (erm)
2372  return erm;
2373  }
2374  if (!missing_ok)
2375  elog(ERROR, "failed to find ExecRowMark for rangetable index %u", rti);
2376  return NULL;
2377 }

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

Referenced by ExecInitLockRows(), and ExecInitModifyTable().

◆ ExecGetAncestorResultRels()

List* ExecGetAncestorResultRels ( EState estate,
ResultRelInfo resultRelInfo 
)

Definition at line 1359 of file execMain.c.

1360 {
1361  ResultRelInfo *rootRelInfo = resultRelInfo->ri_RootResultRelInfo;
1362  Relation partRel = resultRelInfo->ri_RelationDesc;
1363  Oid rootRelOid;
1364 
1365  if (!partRel->rd_rel->relispartition)
1366  elog(ERROR, "cannot find ancestors of a non-partition result relation");
1367  Assert(rootRelInfo != NULL);
1368  rootRelOid = RelationGetRelid(rootRelInfo->ri_RelationDesc);
1369  if (resultRelInfo->ri_ancestorResultRels == NIL)
1370  {
1371  ListCell *lc;
1372  List *oids = get_partition_ancestors(RelationGetRelid(partRel));
1373  List *ancResultRels = NIL;
1374 
1375  foreach(lc, oids)
1376  {
1377  Oid ancOid = lfirst_oid(lc);
1378  Relation ancRel;
1379  ResultRelInfo *rInfo;
1380 
1381  /*
1382  * Ignore the root ancestor here, and use ri_RootResultRelInfo
1383  * (below) for it instead. Also, we stop climbing up the
1384  * hierarchy when we find the table that was mentioned in the
1385  * query.
1386  */
1387  if (ancOid == rootRelOid)
1388  break;
1389 
1390  /*
1391  * All ancestors up to the root target relation must have been
1392  * locked by the planner or AcquireExecutorLocks().
1393  */
1394  ancRel = table_open(ancOid, NoLock);
1395  rInfo = makeNode(ResultRelInfo);
1396 
1397  /* dummy rangetable index */
1398  InitResultRelInfo(rInfo, ancRel, 0, NULL,
1399  estate->es_instrument);
1400  ancResultRels = lappend(ancResultRels, rInfo);
1401  }
1402  ancResultRels = lappend(ancResultRels, rootRelInfo);
1403  resultRelInfo->ri_ancestorResultRels = ancResultRels;
1404  }
1405 
1406  /* We must have found some ancestor */
1407  Assert(resultRelInfo->ri_ancestorResultRels != NIL);
1408 
1409  return resultRelInfo->ri_ancestorResultRels;
1410 }
void InitResultRelInfo(ResultRelInfo *resultRelInfo, Relation resultRelationDesc, Index resultRelationIndex, ResultRelInfo *partition_root_rri, int instrument_options)
Definition: execMain.c:1188
#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 1283 of file execMain.c.

1285 {
1286  ResultRelInfo *rInfo;
1287  ListCell *l;
1288  Relation rel;
1289  MemoryContext oldcontext;
1290 
1291  /* Search through the query result relations */
1292  foreach(l, estate->es_opened_result_relations)
1293  {
1294  rInfo = lfirst(l);
1295  if (RelationGetRelid(rInfo->ri_RelationDesc) == relid)
1296  return rInfo;
1297  }
1298 
1299  /*
1300  * Search through the result relations that were created during tuple
1301  * routing, if any.
1302  */
1303  foreach(l, estate->es_tuple_routing_result_relations)
1304  {
1305  rInfo = (ResultRelInfo *) lfirst(l);
1306  if (RelationGetRelid(rInfo->ri_RelationDesc) == relid)
1307  return rInfo;
1308  }
1309 
1310  /* Nope, but maybe we already made an extra ResultRelInfo for it */
1311  foreach(l, estate->es_trig_target_relations)
1312  {
1313  rInfo = (ResultRelInfo *) lfirst(l);
1314  if (RelationGetRelid(rInfo->ri_RelationDesc) == relid)
1315  return rInfo;
1316  }
1317  /* Nope, so we need a new one */
1318 
1319  /*
1320  * Open the target relation's relcache entry. We assume that an
1321  * appropriate lock is still held by the backend from whenever the trigger
1322  * event got queued, so we need take no new lock here. Also, we need not
1323  * recheck the relkind, so no need for CheckValidResultRel.
1324  */
1325  rel = table_open(relid, NoLock);
1326 
1327  /*
1328  * Make the new entry in the right context.
1329  */
1330  oldcontext = MemoryContextSwitchTo(estate->es_query_cxt);
1331  rInfo = makeNode(ResultRelInfo);
1332  InitResultRelInfo(rInfo,
1333  rel,
1334  0, /* dummy rangetable index */
1335  rootRelInfo,
1336  estate->es_instrument);
1337  estate->es_trig_target_relations =
1338  lappend(estate->es_trig_target_relations, rInfo);
1339  MemoryContextSwitchTo(oldcontext);
1340 
1341  /*
1342  * Currently, we don't need any index information in ResultRelInfos used
1343  * only for triggers, so no need to call ExecOpenIndices.
1344  */
1345 
1346  return rInfo;
1347 }
List * es_tuple_routing_result_relations
Definition: execnodes.h:648

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

1781 {
1782  ExprContext *econtext;
1783  bool success;
1784 
1785  /*
1786  * If first time through, build expression state tree for the partition
1787  * check expression. (In the corner case where the partition check
1788  * expression is empty, ie there's a default partition and nothing else,
1789  * we'll be fooled into executing this code each time through. But it's
1790  * pretty darn cheap in that case, so we don't worry about it.)
1791  */
1792  if (resultRelInfo->ri_PartitionCheckExpr == NULL)
1793  {
1794  /*
1795  * Ensure that the qual tree and prepared expression are in the
1796  * query-lifespan context.
1797  */
1799  List *qual = RelationGetPartitionQual(resultRelInfo->ri_RelationDesc);
1800 
1801  resultRelInfo->ri_PartitionCheckExpr = ExecPrepareCheck(qual, estate);
1802  MemoryContextSwitchTo(oldcxt);
1803  }
1804 
1805  /*
1806  * We will use the EState's per-tuple context for evaluating constraint
1807  * expressions (creating it if it's not already there).
1808  */
1809  econtext = GetPerTupleExprContext(estate);
1810 
1811  /* Arrange for econtext's scan tuple to be the tuple under test */
1812  econtext->ecxt_scantuple = slot;
1813 
1814  /*
1815  * As in case of the catalogued constraints, we treat a NULL result as
1816  * success here, not a failure.
1817  */
1818  success = ExecCheck(resultRelInfo->ri_PartitionCheckExpr, econtext);
1819 
1820  /* if asked to emit error, don't actually return on failure */
1821  if (!success && emitError)
1822  ExecPartitionCheckEmitError(resultRelInfo, slot, estate);
1823 
1824  return success;
1825 }
bool ExecCheck(ExprState *state, ExprContext *econtext)
Definition: execExpr.c:842
ExprState * ExecPrepareCheck(List *qual, EState *estate)
Definition: execExpr.c:786
void ExecPartitionCheckEmitError(ResultRelInfo *resultRelInfo, TupleTableSlot *slot, EState *estate)
Definition: execMain.c:1832
static bool success
Definition: initdb.c:178
List * RelationGetPartitionQual(Relation rel)
Definition: partcache.c:282
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 1832 of file execMain.c.

1835 {
1836  Oid root_relid;
1837  TupleDesc tupdesc;
1838  char *val_desc;
1839  Bitmapset *modifiedCols;
1840 
1841  /*
1842  * If the tuple has been routed, it's been converted to the partition's
1843  * rowtype, which might differ from the root table's. We must convert it
1844  * back to the root table's rowtype so that val_desc in the error message
1845  * matches the input tuple.
1846  */
1847  if (resultRelInfo->ri_RootResultRelInfo)
1848  {
1849  ResultRelInfo *rootrel = resultRelInfo->ri_RootResultRelInfo;
1850  TupleDesc old_tupdesc;
1851  AttrMap *map;
1852 
1853  root_relid = RelationGetRelid(rootrel->ri_RelationDesc);
1854  tupdesc = RelationGetDescr(rootrel->ri_RelationDesc);
1855 
1856  old_tupdesc = RelationGetDescr(resultRelInfo->ri_RelationDesc);
1857  /* a reverse map */
1858  map = build_attrmap_by_name_if_req(old_tupdesc, tupdesc, false);
1859 
1860  /*
1861  * Partition-specific slot's tupdesc can't be changed, so allocate a
1862  * new one.
1863  */
1864  if (map != NULL)
1865  slot = execute_attr_map_slot(map, slot,
1866  MakeTupleTableSlot(tupdesc, &TTSOpsVirtual));
1867  modifiedCols = bms_union(ExecGetInsertedCols(rootrel, estate),
1868  ExecGetUpdatedCols(rootrel, estate));
1869  }
1870  else
1871  {
1872  root_relid = RelationGetRelid(resultRelInfo->ri_RelationDesc);
1873  tupdesc = RelationGetDescr(resultRelInfo->ri_RelationDesc);
1874  modifiedCols = bms_union(ExecGetInsertedCols(resultRelInfo, estate),
1875  ExecGetUpdatedCols(resultRelInfo, estate));
1876  }
1877 
1878  val_desc = ExecBuildSlotValueDescription(root_relid,
1879  slot,
1880  tupdesc,
1881  modifiedCols,
1882  64);
1883  ereport(ERROR,
1884  (errcode(ERRCODE_CHECK_VIOLATION),
1885  errmsg("new row for relation \"%s\" violates partition constraint",
1886  RelationGetRelationName(resultRelInfo->ri_RelationDesc)),
1887  val_desc ? errdetail("Failing row contains %s.", val_desc) : 0,
1888  errtable(resultRelInfo->ri_RelationDesc)));
1889 }
int errtable(Relation rel)
Definition: relcache.c:5906

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

1420 {
1421  ListCell *lc;
1422 
1423  /*
1424  * Make sure nodes run forward.
1425  */
1427 
1428  /*
1429  * Run any secondary ModifyTable nodes to completion, in case the main
1430  * query did not fetch all rows from them. (We do this to ensure that
1431  * such nodes have predictable results.)
1432  */
1433  foreach(lc, estate->es_auxmodifytables)
1434  {
1435  PlanState *ps = (PlanState *) lfirst(lc);
1436 
1437  for (;;)
1438  {
1439  TupleTableSlot *slot;
1440 
1441  /* Reset the per-output-tuple exprcontext each time */
1442  ResetPerTupleExprContext(estate);
1443 
1444  slot = ExecProcNode(ps);
1445 
1446  if (TupIsNull(slot))
1447  break;
1448  }
1449  }
1450 }
#define ResetPerTupleExprContext(estate)
Definition: executor.h:547
struct parser_state ps
List * es_auxmodifytables
Definition: execnodes.h:674

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

1706 {
1707  Relation rel = resultRelInfo->ri_RelationDesc;
1708  int ncheck = rel->rd_att->constr->num_check;
1709  ConstrCheck *check = rel->rd_att->constr->check;
1710  ExprContext *econtext;
1711  MemoryContext oldContext;
1712  int i;
1713 
1714  /*
1715  * CheckConstraintFetch let this pass with only a warning, but now we
1716  * should fail rather than possibly failing to enforce an important
1717  * constraint.
1718  */
1719  if (ncheck != rel->rd_rel->relchecks)
1720  elog(ERROR, "%d pg_constraint record(s) missing for relation \"%s\"",
1721  rel->rd_rel->relchecks - ncheck, RelationGetRelationName(rel));
1722 
1723  /*
1724  * If first time through for this result relation, build expression
1725  * nodetrees for rel's constraint expressions. Keep them in the per-query
1726  * memory context so they'll survive throughout the query.
1727  */
1728  if (resultRelInfo->ri_ConstraintExprs == NULL)
1729  {
1730  oldContext = MemoryContextSwitchTo(estate->es_query_cxt);
1731  resultRelInfo->ri_ConstraintExprs =
1732  (ExprState **) palloc(ncheck * sizeof(ExprState *));
1733  for (i = 0; i < ncheck; i++)
1734  {
1735  Expr *checkconstr;
1736 
1737  checkconstr = stringToNode(check[i].ccbin);
1738  resultRelInfo->ri_ConstraintExprs[i] =
1739  ExecPrepareExpr(checkconstr, estate);
1740  }
1741  MemoryContextSwitchTo(oldContext);
1742  }
1743 
1744  /*
1745  * We will use the EState's per-tuple context for evaluating constraint
1746  * expressions (creating it if it's not already there).
1747  */
1748  econtext = GetPerTupleExprContext(estate);
1749 
1750  /* Arrange for econtext's scan tuple to be the tuple under test */
1751  econtext->ecxt_scantuple = slot;
1752 
1753  /* And evaluate the constraints */
1754  for (i = 0; i < ncheck; i++)
1755  {
1756  ExprState *checkconstr = resultRelInfo->ri_ConstraintExprs[i];
1757 
1758  /*
1759  * NOTE: SQL specifies that a NULL result from a constraint expression
1760  * is not to be treated as a failure. Therefore, use ExecCheck not
1761  * ExecQual.
1762  */
1763  if (!ExecCheck(checkconstr, econtext))
1764  return check[i].ccname;
1765  }
1766 
1767  /* NULL result means no error */
1768  return NULL;
1769 }
ExprState * ExecPrepareExpr(Expr *node, EState *estate)
Definition: execExpr.c:735
void * palloc(Size size)
Definition: mcxt.c:1210
void * stringToNode(const char *str)
Definition: read.c:90
char * ccname
Definition: tupdesc.h:30
TupleDesc rd_att
Definition: rel.h:111
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 2338 of file execMain.c.

2339 {
2340  Bitmapset *keyCols;
2341  Bitmapset *updatedCols;
2342 
2343  /*
2344  * Compute lock mode to use. If columns that are part of the key have not
2345  * been modified, then we can use a weaker lock, allowing for better
2346  * concurrency.
2347  */
2348  updatedCols = ExecGetAllUpdatedCols(relinfo, estate);
2349  keyCols = RelationGetIndexAttrBitmap(relinfo->ri_RelationDesc,
2351 
2352  if (bms_overlap(keyCols, updatedCols))
2353  return LockTupleExclusive;
2354 
2355  return LockTupleNoKeyExclusive;
2356 }
bool bms_overlap(const Bitmapset *a, const Bitmapset *b)
Definition: bitmapset.c:511
Bitmapset * ExecGetAllUpdatedCols(ResultRelInfo *relinfo, EState *estate)
Definition: execUtils.c:1350
@ LockTupleExclusive
Definition: lockoptions.h:58
@ LockTupleNoKeyExclusive
Definition: lockoptions.h:56
Bitmapset * RelationGetIndexAttrBitmap(Relation relation, IndexAttrBitmapKind attrKind)
Definition: relcache.c:5169
@ INDEX_ATTR_BITMAP_KEY
Definition: relcache.h:59

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

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

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

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

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

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

529 {
530  EState *estate;
531  MemoryContext oldcontext;
532 
533  /* sanity checks */
534  Assert(queryDesc != NULL);
535 
536  estate = queryDesc->estate;
537 
538  Assert(estate != NULL);
539 
540  /* It's probably not sensible to rescan updating queries */
541  Assert(queryDesc->operation == CMD_SELECT);
542 
543  /*
544  * Switch into per-query memory context
545  */
546  oldcontext = MemoryContextSwitchTo(estate->es_query_cxt);
547 
548  /*
549  * rescan plan
550  */
551  ExecReScan(queryDesc->planstate);
552 
553  MemoryContextSwitchTo(oldcontext);
554 }
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 301 of file execMain.c.

304 {
305  if (ExecutorRun_hook)
306  (*ExecutorRun_hook) (queryDesc, direction, count, execute_once);
307  else
308  standard_ExecutorRun(queryDesc, direction, count, execute_once);
309 }
void standard_ExecutorRun(QueryDesc *queryDesc, ScanDirection direction, uint64 count, bool execute_once)
Definition: execMain.c:312
ExecutorRun_hook_type ExecutorRun_hook
Definition: execMain.c: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 2038 of file execMain.c.

2040 {
2041  Relation rel = resultRelInfo->ri_RelationDesc;
2042  TupleDesc tupdesc = RelationGetDescr(rel);
2043  ExprContext *econtext;
2044  ListCell *l1,
2045  *l2;
2046 
2047  /*
2048  * We will use the EState's per-tuple context for evaluating constraint
2049  * expressions (creating it if it's not already there).
2050  */
2051  econtext = GetPerTupleExprContext(estate);
2052 
2053  /* Arrange for econtext's scan tuple to be the tuple under test */
2054  econtext->ecxt_scantuple = slot;
2055 
2056  /* Check each of the constraints */
2057  forboth(l1, resultRelInfo->ri_WithCheckOptions,
2058  l2, resultRelInfo->ri_WithCheckOptionExprs)
2059  {
2060  WithCheckOption *wco = (WithCheckOption *) lfirst(l1);
2061  ExprState *wcoExpr = (ExprState *) lfirst(l2);
2062 
2063  /*
2064  * Skip any WCOs which are not the kind we are looking for at this
2065  * time.
2066  */
2067  if (wco->kind != kind)
2068  continue;
2069 
2070  /*
2071  * WITH CHECK OPTION checks are intended to ensure that the new tuple
2072  * is visible (in the case of a view) or that it passes the
2073  * 'with-check' policy (in the case of row security). If the qual
2074  * evaluates to NULL or FALSE, then the new tuple won't be included in
2075  * the view or doesn't pass the 'with-check' policy for the table.
2076  */
2077  if (!ExecQual(wcoExpr, econtext))
2078  {
2079  char *val_desc;
2080  Bitmapset *modifiedCols;
2081 
2082  switch (wco->kind)
2083  {
2084  /*
2085  * For WITH CHECK OPTIONs coming from views, we might be
2086  * able to provide the details on the row, depending on
2087  * the permissions on the relation (that is, if the user
2088  * could view it directly anyway). For RLS violations, we
2089  * don't include the data since we don't know if the user
2090  * should be able to view the tuple as that depends on the
2091  * USING policy.
2092  */
2093  case WCO_VIEW_CHECK:
2094  /* See the comment in ExecConstraints(). */
2095  if (resultRelInfo->ri_RootResultRelInfo)
2096  {
2097  ResultRelInfo *rootrel = resultRelInfo->ri_RootResultRelInfo;
2098  TupleDesc old_tupdesc = RelationGetDescr(rel);
2099  AttrMap *map;
2100 
2101  tupdesc = RelationGetDescr(rootrel->ri_RelationDesc);
2102  /* a reverse map */
2103  map = build_attrmap_by_name_if_req(old_tupdesc,
2104  tupdesc,
2105  false);
2106 
2107  /*
2108  * Partition-specific slot's tupdesc can't be changed,
2109  * so allocate a new one.
2110  */
2111  if (map != NULL)
2112  slot = execute_attr_map_slot(map, slot,
2113  MakeTupleTableSlot(tupdesc, &TTSOpsVirtual));
2114 
2115  modifiedCols = bms_union(ExecGetInsertedCols(rootrel, estate),
2116  ExecGetUpdatedCols(rootrel, estate));
2117  rel = rootrel->ri_RelationDesc;
2118  }
2119  else
2120  modifiedCols = bms_union(ExecGetInsertedCols(resultRelInfo, estate),
2121  ExecGetUpdatedCols(resultRelInfo, estate));
2123  slot,
2124  tupdesc,
2125  modifiedCols,
2126  64);
2127 
2128  ereport(ERROR,
2129  (errcode(ERRCODE_WITH_CHECK_OPTION_VIOLATION),
2130  errmsg("new row violates check option for view \"%s\"",
2131  wco->relname),
2132  val_desc ? errdetail("Failing row contains %s.",
2133  val_desc) : 0));
2134  break;
2135  case WCO_RLS_INSERT_CHECK:
2136  case WCO_RLS_UPDATE_CHECK:
2137  if (wco->polname != NULL)
2138  ereport(ERROR,
2139  (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
2140  errmsg("new row violates row-level security policy \"%s\" for table \"%s\"",
2141  wco->polname, wco->relname)));
2142  else
2143  ereport(ERROR,
2144  (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
2145  errmsg("new row violates row-level security policy for table \"%s\"",
2146  wco->relname)));
2147  break;
2150  if (wco->polname != NULL)
2151  ereport(ERROR,
2152  (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
2153  errmsg("target row violates row-level security policy \"%s\" (USING expression) for table \"%s\"",
2154  wco->polname, wco->relname)));
2155  else
2156  ereport(ERROR,
2157  (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
2158  errmsg("target row violates row-level security policy (USING expression) for table \"%s\"",
2159  wco->relname)));
2160  break;
2162  if (wco->polname != NULL)
2163  ereport(ERROR,
2164  (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
2165  errmsg("new row violates row-level security policy \"%s\" (USING expression) for table \"%s\"",
2166  wco->polname, wco->relname)));
2167  else
2168  ereport(ERROR,
2169  (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
2170  errmsg("new row violates row-level security policy (USING expression) for table \"%s\"",
2171  wco->relname)));
2172  break;
2173  default:
2174  elog(ERROR, "unrecognized WCO kind: %u", wco->kind);
2175  break;
2176  }
2177  }
2178  }
2179 }
static bool ExecQual(ExprState *state, ExprContext *econtext)
Definition: executor.h:401
@ WCO_RLS_MERGE_UPDATE_CHECK
Definition: parsenodes.h:1318
@ WCO_RLS_CONFLICT_CHECK
Definition: parsenodes.h:1317
@ WCO_RLS_INSERT_CHECK
Definition: parsenodes.h:1315
@ WCO_VIEW_CHECK
Definition: parsenodes.h:1314
@ WCO_RLS_UPDATE_CHECK
Definition: parsenodes.h:1316
@ WCO_RLS_MERGE_DELETE_CHECK
Definition: parsenodes.h:1319
#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 797 of file execMain.c.

798 {
799  CmdType operation = queryDesc->operation;
800  PlannedStmt *plannedstmt = queryDesc->plannedstmt;
801  Plan *plan = plannedstmt->planTree;
802  List *rangeTable = plannedstmt->rtable;
803  EState *estate = queryDesc->estate;
804  PlanState *planstate;
805  TupleDesc tupType;
806  ListCell *l;
807  int i;
808 
809  /*
810  * Do permissions checks
811  */
812  ExecCheckPermissions(rangeTable, plannedstmt->permInfos, true);
813 
814  /*
815  * initialize the node's execution state
816  */
817  ExecInitRangeTable(estate, rangeTable, plannedstmt->permInfos);
818 
819  estate->es_plannedstmt = plannedstmt;
820  estate->es_part_prune_infos = plannedstmt->partPruneInfos;
821 
822  /*
823  * Next, build the ExecRowMark array from the PlanRowMark(s), if any.
824  */
825  if (plannedstmt->rowMarks)
826  {
827  estate->es_rowmarks = (ExecRowMark **)
828  palloc0(estate->es_range_table_size * sizeof(ExecRowMark *));
829  foreach(l, plannedstmt->rowMarks)
830  {
831  PlanRowMark *rc = (PlanRowMark *) lfirst(l);
832  Oid relid;
833  Relation relation;
834  ExecRowMark *erm;
835 
836  /* ignore "parent" rowmarks; they are irrelevant at runtime */
837  if (rc->isParent)
838  continue;
839 
840  /* get relation's OID (will produce InvalidOid if subquery) */
841  relid = exec_rt_fetch(rc->rti, estate)->relid;
842 
843  /* open relation, if we need to access it for this mark type */
844  switch (rc->markType)
845  {
846  case ROW_MARK_EXCLUSIVE:
848  case ROW_MARK_SHARE:
849  case ROW_MARK_KEYSHARE:
850  case ROW_MARK_REFERENCE:
851  relation = ExecGetRangeTableRelation(estate, rc->rti);
852  break;
853  case ROW_MARK_COPY:
854  /* no physical table access is required */
855  relation = NULL;
856  break;
857  default:
858  elog(ERROR, "unrecognized markType: %d", rc->markType);
859  relation = NULL; /* keep compiler quiet */
860  break;
861  }
862 
863  /* Check that relation is a legal target for marking */
864  if (relation)
865  CheckValidRowMarkRel(relation, rc->markType);
866 
867  erm = (ExecRowMark *) palloc(sizeof(ExecRowMark));
868  erm->relation = relation;
869  erm->relid = relid;
870  erm->rti = rc->rti;
871  erm->prti = rc->prti;
872  erm->rowmarkId = rc->rowmarkId;
873  erm->markType = rc->markType;
874  erm->strength = rc->strength;
875  erm->waitPolicy = rc->waitPolicy;
876  erm->ermActive = false;
878  erm->ermExtra = NULL;
879 
880  Assert(erm->rti > 0 && erm->rti <= estate->es_range_table_size &&
881  estate->es_rowmarks[erm->rti - 1] == NULL);
882 
883  estate->es_rowmarks[erm->rti - 1] = erm;
884  }
885  }
886 
887  /*
888  * Initialize the executor's tuple table to empty.
889  */
890  estate->es_tupleTable = NIL;
891 
892  /* signal that this EState is not used for EPQ */
893  estate->es_epq_active = NULL;
894 
895  /*
896  * Initialize private state information for each SubPlan. We must do this
897  * before running ExecInitNode on the main query tree, since
898  * ExecInitSubPlan expects to be able to find these entries.
899  */
900  Assert(estate->es_subplanstates == NIL);
901  i = 1; /* subplan indices count from 1 */
902  foreach(l, plannedstmt->subplans)
903  {
904  Plan *subplan = (Plan *) lfirst(l);
905  PlanState *subplanstate;
906  int sp_eflags;
907 
908  /*
909  * A subplan will never need to do BACKWARD scan nor MARK/RESTORE. If
910  * it is a parameterless subplan (not initplan), we suggest that it be
911  * prepared to handle REWIND efficiently; otherwise there is no need.
912  */
913  sp_eflags = eflags
915  if (bms_is_member(i, plannedstmt->rewindPlanIDs))
916  sp_eflags |= EXEC_FLAG_REWIND;
917 
918  subplanstate = ExecInitNode(subplan, estate, sp_eflags);
919 
920  estate->es_subplanstates = lappend(estate->es_subplanstates,
921  subplanstate);
922 
923  i++;
924  }
925 
926  /*
927  * Initialize the private state information for all the nodes in the query
928  * tree. This opens files, allocates storage and leaves us ready to start
929  * processing tuples.
930  */
931  planstate = ExecInitNode(plan, estate, eflags);
932 
933  /*
934  * Get the tuple descriptor describing the type of tuples to return.
935  */
936  tupType = ExecGetResultType(planstate);
937 
938  /*
939  * Initialize the junk filter if needed. SELECT queries need a filter if
940  * there are any junk attrs in the top-level tlist.
941  */
942  if (operation == CMD_SELECT)
943  {
944  bool junk_filter_needed = false;
945  ListCell *tlist;
946 
947  foreach(tlist, plan->targetlist)
948  {
949  TargetEntry *tle = (TargetEntry *) lfirst(tlist);
950 
951  if (tle->resjunk)
952  {
953  junk_filter_needed = true;
954  break;
955  }
956  }
957 
958  if (junk_filter_needed)
959  {
960  JunkFilter *j;
961  TupleTableSlot *slot;
962 
963  slot = ExecInitExtraTupleSlot(estate, NULL, &TTSOpsVirtual);
964  j = ExecInitJunkFilter(planstate->plan->targetlist,
965  slot);
966  estate->es_junkFilter = j;
967 
968  /* Want to return the cleaned tuple type */
969  tupType = j->jf_cleanTupType;
970  }
971  }
972 
973  queryDesc->tupDesc = tupType;
974  queryDesc->planstate = planstate;
975 }
JunkFilter * ExecInitJunkFilter(List *targetList, TupleTableSlot *slot)
Definition: execJunk.c:60
static void CheckValidRowMarkRel(Relation rel, RowMarkType markType)
Definition: execMain.c:1123
bool ExecCheckPermissions(List *rangeTable, List *rteperminfos, bool ereport_on_violation)
Definition: execMain.c:574
TupleTableSlot * ExecInitExtraTupleSlot(EState *estate, TupleDesc tupledesc, const TupleTableSlotOps *tts_ops)
Definition: execTuples.c:1831
TupleDesc ExecGetResultType(PlanState *planstate)
Definition: execUtils.c:498
void ExecInitRangeTable(EState *estate, List *rangeTable, List *permInfos)
Definition: execUtils.c:759
Relation ExecGetRangeTableRelation(EState *estate, Index rti)
Definition: execUtils.c:793
#define EXEC_FLAG_REWIND
Definition: executor.h:57
static RangeTblEntry * exec_rt_fetch(Index rti, EState *estate)
Definition: executor.h:576
#define EXEC_FLAG_WITH_NO_DATA
Definition: executor.h:61
#define EXEC_FLAG_EXPLAIN_ONLY
Definition: executor.h:56
int j
Definition: isn.c:74
static void ItemPointerSetInvalid(ItemPointerData *pointer)
Definition: itemptr.h:184
CmdType
Definition: nodes.h:274
@ ROW_MARK_SHARE
Definition: plannodes.h:1332
@ ROW_MARK_EXCLUSIVE
Definition: plannodes.h:1330
@ ROW_MARK_NOKEYEXCLUSIVE
Definition: plannodes.h:1331
@ ROW_MARK_KEYSHARE
Definition: plannodes.h:1333
List * es_part_prune_infos
Definition: execnodes.h:626
ItemPointerData curCtid
Definition: execnodes.h:748
LockClauseStrength strength
Definition: execnodes.h:745
bool ermActive
Definition: execnodes.h:747
LockWaitPolicy waitPolicy
Definition: execnodes.h:746
void * ermExtra
Definition: execnodes.h:749
LockClauseStrength strength
Definition: plannodes.h:1388
Index prti
Definition: plannodes.h:1384
RowMarkType markType
Definition: plannodes.h:1386
LockWaitPolicy waitPolicy
Definition: plannodes.h:1389
bool isParent
Definition: plannodes.h:1390
Index rowmarkId
Definition: plannodes.h:1385
List * targetlist
Definition: plannodes.h:156
struct Plan * planTree
Definition: plannodes.h:71
List * rowMarks
Definition: plannodes.h:91
Bitmapset * rewindPlanIDs
Definition: plannodes.h:89
List * rtable
Definition: plannodes.h:76
List * partPruneInfos
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_part_prune_infos, EState::es_plannedstmt, EState::es_range_table_size, EState::es_rowmarks, EState::es_subplanstates, EState::es_tupleTable, QueryDesc::estate, EXEC_FLAG_EXPLAIN_ONLY, EXEC_FLAG_REWIND, EXEC_FLAG_WITH_NO_DATA, exec_rt_fetch(), ExecCheckPermissions(), ExecGetRangeTableRelation(), ExecGetResultType(), ExecInitExtraTupleSlot(), ExecInitJunkFilter(), ExecInitNode(), ExecInitRangeTable(), i, PlanRowMark::isParent, ItemPointerSetInvalid(), j, lappend(), lfirst, ExecRowMark::markType, PlanRowMark::markType, NIL, QueryDesc::operation, palloc(), palloc0(), PlannedStmt::partPruneInfos, PlannedStmt::permInfos, PlanState::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 1188 of file execMain.c.

1193 {
1194  MemSet(resultRelInfo, 0, sizeof(ResultRelInfo));
1195  resultRelInfo->type = T_ResultRelInfo;
1196  resultRelInfo->ri_RangeTableIndex = resultRelationIndex;
1197  resultRelInfo->ri_RelationDesc = resultRelationDesc;
1198  resultRelInfo->ri_NumIndices = 0;
1199  resultRelInfo->ri_IndexRelationDescs = NULL;
1200  resultRelInfo->ri_IndexRelationInfo = NULL;
1201  /* make a copy so as not to depend on relcache info not changing... */
1202  resultRelInfo->ri_TrigDesc = CopyTriggerDesc(resultRelationDesc->trigdesc);
1203  if (resultRelInfo->ri_TrigDesc)
1204  {
1205  int n = resultRelInfo->ri_TrigDesc->numtriggers;
1206 
1207  resultRelInfo->ri_TrigFunctions = (FmgrInfo *)
1208  palloc0(n * sizeof(FmgrInfo));
1209  resultRelInfo->ri_TrigWhenExprs = (ExprState **)
1210  palloc0(n * sizeof(ExprState *));
1211  if (instrument_options)
1212  resultRelInfo->ri_TrigInstrument = InstrAlloc(n, instrument_options, false);
1213  }
1214  else
1215  {
1216  resultRelInfo->ri_TrigFunctions = NULL;
1217  resultRelInfo->ri_TrigWhenExprs = NULL;
1218  resultRelInfo->ri_TrigInstrument = NULL;
1219  }
1220  if (resultRelationDesc->rd_rel->relkind == RELKIND_FOREIGN_TABLE)
1221  resultRelInfo->ri_FdwRoutine = GetFdwRoutineForRelation(resultRelationDesc, true);
1222  else
1223  resultRelInfo->ri_FdwRoutine = NULL;
1224 
1225  /* The following fields are set later if needed */
1226  resultRelInfo->ri_RowIdAttNo = 0;
1227  resultRelInfo->ri_extraUpdatedCols = NULL;
1228  resultRelInfo->ri_projectNew = NULL;
1229  resultRelInfo->ri_newTupleSlot = NULL;
1230  resultRelInfo->ri_oldTupleSlot = NULL;
1231  resultRelInfo->ri_projectNewInfoValid = false;
1232  resultRelInfo->ri_FdwState = NULL;
1233  resultRelInfo->ri_usesFdwDirectModify = false;
1234  resultRelInfo->ri_ConstraintExprs = NULL;
1235  resultRelInfo->ri_GeneratedExprsI = NULL;
1236  resultRelInfo->ri_GeneratedExprsU = NULL;
1237  resultRelInfo->ri_projectReturning = NULL;
1238  resultRelInfo->ri_onConflictArbiterIndexes = NIL;
1239  resultRelInfo->ri_onConflict = NULL;
1240  resultRelInfo->ri_ReturningSlot = NULL;
1241  resultRelInfo->ri_TrigOldSlot = NULL;
1242  resultRelInfo->ri_TrigNewSlot = NULL;
1243  resultRelInfo->ri_matchedMergeAction = NIL;
1244  resultRelInfo->ri_notMatchedMergeAction = NIL;
1245 
1246  /*
1247  * Only ExecInitPartitionInfo() and ExecInitPartitionDispatchInfo() pass
1248  * non-NULL partition_root_rri. For child relations that are part of the
1249  * initial query rather than being dynamically added by tuple routing,
1250  * this field is filled in ExecInitModifyTable().
1251  */
1252  resultRelInfo->ri_RootResultRelInfo = partition_root_rri;
1253  /* Set by ExecGetRootToChildMap */
1254  resultRelInfo->ri_RootToChildMap = NULL;
1255  resultRelInfo->ri_RootToChildMapValid = false;
1256  /* Set by ExecInitRoutingInfo */
1257  resultRelInfo->ri_PartitionTupleSlot = NULL;
1258  resultRelInfo->ri_ChildToRootMap = NULL;
1259  resultRelInfo->ri_ChildToRootMapValid = false;
1260  resultRelInfo->ri_CopyMultiInsertBuffer = NULL;
1261 }
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:2096

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

472 {
473  EState *estate;
474  MemoryContext oldcontext;
475 
476  /* sanity checks */
477  Assert(queryDesc != NULL);
478 
479  estate = queryDesc->estate;
480 
481  Assert(estate != NULL);
482 
483  /*
484  * Check that ExecutorFinish was called, unless in EXPLAIN-only mode. This
485  * Assert is needed because ExecutorFinish is new as of 9.1, and callers
486  * might forget to call it.
487  */
488  Assert(estate->es_finished ||
490 
491  /*
492  * Switch into per-query memory context to run ExecEndPlan
493  */
494  oldcontext = MemoryContextSwitchTo(estate->es_query_cxt);
495 
496  ExecEndPlan(queryDesc->planstate, estate);
497 
498  /* do away with our snapshots */
501 
502  /*
503  * Must switch out of context before destroying it
504  */
505  MemoryContextSwitchTo(oldcontext);
506 
507  /*
508  * Release EState and per-query memory context. This should release
509  * everything the executor has allocated.
510  */
511  FreeExecutorState(estate);
512 
513  /* Reset queryDesc fields that no longer point to anything */
514  queryDesc->tupDesc = NULL;
515  queryDesc->estate = NULL;
516  queryDesc->planstate = NULL;
517  queryDesc->totaltime = NULL;
518 }
static void ExecEndPlan(PlanState *planstate, EState *estate)
Definition: execMain.c:1465
void UnregisterSnapshot(Snapshot snapshot)
Definition: snapmgr.c:871
bool es_finished
Definition: execnodes.h:668
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 411 of file execMain.c.

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

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

314 {
315  EState *estate;
316  CmdType operation;
318  bool sendTuples;
319  MemoryContext oldcontext;
320 
321  /* sanity checks */
322  Assert(queryDesc != NULL);
323 
324  estate = queryDesc->estate;
325 
326  Assert(estate != NULL);
328 
329  /*
330  * Switch into per-query memory context
331  */
332  oldcontext = MemoryContextSwitchTo(estate->es_query_cxt);
333 
334  /* Allow instrumentation of Executor overall runtime */
335  if (queryDesc->totaltime)
336  InstrStartNode(queryDesc->totaltime);
337 
338  /*
339  * extract information from the query descriptor and the query feature.
340  */
341  operation = queryDesc->operation;
342  dest = queryDesc->dest;
343 
344  /*
345  * startup tuple receiver, if we will be emitting tuples
346  */
347  estate->es_processed = 0;
348 
349  sendTuples = (operation == CMD_SELECT ||
350  queryDesc->plannedstmt->hasReturning);
351 
352  if (sendTuples)
353  dest->rStartup(dest, operation, queryDesc->tupDesc);
354 
355  /*
356  * run plan
357  */
358  if (!ScanDirectionIsNoMovement(direction))
359  {
360  if (execute_once && queryDesc->already_executed)
361  elog(ERROR, "can't re-execute query flagged for single execution");
362  queryDesc->already_executed = true;
363 
364  ExecutePlan(estate,
365  queryDesc->planstate,
366  queryDesc->plannedstmt->parallelModeNeeded,
367  operation,
368  sendTuples,
369  count,
370  direction,
371  dest,
372  execute_once);
373  }
374 
375  /*
376  * shutdown tuple receiver, if we started it
377  */
378  if (sendTuples)
379  dest->rShutdown(dest);
380 
381  if (queryDesc->totaltime)
382  InstrStopNode(queryDesc->totaltime, estate->es_processed);
383 
384  MemoryContextSwitchTo(oldcontext);
385 }
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:1588
#define ScanDirectionIsNoMovement(direction)
Definition: sdir.h:57
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, 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:763
static void InitPlan(QueryDesc *queryDesc, int eflags)
Definition: execMain.c:797
@ CMD_MERGE
Definition: nodes.h:280
Snapshot RegisterSnapshot(Snapshot snapshot)
Definition: snapmgr.c:829
int es_jit_flags
Definition: execnodes.h:705
const char * es_sourceText
Definition: execnodes.h:627
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:4980
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().