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

Go to the source code of this file.

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

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

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

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

◆ CheckValidRowMarkRel()

static void CheckValidRowMarkRel ( Relation  rel,
RowMarkType  markType 
)
static

Definition at line 1117 of file execMain.c.

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

Referenced by InitPlan().

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

◆ EvalPlanQual()

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

Definition at line 2327 of file execMain.c.

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

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

2329 {
2330  TupleTableSlot *slot;
2331  TupleTableSlot *testslot;
2332 
2333  Assert(rti > 0);
2334 
2335  /*
2336  * Need to run a recheck subquery. Initialize or reinitialize EPQ state.
2337  */
2338  EvalPlanQualBegin(epqstate);
2339 
2340  /*
2341  * Callers will often use the EvalPlanQualSlot to store the tuple to avoid
2342  * an unnecessary copy.
2343  */
2344  testslot = EvalPlanQualSlot(epqstate, relation, rti);
2345  if (testslot != inputslot)
2346  ExecCopySlot(testslot, inputslot);
2347 
2348  /*
2349  * Run the EPQ query. We assume it will return at most one tuple.
2350  */
2351  slot = EvalPlanQualNext(epqstate);
2352 
2353  /*
2354  * If we got a tuple, force the slot to materialize the tuple so that it
2355  * is not dependent on any local state in the EPQ query (in particular,
2356  * it's highly likely that the slot contains references to any pass-by-ref
2357  * datums that may be present in copyTuple). As with the next step, this
2358  * is to guard against early re-use of the EPQ query.
2359  */
2360  if (!TupIsNull(slot))
2361  ExecMaterializeSlot(slot);
2362 
2363  /*
2364  * Clear out the test tuple. This is needed in case the EPQ query is
2365  * re-used to test a tuple for a different relation. (Not clear that can
2366  * really happen, but let's be safe.)
2367  */
2368  ExecClearTuple(testslot);
2369 
2370  return slot;
2371 }
static TupleTableSlot * ExecCopySlot(TupleTableSlot *dstslot, TupleTableSlot *srcslot)
Definition: tuptable.h:475
static TupleTableSlot * ExecClearTuple(TupleTableSlot *slot)
Definition: tuptable.h:425
TupleTableSlot * EvalPlanQualNext(EPQState *epqstate)
Definition: execMain.c:2573
TupleTableSlot * EvalPlanQualSlot(EPQState *epqstate, Relation relation, Index rti)
Definition: execMain.c:2436
#define TupIsNull(slot)
Definition: tuptable.h:292
static void ExecMaterializeSlot(TupleTableSlot *slot)
Definition: tuptable.h:443
#define Assert(condition)
Definition: c.h:804
void EvalPlanQualBegin(EPQState *epqstate)
Definition: execMain.c:2589

◆ EvalPlanQualBegin()

void EvalPlanQualBegin ( EPQState epqstate)

Definition at line 2589 of file execMain.c.

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

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

2590 {
2591  EState *parentestate = epqstate->parentestate;
2592  EState *recheckestate = epqstate->recheckestate;
2593 
2594  if (recheckestate == NULL)
2595  {
2596  /* First time through, so create a child EState */
2597  EvalPlanQualStart(epqstate, epqstate->plan);
2598  }
2599  else
2600  {
2601  /*
2602  * We already have a suitable child EPQ tree, so just reset it.
2603  */
2604  Index rtsize = parentestate->es_range_table_size;
2605  PlanState *rcplanstate = epqstate->recheckplanstate;
2606 
2607  MemSet(epqstate->relsubs_done, 0, rtsize * sizeof(bool));
2608 
2609  /* Recopy current values of parent parameters */
2610  if (parentestate->es_plannedstmt->paramExecTypes != NIL)
2611  {
2612  int i;
2613 
2614  /*
2615  * Force evaluation of any InitPlan outputs that could be needed
2616  * by the subplan, just in case they got reset since
2617  * EvalPlanQualStart (see comments therein).
2618  */
2619  ExecSetParamPlanMulti(rcplanstate->plan->extParam,
2620  GetPerTupleExprContext(parentestate));
2621 
2622  i = list_length(parentestate->es_plannedstmt->paramExecTypes);
2623 
2624  while (--i >= 0)
2625  {
2626  /* copy value if any, but not execPlan link */
2627  recheckestate->es_param_exec_vals[i].value =
2628  parentestate->es_param_exec_vals[i].value;
2629  recheckestate->es_param_exec_vals[i].isnull =
2630  parentestate->es_param_exec_vals[i].isnull;
2631  }
2632  }
2633 
2634  /*
2635  * Mark child plan tree as needing rescan at all scan nodes. The
2636  * first ExecProcNode will take care of actually doing the rescan.
2637  */
2638  rcplanstate->chgParam = bms_add_member(rcplanstate->chgParam,
2639  epqstate->epqParam);
2640  }
2641 }
List * paramExecTypes
Definition: plannodes.h:84
#define NIL
Definition: pg_list.h:65
void ExecSetParamPlanMulti(const Bitmapset *params, ExprContext *econtext)
Definition: nodeSubplan.c:1253
PlannedStmt * es_plannedstmt
Definition: execnodes.h:538
#define MemSet(start, val, len)
Definition: c.h:1008
EState * parentestate
Definition: execnodes.h:1077
#define GetPerTupleExprContext(estate)
Definition: executor.h:509
ParamExecData * es_param_exec_vals
Definition: execnodes.h:567
EState * recheckestate
Definition: execnodes.h:1107
bool isnull
Definition: params.h:150
static void EvalPlanQualStart(EPQState *epqstate, Plan *planTree)
Definition: execMain.c:2650
bool * relsubs_done
Definition: execnodes.h:1120
Bitmapset * chgParam
Definition: execnodes.h:973
Plan * plan
Definition: execnodes.h:1093
unsigned int Index
Definition: c.h:549
Plan * plan
Definition: execnodes.h:941
static int list_length(const List *l)
Definition: pg_list.h:149
Bitmapset * extParam
Definition: plannodes.h:154
Index es_range_table_size
Definition: execnodes.h:533
Bitmapset * bms_add_member(Bitmapset *a, int x)
Definition: bitmapset.c:736
int i
Datum value
Definition: params.h:149
int epqParam
Definition: execnodes.h:1078
PlanState * recheckplanstate
Definition: execnodes.h:1122

◆ EvalPlanQualEnd()

void EvalPlanQualEnd ( EPQState epqstate)

Definition at line 2801 of file execMain.c.

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(), and ExecEndModifyTable().

2802 {
2803  EState *estate = epqstate->recheckestate;
2804  Index rtsize;
2805  MemoryContext oldcontext;
2806  ListCell *l;
2807 
2808  rtsize = epqstate->parentestate->es_range_table_size;
2809 
2810  /*
2811  * We may have a tuple table, even if EPQ wasn't started, because we allow
2812  * use of EvalPlanQualSlot() without calling EvalPlanQualBegin().
2813  */
2814  if (epqstate->tuple_table != NIL)
2815  {
2816  memset(epqstate->relsubs_slot, 0,
2817  rtsize * sizeof(TupleTableSlot *));
2818  ExecResetTupleTable(epqstate->tuple_table, true);
2819  epqstate->tuple_table = NIL;
2820  }
2821 
2822  /* EPQ wasn't started, nothing further to do */
2823  if (estate == NULL)
2824  return;
2825 
2826  oldcontext = MemoryContextSwitchTo(estate->es_query_cxt);
2827 
2828  ExecEndNode(epqstate->recheckplanstate);
2829 
2830  foreach(l, estate->es_subplanstates)
2831  {
2832  PlanState *subplanstate = (PlanState *) lfirst(l);
2833 
2834  ExecEndNode(subplanstate);
2835  }
2836 
2837  /* throw away the per-estate tuple table, some node may have used it */
2838  ExecResetTupleTable(estate->es_tupleTable, false);
2839 
2840  /* Close any result and trigger target relations attached to this EState */
2841  ExecCloseResultRelations(estate);
2842 
2843  MemoryContextSwitchTo(oldcontext);
2844 
2845  FreeExecutorState(estate);
2846 
2847  /* Mark EPQState idle */
2848  epqstate->origslot = NULL;
2849  epqstate->recheckestate = NULL;
2850  epqstate->recheckplanstate = NULL;
2851  epqstate->relsubs_rowmark = NULL;
2852  epqstate->relsubs_done = NULL;
2853 }
TupleTableSlot ** relsubs_slot
Definition: execnodes.h:1086
#define NIL
Definition: pg_list.h:65
void ExecEndNode(PlanState *node)
Definition: execProcnode.c:543
void ExecCloseResultRelations(EState *estate)
Definition: execMain.c:1416
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:109
EState * parentestate
Definition: execnodes.h:1077
void FreeExecutorState(EState *estate)
Definition: execUtils.c:186
MemoryContext es_query_cxt
Definition: execnodes.h:572
EState * recheckestate
Definition: execnodes.h:1107
List * tuple_table
Definition: execnodes.h:1085
bool * relsubs_done
Definition: execnodes.h:1120
TupleTableSlot * origslot
Definition: execnodes.h:1102
List * es_tupleTable
Definition: execnodes.h:574
void ExecResetTupleTable(List *tupleTable, bool shouldFree)
Definition: execTuples.c:1161
unsigned int Index
Definition: c.h:549
#define lfirst(lc)
Definition: pg_list.h:169
Index es_range_table_size
Definition: execnodes.h:533
List * es_subplanstates
Definition: execnodes.h:584
ExecAuxRowMark ** relsubs_rowmark
Definition: execnodes.h:1114
PlanState * recheckplanstate
Definition: execnodes.h:1122

◆ EvalPlanQualFetchRowMark()

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

Definition at line 2464 of file execMain.c.

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

Referenced by ExecScanFetch().

2465 {
2466  ExecAuxRowMark *earm = epqstate->relsubs_rowmark[rti - 1];
2467  ExecRowMark *erm = earm->rowmark;
2468  Datum datum;
2469  bool isNull;
2470 
2471  Assert(earm != NULL);
2472  Assert(epqstate->origslot != NULL);
2473 
2475  elog(ERROR, "EvalPlanQual doesn't support locking rowmarks");
2476 
2477  /* if child rel, must check whether it produced this row */
2478  if (erm->rti != erm->prti)
2479  {
2480  Oid tableoid;
2481 
2482  datum = ExecGetJunkAttribute(epqstate->origslot,
2483  earm->toidAttNo,
2484  &isNull);
2485  /* non-locked rels could be on the inside of outer joins */
2486  if (isNull)
2487  return false;
2488 
2489  tableoid = DatumGetObjectId(datum);
2490 
2491  Assert(OidIsValid(erm->relid));
2492  if (tableoid != erm->relid)
2493  {
2494  /* this child is inactive right now */
2495  return false;
2496  }
2497  }
2498 
2499  if (erm->markType == ROW_MARK_REFERENCE)
2500  {
2501  Assert(erm->relation != NULL);
2502 
2503  /* fetch the tuple's ctid */
2504  datum = ExecGetJunkAttribute(epqstate->origslot,
2505  earm->ctidAttNo,
2506  &isNull);
2507  /* non-locked rels could be on the inside of outer joins */
2508  if (isNull)
2509  return false;
2510 
2511  /* fetch requests on foreign tables must be passed to their FDW */
2512  if (erm->relation->rd_rel->relkind == RELKIND_FOREIGN_TABLE)
2513  {
2514  FdwRoutine *fdwroutine;
2515  bool updated = false;
2516 
2517  fdwroutine = GetFdwRoutineForRelation(erm->relation, false);
2518  /* this should have been checked already, but let's be safe */
2519  if (fdwroutine->RefetchForeignRow == NULL)
2520  ereport(ERROR,
2521  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2522  errmsg("cannot lock rows in foreign table \"%s\"",
2524 
2525  fdwroutine->RefetchForeignRow(epqstate->recheckestate,
2526  erm,
2527  datum,
2528  slot,
2529  &updated);
2530  if (TupIsNull(slot))
2531  elog(ERROR, "failed to fetch tuple for EvalPlanQual recheck");
2532 
2533  /*
2534  * Ideally we'd insist on updated == false here, but that assumes
2535  * that FDWs can track that exactly, which they might not be able
2536  * to. So just ignore the flag.
2537  */
2538  return true;
2539  }
2540  else
2541  {
2542  /* ordinary table, fetch the tuple */
2544  (ItemPointer) DatumGetPointer(datum),
2545  SnapshotAny, slot))
2546  elog(ERROR, "failed to fetch tuple for EvalPlanQual recheck");
2547  return true;
2548  }
2549  }
2550  else
2551  {
2552  Assert(erm->markType == ROW_MARK_COPY);
2553 
2554  /* fetch the whole-row Var for the relation */
2555  datum = ExecGetJunkAttribute(epqstate->origslot,
2556  earm->wholeAttNo,
2557  &isNull);
2558  /* non-locked rels could be on the inside of outer joins */
2559  if (isNull)
2560  return false;
2561 
2562  ExecStoreHeapTupleDatum(datum, slot);
2563  return true;
2564  }
2565 }
Relation relation
Definition: execnodes.h:644
#define DatumGetObjectId(X)
Definition: postgres.h:500
int errcode(int sqlerrcode)
Definition: elog.c:704
Form_pg_class rd_rel
Definition: rel.h:110
unsigned int Oid
Definition: postgres_ext.h:31
#define OidIsValid(objectId)
Definition: c.h:710
#define RowMarkRequiresRowShareLock(marktype)
Definition: plannodes.h:1033
ExecRowMark * rowmark
Definition: execnodes.h:671
#define ERROR
Definition: elog.h:45
EState * recheckestate
Definition: execnodes.h:1107
Index rti
Definition: execnodes.h:646
AttrNumber wholeAttNo
Definition: execnodes.h:674
Index prti
Definition: execnodes.h:647
#define RelationGetRelationName(relation)
Definition: rel.h:491
#define TupIsNull(slot)
Definition: tuptable.h:292
TupleTableSlot * origslot
Definition: execnodes.h:1102
void ExecStoreHeapTupleDatum(Datum data, TupleTableSlot *slot)
Definition: execTuples.c:1576
static bool table_tuple_fetch_row_version(Relation rel, ItemPointer tid, Snapshot snapshot, TupleTableSlot *slot)
Definition: tableam.h:1170
uintptr_t Datum
Definition: postgres.h:367
#define ereport(elevel,...)
Definition: elog.h:155
#define Assert(condition)
Definition: c.h:804
RowMarkType markType
Definition: execnodes.h:649
AttrNumber toidAttNo
Definition: execnodes.h:673
#define SnapshotAny
Definition: snapmgr.h:68
#define DatumGetPointer(X)
Definition: postgres.h:549
int errmsg(const char *fmt,...)
Definition: elog.c:915
FdwRoutine * GetFdwRoutineForRelation(Relation relation, bool makecopy)
Definition: foreign.c:427
Datum ExecGetJunkAttribute(TupleTableSlot *slot, AttrNumber attno, bool *isNull)
Definition: execJunk.c:273
#define elog(elevel,...)
Definition: elog.h:228
ExecAuxRowMark ** relsubs_rowmark
Definition: execnodes.h:1114
AttrNumber ctidAttNo
Definition: execnodes.h:672
RefetchForeignRow_function RefetchForeignRow
Definition: fdwapi.h:235

