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/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 ExecCheckRTEPerms (RangeTblEntry *rte)
 
static bool ExecCheckRTEPermsModified (Oid relOid, Oid userid, Bitmapset *modifiedCols, AclMode requiredPerms)
 
static void ExecCheckXactReadOnly (PlannedStmt *plannedstmt)
 
static char * ExecBuildSlotValueDescription (Oid reloid, TupleTableSlot *slot, TupleDesc tupdesc, Bitmapset *modifiedCols, int maxfieldlen)
 
static void EvalPlanQualStart (EPQState *epqstate, Plan *planTree)
 
void ExecutorStart (QueryDesc *queryDesc, int eflags)
 
void standard_ExecutorStart (QueryDesc *queryDesc, int eflags)
 
void ExecutorRun (QueryDesc *queryDesc, ScanDirection direction, uint64 count, bool execute_once)
 
void standard_ExecutorRun (QueryDesc *queryDesc, ScanDirection direction, uint64 count, bool execute_once)
 
void ExecutorFinish (QueryDesc *queryDesc)
 
void standard_ExecutorFinish (QueryDesc *queryDesc)
 
void ExecutorEnd (QueryDesc *queryDesc)
 
void standard_ExecutorEnd (QueryDesc *queryDesc)
 
void ExecutorRewind (QueryDesc *queryDesc)
 
bool ExecCheckRTPerms (List *rangeTable, bool ereport_on_violation)
 
void CheckValidResultRel (ResultRelInfo *resultRelInfo, CmdType operation)
 
