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

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

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

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

Referenced by InitPlan().

◆ EvalPlanQual()

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

Definition at line 2457 of file execMain.c.

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

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

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

◆ EvalPlanQualBegin()

void EvalPlanQualBegin ( EPQState epqstate)

Definition at line 2720 of file execMain.c.

2721 {
2722  EState *parentestate = epqstate->parentestate;
2723  EState *recheckestate = epqstate->recheckestate;
2724 
2725  if (recheckestate == NULL)
2726  {
2727  /* First time through, so create a child EState */
2728  EvalPlanQualStart(epqstate, epqstate->plan);
2729  }
2730  else
2731  {
2732  /*
2733  * We already have a suitable child EPQ tree, so just reset it.
2734  */
2735  Index rtsize = parentestate->es_range_table_size;
2736  PlanState *rcplanstate = epqstate->recheckplanstate;
2737 
2738  MemSet(epqstate->relsubs_done, 0, rtsize * sizeof(bool));
2739 
2740  /* Recopy current values of parent parameters */
2741  if (parentestate->es_plannedstmt->paramExecTypes != NIL)
2742  {
2743  int i;
2744 
2745  /*
2746  * Force evaluation of any InitPlan outputs that could be needed
2747  * by the subplan, just in case they got reset since
2748  * EvalPlanQualStart (see comments therein).
2749  */
2750  ExecSetParamPlanMulti(rcplanstate->plan->extParam,
2751  GetPerTupleExprContext(parentestate));
2752 
2753  i = list_length(parentestate->es_plannedstmt->paramExecTypes);
2754 
2755  while (--i >= 0)
2756  {
2757  /* copy value if any, but not execPlan link */
2758  recheckestate->es_param_exec_vals[i].value =
2759  parentestate->es_param_exec_vals[i].value;
2760  recheckestate->es_param_exec_vals[i].isnull =
2761  parentestate->es_param_exec_vals[i].isnull;
2762  }
2763  }
2764 
2765  /*
2766  * Mark child plan tree as needing rescan at all scan nodes. The
2767  * first ExecProcNode will take care of actually doing the rescan.
2768  */
2769  rcplanstate->chgParam = bms_add_member(rcplanstate->chgParam,
2770  epqstate->epqParam);
2771  }
2772 }
Bitmapset * bms_add_member(Bitmapset *a, int x)
Definition: bitmapset.c:738
unsigned int Index
Definition: c.h:560
#define MemSet(start, val, len)
Definition: c.h:1019
static void EvalPlanQualStart(EPQState *epqstate, Plan *planTree)
Definition: execMain.c:2781
#define GetPerTupleExprContext(estate)
Definition: executor.h:537
int i
Definition: isn.c:73
void ExecSetParamPlanMulti(const Bitmapset *params, ExprContext *econtext)
Definition: nodeSubplan.c:1253
static int list_length(const List *l)
Definition: pg_list.h:149
#define NIL
Definition: pg_list.h:65
Plan * plan
Definition: execnodes.h:1151
int epqParam
Definition: execnodes.h:1136
EState * parentestate
Definition: execnodes.h:1135
EState * recheckestate
Definition: execnodes.h:1165
PlanState * recheckplanstate
Definition: execnodes.h:1180
bool * relsubs_done
Definition: execnodes.h:1178
PlannedStmt * es_plannedstmt
Definition: execnodes.h:598
ParamExecData * es_param_exec_vals
Definition: execnodes.h:627
Index es_range_table_size
Definition: execnodes.h:593
bool isnull
Definition: params.h:150
Datum value
Definition: params.h:149
Plan * plan
Definition: execnodes.h:998
Bitmapset * chgParam
Definition: execnodes.h:1030
Bitmapset * extParam
Definition: plannodes.h:160
List * paramExecTypes
Definition: plannodes.h:85

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

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

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

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

◆ EvalPlanQualFetchRowMark()

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

Definition at line 2595 of file execMain.c.

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

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

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

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

◆ EvalPlanQualNext()

TupleTableSlot* EvalPlanQualNext ( EPQState epqstate)

Definition at line 2704 of file execMain.c.

2705 {
2706  MemoryContext oldcontext;
2707  TupleTableSlot *slot;
2708 
2709  oldcontext = MemoryContextSwitchTo(epqstate->recheckestate->es_query_cxt);
2710  slot = ExecProcNode(epqstate->recheckplanstate);
2711  MemoryContextSwitchTo(oldcontext);
2712 
2713  return slot;
2714 }
static TupleTableSlot * ExecProcNode(PlanState *node)
Definition: executor.h: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 2550 of file execMain.c.

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

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