◆ EvalPlanQualInit()

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

Definition at line 2381 of file execMain.c.

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

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

2383 {
2384  Index rtsize = parentestate->es_range_table_size;
2385 
2386  /* initialize data not changing over EPQState's lifetime */
2387  epqstate->parentestate = parentestate;
2388  epqstate->epqParam = epqParam;
2389 
2390  /*
2391  * Allocate space to reference a slot for each potential rti - do so now
2392  * rather than in EvalPlanQualBegin(), as done for other dynamically
2393  * allocated resources, so EvalPlanQualSlot() can be used to hold tuples
2394  * that *may* need EPQ later, without forcing the overhead of
2395  * EvalPlanQualBegin().
2396  */
2397  epqstate->tuple_table = NIL;
2398  epqstate->relsubs_slot = (TupleTableSlot **)
2399  palloc0(rtsize * sizeof(TupleTableSlot *));
2400 
2401  /* ... and remember data that EvalPlanQualBegin will need */
2402  epqstate->plan = subplan;
2403  epqstate->arowMarks = auxrowmarks;
2404 
2405  /* ... and mark the EPQ state inactive */
2406  epqstate->origslot = NULL;
2407  epqstate->recheckestate = NULL;
2408  epqstate->recheckplanstate = NULL;
2409  epqstate->relsubs_rowmark = NULL;
2410  epqstate->relsubs_done = NULL;
2411 }
TupleTableSlot ** relsubs_slot
Definition: execnodes.h:1086
#define NIL
Definition: pg_list.h:65
EState * parentestate
Definition: execnodes.h:1077
EState * recheckestate
Definition: execnodes.h:1107
List * arowMarks
Definition: execnodes.h:1094
List * tuple_table
Definition: execnodes.h:1085
bool * relsubs_done
Definition: execnodes.h:1120
TupleTableSlot * origslot
Definition: execnodes.h:1102
Plan * plan
Definition: execnodes.h:1093
void * palloc0(Size size)
Definition: mcxt.c:981
unsigned int Index
Definition: c.h:549
Index es_range_table_size
Definition: execnodes.h:533
int epqParam
Definition: execnodes.h:1078
ExecAuxRowMark ** relsubs_rowmark
Definition: execnodes.h:1114
PlanState * recheckplanstate
Definition: execnodes.h:1122

◆ EvalPlanQualNext()

TupleTableSlot* EvalPlanQualNext ( EPQState epqstate)

Definition at line 2573 of file execMain.c.

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

Referenced by EvalPlanQual(), and ExecLockRows().

2574 {
2575  MemoryContext oldcontext;
2576  TupleTableSlot *slot;
2577 
2578  oldcontext = MemoryContextSwitchTo(epqstate->recheckestate->es_query_cxt);
2579  slot = ExecProcNode(epqstate->recheckplanstate);
2580  MemoryContextSwitchTo(oldcontext);
2581 
2582  return slot;
2583 }
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:109
MemoryContext es_query_cxt
Definition: execnodes.h:572
EState * recheckestate
Definition: execnodes.h:1107
static TupleTableSlot * ExecProcNode(PlanState *node)
Definition: executor.h:242
PlanState * recheckplanstate
Definition: execnodes.h:1122

◆ EvalPlanQualSetPlan()

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

Definition at line 2419 of file execMain.c.

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

Referenced by ExecInitModifyTable(), and ExecModifyTable().

2420 {
2421  /* If we have a live EPQ query, shut it down */
2422  EvalPlanQualEnd(epqstate);
2423  /* And set/change the plan pointer */
2424  epqstate->plan = subplan;
2425  /* The rowmarks depend on the plan, too */
2426  epqstate->arowMarks = auxrowmarks;
2427 }
void EvalPlanQualEnd(EPQState *epqstate)
Definition: execMain.c:2801
List * arowMarks
Definition: execnodes.h:1094
Plan * plan
Definition: execnodes.h:1093

◆ EvalPlanQualSlot()

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

Definition at line 2436 of file execMain.c.

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

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

2438 {
2439  TupleTableSlot **slot;
2440 
2441  Assert(relation);
2442  Assert(rti > 0 && rti <= epqstate->parentestate->es_range_table_size);
2443  slot = &epqstate->relsubs_slot[rti - 1];
2444 
2445  if (*slot == NULL)
2446  {
2447  MemoryContext oldcontext;
2448 
2449  oldcontext = MemoryContextSwitchTo(epqstate->parentestate->es_query_cxt);
2450  *slot = table_slot_create(relation, &epqstate->tuple_table);
2451  MemoryContextSwitchTo(oldcontext);
2452  }
2453 
2454  return *slot;
2455 }
TupleTableSlot * table_slot_create(Relation relation, List **reglist)
Definition: tableam.c:91
TupleTableSlot ** relsubs_slot
Definition: execnodes.h:1086
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:109
EState * parentestate
Definition: execnodes.h:1077
MemoryContext es_query_cxt
Definition: execnodes.h:572
List * tuple_table
Definition: execnodes.h:1085
#define Assert(condition)
Definition: c.h:804

◆ EvalPlanQualStart()

static void EvalPlanQualStart ( EPQState epqstate,
Plan planTree 
)
static

Definition at line 2650 of file execMain.c.

References EPQState::arowMarks, Assert, CreateExecutorState(), EState::es_crosscheck_snapshot, EState::es_direction, EState::es_epq_active, EState::es_instrument, EState::es_junkFilter, EState::es_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().

2651 {
2652  EState *parentestate = epqstate->parentestate;
2653  Index rtsize = parentestate->es_range_table_size;
2654  EState *rcestate;
2655  MemoryContext oldcontext;
2656  ListCell *l;
2657 
2658  epqstate->recheckestate = rcestate = CreateExecutorState();
2659 
2660  oldcontext = MemoryContextSwitchTo(rcestate->es_query_cxt);
2661 
2662  /* signal that this is an EState for executing EPQ */
2663  rcestate->es_epq_active = epqstate;
2664 
2665  /*
2666  * Child EPQ EStates share the parent's copy of unchanging state such as
2667  * the snapshot, rangetable, and external Param info. They need their own
2668  * copies of local state, including a tuple table, es_param_exec_vals,
2669  * result-rel info, etc.
2670  */
2671  rcestate->es_direction = ForwardScanDirection;
2672  rcestate->es_snapshot = parentestate->es_snapshot;
2673  rcestate->es_crosscheck_snapshot = parentestate->es_crosscheck_snapshot;
2674  rcestate->es_range_table = parentestate->es_range_table;
2675  rcestate->es_range_table_size = parentestate->es_range_table_size;
2676  rcestate->es_relations = parentestate->es_relations;
2677  rcestate->es_queryEnv = parentestate->es_queryEnv;
2678  rcestate->es_rowmarks = parentestate->es_rowmarks;
2679  rcestate->es_plannedstmt = parentestate->es_plannedstmt;
2680  rcestate->es_junkFilter = parentestate->es_junkFilter;
2681  rcestate->es_output_cid = parentestate->es_output_cid;
2682 
2683  /*
2684  * ResultRelInfos needed by subplans are initialized from scratch when the
2685  * subplans themselves are initialized.
2686  */
2687  rcestate->es_result_relations = NULL;
2688  /* es_trig_target_relations must NOT be copied */
2689  rcestate->es_top_eflags = parentestate->es_top_eflags;
2690  rcestate->es_instrument = parentestate->es_instrument;
2691  /* es_auxmodifytables must NOT be copied */
2692 
2693  /*
2694  * The external param list is simply shared from parent. The internal
2695  * param workspace has to be local state, but we copy the initial values
2696  * from the parent, so as to have access to any param values that were
2697  * already set from other parts of the parent's plan tree.
2698  */
2699  rcestate->es_param_list_info = parentestate->es_param_list_info;
2700  if (parentestate->es_plannedstmt->paramExecTypes != NIL)
2701  {
2702  int i;
2703 
2704  /*
2705  * Force evaluation of any InitPlan outputs that could be needed by
2706  * the subplan. (With more complexity, maybe we could postpone this
2707  * till the subplan actually demands them, but it doesn't seem worth
2708  * the trouble; this is a corner case already, since usually the
2709  * InitPlans would have been evaluated before reaching EvalPlanQual.)
2710  *
2711  * This will not touch output params of InitPlans that occur somewhere
2712  * within the subplan tree, only those that are attached to the
2713  * ModifyTable node or above it and are referenced within the subplan.
2714  * That's OK though, because the planner would only attach such
2715  * InitPlans to a lower-level SubqueryScan node, and EPQ execution
2716  * will not descend into a SubqueryScan.
2717  *
2718  * The EState's per-output-tuple econtext is sufficiently short-lived
2719  * for this, since it should get reset before there is any chance of
2720  * doing EvalPlanQual again.
2721  */
2722  ExecSetParamPlanMulti(planTree->extParam,
2723  GetPerTupleExprContext(parentestate));
2724 
2725  /* now make the internal param workspace ... */
2726  i = list_length(parentestate->es_plannedstmt->paramExecTypes);
2727  rcestate->es_param_exec_vals = (ParamExecData *)
2728  palloc0(i * sizeof(ParamExecData));
2729  /* ... and copy down all values, whether really needed or not */
2730  while (--i >= 0)
2731  {
2732  /* copy value if any, but not execPlan link */
2733  rcestate->es_param_exec_vals[i].value =
2734  parentestate->es_param_exec_vals[i].value;
2735  rcestate->es_param_exec_vals[i].isnull =
2736  parentestate->es_param_exec_vals[i].isnull;
2737  }
2738  }
2739 
2740  /*
2741  * Initialize private state information for each SubPlan. We must do this
2742  * before running ExecInitNode on the main query tree, since
2743  * ExecInitSubPlan expects to be able to find these entries. Some of the
2744  * SubPlans might not be used in the part of the plan tree we intend to
2745  * run, but since it's not easy to tell which, we just initialize them
2746  * all.
2747  */
2748  Assert(rcestate->es_subplanstates == NIL);
2749  foreach(l, parentestate->es_plannedstmt->subplans)
2750  {
2751  Plan *subplan = (Plan *) lfirst(l);
2752  PlanState *subplanstate;
2753 
2754  subplanstate = ExecInitNode(subplan, rcestate, 0);
2755  rcestate->es_subplanstates = lappend(rcestate->es_subplanstates,
2756  subplanstate);
2757  }
2758 
2759  /*
2760  * Build an RTI indexed array of rowmarks, so that
2761  * EvalPlanQualFetchRowMark() can efficiently access the to be fetched
2762  * rowmark.
2763  */
2764  epqstate->relsubs_rowmark = (ExecAuxRowMark **)
2765  palloc0(rtsize * sizeof(ExecAuxRowMark *));
2766  foreach(l, epqstate->arowMarks)
2767  {
2768  ExecAuxRowMark *earm = (ExecAuxRowMark *) lfirst(l);
2769 
2770  epqstate->relsubs_rowmark[earm->rowmark->rti - 1] = earm;
2771  }
2772 
2773  /*
2774  * Initialize per-relation EPQ tuple states to not-fetched.
2775  */
2776  epqstate->relsubs_done = (bool *)
2777  palloc0(rtsize * sizeof(bool));
2778 
2779  /*
2780  * Initialize the private state information for all the nodes in the part
2781  * of the plan tree we need to run. This opens files, allocates storage
2782  * and leaves us ready to start processing tuples.
2783  */
2784  epqstate->recheckplanstate = ExecInitNode(planTree, rcestate, 0);
2785 
2786  MemoryContextSwitchTo(oldcontext);
2787 }
List * paramExecTypes
Definition: plannodes.h:84
#define NIL
Definition: pg_list.h:65
JunkFilter * es_junkFilter
Definition: execnodes.h:541
void ExecSetParamPlanMulti(const Bitmapset *params, ExprContext *econtext)
Definition: nodeSubplan.c:1253
CommandId es_output_cid
Definition: execnodes.h:544
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:109
PlannedStmt * es_plannedstmt
Definition: execnodes.h:538
Snapshot es_crosscheck_snapshot
Definition: execnodes.h:531
Snapshot es_snapshot
Definition: execnodes.h:530
List * es_range_table
Definition: execnodes.h:532
EState * parentestate
Definition: execnodes.h:1077
ScanDirection es_direction
Definition: execnodes.h:529
struct EPQState * es_epq_active
Definition: execnodes.h:601
ExecRowMark * rowmark
Definition: execnodes.h:671
struct ExecRowMark ** es_rowmarks
Definition: execnodes.h:536
#define GetPerTupleExprContext(estate)
Definition: executor.h:509
ParamExecData * es_param_exec_vals
Definition: execnodes.h:567
MemoryContext es_query_cxt
Definition: execnodes.h:572
EState * recheckestate
Definition: execnodes.h:1107
bool isnull
Definition: params.h:150
List * arowMarks
Definition: execnodes.h:1094
Index rti
Definition: execnodes.h:646
bool * relsubs_done
Definition: execnodes.h:1120
int es_instrument
Definition: execnodes.h:579
ResultRelInfo ** es_result_relations
Definition: execnodes.h:547
EState * CreateExecutorState(void)
Definition: execUtils.c:90
List * lappend(List *list, void *datum)
Definition: list.c:336
QueryEnvironment * es_queryEnv
Definition: execnodes.h:569
void * palloc0(Size size)
Definition: mcxt.c:981
unsigned int Index
Definition: c.h:549
List * subplans
Definition: plannodes.h:73
#define Assert(condition)
Definition: c.h:804
#define lfirst(lc)
Definition: pg_list.h:169
Relation * es_relations
Definition: execnodes.h:534
static int list_length(const List *l)
Definition: pg_list.h:149
Bitmapset * extParam
Definition: plannodes.h:154
Index es_range_table_size
Definition: execnodes.h:533
List * es_subplanstates
Definition: execnodes.h:584
int es_top_eflags
Definition: execnodes.h:578
int i
Datum value
Definition: params.h:149
ParamListInfo es_param_list_info
Definition: execnodes.h:566
PlanState * ExecInitNode(Plan *node, EState *estate, int eflags)
Definition: execProcnode.c:139
ExecAuxRowMark ** relsubs_rowmark
Definition: execnodes.h:1114
PlanState * recheckplanstate
Definition: execnodes.h:1122