void InitResultRelInfo (ResultRelInfo *resultRelInfo, Relation resultRelationDesc, Index resultRelationIndex, 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 995 of file execMain.c.

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

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

2466 {
2467  TupleTableSlot *slot;
2468  TupleTableSlot *testslot;
2469 
2470  Assert(rti > 0);
2471 
2472  /*
2473  * Need to run a recheck subquery. Initialize or reinitialize EPQ state.
2474  */
2475  EvalPlanQualBegin(epqstate);
2476 
2477  /*
2478  * Callers will often use the EvalPlanQualSlot to store the tuple to avoid
2479  * an unnecessary copy.
2480  */
2481  testslot = EvalPlanQualSlot(epqstate, relation, rti);
2482  if (testslot != inputslot)
2483  ExecCopySlot(testslot, inputslot);
2484 
2485  /*
2486  * Run the EPQ query. We assume it will return at most one tuple.
2487  */
2488  slot = EvalPlanQualNext(epqstate);
2489 
2490  /*
2491  * If we got a tuple, force the slot to materialize the tuple so that it
2492  * is not dependent on any local state in the EPQ query (in particular,
2493  * it's highly likely that the slot contains references to any pass-by-ref
2494  * datums that may be present in copyTuple). As with the next step, this
2495  * is to guard against early re-use of the EPQ query.
2496  */
2497  if (!TupIsNull(slot))
2498  ExecMaterializeSlot(slot);
2499 
2500  /*
2501  * Clear out the test tuple. This is needed in case the EPQ query is
2502  * re-used to test a tuple for a different relation. (Not clear that can
2503  * really happen, but let's be safe.)
2504  */
2505  ExecClearTuple(testslot);
2506 
2507  return slot;
2508 }
void EvalPlanQualBegin(EPQState *epqstate)
Definition: execMain.c:2727
TupleTableSlot * EvalPlanQualNext(EPQState *epqstate)
Definition: execMain.c:2711
TupleTableSlot * EvalPlanQualSlot(EPQState *epqstate, Relation relation, Index rti)
Definition: execMain.c:2574
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 2727 of file execMain.c.

2728 {
2729  EState *parentestate = epqstate->parentestate;
2730  EState *recheckestate = epqstate->recheckestate;
2731 
2732  if (recheckestate == NULL)
2733  {
2734  /* First time through, so create a child EState */
2735  EvalPlanQualStart(epqstate, epqstate->plan);
2736  }
2737  else
2738  {
2739  /*
2740  * We already have a suitable child EPQ tree, so just reset it.
2741  */
2742  Index rtsize = parentestate->es_range_table_size;
2743  PlanState *rcplanstate = epqstate->recheckplanstate;
2744 
2745  MemSet(epqstate->relsubs_done, 0, rtsize * sizeof(bool));
2746 
2747  /* Recopy current values of parent parameters */
2748  if (parentestate->es_plannedstmt->paramExecTypes != NIL)
2749  {
2750  int i;
2751 
2752  /*
2753  * Force evaluation of any InitPlan outputs that could be needed
2754  * by the subplan, just in case they got reset since
2755  * EvalPlanQualStart (see comments therein).
2756  */
2757  ExecSetParamPlanMulti(rcplanstate->plan->extParam,
2758  GetPerTupleExprContext(parentestate));
2759 
2760  i = list_length(parentestate->es_plannedstmt->paramExecTypes);
2761 
2762  while (--i >= 0)
2763  {
2764  /* copy value if any, but not execPlan link */
2765  recheckestate->es_param_exec_vals[i].value =
2766  parentestate->es_param_exec_vals[i].value;
2767  recheckestate->es_param_exec_vals[i].isnull =
2768  parentestate->es_param_exec_vals[i].isnull;
2769  }
2770  }
2771 
2772  /*
2773  * Mark child plan tree as needing rescan at all scan nodes. The
2774  * first ExecProcNode will take care of actually doing the rescan.
2775  */
2776  rcplanstate->chgParam = bms_add_member(rcplanstate->chgParam,
2777  epqstate->epqParam);
2778  }
2779 }
Bitmapset * bms_add_member(Bitmapset *a, int x)
Definition: bitmapset.c:739
unsigned int Index
Definition: c.h:550
#define MemSet(start, val, len)
Definition: c.h:953
static void EvalPlanQualStart(EPQState *epqstate, Plan *planTree)
Definition: execMain.c:2788
#define GetPerTupleExprContext(estate)
Definition: executor.h:535
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:150
#define NIL
Definition: pg_list.h:66
Plan * plan
Definition: execnodes.h:1182
int epqParam
Definition: execnodes.h:1167
EState * parentestate
Definition: execnodes.h:1166
EState * recheckestate
Definition: execnodes.h:1196
PlanState * recheckplanstate
Definition: execnodes.h:1211
bool * relsubs_done
Definition: execnodes.h:1209
PlannedStmt * es_plannedstmt
Definition: execnodes.h:620
ParamExecData * es_param_exec_vals
Definition: execnodes.h:650
Index es_range_table_size
Definition: execnodes.h:615
bool isnull
Definition: params.h:150
Datum value
Definition: params.h:149
Plan * plan
Definition: execnodes.h:1029
Bitmapset * chgParam
Definition: execnodes.h:1061
Bitmapset * extParam
Definition: plannodes.h:171
List * paramExecTypes
Definition: plannodes.h:94

References bms_add_member(), PlanState::chgParam, EPQState::epqParam, EState::es_param_exec_vals, EState::es_plannedstmt, EState::es_range_table_size, EvalPlanQualStart(), ExecSetParamPlanMulti(), Plan::extParam, GetPerTupleExprContext, i, ParamExecData::isnull, list_length(), 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 2939 of file execMain.c.

2940 {
2941  EState *estate = epqstate->recheckestate;
2942  Index rtsize;
2943  MemoryContext oldcontext;
2944  ListCell *l;
2945 
2946  rtsize = epqstate->parentestate->es_range_table_size;
2947 
2948  /*
2949  * We may have a tuple table, even if EPQ wasn't started, because we allow
2950  * use of EvalPlanQualSlot() without calling EvalPlanQualBegin().
2951  */
2952  if (epqstate->tuple_table != NIL)
2953  {
2954  memset(epqstate->relsubs_slot, 0,
2955  rtsize * sizeof(TupleTableSlot *));
2956  ExecResetTupleTable(epqstate->tuple_table, true);
2957  epqstate->tuple_table = NIL;
2958  }
2959 
2960  /* EPQ wasn't started, nothing further to do */
2961  if (estate == NULL)
2962  return;
2963 
2964  oldcontext = MemoryContextSwitchTo(estate->es_query_cxt);
2965 
2966  ExecEndNode(epqstate->recheckplanstate);
2967 
2968  foreach(l, estate->es_subplanstates)
2969  {
2970  PlanState *subplanstate = (PlanState *) lfirst(l);
2971 
2972  ExecEndNode(subplanstate);
2973  }
2974 
2975  /* throw away the per-estate tuple table, some node may have used it */
2976  ExecResetTupleTable(estate->es_tupleTable, false);
2977 
2978  /* Close any result and trigger target relations attached to this EState */
2979  ExecCloseResultRelations(estate);
2980 
2981  MemoryContextSwitchTo(oldcontext);
2982 
2983  FreeExecutorState(estate);
2984 
2985  /* Mark EPQState idle */
2986  epqstate->origslot = NULL;
2987  epqstate->recheckestate = NULL;
2988  epqstate->recheckplanstate = NULL;
2989  epqstate->relsubs_rowmark = NULL;
2990  epqstate->relsubs_done = NULL;
2991 }
void ExecCloseResultRelations(EState *estate)
Definition: execMain.c:1511
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:188
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:135
#define lfirst(lc)
Definition: pg_list.h:170
ExecAuxRowMark ** relsubs_rowmark
Definition: execnodes.h:1203
TupleTableSlot * origslot
Definition: execnodes.h:1191
TupleTableSlot ** relsubs_slot
Definition: execnodes.h:1175
List * tuple_table
Definition: execnodes.h:1174
MemoryContext es_query_cxt
Definition: execnodes.h:655
List * es_tupleTable
Definition: execnodes.h:657
List * es_subplanstates
Definition: execnodes.h:667

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

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

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

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

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

2712 {
2713  MemoryContext oldcontext;
2714  TupleTableSlot *slot;
2715 
2716  oldcontext = MemoryContextSwitchTo(epqstate->recheckestate->es_query_cxt);
2717  slot = ExecProcNode(epqstate->recheckplanstate);
2718  MemoryContextSwitchTo(oldcontext);
2719 
2720  return slot;
2721 }
static TupleTableSlot * ExecProcNode(PlanState *node)
Definition: executor.h:254

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

2558 {
2559  /* If we have a live EPQ query, shut it down */
2560  EvalPlanQualEnd(epqstate);
2561  /* And set/change the plan pointer */
2562  epqstate->plan = subplan;
2563  /* The rowmarks depend on the plan, too */
2564  epqstate->arowMarks = auxrowmarks;
2565 }
void EvalPlanQualEnd(EPQState *epqstate)
Definition: execMain.c:2939

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

Referenced by ExecInitModifyTable().

◆ EvalPlanQualSlot()

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

Definition at line 2574 of file execMain.c.

2576 {
2577  TupleTableSlot **slot;
2578 
2579  Assert(relation);
2580  Assert(rti > 0 && rti <= epqstate->parentestate->es_range_table_size);
2581  slot = &epqstate->relsubs_slot[rti - 1];
2582 
2583  if (*slot == NULL)
2584  {
2585  MemoryContext oldcontext;
2586 
2587  oldcontext = MemoryContextSwitchTo(epqstate->parentestate->es_query_cxt);
2588  *slot = table_slot_create(relation, &epqstate->tuple_table);
2589  MemoryContextSwitchTo(oldcontext);
2590  }
2591 
2592  return *slot;
2593 }
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 2788 of file execMain.c.

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

References EPQState::arowMarks, Assert(), CreateExecutorState(), EState::es_crosscheck_snapshot, EState::es_direction, EState::es_epq_active, EState::es_instrument, EState::es_junkFilter, EState::es_output_cid, EState::es_param_exec_vals, EState::es_param_list_info, EState::es_plannedstmt, EState::es_query_cxt, EState::es_queryEnv, EState::es_range_table, EState::es_range_table_size, EState::es_relations, EState::es_result_relations, EState::es_rowmarks, EState::es_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 2394 of file execMain.c.

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

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

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

◆ ExecCheckRTEPerms()

static bool ExecCheckRTEPerms ( RangeTblEntry rte)
static

Definition at line 601 of file execMain.c.

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

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

Referenced by ExecCheckRTPerms().

◆ ExecCheckRTEPermsModified()

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

Definition at line 721 of file execMain.c.

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

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

Referenced by ExecCheckRTEPerms().

◆ ExecCheckRTPerms()

bool ExecCheckRTPerms ( List rangeTable,
bool  ereport_on_violation 
)

Definition at line 570 of file execMain.c.

571 {
572  ListCell *l;
573  bool result = true;
574 
575  foreach(l, rangeTable)
576  {
577  RangeTblEntry *rte = (RangeTblEntry *) lfirst(l);
578 
579  result = ExecCheckRTEPerms(rte);
580  if (!result)
581  {
582  Assert(rte->rtekind == RTE_RELATION);
583  if (ereport_on_violation)
585  get_rel_name(rte->relid));
586  return false;
587  }
588  }
589 
591  result = (*ExecutorCheckPerms_hook) (rangeTable,
592  ereport_on_violation);
593  return result;
594 }
@ ACLCHECK_NO_PRIV
Definition: acl.h:185
void aclcheck_error(AclResult aclerr, ObjectType objtype, const char *objectname)
Definition: aclchk.c:3485
ExecutorCheckPerms_hook_type ExecutorCheckPerms_hook
Definition: execMain.c:78
static bool ExecCheckRTEPerms(RangeTblEntry *rte)
Definition: execMain.c:601
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)

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

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