Referenced by ExecInitModifyTable().

◆ EvalPlanQualSlot()

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

Definition at line 2567 of file execMain.c.

2569 {
2570  TupleTableSlot **slot;
2571 
2572  Assert(relation);
2573  Assert(rti > 0 && rti <= epqstate->parentestate->es_range_table_size);
2574  slot = &epqstate->relsubs_slot[rti - 1];
2575 
2576  if (*slot == NULL)
2577  {
2578  MemoryContext oldcontext;
2579 
2580  oldcontext = MemoryContextSwitchTo(epqstate->parentestate->es_query_cxt);
2581  *slot = table_slot_create(relation, &epqstate->tuple_table);
2582  MemoryContextSwitchTo(oldcontext);
2583  }
2584 
2585  return *slot;
2586 }
TupleTableSlot * table_slot_create(Relation relation, List **reglist)
Definition: tableam.c:91

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

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

◆ EvalPlanQualStart()

static void EvalPlanQualStart ( EPQState epqstate,
Plan planTree 
)
static

Definition at line 2781 of file execMain.c.

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

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

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

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

Referenced by ExecInitLockRows(), and ExecInitModifyTable().

◆ ExecBuildSlotValueDescription()

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

Definition at line 2201 of file execMain.c.

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

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 = 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:176
@ ACLMASK_ALL
Definition: acl.h:175
AclResult pg_attribute_aclcheck_all(Oid table_oid, Oid roleid, AclMode mode, AclMaskHow how)
Definition: aclchk.c:4922
AclMode pg_class_aclmask(Oid table_oid, Oid roleid, AclMode mask, AclMaskHow how)
Definition: aclchk.c:4032
int16 AttrNumber
Definition: attnum.h:21
#define InvalidAttrNumber
Definition: attnum.h:23
int bms_next_member(const Bitmapset *a, int prevbit)
Definition: bitmapset.c:1045
bool bms_is_empty(const Bitmapset *a)
Definition: bitmapset.c:703
static bool ExecCheckRTEPermsModified(Oid relOid, Oid userid, Bitmapset *modifiedCols, AclMode requiredPerms)
Definition: execMain.c:721
#define ACL_INSERT
Definition: parsenodes.h:82
#define ACL_UPDATE
Definition: parsenodes.h:84
@ RTE_RELATION
Definition: parsenodes.h:998
uint32 AclMode
Definition: parsenodes.h:80
AclMode requiredPerms
Definition: parsenodes.h:1165
Bitmapset * updatedCols
Definition: parsenodes.h:1169
Bitmapset * selectedCols
Definition: parsenodes.h:1167
Bitmapset * insertedCols
Definition: parsenodes.h:1168
RTEKind rtekind
Definition: parsenodes.h:1015

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

Referenced by ExecCheckRTPerms().

◆ 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:183
void aclcheck_error(AclResult aclerr, ObjectType objtype, const char *objectname)
Definition: aclchk.c:3512
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:1984
char * get_rel_name(Oid relid)
Definition: lsyscache.c:1909
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:1933
bool isTempNamespace(Oid namespaceId)
Definition: namespace.c:3203
@ CMD_SELECT
Definition: nodes.h:721
Definition: nodes.h:574
bool hasModifyingCTE
Definition: plannodes.h:53
CmdType commandType
Definition: plannodes.h:47
List * rtable
Definition: plannodes.h:67
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 1567 of file execMain.c.

1568 {
1569  int i;
1570 
1571  for (i = 0; i < estate->es_range_table_size; i++)
1572  {
1573  if (estate->es_relations[i])
1574  table_close(estate->es_relations[i], NoLock);
1575  }
1576 }
#define NoLock
Definition: lockdefs.h:34
void table_close(Relation relation, LOCKMODE lockmode)
Definition: table.c:167

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

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

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

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

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

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

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

Referenced by standard_ExecutorEnd().

◆ ExecFindRowMark()

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

Definition at line 2364 of file execMain.c.

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

References elog, ERROR, and EState::es_rowmarks.

Referenced by ExecInitLockRows(), and ExecInitModifyTable().

◆ ExecGetAncestorResultRels()

List* ExecGetAncestorResultRels ( EState estate,
ResultRelInfo resultRelInfo 
)