◆ ExecBuildAuxRowMark()

ExecAuxRowMark* ExecBuildAuxRowMark ( ExecRowMark erm,
List targetlist 
)

Definition at line 2257 of file execMain.c.

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

Referenced by ExecInitLockRows(), and ExecInitModifyTable().

2258 {
2259  ExecAuxRowMark *aerm = (ExecAuxRowMark *) palloc0(sizeof(ExecAuxRowMark));
2260  char resname[32];
2261 
2262  aerm->rowmark = erm;
2263 
2264  /* Look up the resjunk columns associated with this rowmark */
2265  if (erm->markType != ROW_MARK_COPY)
2266  {
2267  /* need ctid for all methods other than COPY */
2268  snprintf(resname, sizeof(resname), "ctid%u", erm->rowmarkId);
2269  aerm->ctidAttNo = ExecFindJunkAttributeInTlist(targetlist,
2270  resname);
2271  if (!AttributeNumberIsValid(aerm->ctidAttNo))
2272  elog(ERROR, "could not find junk %s column", resname);
2273  }
2274  else
2275  {
2276  /* need wholerow if COPY */
2277  snprintf(resname, sizeof(resname), "wholerow%u", erm->rowmarkId);
2278  aerm->wholeAttNo = ExecFindJunkAttributeInTlist(targetlist,
2279  resname);
2280  if (!AttributeNumberIsValid(aerm->wholeAttNo))
2281  elog(ERROR, "could not find junk %s column", resname);
2282  }
2283 
2284  /* if child rel, need tableoid */
2285  if (erm->rti != erm->prti)
2286  {
2287  snprintf(resname, sizeof(resname), "tableoid%u", erm->rowmarkId);
2288  aerm->toidAttNo = ExecFindJunkAttributeInTlist(targetlist,
2289  resname);
2290  if (!AttributeNumberIsValid(aerm->toidAttNo))
2291  elog(ERROR, "could not find junk %s column", resname);
2292  }
2293 
2294  return aerm;
2295 }
AttrNumber ExecFindJunkAttributeInTlist(List *targetlist, const char *attrName)
Definition: execJunk.c:246
ExecRowMark * rowmark
Definition: execnodes.h:671
#define ERROR
Definition: elog.h:45
Index rti
Definition: execnodes.h:646
AttrNumber wholeAttNo
Definition: execnodes.h:674
Index prti
Definition: execnodes.h:647
Index rowmarkId
Definition: execnodes.h:648
#define AttributeNumberIsValid(attributeNumber)
Definition: attnum.h:34
void * palloc0(Size size)
Definition: mcxt.c:981
RowMarkType markType
Definition: execnodes.h:649
AttrNumber toidAttNo
Definition: execnodes.h:673
#define elog(elevel,...)
Definition: elog.h:228
#define snprintf
Definition: port.h:215
AttrNumber ctidAttNo
Definition: execnodes.h:672

◆ ExecBuildSlotValueDescription()

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

Definition at line 2071 of file execMain.c.

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

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

2076 {
2078  StringInfoData collist;
2079  bool write_comma = false;
2080  bool write_comma_collist = false;
2081  int i;
2082  AclResult aclresult;
2083  bool table_perm = false;
2084  bool any_perm = false;
2085 
2086  /*
2087  * Check if RLS is enabled and should be active for the relation; if so,
2088  * then don't return anything. Otherwise, go through normal permission
2089  * checks.
2090  */
2091  if (check_enable_rls(reloid, InvalidOid, true) == RLS_ENABLED)
2092  return NULL;
2093 
2094  initStringInfo(&buf);
2095 
2096  appendStringInfoChar(&buf, '(');
2097 
2098  /*
2099  * Check if the user has permissions to see the row. Table-level SELECT
2100  * allows access to all columns. If the user does not have table-level
2101  * SELECT then we check each column and include those the user has SELECT
2102  * rights on. Additionally, we always include columns the user provided
2103  * data for.
2104  */
2105  aclresult = pg_class_aclcheck(reloid, GetUserId(), ACL_SELECT);
2106  if (aclresult != ACLCHECK_OK)
2107  {
2108  /* Set up the buffer for the column list */
2109  initStringInfo(&collist);
2110  appendStringInfoChar(&collist, '(');
2111  }
2112  else
2113  table_perm = any_perm = true;
2114 
2115  /* Make sure the tuple is fully deconstructed */
2116  slot_getallattrs(slot);
2117 
2118  for (i = 0; i < tupdesc->natts; i++)
2119  {
2120  bool column_perm = false;
2121  char *val;
2122  int vallen;
2123  Form_pg_attribute att = TupleDescAttr(tupdesc, i);
2124 
2125  /* ignore dropped columns */
2126  if (att->attisdropped)
2127  continue;
2128 
2129  if (!table_perm)
2130  {
2131  /*
2132  * No table-level SELECT, so need to make sure they either have
2133  * SELECT rights on the column or that they have provided the data
2134  * for the column. If not, omit this column from the error
2135  * message.
2136  */
2137  aclresult = pg_attribute_aclcheck(reloid, att->attnum,
2138  GetUserId(), ACL_SELECT);
2140  modifiedCols) || aclresult == ACLCHECK_OK)
2141  {
2142  column_perm = any_perm = true;
2143 
2144  if (write_comma_collist)
2145  appendStringInfoString(&collist, ", ");
2146  else
2147  write_comma_collist = true;
2148 
2149  appendStringInfoString(&collist, NameStr(att->attname));
2150  }
2151  }
2152 
2153  if (table_perm || column_perm)
2154  {
2155  if (slot->tts_isnull[i])
2156  val = "null";
2157  else
2158  {
2159  Oid foutoid;
2160  bool typisvarlena;
2161 
2162  getTypeOutputInfo(att->atttypid,
2163  &foutoid, &typisvarlena);
2164  val = OidOutputFunctionCall(foutoid, slot->tts_values[i]);
2165  }
2166 
2167  if (write_comma)
2168  appendStringInfoString(&buf, ", ");
2169  else
2170  write_comma = true;
2171 
2172  /* truncate if needed */
2173  vallen = strlen(val);
2174  if (vallen <= maxfieldlen)
2175  appendBinaryStringInfo(&buf, val, vallen);
2176  else
2177  {
2178  vallen = pg_mbcliplen(val, vallen, maxfieldlen);
2179  appendBinaryStringInfo(&buf, val, vallen);
2180  appendStringInfoString(&buf, "...");
2181  }
2182  }
2183  }
2184 
2185  /* If we end up with zero columns being returned, then return NULL. */
2186  if (!any_perm)
2187  return NULL;
2188 
2189  appendStringInfoChar(&buf, ')');
2190 
2191  if (!table_perm)
2192  {
2193  appendStringInfoString(&collist, ") = ");
2194  appendBinaryStringInfo(&collist, buf.data, buf.len);
2195 
2196  return collist.data;
2197  }
2198 
2199  return buf.data;
2200 }
void getTypeOutputInfo(Oid type, Oid *typOutput, bool *typIsVarlena)
Definition: lsyscache.c:2854
AclResult pg_attribute_aclcheck(Oid table_oid, AttrNumber attnum, Oid roleid, AclMode mode)
Definition: aclchk.c:4468
Oid GetUserId(void)
Definition: miscinit.c:476
#define TupleDescAttr(tupdesc, i)
Definition: tupdesc.h:92
Datum * tts_values
Definition: tuptable.h:126
#define FirstLowInvalidHeapAttributeNumber
Definition: sysattr.h:27
unsigned int Oid
Definition: postgres_ext.h:31
int pg_mbcliplen(const char *mbstr, int len, int limit)
Definition: mbutils.c:967
static void slot_getallattrs(TupleTableSlot *slot)
Definition: tuptable.h:354
void appendStringInfoString(StringInfo str, const char *s)
Definition: stringinfo.c:176
static char * buf
Definition: pg_test_fsync.c:68
bool * tts_isnull
Definition: tuptable.h:128
FormData_pg_attribute * Form_pg_attribute
Definition: pg_attribute.h:197
void appendStringInfoChar(StringInfo str, char ch)
Definition: stringinfo.c:188
void initStringInfo(StringInfo str)
Definition: stringinfo.c:59
AclResult
Definition: acl.h:177
#define ACL_SELECT
Definition: parsenodes.h:75
#define InvalidOid
Definition: postgres_ext.h:36
int check_enable_rls(Oid relid, Oid checkAsUser, bool noError)
Definition: rls.c:52
AclResult pg_class_aclcheck(Oid table_oid, Oid roleid, AclMode mode)
Definition: aclchk.c:4582
char * OidOutputFunctionCall(Oid functionId, Datum val)
Definition: fmgr.c:1656
int i
#define NameStr(name)
Definition: c.h:681
bool bms_is_member(int x, const Bitmapset *a)
Definition: bitmapset.c:427
void appendBinaryStringInfo(StringInfo str, const char *data, int datalen)
Definition: stringinfo.c:227
long val
Definition: informix.c:664

◆ ExecCheckRTEPerms()

static bool ExecCheckRTEPerms ( RangeTblEntry rte)
static

Definition at line 588 of file execMain.c.

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

Referenced by ExecCheckRTPerms().

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

◆ ExecCheckRTEPermsModified()

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

Definition at line 708 of file execMain.c.

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

Referenced by ExecCheckRTEPerms().