◆ ExecCheckXactReadOnly()

static void ExecCheckXactReadOnly ( PlannedStmt plannedstmt)
static

Definition at line 768 of file execMain.c.

769 {
770  ListCell *l;
771 
772  /*
773  * Fail if write permissions are requested in parallel mode for table
774  * (temp or non-temp), otherwise fail for any non-temp table.
775  */
776  foreach(l, plannedstmt->rtable)
777  {
778  RangeTblEntry *rte = (RangeTblEntry *) lfirst(l);
779 
780  if (rte->rtekind != RTE_RELATION)
781  continue;
782 
783  if ((rte->requiredPerms & (~ACL_SELECT)) == 0)
784  continue;
785 
787  continue;
788 
790  }
791 
792  if (plannedstmt->commandType != CMD_SELECT || plannedstmt->hasModifyingCTE)
794 }
Oid get_rel_namespace(Oid relid)
Definition: lsyscache.c:1934
bool isTempNamespace(Oid namespaceId)
Definition: namespace.c:3200
@ CMD_SELECT
Definition: nodes.h:265
Definition: nodes.h:118
bool hasModifyingCTE
Definition: plannodes.h:59
CmdType commandType
Definition: plannodes.h:53
List * rtable
Definition: plannodes.h:76
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, PreventCommandIfParallelMode(), PreventCommandIfReadOnly(), RangeTblEntry::relid, RangeTblEntry::requiredPerms, PlannedStmt::rtable, RTE_RELATION, and RangeTblEntry::rtekind.