Definition at line 1362 of file execMain.c.

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

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

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

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

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

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

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

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

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

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

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

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

Referenced by ExecConstraints().

◆ ExecUpdateLockMode()

LockTupleMode ExecUpdateLockMode ( EState estate,
ResultRelInfo relinfo 
)

Definition at line 2338 of file execMain.c.

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

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

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

◆ ExecutePlan()

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

Definition at line 1591 of file execMain.c.

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

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:49
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 2039 of file execMain.c.

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

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

References Assert(), bms_is_member(), CheckValidRowMarkRel(), CMD_SELECT, ExecRowMark::curCtid, elog, ExecRowMark::ermActive, ExecRowMark::ermExtra, ERROR, EState::es_epq_active, EState::es_junkFilter, EState::es_plannedstmt, EState::es_range_table_size, EState::es_rowmarks, EState::es_subplanstates, EState::es_tupleTable, QueryDesc::estate, EXEC_FLAG_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(), 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 1195 of file execMain.c.

1200 {
1201  MemSet(resultRelInfo, 0, sizeof(ResultRelInfo));
1202  resultRelInfo->type = T_ResultRelInfo;
1203  resultRelInfo->ri_RangeTableIndex = resultRelationIndex;
1204  resultRelInfo->ri_RelationDesc = resultRelationDesc;
1205  resultRelInfo->ri_NumIndices = 0;
1206  resultRelInfo->ri_IndexRelationDescs = NULL;
1207  resultRelInfo->ri_IndexRelationInfo = NULL;
1208  /* make a copy so as not to depend on relcache info not changing... */
1209  resultRelInfo->ri_TrigDesc = CopyTriggerDesc(resultRelationDesc->trigdesc);
1210  if (resultRelInfo->ri_TrigDesc)
1211  {
1212  int n = resultRelInfo->ri_TrigDesc->numtriggers;
1213 
1214  resultRelInfo->ri_TrigFunctions = (FmgrInfo *)
1215  palloc0(n * sizeof(FmgrInfo));
1216  resultRelInfo->ri_TrigWhenExprs = (ExprState **)
1217  palloc0(n * sizeof(ExprState *));
1218  if (instrument_options)
1219  resultRelInfo->ri_TrigInstrument = InstrAlloc(n, instrument_options, false);
1220  }
1221  else
1222  {
1223  resultRelInfo->ri_TrigFunctions = NULL;
1224  resultRelInfo->ri_TrigWhenExprs = NULL;
1225  resultRelInfo->ri_TrigInstrument = NULL;
1226  }
1227  if (resultRelationDesc->rd_rel->relkind == RELKIND_FOREIGN_TABLE)
1228  resultRelInfo->ri_FdwRoutine = GetFdwRoutineForRelation(resultRelationDesc, true);
1229  else
1230  resultRelInfo->ri_FdwRoutine = NULL;
1231 
1232  /* The following fields are set later if needed */
1233  resultRelInfo->ri_RowIdAttNo = 0;
1234  resultRelInfo->ri_projectNew = NULL;
1235  resultRelInfo->ri_newTupleSlot = NULL;
1236  resultRelInfo->ri_oldTupleSlot = NULL;
1237  resultRelInfo->ri_projectNewInfoValid = false;
1238  resultRelInfo->ri_FdwState = NULL;
1239  resultRelInfo->ri_usesFdwDirectModify = false;
1240  resultRelInfo->ri_ConstraintExprs = NULL;
1241  resultRelInfo->ri_GeneratedExprs = NULL;
1242  resultRelInfo->ri_projectReturning = NULL;
1243  resultRelInfo->ri_onConflictArbiterIndexes = NIL;
1244  resultRelInfo->ri_onConflict = NULL;
1245  resultRelInfo->ri_ReturningSlot = NULL;
1246  resultRelInfo->ri_TrigOldSlot = NULL;
1247  resultRelInfo->ri_TrigNewSlot = NULL;
1248  resultRelInfo->ri_matchedMergeAction = NIL;
1249  resultRelInfo->ri_notMatchedMergeAction = NIL;
1250 
1251  /*
1252  * Only ExecInitPartitionInfo() and ExecInitPartitionDispatchInfo() pass
1253  * non-NULL partition_root_rri. For child relations that are part of the
1254  * initial query rather than being dynamically added by tuple routing,
1255  * this field is filled in ExecInitModifyTable().
1256  */
1257  resultRelInfo->ri_RootResultRelInfo = partition_root_rri;
1258  resultRelInfo->ri_RootToPartitionMap = NULL; /* set by
1259  * ExecInitRoutingInfo */
1260  resultRelInfo->ri_PartitionTupleSlot = NULL; /* ditto */
1261  resultRelInfo->ri_ChildToRootMap = NULL;
1262  resultRelInfo->ri_ChildToRootMapValid = false;
1263  resultRelInfo->ri_CopyMultiInsertBuffer = NULL;
1264 }
Instrumentation * InstrAlloc(int n, int instrument_options, bool async_mode)
Definition: instrument.c:31
@ T_ResultRelInfo
Definition: nodes.h:39
Definition: fmgr.h:57
List * ri_matchedMergeAction
Definition: execnodes.h:520
TupleTableSlot * ri_PartitionTupleSlot
Definition: execnodes.h:540
List * ri_notMatchedMergeAction
Definition: execnodes.h:521
bool ri_projectNewInfoValid
Definition: execnodes.h:457
OnConflictSetState * ri_onConflict
Definition: execnodes.h:517
List * ri_onConflictArbiterIndexes
Definition: execnodes.h:514
Instrumentation * ri_TrigInstrument
Definition: execnodes.h:469
RelationPtr ri_IndexRelationDescs
Definition: execnodes.h:439
TupleTableSlot * ri_ReturningSlot
Definition: execnodes.h:472
ExprState ** ri_GeneratedExprs
Definition: execnodes.h:502
TupleTableSlot * ri_oldTupleSlot
Definition: execnodes.h:455
struct CopyMultiInsertBuffer * ri_CopyMultiInsertBuffer
Definition: execnodes.h:552
TriggerDesc * ri_TrigDesc
Definition: execnodes.h:460
TupleConversionMap * ri_ChildToRootMap
Definition: execnodes.h:548
void * ri_FdwState
Definition: execnodes.h:480
bool ri_ChildToRootMapValid
Definition: execnodes.h:549
TupleTableSlot * ri_newTupleSlot
Definition: execnodes.h:453
ProjectionInfo * ri_projectNew
Definition: execnodes.h:451
NodeTag type
Definition: execnodes.h:427
ProjectionInfo * ri_projectReturning
Definition: execnodes.h:511
ExprState ** ri_TrigWhenExprs
Definition: execnodes.h:466
FmgrInfo * ri_TrigFunctions
Definition: execnodes.h:463
TupleConversionMap * ri_RootToPartitionMap
Definition: execnodes.h:539
bool ri_usesFdwDirectModify
Definition: execnodes.h:483
AttrNumber ri_RowIdAttNo
Definition: execnodes.h:448
IndexInfo ** ri_IndexRelationInfo
Definition: execnodes.h:442
TupleTableSlot * ri_TrigNewSlot
Definition: execnodes.h:474
TupleTableSlot * ri_TrigOldSlot
Definition: execnodes.h:473
int numtriggers
Definition: reltrigger.h:50
TriggerDesc * CopyTriggerDesc(TriggerDesc *trigdesc)
Definition: trigger.c:2099

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_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_RootToPartitionMap, ResultRelInfo::ri_RowIdAttNo, ResultRelInfo::ri_TrigDesc, ResultRelInfo::ri_TrigFunctions, ResultRelInfo::ri_TrigInstrument, ResultRelInfo::ri_TrigNewSlot, ResultRelInfo::ri_TrigOldSlot, ResultRelInfo::ri_TrigWhenExprs, ResultRelInfo::ri_usesFdwDirectModify, T_ResultRelInfo, RelationData::trigdesc, and ResultRelInfo::type.

Referenced by 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:1468
void UnregisterSnapshot(Snapshot snapshot)
Definition: snapmgr.c:869
bool es_finished
Definition: execnodes.h:640
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:1422
#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:4981

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:1591
#define ScanDirectionIsNoMovement(direction)
Definition: sdir.h:48
bool hasReturning
Definition: plannodes.h:51
bool parallelModeNeeded
Definition: plannodes.h:61
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:725
Snapshot RegisterSnapshot(Snapshot snapshot)
Definition: snapmgr.c:827
int es_jit_flags
Definition: execnodes.h:677
const char * es_sourceText
Definition: execnodes.h:599
int jitFlags
Definition: plannodes.h:63
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:4961
bool XactReadOnly
Definition: xact.c:81
bool IsInParallelMode(void)
Definition: xact.c:1065
CommandId GetCurrentCommandId(bool used)
Definition: xact.c:814

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