710 {
711  int col = -1;
712 
713  /*
714  * When the query doesn't explicitly update any columns, allow the query
715  * if we have permission on any column of the rel. This is to handle
716  * SELECT FOR UPDATE as well as possible corner cases in UPDATE.
717  */
718  if (bms_is_empty(modifiedCols))
719  {
720  if (pg_attribute_aclcheck_all(relOid, userid, requiredPerms,
722  return false;
723  }
724 
725  while ((col = bms_next_member(modifiedCols, col)) >= 0)
726  {
727  /* bit #s are offset by FirstLowInvalidHeapAttributeNumber */
729 
730  if (attno == InvalidAttrNumber)
731  {
732  /* whole-row reference can't happen here */
733  elog(ERROR, "whole-row update is not implemented");
734  }
735  else
736  {
737  if (pg_attribute_aclcheck(relOid, attno, userid,
738  requiredPerms) != ACLCHECK_OK)
739  return false;
740  }
741  }
742  return true;
743 }
AclResult pg_attribute_aclcheck(Oid table_oid, AttrNumber attnum, Oid roleid, AclMode mode)
Definition: aclchk.c:4468
int bms_next_member(const Bitmapset *a, int prevbit)
Definition: bitmapset.c:1043
#define FirstLowInvalidHeapAttributeNumber
Definition: sysattr.h:27
#define ERROR
Definition: elog.h:45
bool bms_is_empty(const Bitmapset *a)
Definition: bitmapset.c:701
AclResult pg_attribute_aclcheck_all(Oid table_oid, Oid roleid, AclMode mode, AclMaskHow how)
Definition: aclchk.c:4497
#define InvalidAttrNumber
Definition: attnum.h:23
#define elog(elevel,...)
Definition: elog.h:228
int16 AttrNumber
Definition: attnum.h:21

◆ ExecCheckRTPerms()

bool ExecCheckRTPerms ( List rangeTable,
bool  ereport_on_violation 
)

Definition at line 557 of file execMain.c.

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

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

558 {
559  ListCell *l;
560  bool result = true;
561 
562  foreach(l, rangeTable)
563  {
564  RangeTblEntry *rte = (RangeTblEntry *) lfirst(l);
565 
566  result = ExecCheckRTEPerms(rte);
567  if (!result)
568  {
569  Assert(rte->rtekind == RTE_RELATION);
570  if (ereport_on_violation)
572  get_rel_name(rte->relid));
573  return false;
574  }
575  }
576 
578  result = (*ExecutorCheckPerms_hook) (rangeTable,
579  ereport_on_violation);
580  return result;
581 }
char get_rel_relkind(Oid relid)
Definition: lsyscache.c:1974
void aclcheck_error(AclResult aclerr, ObjectType objtype, const char *objectname)
Definition: aclchk.c:3313
static bool ExecCheckRTEPerms(RangeTblEntry *rte)
Definition: execMain.c:588
ExecutorCheckPerms_hook_type ExecutorCheckPerms_hook
Definition: execMain.c:76
#define Assert(condition)
Definition: c.h:804
#define lfirst(lc)
Definition: pg_list.h:169
RTEKind rtekind
Definition: parsenodes.h:981
ObjectType get_relkind_objtype(char relkind)
char * get_rel_name(Oid relid)
Definition: lsyscache.c:1899

◆ ExecCheckXactReadOnly()

static void ExecCheckXactReadOnly ( PlannedStmt plannedstmt)
static

Definition at line 755 of file execMain.c.

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

Referenced by standard_ExecutorStart().

756 {
757  ListCell *l;
758 
759  /*
760  * Fail if write permissions are requested in parallel mode for table
761  * (temp or non-temp), otherwise fail for any non-temp table.
762  */
763  foreach(l, plannedstmt->rtable)
764  {
765  RangeTblEntry *rte = (RangeTblEntry *) lfirst(l);
766 
767  if (rte->rtekind != RTE_RELATION)
768  continue;
769 
770  if ((rte->requiredPerms & (~ACL_SELECT)) == 0)
771  continue;
772 
774  continue;
775 
777  }
778 
779  if (plannedstmt->commandType != CMD_SELECT || plannedstmt->hasModifyingCTE)
781 }
void PreventCommandIfParallelMode(const char *cmdname)
Definition: utility.c:426
static const char * CreateCommandName(Node *parsetree)
Definition: utility.h:99
Oid get_rel_namespace(Oid relid)
Definition: lsyscache.c:1923
Definition: nodes.h:530
AclMode requiredPerms
Definition: parsenodes.h:1124
bool isTempNamespace(Oid namespaceId)
Definition: namespace.c:3156
CmdType commandType
Definition: plannodes.h:46
#define ACL_SELECT
Definition: parsenodes.h:75
#define lfirst(lc)
Definition: pg_list.h:169
bool hasModifyingCTE
Definition: plannodes.h:52
List * rtable
Definition: plannodes.h:66
void PreventCommandIfReadOnly(const char *cmdname)
Definition: utility.c:408
RTEKind rtekind
Definition: parsenodes.h:981

◆ ExecCloseRangeTableRelations()

void ExecCloseRangeTableRelations ( EState estate)

Definition at line 1459 of file execMain.c.

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

Referenced by CopyFrom(), and ExecEndPlan().

1460 {
1461  int i;
1462 
1463  for (i = 0; i < estate->es_range_table_size; i++)
1464  {
1465  if (estate->es_relations[i])
1466  table_close(estate->es_relations[i], NoLock);
1467  }
1468 }
void table_close(Relation relation, LOCKMODE lockmode)
Definition: table.c:167
#define NoLock
Definition: lockdefs.h:34
Relation * es_relations
Definition: execnodes.h:534
Index es_range_table_size
Definition: execnodes.h:533
int i

◆ ExecCloseResultRelations()

void ExecCloseResultRelations ( EState estate)

Definition at line 1416 of file execMain.c.

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

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

1417 {
1418  ListCell *l;
1419 
1420  /*
1421  * close indexes of result relation(s) if any. (Rels themselves are
1422  * closed in ExecCloseRangeTableRelations())
1423  */
1424  foreach(l, estate->es_opened_result_relations)
1425  {
1426  ResultRelInfo *resultRelInfo = lfirst(l);
1427 
1428  ExecCloseIndices(resultRelInfo);
1429  }
1430 
1431  /* Close any relations that have been opened by ExecGetTriggerResultRel(). */
1432  foreach(l, estate->es_trig_target_relations)
1433  {
1434  ResultRelInfo *resultRelInfo = (ResultRelInfo *) lfirst(l);
1435 
1436  /*
1437  * Assert this is a "dummy" ResultRelInfo, see above. Otherwise we
1438  * might be issuing a duplicate close against a Relation opened by
1439  * ExecGetRangeTableRelation.
1440  */
1441  Assert(resultRelInfo->ri_RangeTableIndex == 0);
1442 
1443  /*
1444  * Since ExecGetTriggerResultRel doesn't call ExecOpenIndices for
1445  * these rels, we needn't call ExecCloseIndices either.
1446  */
1447  Assert(resultRelInfo->ri_NumIndices == 0);
1448 
1449  table_close(resultRelInfo->ri_RelationDesc, NoLock);
1450  }
1451 }
int ri_NumIndices
Definition: execnodes.h:418
Relation ri_RelationDesc
Definition: execnodes.h:415
void table_close(Relation relation, LOCKMODE lockmode)
Definition: table.c:167
Index ri_RangeTableIndex
Definition: execnodes.h:412
#define NoLock
Definition: lockdefs.h:34
List * es_opened_result_relations
Definition: execnodes.h:550
List * es_trig_target_relations
Definition: execnodes.h:563
#define Assert(condition)
Definition: c.h:804
#define lfirst(lc)
Definition: pg_list.h:169
void ExecCloseIndices(ResultRelInfo *resultRelInfo)
Definition: execIndexing.c:231

◆ ExecConstraints()

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

Definition at line 1789 of file execMain.c.

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, TupleConstr::num_check, RelationGetDescr, RelationGetRelationName, RelationGetRelid, ResultRelInfo::ri_RelationDesc, ResultRelInfo::ri_RootResultRelInfo, slot_attisnull(), TTSOpsVirtual, and TupleDescAttr.

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

1791 {
1792  Relation rel = resultRelInfo->ri_RelationDesc;
1793  TupleDesc tupdesc = RelationGetDescr(rel);
1794  TupleConstr *constr = tupdesc->constr;
1795  Bitmapset *modifiedCols;
1796 
1797  Assert(constr); /* we should not be called otherwise */
1798 
1799  if (constr->has_not_null)
1800  {
1801  int natts = tupdesc->natts;
1802  int attrChk;
1803 
1804  for (attrChk = 1; attrChk <= natts; attrChk++)
1805  {
1806  Form_pg_attribute att = TupleDescAttr(tupdesc, attrChk - 1);
1807 
1808  if (att->attnotnull && slot_attisnull(slot, attrChk))
1809  {
1810  char *val_desc;
1811  Relation orig_rel = rel;
1812  TupleDesc orig_tupdesc = RelationGetDescr(rel);
1813 
1814  /*
1815  * If the tuple has been routed, it's been converted to the
1816  * partition's rowtype, which might differ from the root
1817  * table's. We must convert it back to the root table's
1818  * rowtype so that val_desc shown error message matches the
1819  * input tuple.
1820  */
1821  if (resultRelInfo->ri_RootResultRelInfo)
1822  {
1823  ResultRelInfo *rootrel = resultRelInfo->ri_RootResultRelInfo;
1824  AttrMap *map;
1825 
1826  tupdesc = RelationGetDescr(rootrel->ri_RelationDesc);
1827  /* a reverse map */
1828  map = build_attrmap_by_name_if_req(orig_tupdesc,
1829  tupdesc);
1830 
1831  /*
1832  * Partition-specific slot's tupdesc can't be changed, so
1833  * allocate a new one.
1834  */
1835  if (map != NULL)
1836  slot = execute_attr_map_slot(map, slot,
1837  MakeTupleTableSlot(tupdesc, &TTSOpsVirtual));
1838  modifiedCols = bms_union(ExecGetInsertedCols(rootrel, estate),
1839  ExecGetUpdatedCols(rootrel, estate));
1840  rel = rootrel->ri_RelationDesc;
1841  }
1842  else
1843  modifiedCols = bms_union(ExecGetInsertedCols(resultRelInfo, estate),
1844  ExecGetUpdatedCols(resultRelInfo, estate));
1846  slot,
1847  tupdesc,
1848  modifiedCols,
1849  64);
1850 
1851  ereport(ERROR,
1852  (errcode(ERRCODE_NOT_NULL_VIOLATION),
1853  errmsg("null value in column \"%s\" of relation \"%s\" violates not-null constraint",
1854  NameStr(att->attname),
1855  RelationGetRelationName(orig_rel)),
1856  val_desc ? errdetail("Failing row contains %s.", val_desc) : 0,
1857  errtablecol(orig_rel, attrChk)));
1858  }
1859  }
1860  }
1861 
1862  if (constr->num_check > 0)
1863  {
1864  const char *failed;
1865 
1866  if ((failed = ExecRelCheck(resultRelInfo, slot, estate)) != NULL)
1867  {
1868  char *val_desc;
1869  Relation orig_rel = rel;
1870 
1871  /* See the comment above. */
1872  if (resultRelInfo->ri_RootResultRelInfo)
1873  {
1874  ResultRelInfo *rootrel = resultRelInfo->ri_RootResultRelInfo;
1875  TupleDesc old_tupdesc = RelationGetDescr(rel);
1876  AttrMap *map;
1877 
1878  tupdesc = RelationGetDescr(rootrel->ri_RelationDesc);
1879  /* a reverse map */
1880  map = build_attrmap_by_name_if_req(old_tupdesc,
1881  tupdesc);
1882 
1883  /*
1884  * Partition-specific slot's tupdesc can't be changed, so
1885  * allocate a new one.
1886  */
1887  if (map != NULL)
1888  slot = execute_attr_map_slot(map, slot,
1889  MakeTupleTableSlot(tupdesc, &TTSOpsVirtual));
1890  modifiedCols = bms_union(ExecGetInsertedCols(rootrel, estate),
1891  ExecGetUpdatedCols(rootrel, estate));
1892  rel = rootrel->ri_RelationDesc;
1893  }
1894  else
1895  modifiedCols = bms_union(ExecGetInsertedCols(resultRelInfo, estate),
1896  ExecGetUpdatedCols(resultRelInfo, estate));
1898  slot,
1899  tupdesc,
1900  modifiedCols,
1901  64);
1902  ereport(ERROR,
1903  (errcode(ERRCODE_CHECK_VIOLATION),
1904  errmsg("new row for relation \"%s\" violates check constraint \"%s\"",
1905  RelationGetRelationName(orig_rel), failed),
1906  val_desc ? errdetail("Failing row contains %s.", val_desc) : 0,
1907  errtableconstraint(orig_rel, failed)));
1908  }
1909  }
1910 }
Relation ri_RelationDesc
Definition: execnodes.h:415
#define RelationGetDescr(relation)
Definition: rel.h:483
#define TupleDescAttr(tupdesc, i)
Definition: tupdesc.h:92
Bitmapset * ExecGetUpdatedCols(ResultRelInfo *relinfo, EState *estate)
Definition: execUtils.c:1269
const TupleTableSlotOps TTSOpsVirtual
Definition: execTuples.c:83
int errcode(int sqlerrcode)
Definition: elog.c:704
Definition: attmap.h:34
int errtableconstraint(Relation rel, const char *conname)
Definition: relcache.c:5563
AttrMap * build_attrmap_by_name_if_req(TupleDesc indesc, TupleDesc outdesc)
Definition: attmap.c:259
#define ERROR
Definition: elog.h:45
static char * ExecBuildSlotValueDescription(Oid reloid, TupleTableSlot *slot, TupleDesc tupdesc, Bitmapset *modifiedCols, int maxfieldlen)
Definition: execMain.c:2071
struct ResultRelInfo * ri_RootResultRelInfo
Definition: execnodes.h:503
TupleConstr * constr
Definition: tupdesc.h:85
int errdetail(const char *fmt,...)
Definition: elog.c:1048
#define RelationGetRelationName(relation)
Definition: rel.h:491
FormData_pg_attribute * Form_pg_attribute
Definition: pg_attribute.h:197
TupleTableSlot * MakeTupleTableSlot(TupleDesc tupleDesc, const TupleTableSlotOps *tts_ops)
Definition: execTuples.c:1082
uint16 num_check
Definition: tupdesc.h:43
static const char * ExecRelCheck(ResultRelInfo *resultRelInfo, TupleTableSlot *slot, EState *estate)
Definition: execMain.c:1599
#define ereport(elevel,...)
Definition: elog.h:155
TupleTableSlot * execute_attr_map_slot(AttrMap *attrMap, TupleTableSlot *in_slot, TupleTableSlot *out_slot)
Definition: tupconvert.c:177
#define Assert(condition)
Definition: c.h:804
int errtablecol(Relation rel, int attnum)
Definition: relcache.c:5526
Bitmapset * bms_union(const Bitmapset *a, const Bitmapset *b)
Definition: bitmapset.c:225
Bitmapset * ExecGetInsertedCols(ResultRelInfo *relinfo, EState *estate)
Definition: execUtils.c:1230
int errmsg(const char *fmt,...)
Definition: elog.c:915
#define NameStr(name)
Definition: c.h:681
bool has_not_null
Definition: tupdesc.h:44
static bool slot_attisnull(TupleTableSlot *slot, int attnum)
Definition: tuptable.h:367
#define RelationGetRelid(relation)
Definition: rel.h:457

◆ ExecEndPlan()

static void ExecEndPlan ( PlanState planstate,
EState estate 
)
static

Definition at line 1377 of file execMain.c.

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

Referenced by standard_ExecutorEnd().

1378 {
1379  ListCell *l;
1380 
1381  /*
1382  * shut down the node-type-specific query processing
1383  */
1384  ExecEndNode(planstate);
1385 
1386  /*
1387  * for subplans too
1388  */
1389  foreach(l, estate->es_subplanstates)
1390  {
1391  PlanState *subplanstate = (PlanState *) lfirst(l);
1392 
1393  ExecEndNode(subplanstate);
1394  }
1395 
1396  /*
1397  * destroy the executor's tuple table. Actually we only care about
1398  * releasing buffer pins and tupdesc refcounts; there's no need to pfree
1399  * the TupleTableSlots, since the containing memory context is about to go
1400  * away anyway.
1401  */
1402  ExecResetTupleTable(estate->es_tupleTable, false);
1403 
1404  /*
1405  * Close any Relations that have been opened for range table entries or
1406  * result relations.
1407  */
1408  ExecCloseResultRelations(estate);
1410 }
void ExecEndNode(PlanState *node)
Definition: execProcnode.c:543
void ExecCloseResultRelations(EState *estate)
Definition: execMain.c:1416
void ExecCloseRangeTableRelations(EState *estate)
Definition: execMain.c:1459
List * es_tupleTable
Definition: execnodes.h:574
void ExecResetTupleTable(List *tupleTable, bool shouldFree)
Definition: execTuples.c:1161
#define lfirst(lc)
Definition: pg_list.h:169
List * es_subplanstates
Definition: execnodes.h:584