Referenced by standard_ExecutorStart().

◆ ExecCloseRangeTableRelations()

void ExecCloseRangeTableRelations ( EState estate)

Definition at line 1571 of file execMain.c.

1572 {
1573  int i;
1574 
1575  for (i = 0; i < estate->es_range_table_size; i++)
1576  {
1577  if (estate->es_relations[i])
1578  table_close(estate->es_relations[i], NoLock);
1579  }
1580 }
#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 1511 of file execMain.c.

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

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

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

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

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

2372 {
2373  if (rti > 0 && rti <= estate->es_range_table_size &&
2374  estate->es_rowmarks != NULL)
2375  {
2376  ExecRowMark *erm = estate->es_rowmarks[rti - 1];
2377 
2378  if (erm)
2379  return erm;
2380  }
2381  if (!missing_ok)
2382  elog(ERROR, "failed to find ExecRowMark for rangetable index %u", rti);
2383  return NULL;
2384 }

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

Referenced by ExecInitLockRows(), and ExecInitModifyTable().

◆ ExecGetAncestorResultRels()

List* ExecGetAncestorResultRels ( EState estate,
ResultRelInfo resultRelInfo 
)

Definition at line 1366 of file execMain.c.

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

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

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

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

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

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

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

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

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

Referenced by standard_ExecutorFinish().