◆ ExecFindRowMark()

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

Definition at line 2234 of file execMain.c.

References elog, ERROR, and EState::es_rowmarks.

Referenced by ExecInitLockRows(), and ExecInitModifyTable().

2235 {
2236  if (rti > 0 && rti <= estate->es_range_table_size &&
2237  estate->es_rowmarks != NULL)
2238  {
2239  ExecRowMark *erm = estate->es_rowmarks[rti - 1];
2240 
2241  if (erm)
2242  return erm;
2243  }
2244  if (!missing_ok)
2245  elog(ERROR, "failed to find ExecRowMark for rangetable index %u", rti);
2246  return NULL;
2247 }
struct ExecRowMark ** es_rowmarks
Definition: execnodes.h:536
#define ERROR
Definition: elog.h:45
#define elog(elevel,...)
Definition: elog.h:228

◆ ExecGetTriggerResultRel()

ResultRelInfo* ExecGetTriggerResultRel ( EState estate,
Oid  relid 
)

Definition at line 1259 of file execMain.c.

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

1260 {
1261  ResultRelInfo *rInfo;
1262  ListCell *l;
1263  Relation rel;
1264  MemoryContext oldcontext;
1265 
1266  /* First, search through the query result relations */
1267  foreach(l, estate->es_opened_result_relations)
1268  {
1269  rInfo = lfirst(l);
1270  if (RelationGetRelid(rInfo->ri_RelationDesc) == relid)
1271  return rInfo;
1272  }
1273 
1274  /*
1275  * Third, search through the result relations that were created during
1276  * tuple routing, if any.
1277  */
1278  foreach(l, estate->es_tuple_routing_result_relations)
1279  {
1280  rInfo = (ResultRelInfo *) lfirst(l);
1281  if (RelationGetRelid(rInfo->ri_RelationDesc) == relid)
1282  return rInfo;
1283  }
1284 
1285  /* Nope, but maybe we already made an extra ResultRelInfo for it */
1286  foreach(l, estate->es_trig_target_relations)
1287  {
1288  rInfo = (ResultRelInfo *) lfirst(l);
1289  if (RelationGetRelid(rInfo->ri_RelationDesc) == relid)
1290  return rInfo;
1291  }
1292  /* Nope, so we need a new one */
1293 
1294  /*
1295  * Open the target relation's relcache entry. We assume that an
1296  * appropriate lock is still held by the backend from whenever the trigger
1297  * event got queued, so we need take no new lock here. Also, we need not
1298  * recheck the relkind, so no need for CheckValidResultRel.
1299  */
1300  rel = table_open(relid, NoLock);
1301 
1302  /*
1303  * Make the new entry in the right context.
1304  */
1305  oldcontext = MemoryContextSwitchTo(estate->es_query_cxt);
1306  rInfo = makeNode(ResultRelInfo);
1307  InitResultRelInfo(rInfo,
1308  rel,
1309  0, /* dummy rangetable index */
1310  NULL,
1311  estate->es_instrument);
1312  estate->es_trig_target_relations =
1313  lappend(estate->es_trig_target_relations, rInfo);
1314  MemoryContextSwitchTo(oldcontext);
1315 
1316  /*
1317  * Currently, we don't need any index information in ResultRelInfos used
1318  * only for triggers, so no need to call ExecOpenIndices.
1319  */
1320 
1321  return rInfo;
1322 }
Relation ri_RelationDesc
Definition: execnodes.h:415
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:109
MemoryContext es_query_cxt
Definition: execnodes.h:572
#define NoLock
Definition: lockdefs.h:34
List * es_opened_result_relations
Definition: execnodes.h:550
int es_instrument
Definition: execnodes.h:579
List * lappend(List *list, void *datum)
Definition: list.c:336
List * es_trig_target_relations
Definition: execnodes.h:563
void InitResultRelInfo(ResultRelInfo *resultRelInfo, Relation resultRelationDesc, Index resultRelationIndex, ResultRelInfo *partition_root_rri, int instrument_options)
Definition: execMain.c:1182
List * es_tuple_routing_result_relations
Definition: execnodes.h:560
#define makeNode(_type_)
Definition: nodes.h:578
#define lfirst(lc)
Definition: pg_list.h:169
Relation table_open(Oid relationId, LOCKMODE lockmode)
Definition: table.c:39
#define RelationGetRelid(relation)
Definition: rel.h:457

◆ ExecPartitionCheck()

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

Definition at line 1665 of file execMain.c.

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

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

1667 {
1668  ExprContext *econtext;
1669  bool success;
1670 
1671  /*
1672  * If first time through, build expression state tree for the partition
1673  * check expression. (In the corner case where the partition check
1674  * expression is empty, ie there's a default partition and nothing else,
1675  * we'll be fooled into executing this code each time through. But it's
1676  * pretty darn cheap in that case, so we don't worry about it.)
1677  */
1678  if (resultRelInfo->ri_PartitionCheckExpr == NULL)
1679  {
1680  /*
1681  * Ensure that the qual tree and prepared expression are in the
1682  * query-lifespan context.
1683  */
1685  List *qual = RelationGetPartitionQual(resultRelInfo->ri_RelationDesc);
1686 
1687  resultRelInfo->ri_PartitionCheckExpr = ExecPrepareCheck(qual, estate);
1688  MemoryContextSwitchTo(oldcxt);
1689  }
1690 
1691  /*
1692  * We will use the EState's per-tuple context for evaluating constraint
1693  * expressions (creating it if it's not already there).
1694  */
1695  econtext = GetPerTupleExprContext(estate);
1696 
1697  /* Arrange for econtext's scan tuple to be the tuple under test */
1698  econtext->ecxt_scantuple = slot;
1699 
1700  /*
1701  * As in case of the catalogued constraints, we treat a NULL result as
1702  * success here, not a failure.
1703  */
1704  success = ExecCheck(resultRelInfo->ri_PartitionCheckExpr, econtext);
1705 
1706  /* if asked to emit error, don't actually return on failure */
1707  if (!success && emitError)
1708  ExecPartitionCheckEmitError(resultRelInfo, slot, estate);
1709 
1710  return success;
1711 }
Relation ri_RelationDesc
Definition: execnodes.h:415
ExprState * ExecPrepareCheck(List *qual, EState *estate)
Definition: execExpr.c:543
ExprState * ri_PartitionCheckExpr
Definition: execnodes.h:489
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:109
#define GetPerTupleExprContext(estate)
Definition: executor.h:509
MemoryContext es_query_cxt
Definition: execnodes.h:572
void ExecPartitionCheckEmitError(ResultRelInfo *resultRelInfo, TupleTableSlot *slot, EState *estate)
Definition: execMain.c:1718
TupleTableSlot * ecxt_scantuple
Definition: execnodes.h:225
List * RelationGetPartitionQual(Relation rel)
Definition: partcache.c:276
bool ExecCheck(ExprState *state, ExprContext *econtext)
Definition: execExpr.c:599
static bool success
Definition: initdb.c:164
Definition: pg_list.h:50

◆ ExecPartitionCheckEmitError()

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

Definition at line 1718 of file execMain.c.

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

1721 {
1722  Oid root_relid;
1723  TupleDesc tupdesc;
1724  char *val_desc;
1725  Bitmapset *modifiedCols;
1726 
1727  /*
1728  * If the tuple has been routed, it's been converted to the partition's
1729  * rowtype, which might differ from the root table's. We must convert it
1730  * back to the root table's rowtype so that val_desc in the error message
1731  * matches the input tuple.
1732  */
1733  if (resultRelInfo->ri_RootResultRelInfo)
1734  {
1735  ResultRelInfo *rootrel = resultRelInfo->ri_RootResultRelInfo;
1736  TupleDesc old_tupdesc;
1737  AttrMap *map;
1738 
1739  root_relid = RelationGetRelid(rootrel->ri_RelationDesc);
1740  tupdesc = RelationGetDescr(rootrel->ri_RelationDesc);
1741 
1742  old_tupdesc = RelationGetDescr(resultRelInfo->ri_RelationDesc);
1743  /* a reverse map */
1744  map = build_attrmap_by_name_if_req(old_tupdesc, tupdesc);
1745 
1746  /*
1747  * Partition-specific slot's tupdesc can't be changed, so allocate a
1748  * new one.
1749  */
1750  if (map != NULL)
1751  slot = execute_attr_map_slot(map, slot,
1752  MakeTupleTableSlot(tupdesc, &TTSOpsVirtual));
1753  modifiedCols = bms_union(ExecGetInsertedCols(rootrel, estate),
1754  ExecGetUpdatedCols(rootrel, estate));
1755  }
1756  else
1757  {
1758  root_relid = RelationGetRelid(resultRelInfo->ri_RelationDesc);
1759  tupdesc = RelationGetDescr(resultRelInfo->ri_RelationDesc);
1760  modifiedCols = bms_union(ExecGetInsertedCols(resultRelInfo, estate),
1761  ExecGetUpdatedCols(resultRelInfo, estate));
1762  }
1763 
1764  val_desc = ExecBuildSlotValueDescription(root_relid,
1765  slot,
1766  tupdesc,
1767  modifiedCols,
1768  64);
1769  ereport(ERROR,
1770  (errcode(ERRCODE_CHECK_VIOLATION),
1771  errmsg("new row for relation \"%s\" violates partition constraint",
1772  RelationGetRelationName(resultRelInfo->ri_RelationDesc)),
1773  val_desc ? errdetail("Failing row contains %s.", val_desc) : 0,
1774  errtable(resultRelInfo->ri_RelationDesc)));
1775 }
Relation ri_RelationDesc
Definition: execnodes.h:415
#define RelationGetDescr(relation)
Definition: rel.h:483
Bitmapset * ExecGetUpdatedCols(ResultRelInfo *relinfo, EState *estate)
Definition: execUtils.c:1269
const TupleTableSlotOps TTSOpsVirtual
Definition: execTuples.c:83
int errcode(int sqlerrcode)
Definition: elog.c:704
unsigned int Oid
Definition: postgres_ext.h:31
Definition: attmap.h:34
AttrMap * build_attrmap_by_name_if_req(TupleDesc indesc, TupleDesc outdesc)
Definition: attmap.c:259
#define ERROR
Definition: elog.h:45
static char * ExecBuildSlotValueDescription(Oid reloid, TupleTableSlot *slot, TupleDesc tupdesc, Bitmapset *modifiedCols, int maxfieldlen)
Definition: execMain.c:2071
struct ResultRelInfo * ri_RootResultRelInfo
Definition: execnodes.h:503
int errdetail(const char *fmt,...)
Definition: elog.c:1048
#define RelationGetRelationName(relation)
Definition: rel.h:491
TupleTableSlot * MakeTupleTableSlot(TupleDesc tupleDesc, const TupleTableSlotOps *tts_ops)
Definition: execTuples.c:1082
#define ereport(elevel,...)
Definition: elog.h:155
TupleTableSlot * execute_attr_map_slot(AttrMap *attrMap, TupleTableSlot *in_slot, TupleTableSlot *out_slot)
Definition: tupconvert.c:177
Bitmapset * bms_union(const Bitmapset *a, const Bitmapset *b)
Definition: bitmapset.c:225
Bitmapset * ExecGetInsertedCols(ResultRelInfo *relinfo, EState *estate)
Definition: execUtils.c:1230
int errmsg(const char *fmt,...)
Definition: elog.c:915
int errtable(Relation rel)
Definition: relcache.c:5509
#define RelationGetRelid(relation)
Definition: rel.h:457

◆ ExecPostprocessPlan()

static void ExecPostprocessPlan ( EState estate)
static

Definition at line 1331 of file execMain.c.

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

Referenced by standard_ExecutorFinish().

1332 {
1333  ListCell *lc;
1334 
1335  /*
1336  * Make sure nodes run forward.
1337  */
1339 
1340  /*
1341  * Run any secondary ModifyTable nodes to completion, in case the main
1342  * query did not fetch all rows from them. (We do this to ensure that
1343  * such nodes have predictable results.)
1344  */
1345  foreach(lc, estate->es_auxmodifytables)
1346  {
1347  PlanState *ps = (PlanState *) lfirst(lc);
1348 
1349  for (;;)
1350  {
1351  TupleTableSlot *slot;
1352 
1353  /* Reset the per-output-tuple exprcontext each time */
1354  ResetPerTupleExprContext(estate);
1355 
1356  slot = ExecProcNode(ps);
1357 
1358  if (TupIsNull(slot))
1359  break;
1360  }
1361  }
1362 }
#define ResetPerTupleExprContext(estate)
Definition: executor.h:518
ScanDirection es_direction
Definition: execnodes.h:529
#define TupIsNull(slot)
Definition: tuptable.h:292
List * es_auxmodifytables
Definition: execnodes.h:586
static TupleTableSlot * ExecProcNode(PlanState *node)
Definition: executor.h:242
#define lfirst(lc)
Definition: pg_list.h:169

◆ ExecRelCheck()

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

Definition at line 1599 of file execMain.c.

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

Referenced by ExecConstraints().

1601 {
1602  Relation rel = resultRelInfo->ri_RelationDesc;
1603  int ncheck = rel->rd_att->constr->num_check;
1604  ConstrCheck *check = rel->rd_att->constr->check;
1605  ExprContext *econtext;
1606  MemoryContext oldContext;
1607  int i;
1608 
1609  /*
1610  * If first time through for this result relation, build expression
1611  * nodetrees for rel's constraint expressions. Keep them in the per-query
1612  * memory context so they'll survive throughout the query.
1613  */
1614  if (resultRelInfo->ri_ConstraintExprs == NULL)
1615  {
1616  oldContext = MemoryContextSwitchTo(estate->es_query_cxt);
1617  resultRelInfo->ri_ConstraintExprs =
1618  (ExprState **) palloc(ncheck * sizeof(ExprState *));
1619  for (i = 0; i < ncheck; i++)
1620  {
1621  Expr *checkconstr;
1622 
1623  checkconstr = stringToNode(check[i].ccbin);
1624  resultRelInfo->ri_ConstraintExprs[i] =
1625  ExecPrepareExpr(checkconstr, estate);
1626  }
1627  MemoryContextSwitchTo(oldContext);
1628  }
1629 
1630  /*
1631  * We will use the EState's per-tuple context for evaluating constraint
1632  * expressions (creating it if it's not already there).
1633  */
1634  econtext = GetPerTupleExprContext(estate);
1635 
1636  /* Arrange for econtext's scan tuple to be the tuple under test */
1637  econtext->ecxt_scantuple = slot;
1638 
1639  /* And evaluate the constraints */
1640  for (i = 0; i < ncheck; i++)
1641  {
1642  ExprState *checkconstr = resultRelInfo->ri_ConstraintExprs[i];
1643 
1644  /*
1645  * NOTE: SQL specifies that a NULL result from a constraint expression
1646  * is not to be treated as a failure. Therefore, use ExecCheck not
1647  * ExecQual.
1648  */
1649  if (!ExecCheck(checkconstr, econtext))
1650  return check[i].ccname;
1651  }
1652 
1653  /* NULL result means no error */
1654  return NULL;
1655 }
Relation ri_RelationDesc
Definition: execnodes.h:415
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:109
void * stringToNode(const char *str)
Definition: read.c:89
ExprState * ExecPrepareExpr(Expr *node, EState *estate)
Definition: execExpr.c:492
#define GetPerTupleExprContext(estate)
Definition: executor.h:509
MemoryContext es_query_cxt
Definition: execnodes.h:572
TupleConstr * constr
Definition: tupdesc.h:85
char * ccname
Definition: tupdesc.h:30
ExprState ** ri_ConstraintExprs
Definition: execnodes.h:465
TupleDesc rd_att
Definition: rel.h:111
uint16 num_check
Definition: tupdesc.h:43
TupleTableSlot * ecxt_scantuple
Definition: execnodes.h:225
void * palloc(Size size)
Definition: mcxt.c:950
int i
bool ExecCheck(ExprState *state, ExprContext *econtext)
Definition: execExpr.c:599
ConstrCheck * check
Definition: tupdesc.h:40

◆ ExecUpdateLockMode()

LockTupleMode ExecUpdateLockMode ( EState estate,
ResultRelInfo relinfo 
)

Definition at line 2208 of file execMain.c.

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

Referenced by ExecBRUpdateTriggers(), and ExecOnConflictUpdate().

2209 {
2210  Bitmapset *keyCols;
2211  Bitmapset *updatedCols;
2212 
2213  /*
2214  * Compute lock mode to use. If columns that are part of the key have not
2215  * been modified, then we can use a weaker lock, allowing for better
2216  * concurrency.
2217  */
2218  updatedCols = ExecGetAllUpdatedCols(relinfo, estate);
2219  keyCols = RelationGetIndexAttrBitmap(relinfo->ri_RelationDesc,
2221 
2222  if (bms_overlap(keyCols, updatedCols))
2223  return LockTupleExclusive;
2224 
2225  return LockTupleNoKeyExclusive;
2226 }
Relation ri_RelationDesc
Definition: execnodes.h:415
Bitmapset * ExecGetAllUpdatedCols(ResultRelInfo *relinfo, EState *estate)
Definition: execUtils.c:1321
bool bms_overlap(const Bitmapset *a, const Bitmapset *b)
Definition: bitmapset.c:494
Bitmapset * RelationGetIndexAttrBitmap(Relation relation, IndexAttrBitmapKind attrKind)
Definition: relcache.c:4956

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

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

Referenced by standard_ExecutorRun().

1492 {
1493  TupleTableSlot *slot;
1494  uint64 current_tuple_count;
1495 
1496  /*
1497  * initialize local variables
1498  */
1499  current_tuple_count = 0;
1500 
1501  /*
1502  * Set the direction.
1503  */
1504  estate->es_direction = direction;
1505 
1506  /*
1507  * If the plan might potentially be executed multiple times, we must force
1508  * it to run without parallelism, because we might exit early.
1509  */
1510  if (!execute_once)
1511  use_parallel_mode = false;
1512 
1513  estate->es_use_parallel_mode = use_parallel_mode;
1514  if (use_parallel_mode)
1516 
1517  /*
1518  * Loop until we've processed the proper number of tuples from the plan.
1519  */
1520  for (;;)
1521  {
1522  /* Reset the per-output-tuple exprcontext */
1523  ResetPerTupleExprContext(estate);
1524 
1525  /*
1526  * Execute the plan and obtain a tuple
1527  */
1528  slot = ExecProcNode(planstate);
1529 
1530  /*
1531  * if the tuple is null, then we assume there is nothing more to
1532  * process so we just end the loop...
1533  */
1534  if (TupIsNull(slot))
1535  break;
1536 
1537  /*
1538  * If we have a junk filter, then project a new tuple with the junk
1539  * removed.
1540  *
1541  * Store this new "clean" tuple in the junkfilter's resultSlot.
1542  * (Formerly, we stored it back over the "dirty" tuple, which is WRONG
1543  * because that tuple slot has the wrong descriptor.)
1544  */
1545  if (estate->es_junkFilter != NULL)
1546  slot = ExecFilterJunk(estate->es_junkFilter, slot);
1547 
1548  /*
1549  * If we are supposed to send the tuple somewhere, do so. (In
1550  * practice, this is probably always the case at this point.)
1551  */
1552  if (sendTuples)
1553  {
1554  /*
1555  * If we are not able to send the tuple, we assume the destination
1556  * has closed and no more tuples can be sent. If that's the case,
1557  * end the loop.
1558  */
1559  if (!dest->receiveSlot(slot, dest))
1560  break;
1561  }
1562 
1563  /*
1564  * Count tuples processed, if this is a SELECT. (For other operation
1565  * types, the ModifyTable plan node must count the appropriate
1566  * events.)
1567  */
1568  if (operation == CMD_SELECT)
1569  (estate->es_processed)++;
1570 
1571  /*
1572  * check our tuple count.. if we've processed the proper number then
1573  * quit, else loop again and process more tuples. Zero numberTuples
1574  * means no limit.
1575  */
1576  current_tuple_count++;
1577  if (numberTuples && numberTuples == current_tuple_count)
1578  break;
1579  }
1580 
1581  /*
1582  * If we know we won't need to back up, we can release resources at this
1583  * point.
1584  */
1585  if (!(estate->es_top_eflags & EXEC_FLAG_BACKWARD))
1586  (void) ExecShutdownNode(planstate);
1587 
1588  if (use_parallel_mode)
1589  ExitParallelMode();
1590 }
bool(* receiveSlot)(TupleTableSlot *slot, DestReceiver *self)
Definition: dest.h:119
JunkFilter * es_junkFilter
Definition: execnodes.h:541
#define ResetPerTupleExprContext(estate)
Definition: executor.h:518
bool ExecShutdownNode(PlanState *node)
Definition: execProcnode.c:751
ScanDirection es_direction
Definition: execnodes.h:529
bool es_use_parallel_mode
Definition: execnodes.h:603
void ExitParallelMode(void)
Definition: xact.c:992
#define EXEC_FLAG_BACKWARD
Definition: executor.h:58
#define TupIsNull(slot)
Definition: tuptable.h:292
TupleTableSlot * ExecFilterJunk(JunkFilter *junkfilter, TupleTableSlot *slot)
Definition: execJunk.c:287
static TupleTableSlot * ExecProcNode(PlanState *node)
Definition: executor.h:242
uint64 es_processed
Definition: execnodes.h:576
void EnterParallelMode(void)
Definition: xact.c:979
int es_top_eflags
Definition: execnodes.h:578

◆ ExecutorEnd()

void ExecutorEnd ( QueryDesc queryDesc)

Definition at line 448 of file execMain.c.

References ExecutorEnd_hook, and standard_ExecutorEnd().

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

449 {
450  if (ExecutorEnd_hook)
451  (*ExecutorEnd_hook) (queryDesc);
452  else
453  standard_ExecutorEnd(queryDesc);
454 }
void standard_ExecutorEnd(QueryDesc *queryDesc)
Definition: execMain.c:457
ExecutorEnd_hook_type ExecutorEnd_hook
Definition: execMain.c:73

◆ ExecutorFinish()

void ExecutorFinish ( QueryDesc queryDesc)

Definition at line 388 of file execMain.c.

References ExecutorFinish_hook, and standard_ExecutorFinish().

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

389 {
391  (*ExecutorFinish_hook) (queryDesc);
392  else
393  standard_ExecutorFinish(queryDesc);
394 }
void standard_ExecutorFinish(QueryDesc *queryDesc)
Definition: execMain.c:397
ExecutorFinish_hook_type ExecutorFinish_hook
Definition: execMain.c:72

◆ ExecutorRewind()

void ExecutorRewind ( QueryDesc queryDesc)

Definition at line 514 of file execMain.c.

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

Referenced by DoPortalRewind(), and PersistHoldablePortal().

515 {
516  EState *estate;
517  MemoryContext oldcontext;
518 
519  /* sanity checks */
520  Assert(queryDesc != NULL);
521 
522  estate = queryDesc->estate;
523 
524  Assert(estate != NULL);
525 
526  /* It's probably not sensible to rescan updating queries */
527  Assert(queryDesc->operation == CMD_SELECT);
528 
529  /*
530  * Switch into per-query memory context
531  */
532  oldcontext = MemoryContextSwitchTo(estate->es_query_cxt);
533 
534  /*
535  * rescan plan
536  */
537  ExecReScan(queryDesc->planstate);
538 
539  MemoryContextSwitchTo(oldcontext);
540 }
EState * estate
Definition: execdesc.h:48
void ExecReScan(PlanState *node)
Definition: execAmi.c:76
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:109
MemoryContext es_query_cxt
Definition: execnodes.h:572
PlanState * planstate
Definition: execdesc.h:49
CmdType operation
Definition: execdesc.h:36
#define Assert(condition)
Definition: c.h:804

◆ ExecutorRun()

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

Definition at line 287 of file execMain.c.

References ExecutorRun_hook, and standard_ExecutorRun().

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

290 {
291  if (ExecutorRun_hook)
292  (*ExecutorRun_hook) (queryDesc, direction, count, execute_once);
293  else
294  standard_ExecutorRun(queryDesc, direction, count, execute_once);
295 }
void standard_ExecutorRun(QueryDesc *queryDesc, ScanDirection direction, uint64 count, bool execute_once)
Definition: execMain.c:298
ExecutorRun_hook_type ExecutorRun_hook
Definition: execMain.c:71

◆ ExecutorStart()

void ExecutorStart ( QueryDesc queryDesc,
int  eflags 
)

Definition at line 129 of file execMain.c.

References ExecutorStart_hook, and standard_ExecutorStart().

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

130 {
131  if (ExecutorStart_hook)
132  (*ExecutorStart_hook) (queryDesc, eflags);
133  else
134  standard_ExecutorStart(queryDesc, eflags);
135 }
void standard_ExecutorStart(QueryDesc *queryDesc, int eflags)
Definition: execMain.c:138
ExecutorStart_hook_type ExecutorStart_hook
Definition: execMain.c:70

◆ ExecWithCheckOptions()

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

Definition at line 1922 of file execMain.c.

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_UPDATE_CHECK, and WCO_VIEW_CHECK.

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

1924 {
1925  Relation rel = resultRelInfo->ri_RelationDesc;
1926  TupleDesc tupdesc = RelationGetDescr(rel);
1927  ExprContext *econtext;
1928  ListCell *l1,
1929  *l2;
1930 
1931  /*
1932  * We will use the EState's per-tuple context for evaluating constraint
1933  * expressions (creating it if it's not already there).
1934  */
1935  econtext = GetPerTupleExprContext(estate);
1936 
1937  /* Arrange for econtext's scan tuple to be the tuple under test */
1938  econtext->ecxt_scantuple = slot;
1939 
1940  /* Check each of the constraints */
1941  forboth(l1, resultRelInfo->ri_WithCheckOptions,
1942  l2, resultRelInfo->ri_WithCheckOptionExprs)
1943  {
1944  WithCheckOption *wco = (WithCheckOption *) lfirst(l1);
1945  ExprState *wcoExpr = (ExprState *) lfirst(l2);
1946 
1947  /*
1948  * Skip any WCOs which are not the kind we are looking for at this
1949  * time.
1950  */
1951  if (wco->kind != kind)
1952  continue;
1953 
1954  /*
1955  * WITH CHECK OPTION checks are intended to ensure that the new tuple
1956  * is visible (in the case of a view) or that it passes the
1957  * 'with-check' policy (in the case of row security). If the qual
1958  * evaluates to NULL or FALSE, then the new tuple won't be included in
1959  * the view or doesn't pass the 'with-check' policy for the table.
1960  */
1961  if (!ExecQual(wcoExpr, econtext))
1962  {
1963  char *val_desc;
1964  Bitmapset *modifiedCols;
1965 
1966  switch (wco->kind)
1967  {
1968  /*
1969  * For WITH CHECK OPTIONs coming from views, we might be
1970  * able to provide the details on the row, depending on
1971  * the permissions on the relation (that is, if the user
1972  * could view it directly anyway). For RLS violations, we
1973  * don't include the data since we don't know if the user
1974  * should be able to view the tuple as that depends on the
1975  * USING policy.
1976  */
1977  case WCO_VIEW_CHECK:
1978  /* See the comment in ExecConstraints(). */
1979  if (resultRelInfo->ri_RootResultRelInfo)
1980  {
1981  ResultRelInfo *rootrel = resultRelInfo->ri_RootResultRelInfo;
1982  TupleDesc old_tupdesc = RelationGetDescr(rel);
1983  AttrMap *map;
1984 
1985  tupdesc = RelationGetDescr(rootrel->ri_RelationDesc);
1986  /* a reverse map */
1987  map = build_attrmap_by_name_if_req(old_tupdesc,
1988  tupdesc);
1989 
1990  /*
1991  * Partition-specific slot's tupdesc can't be changed,
1992  * so allocate a new one.
1993  */
1994  if (map != NULL)
1995  slot = execute_attr_map_slot(map, slot,
1996  MakeTupleTableSlot(tupdesc, &TTSOpsVirtual));
1997 
1998  modifiedCols = bms_union(ExecGetInsertedCols(rootrel, estate),
1999  ExecGetUpdatedCols(rootrel, estate));
2000  rel = rootrel->ri_RelationDesc;
2001  }
2002  else
2003  modifiedCols = bms_union(ExecGetInsertedCols(resultRelInfo, estate),
2004  ExecGetUpdatedCols(resultRelInfo, estate));
2006  slot,
2007  tupdesc,
2008  modifiedCols,
2009  64);
2010 
2011  ereport(ERROR,
2012  (errcode(ERRCODE_WITH_CHECK_OPTION_VIOLATION),
2013  errmsg("new row violates check option for view \"%s\"",
2014  wco->relname),
2015  val_desc ? errdetail("Failing row contains %s.",
2016  val_desc) : 0));
2017  break;
2018  case WCO_RLS_INSERT_CHECK:
2019  case WCO_RLS_UPDATE_CHECK:
2020  if (wco->polname != NULL)
2021  ereport(ERROR,
2022  (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
2023  errmsg("new row violates row-level security policy \"%s\" for table \"%s\"",
2024  wco->polname, wco->relname)));
2025  else
2026  ereport(ERROR,
2027  (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
2028  errmsg("new row violates row-level security policy for table \"%s\"",
2029  wco->relname)));
2030  break;
2032  if (wco->polname != NULL)
2033  ereport(ERROR,
2034  (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
2035  errmsg("new row violates row-level security policy \"%s\" (USING expression) for table \"%s\"",
2036  wco->polname, wco->relname)));
2037  else
2038  ereport(ERROR,
2039  (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
2040  errmsg("new row violates row-level security policy (USING expression) for table \"%s\"",
2041  wco->relname)));
2042  break;
2043  default:
2044  elog(ERROR, "unrecognized WCO kind: %u", wco->kind);
2045  break;
2046  }
2047  }
2048  }
2049 }
Relation ri_RelationDesc
Definition: execnodes.h:415
#define forboth(cell1, list1, cell2, list2)
Definition: pg_list.h:446
#define RelationGetDescr(relation)
Definition: rel.h:483
Bitmapset * ExecGetUpdatedCols(ResultRelInfo *relinfo, EState *estate)
Definition: execUtils.c:1269
const TupleTableSlotOps TTSOpsVirtual
Definition: execTuples.c:83
int errcode(int sqlerrcode)
Definition: elog.c:704
static bool ExecQual(ExprState *state, ExprContext *econtext)
Definition: executor.h:372
Definition: attmap.h:34
List * ri_WithCheckOptionExprs
Definition: execnodes.h:462
#define GetPerTupleExprContext(estate)
Definition: executor.h:509
AttrMap * build_attrmap_by_name_if_req(TupleDesc indesc, TupleDesc outdesc)
Definition: attmap.c:259
#define ERROR
Definition: elog.h:45
static char * ExecBuildSlotValueDescription(Oid reloid, TupleTableSlot *slot, TupleDesc tupdesc, Bitmapset *modifiedCols, int maxfieldlen)
Definition: execMain.c:2071
struct ResultRelInfo * ri_RootResultRelInfo
Definition: execnodes.h:503
int errdetail(const char *fmt,...)
Definition: elog.c:1048
List * ri_WithCheckOptions
Definition: execnodes.h:459
TupleTableSlot * MakeTupleTableSlot(TupleDesc tupleDesc, const TupleTableSlotOps *tts_ops)
Definition: execTuples.c:1082
#define ereport(elevel,...)
Definition: elog.h:155
TupleTableSlot * execute_attr_map_slot(AttrMap *attrMap, TupleTableSlot *in_slot, TupleTableSlot *out_slot)
Definition: tupconvert.c:177
#define lfirst(lc)
Definition: pg_list.h:169
Bitmapset * bms_union(const Bitmapset *a, const Bitmapset *b)
Definition: bitmapset.c:225
TupleTableSlot * ecxt_scantuple
Definition: execnodes.h:225
Bitmapset * ExecGetInsertedCols(ResultRelInfo *relinfo, EState *estate)
Definition: execUtils.c:1230
int errmsg(const char *fmt,...)
Definition: elog.c:915
#define elog(elevel,...)
Definition: elog.h:228
#define RelationGetRelid(relation)
Definition: rel.h:457