◆ ExecRelCheck()

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

Definition at line 1711 of file execMain.c.

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

2346 {
2347  Bitmapset *keyCols;
2348  Bitmapset *updatedCols;
2349 
2350  /*
2351  * Compute lock mode to use. If columns that are part of the key have not
2352  * been modified, then we can use a weaker lock, allowing for better
2353  * concurrency.
2354  */
2355  updatedCols = ExecGetAllUpdatedCols(relinfo, estate);
2356  keyCols = RelationGetIndexAttrBitmap(relinfo->ri_RelationDesc,
2358 
2359  if (bms_overlap(keyCols, updatedCols))
2360  return LockTupleExclusive;
2361 
2362  return LockTupleNoKeyExclusive;
2363 }
bool bms_overlap(const Bitmapset *a, const Bitmapset *b)
Definition: bitmapset.c:495
Bitmapset * ExecGetAllUpdatedCols(ResultRelInfo *relinfo, EState *estate)
Definition: execUtils.c:1388
@ LockTupleExclusive
Definition: lockoptions.h:58
@ LockTupleNoKeyExclusive
Definition: lockoptions.h:56
Bitmapset * RelationGetIndexAttrBitmap(Relation relation, IndexAttrBitmapKind attrKind)
Definition: relcache.c:5168
@ INDEX_ATTR_BITMAP_KEY
Definition: relcache.h:60

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

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

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

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

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

402 {
404  (*ExecutorFinish_hook) (queryDesc);
405  else
406  standard_ExecutorFinish(queryDesc);
407 }
ExecutorFinish_hook_type ExecutorFinish_hook
Definition: execMain.c:74
void standard_ExecutorFinish(QueryDesc *queryDesc)
Definition: execMain.c:410

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

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

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

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

132 {
133  /*
134  * In some cases (e.g. an EXECUTE statement) a query execution will skip
135  * parse analysis, which means that the query_id won't be reported. Note
136  * that it's harmless to report the query_id multiple time, as the call
137  * will be ignored if the top level query_id has already been reported.
138  */
139  pgstat_report_query_id(queryDesc->plannedstmt->queryId, false);
140 
141  if (ExecutorStart_hook)
142  (*ExecutorStart_hook) (queryDesc, eflags);
143  else
144  standard_ExecutorStart(queryDesc, eflags);
145 }
void pgstat_report_query_id(uint64 query_id, bool force)
ExecutorStart_hook_type ExecutorStart_hook
Definition: execMain.c:72
void standard_ExecutorStart(QueryDesc *queryDesc, int eflags)
Definition: execMain.c:148
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 2045 of file execMain.c.

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

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

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

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(), ExecCheckRTPerms(), ExecGetRangeTableRelation(), ExecGetResultType(), ExecInitExtraTupleSlot(), ExecInitJunkFilter(), ExecInitNode(), ExecInitRangeTable(), i, PlanRowMark::isParent, ItemPointerSetInvalid(), j, lappend(), lfirst, ExecRowMark::markType, PlanRowMark::markType, NIL, QueryDesc::operation, palloc(), palloc0(), PlannedStmt::partPruneInfos, PlanState::plan, QueryDesc::plannedstmt, QueryDesc::planstate, PlannedStmt::planTree, ExecRowMark::prti, PlanRowMark::prti, ExecRowMark::relation, ExecRowMark::relid, RangeTblEntry::relid, TargetEntry::resjunk, 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 1196 of file execMain.c.

1201 {
1202  MemSet(resultRelInfo, 0, sizeof(ResultRelInfo));
1203  resultRelInfo->type = T_ResultRelInfo;
1204  resultRelInfo->ri_RangeTableIndex = resultRelationIndex;
1205  resultRelInfo->ri_RelationDesc = resultRelationDesc;
1206  resultRelInfo->ri_NumIndices = 0;
1207  resultRelInfo->ri_IndexRelationDescs = NULL;
1208  resultRelInfo->ri_IndexRelationInfo = NULL;
1209  /* make a copy so as not to depend on relcache info not changing... */
1210  resultRelInfo->ri_TrigDesc = CopyTriggerDesc(resultRelationDesc->trigdesc);
1211  if (resultRelInfo->ri_TrigDesc)
1212  {
1213  int n = resultRelInfo->ri_TrigDesc->numtriggers;
1214 
1215  resultRelInfo->ri_TrigFunctions = (FmgrInfo *)
1216  palloc0(n * sizeof(FmgrInfo));
1217  resultRelInfo->ri_TrigWhenExprs = (ExprState **)
1218  palloc0(n * sizeof(ExprState *));
1219  if (instrument_options)
1220  resultRelInfo->ri_TrigInstrument = InstrAlloc(n, instrument_options, false);
1221  }
1222  else
1223  {
1224  resultRelInfo->ri_TrigFunctions = NULL;
1225  resultRelInfo->ri_TrigWhenExprs = NULL;
1226  resultRelInfo->ri_TrigInstrument = NULL;
1227  }
1228  if (resultRelationDesc->rd_rel->relkind == RELKIND_FOREIGN_TABLE)
1229  resultRelInfo->ri_FdwRoutine = GetFdwRoutineForRelation(resultRelationDesc, true);
1230  else
1231  resultRelInfo->ri_FdwRoutine = NULL;
1232 
1233  /* The following fields are set later if needed */
1234  resultRelInfo->ri_RowIdAttNo = 0;
1235  resultRelInfo->ri_projectNew = NULL;
1236  resultRelInfo->ri_newTupleSlot = NULL;
1237  resultRelInfo->ri_oldTupleSlot = NULL;
1238  resultRelInfo->ri_projectNewInfoValid = false;
1239  resultRelInfo->ri_FdwState = NULL;
1240  resultRelInfo->ri_usesFdwDirectModify = false;
1241  resultRelInfo->ri_ConstraintExprs = NULL;
1242  resultRelInfo->ri_GeneratedExprs = NULL;
1243  resultRelInfo->ri_projectReturning = NULL;
1244  resultRelInfo->ri_onConflictArbiterIndexes = NIL;
1245  resultRelInfo->ri_onConflict = NULL;
1246  resultRelInfo->ri_ReturningSlot = NULL;
1247  resultRelInfo->ri_TrigOldSlot = NULL;
1248  resultRelInfo->ri_TrigNewSlot = NULL;
1249  resultRelInfo->ri_matchedMergeAction = NIL;
1250  resultRelInfo->ri_notMatchedMergeAction = NIL;
1251 
1252  /*
1253  * Only ExecInitPartitionInfo() and ExecInitPartitionDispatchInfo() pass
1254  * non-NULL partition_root_rri. For child relations that are part of the
1255  * initial query rather than being dynamically added by tuple routing,
1256  * this field is filled in ExecInitModifyTable().
1257  */
1258  resultRelInfo->ri_RootResultRelInfo = partition_root_rri;
1259  /* Set by ExecGetRootToChildMap */
1260  resultRelInfo->ri_RootToChildMap = NULL;
1261  resultRelInfo->ri_RootToChildMapValid = false;
1262  /* Set by ExecInitRoutingInfo */
1263  resultRelInfo->ri_PartitionTupleSlot = NULL;
1264  resultRelInfo->ri_ChildToRootMap = NULL;
1265  resultRelInfo->ri_ChildToRootMapValid = false;
1266  resultRelInfo->ri_CopyMultiInsertBuffer = NULL;
1267  resultRelInfo->ri_ModifyTableState = NULL;
1268 }
Instrumentation * InstrAlloc(int n, int instrument_options, bool async_mode)
Definition: instrument.c:31
Definition: fmgr.h:57
TupleConversionMap * ri_RootToChildMap
Definition: execnodes.h:553
List * ri_matchedMergeAction
Definition: execnodes.h:535
TupleTableSlot * ri_PartitionTupleSlot
Definition: execnodes.h:568
List * ri_notMatchedMergeAction
Definition: execnodes.h:536
bool ri_projectNewInfoValid
Definition: execnodes.h:472
OnConflictSetState * ri_onConflict
Definition: execnodes.h:532
List * ri_onConflictArbiterIndexes
Definition: execnodes.h:529
Instrumentation * ri_TrigInstrument
Definition: execnodes.h:484
RelationPtr ri_IndexRelationDescs
Definition: execnodes.h:454
struct ModifyTableState * ri_ModifyTableState
Definition: execnodes.h:580
TupleTableSlot * ri_ReturningSlot
Definition: execnodes.h:487
ExprState ** ri_GeneratedExprs
Definition: execnodes.h:517
TupleTableSlot * ri_oldTupleSlot
Definition: execnodes.h:470
bool ri_RootToChildMapValid
Definition: execnodes.h:554
struct CopyMultiInsertBuffer * ri_CopyMultiInsertBuffer
Definition: execnodes.h:571
TriggerDesc * ri_TrigDesc
Definition: execnodes.h:475
TupleConversionMap * ri_ChildToRootMap
Definition: execnodes.h:547
void * ri_FdwState
Definition: execnodes.h:495
bool ri_ChildToRootMapValid
Definition: execnodes.h:548
TupleTableSlot * ri_newTupleSlot
Definition: execnodes.h:468
ProjectionInfo * ri_projectNew
Definition: execnodes.h:466
NodeTag type
Definition: execnodes.h:442
ProjectionInfo * ri_projectReturning
Definition: execnodes.h:526
ExprState ** ri_TrigWhenExprs
Definition: execnodes.h:481
FmgrInfo * ri_TrigFunctions
Definition: execnodes.h:478
bool ri_usesFdwDirectModify
Definition: execnodes.h:498
AttrNumber ri_RowIdAttNo
Definition: execnodes.h:463
IndexInfo ** ri_IndexRelationInfo
Definition: execnodes.h:457
TupleTableSlot * ri_TrigNewSlot
Definition: execnodes.h:489
TupleTableSlot * ri_TrigOldSlot
Definition: execnodes.h:488
int numtriggers
Definition: reltrigger.h:50
TriggerDesc * CopyTriggerDesc(TriggerDesc *trigdesc)
Definition: trigger.c:2090

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_FdwRoutine, ResultRelInfo::ri_FdwState, ResultRelInfo::ri_GeneratedExprs, ResultRelInfo::ri_IndexRelationDescs, ResultRelInfo::ri_IndexRelationInfo, ResultRelInfo::ri_matchedMergeAction, ResultRelInfo::ri_ModifyTableState, 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 470 of file execMain.c.

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

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

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

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

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

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

Referenced by _PG_init(), and ExecCheckRTPerms().

◆ ExecutorEnd_hook

ExecutorEnd_hook_type ExecutorEnd_hook = NULL

Definition at line 75 of file execMain.c.

Referenced by _PG_init(), and ExecutorEnd().

◆ ExecutorFinish_hook

ExecutorFinish_hook_type ExecutorFinish_hook = NULL

Definition at line 74 of file execMain.c.

Referenced by _PG_init(), and ExecutorFinish().

◆ ExecutorRun_hook

ExecutorRun_hook_type ExecutorRun_hook = NULL

Definition at line 73 of file execMain.c.

Referenced by _PG_init(), and ExecutorRun().

◆ ExecutorStart_hook

ExecutorStart_hook_type ExecutorStart_hook = NULL

Definition at line 72 of file execMain.c.

Referenced by _PG_init(), and ExecutorStart().