◆ InitPlan()

static void InitPlan ( QueryDesc queryDesc,
int  eflags 
)
static

Definition at line 792 of file execMain.c.

References Assert, bms_is_member(), CheckValidRowMarkRel(), CMD_SELECT, ExecRowMark::curCtid, elog, ExecRowMark::ermActive, ExecRowMark::ermExtra, ERROR, EState::es_epq_active, EState::es_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, JunkFilter::jf_cleanTupType, 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().

793 {
794  CmdType operation = queryDesc->operation;
795  PlannedStmt *plannedstmt = queryDesc->plannedstmt;
796  Plan *plan = plannedstmt->planTree;
797  List *rangeTable = plannedstmt->rtable;
798  EState *estate = queryDesc->estate;
799  PlanState *planstate;
800  TupleDesc tupType;
801  ListCell *l;
802  int i;
803 
804  /*
805  * Do permissions checks
806  */
807  ExecCheckRTPerms(rangeTable, true);
808 
809  /*
810  * initialize the node's execution state
811  */
812  ExecInitRangeTable(estate, rangeTable);
813 
814  estate->es_plannedstmt = plannedstmt;
815 
816  /*
817  * Next, build the ExecRowMark array from the PlanRowMark(s), if any.
818  */
819  if (plannedstmt->rowMarks)
820  {
821  estate->es_rowmarks = (ExecRowMark **)
822  palloc0(estate->es_range_table_size * sizeof(ExecRowMark *));
823  foreach(l, plannedstmt->rowMarks)
824  {
825  PlanRowMark *rc = (PlanRowMark *) lfirst(l);
826  Oid relid;
827  Relation relation;
828  ExecRowMark *erm;
829 
830  /* ignore "parent" rowmarks; they are irrelevant at runtime */
831  if (rc->isParent)
832  continue;
833 
834  /* get relation's OID (will produce InvalidOid if subquery) */
835  relid = exec_rt_fetch(rc->rti, estate)->relid;
836 
837  /* open relation, if we need to access it for this mark type */
838  switch (rc->markType)
839  {
840  case ROW_MARK_EXCLUSIVE:
842  case ROW_MARK_SHARE:
843  case ROW_MARK_KEYSHARE:
844  case ROW_MARK_REFERENCE:
845  relation = ExecGetRangeTableRelation(estate, rc->rti);
846  break;
847  case ROW_MARK_COPY:
848  /* no physical table access is required */
849  relation = NULL;
850  break;
851  default:
852  elog(ERROR, "unrecognized markType: %d", rc->markType);
853  relation = NULL; /* keep compiler quiet */
854  break;
855  }
856 
857  /* Check that relation is a legal target for marking */
858  if (relation)
859  CheckValidRowMarkRel(relation, rc->markType);
860 
861  erm = (ExecRowMark *) palloc(sizeof(ExecRowMark));
862  erm->relation = relation;
863  erm->relid = relid;
864  erm->rti = rc->rti;
865  erm->prti = rc->prti;
866  erm->rowmarkId = rc->rowmarkId;
867  erm->markType = rc->markType;
868  erm->strength = rc->strength;
869  erm->waitPolicy = rc->waitPolicy;
870  erm->ermActive = false;
872  erm->ermExtra = NULL;
873 
874  Assert(erm->rti > 0 && erm->rti <= estate->es_range_table_size &&
875  estate->es_rowmarks[erm->rti - 1] == NULL);
876 
877  estate->es_rowmarks[erm->rti - 1] = erm;
878  }
879  }
880 
881  /*
882  * Initialize the executor's tuple table to empty.
883  */
884  estate->es_tupleTable = NIL;
885 
886  /* signal that this EState is not used for EPQ */
887  estate->es_epq_active = NULL;
888 
889  /*
890  * Initialize private state information for each SubPlan. We must do this
891  * before running ExecInitNode on the main query tree, since
892  * ExecInitSubPlan expects to be able to find these entries.
893  */
894  Assert(estate->es_subplanstates == NIL);
895  i = 1; /* subplan indices count from 1 */
896  foreach(l, plannedstmt->subplans)
897  {
898  Plan *subplan = (Plan *) lfirst(l);
899  PlanState *subplanstate;
900  int sp_eflags;
901 
902  /*
903  * A subplan will never need to do BACKWARD scan nor MARK/RESTORE. If
904  * it is a parameterless subplan (not initplan), we suggest that it be
905  * prepared to handle REWIND efficiently; otherwise there is no need.
906  */
907  sp_eflags = eflags
909  if (bms_is_member(i, plannedstmt->rewindPlanIDs))
910  sp_eflags |= EXEC_FLAG_REWIND;
911 
912  subplanstate = ExecInitNode(subplan, estate, sp_eflags);
913 
914  estate->es_subplanstates = lappend(estate->es_subplanstates,
915  subplanstate);
916 
917  i++;
918  }
919 
920  /*
921  * Initialize the private state information for all the nodes in the query
922  * tree. This opens files, allocates storage and leaves us ready to start
923  * processing tuples.
924  */
925  planstate = ExecInitNode(plan, estate, eflags);
926 
927  /*
928  * Get the tuple descriptor describing the type of tuples to return.
929  */
930  tupType = ExecGetResultType(planstate);
931 
932  /*
933  * Initialize the junk filter if needed. SELECT queries need a filter if
934  * there are any junk attrs in the top-level tlist.
935  */
936  if (operation == CMD_SELECT)
937  {
938  bool junk_filter_needed = false;
939  ListCell *tlist;
940 
941  foreach(tlist, plan->targetlist)
942  {
943  TargetEntry *tle = (TargetEntry *) lfirst(tlist);
944 
945  if (tle->resjunk)
946  {
947  junk_filter_needed = true;
948  break;
949  }
950  }
951 
952  if (junk_filter_needed)
953  {
954  JunkFilter *j;
955  TupleTableSlot *slot;
956 
957  slot = ExecInitExtraTupleSlot(estate, NULL, &TTSOpsVirtual);
958  j = ExecInitJunkFilter(planstate->plan->targetlist,
959  slot);
960  estate->es_junkFilter = j;
961 
962  /* Want to return the cleaned tuple type */
963  tupType = j->jf_cleanTupType;
964  }
965  }
966 
967  queryDesc->tupDesc = tupType;
968  queryDesc->planstate = planstate;
969 }
#define NIL
Definition: pg_list.h:65
void ExecInitRangeTable(EState *estate, List *rangeTable)
Definition: execUtils.c:751
JunkFilter * es_junkFilter
Definition: execnodes.h:541
RowMarkType markType
Definition: plannodes.h:1080
TupleTableSlot * ExecInitExtraTupleSlot(EState *estate, TupleDesc tupledesc, const TupleTableSlotOps *tts_ops)
Definition: execTuples.c:1801
EState * estate
Definition: execdesc.h:48
Relation relation
Definition: execnodes.h:644
const TupleTableSlotOps TTSOpsVirtual
Definition: execTuples.c:83
PlannedStmt * es_plannedstmt
Definition: execnodes.h:538
bool ermActive
Definition: execnodes.h:652
Index prti
Definition: plannodes.h:1078
LockWaitPolicy waitPolicy
Definition: execnodes.h:651
#define EXEC_FLAG_WITH_NO_DATA
Definition: executor.h:61
LockClauseStrength strength
Definition: execnodes.h:650
unsigned int Oid
Definition: postgres_ext.h:31
Index rowmarkId
Definition: plannodes.h:1079
LockWaitPolicy waitPolicy
Definition: plannodes.h:1083
static void CheckValidRowMarkRel(Relation rel, RowMarkType markType)
Definition: execMain.c:1117
struct EPQState * es_epq_active
Definition: execnodes.h:601
struct Plan * planTree
Definition: plannodes.h:64
ItemPointerData curCtid
Definition: execnodes.h:653
struct ExecRowMark ** es_rowmarks
Definition: execnodes.h:536
bool resjunk
Definition: primnodes.h:1438
#define ERROR
Definition: elog.h:45
PlanState * planstate
Definition: execdesc.h:49
Index rti
Definition: execnodes.h:646
void * ermExtra
Definition: execnodes.h:654
TupleDesc jf_cleanTupType
Definition: execnodes.h:369
Index prti
Definition: execnodes.h:647
static RangeTblEntry * exec_rt_fetch(Index rti, EState *estate)
Definition: executor.h:547
#define EXEC_FLAG_REWIND
Definition: executor.h:57
Index rowmarkId
Definition: execnodes.h:648
List * lappend(List *list, void *datum)
Definition: list.c:336
TupleDesc tupDesc
Definition: execdesc.h:47
CmdType operation
Definition: execdesc.h:36
List * es_tupleTable
Definition: execnodes.h:574
void * palloc0(Size size)
Definition: mcxt.c:981
List * rowMarks
Definition: plannodes.h:78
Plan * plan
Definition: execnodes.h:941
Relation ExecGetRangeTableRelation(EState *estate, Index rti)
Definition: execUtils.c:782
List * subplans
Definition: plannodes.h:73
#define Assert(condition)
Definition: c.h:804
#define lfirst(lc)
Definition: pg_list.h:169
Bitmapset * rewindPlanIDs
Definition: plannodes.h:76
RowMarkType markType
Definition: execnodes.h:649
LockClauseStrength strength
Definition: plannodes.h:1082
Index es_range_table_size
Definition: execnodes.h:533
List * es_subplanstates
Definition: execnodes.h:584
List * rtable
Definition: plannodes.h:66
TupleDesc ExecGetResultType(PlanState *planstate)
Definition: execUtils.c:490
List * targetlist
Definition: plannodes.h:136
#define ItemPointerSetInvalid(pointer)
Definition: itemptr.h:172
void * palloc(Size size)
Definition: mcxt.c:950
#define elog(elevel,...)
Definition: elog.h:228
int i
bool ExecCheckRTPerms(List *rangeTable, bool ereport_on_violation)
Definition: execMain.c:557
bool isParent
Definition: plannodes.h:1084
PlannedStmt * plannedstmt
Definition: execdesc.h:37
PlanState * ExecInitNode(Plan *node, EState *estate, int eflags)
Definition: execProcnode.c:139
Definition: pg_list.h:50
bool bms_is_member(int x, const Bitmapset *a)
Definition: bitmapset.c:427
#define EXEC_FLAG_EXPLAIN_ONLY
Definition: executor.h:56
JunkFilter * ExecInitJunkFilter(List *targetList, TupleTableSlot *slot)
Definition: execJunk.c:60
CmdType
Definition: nodes.h:673

◆ InitResultRelInfo()

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

Definition at line 1182 of file execMain.c.

References CopyTriggerDesc(), GetFdwRoutineForRelation(), InstrAlloc(), MemSet, NIL, TriggerDesc::numtriggers, palloc0(), RelationData::rd_rel, ResultRelInfo::ri_ChildToRootMap, ResultRelInfo::ri_ConstraintExprs, ResultRelInfo::ri_CopyMultiInsertBuffer, ResultRelInfo::ri_FdwRoutine, ResultRelInfo::ri_FdwState, ResultRelInfo::ri_GeneratedExprs, ResultRelInfo::ri_IndexRelationDescs, ResultRelInfo::ri_IndexRelationInfo, ResultRelInfo::ri_junkFilter, ResultRelInfo::ri_NumIndices, ResultRelInfo::ri_onConflict, ResultRelInfo::ri_onConflictArbiterIndexes, ResultRelInfo::ri_PartitionTupleSlot, ResultRelInfo::ri_projectReturning, ResultRelInfo::ri_RangeTableIndex, ResultRelInfo::ri_RelationDesc, ResultRelInfo::ri_ReturningSlot, ResultRelInfo::ri_RootResultRelInfo, ResultRelInfo::ri_RootToPartitionMap, 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 apply_handle_delete(), apply_handle_insert(), apply_handle_update(), ExecGetTriggerResultRel(), ExecInitPartitionDispatchInfo(), ExecInitPartitionInfo(), ExecInitResultRelation(), and ExecuteTruncateGuts().

1187 {
1188  MemSet(resultRelInfo, 0, sizeof(ResultRelInfo));
1189  resultRelInfo->type = T_ResultRelInfo;
1190  resultRelInfo->ri_RangeTableIndex = resultRelationIndex;
1191  resultRelInfo->ri_RelationDesc = resultRelationDesc;
1192  resultRelInfo->ri_NumIndices = 0;
1193  resultRelInfo->ri_IndexRelationDescs = NULL;
1194  resultRelInfo->ri_IndexRelationInfo = NULL;
1195  /* make a copy so as not to depend on relcache info not changing... */
1196  resultRelInfo->ri_TrigDesc = CopyTriggerDesc(resultRelationDesc->trigdesc);
1197  if (resultRelInfo->ri_TrigDesc)
1198  {
1199  int n = resultRelInfo->ri_TrigDesc->numtriggers;
1200 
1201  resultRelInfo->ri_TrigFunctions = (FmgrInfo *)
1202  palloc0(n * sizeof(FmgrInfo));
1203  resultRelInfo->ri_TrigWhenExprs = (ExprState **)
1204  palloc0(n * sizeof(ExprState *));
1205  if (instrument_options)
1206  resultRelInfo->ri_TrigInstrument = InstrAlloc(n, instrument_options);
1207  }
1208  else
1209  {
1210  resultRelInfo->ri_TrigFunctions = NULL;
1211  resultRelInfo->ri_TrigWhenExprs = NULL;
1212  resultRelInfo->ri_TrigInstrument = NULL;
1213  }
1214  if (resultRelationDesc->rd_rel->relkind == RELKIND_FOREIGN_TABLE)
1215  resultRelInfo->ri_FdwRoutine = GetFdwRoutineForRelation(resultRelationDesc, true);
1216  else
1217  resultRelInfo->ri_FdwRoutine = NULL;
1218 
1219  /* The following fields are set later if needed */
1220  resultRelInfo->ri_FdwState = NULL;
1221  resultRelInfo->ri_usesFdwDirectModify = false;
1222  resultRelInfo->ri_ConstraintExprs = NULL;
1223  resultRelInfo->ri_GeneratedExprs = NULL;
1224  resultRelInfo->ri_junkFilter = NULL;
1225  resultRelInfo->ri_projectReturning = NULL;
1226  resultRelInfo->ri_onConflictArbiterIndexes = NIL;
1227  resultRelInfo->ri_onConflict = NULL;
1228  resultRelInfo->ri_ReturningSlot = NULL;
1229  resultRelInfo->ri_TrigOldSlot = NULL;
1230  resultRelInfo->ri_TrigNewSlot = NULL;
1231  resultRelInfo->ri_RootResultRelInfo = partition_root_rri;
1232  resultRelInfo->ri_RootToPartitionMap = NULL; /* set by
1233  * ExecInitRoutingInfo */
1234  resultRelInfo->ri_PartitionTupleSlot = NULL; /* ditto */
1235  resultRelInfo->ri_ChildToRootMap = NULL;
1236  resultRelInfo->ri_CopyMultiInsertBuffer = NULL;
1237 }
int ri_NumIndices
Definition: execnodes.h:418
#define NIL
Definition: pg_list.h:65
JunkFilter * ri_junkFilter
Definition: execnodes.h:474
Definition: fmgr.h:56
Relation ri_RelationDesc
Definition: execnodes.h:415
struct CopyMultiInsertBuffer * ri_CopyMultiInsertBuffer
Definition: execnodes.h:515
Instrumentation * ri_TrigInstrument
Definition: execnodes.h:436
TupleConversionMap * ri_ChildToRootMap
Definition: execnodes.h:512
Instrumentation * InstrAlloc(int n, int instrument_options)
Definition: instrument.c:31
#define MemSet(start, val, len)
Definition: c.h:1008
Form_pg_class rd_rel
Definition: rel.h:110
TupleTableSlot * ri_TrigNewSlot
Definition: execnodes.h:441
Index ri_RangeTableIndex
Definition: execnodes.h:412
NodeTag type
Definition: execnodes.h:409
TupleTableSlot * ri_PartitionTupleSlot
Definition: execnodes.h:505
TriggerDesc * trigdesc
Definition: rel.h:116
bool ri_usesFdwDirectModify
Definition: execnodes.h:450
struct ResultRelInfo * ri_RootResultRelInfo
Definition: execnodes.h:503
ExprState ** ri_TrigWhenExprs
Definition: execnodes.h:433
TupleTableSlot * ri_ReturningSlot
Definition: execnodes.h:439
ExprState ** ri_GeneratedExprs
Definition: execnodes.h:468
ProjectionInfo * ri_projectReturning
Definition: execnodes.h:480
struct FdwRoutine * ri_FdwRoutine
Definition: execnodes.h:444
ExprState ** ri_ConstraintExprs
Definition: execnodes.h:465
TriggerDesc * ri_TrigDesc
Definition: execnodes.h:427
int numtriggers
Definition: reltrigger.h:50
OnConflictSetState * ri_onConflict
Definition: execnodes.h:486
void * palloc0(Size size)
Definition: mcxt.c:981
void * ri_FdwState
Definition: execnodes.h:447
TupleTableSlot * ri_TrigOldSlot
Definition: execnodes.h:440
TriggerDesc * CopyTriggerDesc(TriggerDesc *trigdesc)
Definition: trigger.c:1865
TupleConversionMap * ri_RootToPartitionMap
Definition: execnodes.h:504
FdwRoutine * GetFdwRoutineForRelation(Relation relation, bool makecopy)
Definition: foreign.c:427
IndexInfo ** ri_IndexRelationInfo
Definition: execnodes.h:424
List * ri_onConflictArbiterIndexes
Definition: execnodes.h:483
RelationPtr ri_IndexRelationDescs
Definition: execnodes.h:421
FmgrInfo * ri_TrigFunctions
Definition: execnodes.h:430

◆ standard_ExecutorEnd()

void standard_ExecutorEnd ( QueryDesc queryDesc)

Definition at line 457 of file execMain.c.

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

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

458 {
459  EState *estate;
460  MemoryContext oldcontext;
461 
462  /* sanity checks */
463  Assert(queryDesc != NULL);
464 
465  estate = queryDesc->estate;
466 
467  Assert(estate != NULL);
468 
469  /*
470  * Check that ExecutorFinish was called, unless in EXPLAIN-only mode. This
471  * Assert is needed because ExecutorFinish is new as of 9.1, and callers
472  * might forget to call it.
473  */
474  Assert(estate->es_finished ||
476 
477  /*
478  * Switch into per-query memory context to run ExecEndPlan
479  */
480  oldcontext = MemoryContextSwitchTo(estate->es_query_cxt);
481 
482  ExecEndPlan(queryDesc->planstate, estate);
483 
484  /* do away with our snapshots */
487 
488  /*
489  * Must switch out of context before destroying it
490  */
491  MemoryContextSwitchTo(oldcontext);
492 
493  /*
494  * Release EState and per-query memory context. This should release
495  * everything the executor has allocated.
496  */
497  FreeExecutorState(estate);
498 
499  /* Reset queryDesc fields that no longer point to anything */
500  queryDesc->tupDesc = NULL;
501  queryDesc->estate = NULL;
502  queryDesc->planstate = NULL;
503  queryDesc->totaltime = NULL;
504 }
EState * estate
Definition: execdesc.h:48
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:109
Snapshot es_crosscheck_snapshot
Definition: execnodes.h:531
Snapshot es_snapshot
Definition: execnodes.h:530
void FreeExecutorState(EState *estate)
Definition: execUtils.c:186
MemoryContext es_query_cxt
Definition: execnodes.h:572
PlanState * planstate
Definition: execdesc.h:49
void UnregisterSnapshot(Snapshot snapshot)
Definition: snapmgr.c:852
TupleDesc tupDesc
Definition: execdesc.h:47
bool es_finished
Definition: execnodes.h:580
struct Instrumentation * totaltime
Definition: execdesc.h:55
#define Assert(condition)
Definition: c.h:804
static void ExecEndPlan(PlanState *planstate, EState *estate)
Definition: execMain.c:1377
int es_top_eflags
Definition: execnodes.h:578
#define EXEC_FLAG_EXPLAIN_ONLY
Definition: executor.h:56

◆ standard_ExecutorFinish()

void standard_ExecutorFinish ( QueryDesc queryDesc)

Definition at line 397 of file execMain.c.

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

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

398 {
399  EState *estate;
400  MemoryContext oldcontext;
401 
402  /* sanity checks */
403  Assert(queryDesc != NULL);
404 
405  estate = queryDesc->estate;
406 
407  Assert(estate != NULL);
409 
410  /* This should be run once and only once per Executor instance */
411  Assert(!estate->es_finished);
412 
413  /* Switch into per-query memory context */
414  oldcontext = MemoryContextSwitchTo(estate->es_query_cxt);
415 
416  /* Allow instrumentation of Executor overall runtime */
417  if (queryDesc->totaltime)
418  InstrStartNode(queryDesc->totaltime);
419 
420  /* Run ModifyTable nodes to completion */
421  ExecPostprocessPlan(estate);
422 
423  /* Execute queued AFTER triggers, unless told not to */
424  if (!(estate->es_top_eflags & EXEC_FLAG_SKIP_TRIGGERS))
425  AfterTriggerEndQuery(estate);
426 
427  if (queryDesc->totaltime)
428  InstrStopNode(queryDesc->totaltime, 0);
429 
430  MemoryContextSwitchTo(oldcontext);
431 
432  estate->es_finished = true;
433 }
void InstrStopNode(Instrumentation *instr, double nTuples)
Definition: instrument.c:83
static void ExecPostprocessPlan(EState *estate)
Definition: execMain.c:1331
EState * estate
Definition: execdesc.h:48
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:109
MemoryContext es_query_cxt
Definition: execnodes.h:572
void InstrStartNode(Instrumentation *instr)
Definition: instrument.c:67
bool es_finished
Definition: execnodes.h:580
struct Instrumentation * totaltime
Definition: execdesc.h:55
#define Assert(condition)
Definition: c.h:804
#define EXEC_FLAG_SKIP_TRIGGERS
Definition: executor.h:60
void AfterTriggerEndQuery(EState *estate)
Definition: trigger.c:4508
int es_top_eflags
Definition: execnodes.h:578
#define EXEC_FLAG_EXPLAIN_ONLY
Definition: executor.h:56

◆ standard_ExecutorRun()

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

Definition at line 298 of file execMain.c.

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

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

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

◆ standard_ExecutorStart()

void standard_ExecutorStart ( QueryDesc queryDesc,
int  eflags 
)

Definition at line 138 of file execMain.c.

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

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

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

Variable Documentation

◆ ExecutorCheckPerms_hook

ExecutorCheckPerms_hook_type ExecutorCheckPerms_hook = NULL

Definition at line 76 of file execMain.c.

Referenced by _PG_init(), and ExecCheckRTPerms().

◆ ExecutorEnd_hook

ExecutorEnd_hook_type ExecutorEnd_hook = NULL

Definition at line 73 of file execMain.c.

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

◆ ExecutorFinish_hook

ExecutorFinish_hook_type ExecutorFinish_hook = NULL

Definition at line 72 of file execMain.c.

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

◆ ExecutorRun_hook

ExecutorRun_hook_type ExecutorRun_hook = NULL

Definition at line 71 of file execMain.c.

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

◆ ExecutorStart_hook

ExecutorStart_hook_type ExecutorStart_hook = NULL

Definition at line 70 of file execMain.c.

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