PostgreSQL Source Code  git master
 All Data Structures Namespaces Files Functions Variables Typedefs Enumerations Enumerator Macros
execMain.c File Reference
#include "postgres.h"
#include "access/htup_details.h"
#include "access/sysattr.h"
#include "access/transam.h"
#include "access/xact.h"
#include "catalog/namespace.h"
#include "catalog/partition.h"
#include "catalog/pg_inherits_fn.h"
#include "catalog/pg_publication.h"
#include "commands/matview.h"
#include "commands/trigger.h"
#include "executor/execdebug.h"
#include "foreign/fdwapi.h"
#include "mb/pg_wchar.h"
#include "miscadmin.h"
#include "optimizer/clauses.h"
#include "parser/parsetree.h"
#include "rewrite/rewriteManip.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/rls.h"
#include "utils/ruleutils.h"
#include "utils/snapmgr.h"
#include "utils/tqual.h"
Include dependency graph for execMain.c:

Go to the source code of this file.

Macros

#define GetInsertedColumns(relinfo, estate)   (rt_fetch((relinfo)->ri_RangeTableIndex, (estate)->es_range_table)->insertedCols)
 
#define GetUpdatedColumns(relinfo, estate)   (rt_fetch((relinfo)->ri_RangeTableIndex, (estate)->es_range_table)->updatedCols)
 

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 char * ExecBuildSlotPartitionKeyDescription (Relation rel, Datum *values, bool *isnull, int maxfieldlen)
 
static void EvalPlanQualStart (EPQState *epqstate, EState *parentestate, Plan *planTree)
 
static void ExecPartitionCheck (ResultRelInfo *resultRelInfo, TupleTableSlot *slot, EState *estate)
 
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, Relation partition_root, int instrument_options)
 
ResultRelInfoExecGetTriggerResultRel (EState *estate, Oid relid)
 
void ExecCleanUpTriggerState (EState *estate)
 
bool ExecContextForcesOids (PlanState *planstate, bool *hasoids)
 
static const char * ExecRelCheck (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 (EState *estate, EPQState *epqstate, Relation relation, Index rti, int lockmode, ItemPointer tid, TransactionId priorXmax)
 
HeapTuple EvalPlanQualFetch (EState *estate, Relation relation, int lockmode, LockWaitPolicy wait_policy, ItemPointer tid, TransactionId priorXmax)
 
void EvalPlanQualInit (EPQState *epqstate, EState *estate, Plan *subplan, List *auxrowmarks, int epqParam)
 
void EvalPlanQualSetPlan (EPQState *epqstate, Plan *subplan, List *auxrowmarks)
 
void EvalPlanQualSetTuple (EPQState *epqstate, Index rti, HeapTuple tuple)
 
HeapTuple EvalPlanQualGetTuple (EPQState *epqstate, Index rti)
 
void EvalPlanQualFetchRowMarks (EPQState *epqstate)
 
TupleTableSlotEvalPlanQualNext (EPQState *epqstate)
 
void EvalPlanQualBegin (EPQState *epqstate, EState *parentestate)
 
void EvalPlanQualEnd (EPQState *epqstate)
 
void ExecSetupPartitionTupleRouting (Relation rel, Index resultRTindex, EState *estate, PartitionDispatch **pd, ResultRelInfo ***partitions, TupleConversionMap ***tup_conv_maps, TupleTableSlot **partition_tuple_slot, int *num_parted, int *num_partitions)
 
int ExecFindPartition (ResultRelInfo *resultRelInfo, PartitionDispatch *pd, TupleTableSlot *slot, EState *estate)
 

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
 

Macro Definition Documentation

#define GetInsertedColumns (   relinfo,
  estate 
)    (rt_fetch((relinfo)->ri_RangeTableIndex, (estate)->es_range_table)->insertedCols)

Definition at line 116 of file execMain.c.

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

#define GetUpdatedColumns (   relinfo,
  estate 
)    (rt_fetch((relinfo)->ri_RangeTableIndex, (estate)->es_range_table)->updatedCols)

Function Documentation

void CheckValidResultRel ( ResultRelInfo resultRelInfo,
CmdType  operation 
)

Definition at line 1100 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, RELKIND_FOREIGN_TABLE, RELKIND_MATVIEW, RELKIND_PARTITIONED_TABLE, RELKIND_RELATION, RELKIND_SEQUENCE, RELKIND_TOASTVALUE, RELKIND_VIEW, ResultRelInfo::ri_FdwRoutine, ResultRelInfo::ri_PartitionRoot, ResultRelInfo::ri_RelationDesc, TriggerDesc::trig_delete_instead_row, TriggerDesc::trig_insert_instead_row, TriggerDesc::trig_update_instead_row, and RelationData::trigdesc.

Referenced by ExecInitModifyTable(), and ExecSetupPartitionTupleRouting().

1101 {
1102  Relation resultRel = resultRelInfo->ri_RelationDesc;
1103  TriggerDesc *trigDesc = resultRel->trigdesc;
1104  FdwRoutine *fdwroutine;
1105 
1106  switch (resultRel->rd_rel->relkind)
1107  {
1108  case RELKIND_RELATION:
1110  CheckCmdReplicaIdentity(resultRel, operation);
1111  break;
1112  case RELKIND_SEQUENCE:
1113  ereport(ERROR,
1114  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1115  errmsg("cannot change sequence \"%s\"",
1116  RelationGetRelationName(resultRel))));
1117  break;
1118  case RELKIND_TOASTVALUE:
1119  ereport(ERROR,
1120  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1121  errmsg("cannot change TOAST relation \"%s\"",
1122  RelationGetRelationName(resultRel))));
1123  break;
1124  case RELKIND_VIEW:
1125 
1126  /*
1127  * Okay only if there's a suitable INSTEAD OF trigger. Messages
1128  * here should match rewriteHandler.c's rewriteTargetView, except
1129  * that we omit errdetail because we haven't got the information
1130  * handy (and given that we really shouldn't get here anyway, it's
1131  * not worth great exertion to get).
1132  */
1133  switch (operation)
1134  {
1135  case CMD_INSERT:
1136  if (!trigDesc || !trigDesc->trig_insert_instead_row)
1137  ereport(ERROR,
1138  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
1139  errmsg("cannot insert into view \"%s\"",
1140  RelationGetRelationName(resultRel)),
1141  errhint("To enable inserting into the view, provide an INSTEAD OF INSERT trigger or an unconditional ON INSERT DO INSTEAD rule.")));
1142  break;
1143  case CMD_UPDATE:
1144  if (!trigDesc || !trigDesc->trig_update_instead_row)
1145  ereport(ERROR,
1146  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
1147  errmsg("cannot update view \"%s\"",
1148  RelationGetRelationName(resultRel)),
1149  errhint("To enable updating the view, provide an INSTEAD OF UPDATE trigger or an unconditional ON UPDATE DO INSTEAD rule.")));
1150  break;
1151  case CMD_DELETE:
1152  if (!trigDesc || !trigDesc->trig_delete_instead_row)
1153  ereport(ERROR,
1154  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
1155  errmsg("cannot delete from view \"%s\"",
1156  RelationGetRelationName(resultRel)),
1157  errhint("To enable deleting from the view, provide an INSTEAD OF DELETE trigger or an unconditional ON DELETE DO INSTEAD rule.")));
1158  break;
1159  default:
1160  elog(ERROR, "unrecognized CmdType: %d", (int) operation);
1161  break;
1162  }
1163  break;
1164  case RELKIND_MATVIEW:
1166  ereport(ERROR,
1167  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1168  errmsg("cannot change materialized view \"%s\"",
1169  RelationGetRelationName(resultRel))));
1170  break;
1171  case RELKIND_FOREIGN_TABLE:
1172  /* Okay only if the FDW supports it */
1173  fdwroutine = resultRelInfo->ri_FdwRoutine;
1174  switch (operation)
1175  {
1176  case CMD_INSERT:
1177 
1178  /*
1179  * If foreign partition to do tuple-routing for, skip the
1180  * check; it's disallowed elsewhere.
1181  */
1182  if (resultRelInfo->ri_PartitionRoot)
1183  break;
1184  if (fdwroutine->ExecForeignInsert == NULL)
1185  ereport(ERROR,
1186  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1187  errmsg("cannot insert into foreign table \"%s\"",
1188  RelationGetRelationName(resultRel))));
1189  if (fdwroutine->IsForeignRelUpdatable != NULL &&
1190  (fdwroutine->IsForeignRelUpdatable(resultRel) & (1 << CMD_INSERT)) == 0)
1191  ereport(ERROR,
1192  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
1193  errmsg("foreign table \"%s\" does not allow inserts",
1194  RelationGetRelationName(resultRel))));
1195  break;
1196  case CMD_UPDATE:
1197  if (fdwroutine->ExecForeignUpdate == NULL)
1198  ereport(ERROR,
1199  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1200  errmsg("cannot update foreign table \"%s\"",
1201  RelationGetRelationName(resultRel))));
1202  if (fdwroutine->IsForeignRelUpdatable != NULL &&
1203  (fdwroutine->IsForeignRelUpdatable(resultRel) & (1 << CMD_UPDATE)) == 0)
1204  ereport(ERROR,
1205  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
1206  errmsg("foreign table \"%s\" does not allow updates",
1207  RelationGetRelationName(resultRel))));
1208  break;
1209  case CMD_DELETE:
1210  if (fdwroutine->ExecForeignDelete == NULL)
1211  ereport(ERROR,
1212  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1213  errmsg("cannot delete from foreign table \"%s\"",
1214  RelationGetRelationName(resultRel))));
1215  if (fdwroutine->IsForeignRelUpdatable != NULL &&
1216  (fdwroutine->IsForeignRelUpdatable(resultRel) & (1 << CMD_DELETE)) == 0)
1217  ereport(ERROR,
1218  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
1219  errmsg("foreign table \"%s\" does not allow deletes",
1220  RelationGetRelationName(resultRel))));
1221  break;
1222  default:
1223  elog(ERROR, "unrecognized CmdType: %d", (int) operation);
1224  break;
1225  }
1226  break;
1227  default:
1228  ereport(ERROR,
1229  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1230  errmsg("cannot change relation \"%s\"",
1231  RelationGetRelationName(resultRel))));
1232  break;
1233  }
1234 }
ExecForeignDelete_function ExecForeignDelete
Definition: fdwapi.h:205
Relation ri_RelationDesc
Definition: execnodes.h:354
int errhint(const char *fmt,...)
Definition: elog.c:987
bool MatViewIncrementalMaintenanceIsEnabled(void)
Definition: matview.c:861
ExecForeignInsert_function ExecForeignInsert
Definition: fdwapi.h:203
Relation ri_PartitionRoot
Definition: execnodes.h:414
#define RELKIND_MATVIEW
Definition: pg_class.h:165
int errcode(int sqlerrcode)
Definition: elog.c:575
Form_pg_class rd_rel
Definition: rel.h:114
bool trig_insert_instead_row
Definition: reltrigger.h:57
#define ERROR
Definition: elog.h:43
TriggerDesc * trigdesc
Definition: rel.h:120
#define RelationGetRelationName(relation)
Definition: rel.h:436
struct FdwRoutine * ri_FdwRoutine
Definition: execnodes.h:378
#define RELKIND_FOREIGN_TABLE
Definition: pg_class.h:167
void CheckCmdReplicaIdentity(Relation rel, CmdType cmd)
#define ereport(elevel, rest)
Definition: elog.h:122
bool trig_update_instead_row
Definition: reltrigger.h:62
#define RELKIND_PARTITIONED_TABLE
Definition: pg_class.h:168
bool trig_delete_instead_row
Definition: reltrigger.h:67
#define RELKIND_TOASTVALUE
Definition: pg_class.h:163
ExecForeignUpdate_function ExecForeignUpdate
Definition: fdwapi.h:204
int errmsg(const char *fmt,...)
Definition: elog.c:797
#define RELKIND_VIEW
Definition: pg_class.h:164
IsForeignRelUpdatable_function IsForeignRelUpdatable
Definition: fdwapi.h:207
#define elog
Definition: elog.h:219
#define RELKIND_RELATION
Definition: pg_class.h:160
#define RELKIND_SEQUENCE
Definition: pg_class.h:162
static void CheckValidRowMarkRel ( Relation  rel,
RowMarkType  markType 
)
static

Definition at line 1243 of file execMain.c.

References ereport, errcode(), errmsg(), ERROR, GetFdwRoutineForRelation(), RelationData::rd_rel, FdwRoutine::RefetchForeignRow, RelationGetRelationName, RELKIND_FOREIGN_TABLE, RELKIND_MATVIEW, RELKIND_PARTITIONED_TABLE, RELKIND_RELATION, RELKIND_SEQUENCE, RELKIND_TOASTVALUE, RELKIND_VIEW, and ROW_MARK_REFERENCE.

Referenced by InitPlan().

1244 {
1245  FdwRoutine *fdwroutine;
1246 
1247  switch (rel->rd_rel->relkind)
1248  {
1249  case RELKIND_RELATION:
1251  /* OK */
1252  break;
1253  case RELKIND_SEQUENCE:
1254  /* Must disallow this because we don't vacuum sequences */
1255  ereport(ERROR,
1256  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1257  errmsg("cannot lock rows in sequence \"%s\"",
1258  RelationGetRelationName(rel))));
1259  break;
1260  case RELKIND_TOASTVALUE:
1261  /* We could allow this, but there seems no good reason to */
1262  ereport(ERROR,
1263  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1264  errmsg("cannot lock rows in TOAST relation \"%s\"",
1265  RelationGetRelationName(rel))));
1266  break;
1267  case RELKIND_VIEW:
1268  /* Should not get here; planner should have expanded the view */
1269  ereport(ERROR,
1270  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1271  errmsg("cannot lock rows in view \"%s\"",
1272  RelationGetRelationName(rel))));
1273  break;
1274  case RELKIND_MATVIEW:
1275  /* Allow referencing a matview, but not actual locking clauses */
1276  if (markType != ROW_MARK_REFERENCE)
1277  ereport(ERROR,
1278  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1279  errmsg("cannot lock rows in materialized view \"%s\"",
1280  RelationGetRelationName(rel))));
1281  break;
1282  case RELKIND_FOREIGN_TABLE:
1283  /* Okay only if the FDW supports it */
1284  fdwroutine = GetFdwRoutineForRelation(rel, false);
1285  if (fdwroutine->RefetchForeignRow == NULL)
1286  ereport(ERROR,
1287  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1288  errmsg("cannot lock rows in foreign table \"%s\"",
1289  RelationGetRelationName(rel))));
1290  break;
1291  default:
1292  ereport(ERROR,
1293  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1294  errmsg("cannot lock rows in relation \"%s\"",
1295  RelationGetRelationName(rel))));
1296  break;
1297  }
1298 }
#define RELKIND_MATVIEW
Definition: pg_class.h:165
int errcode(int sqlerrcode)
Definition: elog.c:575
Form_pg_class rd_rel
Definition: rel.h:114
#define ERROR
Definition: elog.h:43
#define RelationGetRelationName(relation)
Definition: rel.h:436
#define RELKIND_FOREIGN_TABLE
Definition: pg_class.h:167
#define ereport(elevel, rest)
Definition: elog.h:122
#define RELKIND_PARTITIONED_TABLE
Definition: pg_class.h:168
#define RELKIND_TOASTVALUE
Definition: pg_class.h:163
int errmsg(const char *fmt,...)
Definition: elog.c:797
FdwRoutine * GetFdwRoutineForRelation(Relation relation, bool makecopy)
Definition: foreign.c:395
#define RELKIND_VIEW
Definition: pg_class.h:164
#define RELKIND_RELATION
Definition: pg_class.h:160
#define RELKIND_SEQUENCE
Definition: pg_class.h:162
RefetchForeignRow_function RefetchForeignRow
Definition: fdwapi.h:215
TupleTableSlot* EvalPlanQual ( EState estate,
EPQState epqstate,
Relation  relation,
Index  rti,
int  lockmode,
ItemPointer  tid,
TransactionId  priorXmax 
)

Definition at line 2477 of file execMain.c.

References Assert, EvalPlanQualBegin(), EvalPlanQualFetch(), EvalPlanQualFetchRowMarks(), EvalPlanQualNext(), EvalPlanQualSetTuple(), ExecMaterializeSlot(), LockWaitBlock, HeapTupleData::t_self, and TupIsNull.

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

2480 {
2481  TupleTableSlot *slot;
2482  HeapTuple copyTuple;
2483 
2484  Assert(rti > 0);
2485 
2486  /*
2487  * Get and lock the updated version of the row; if fail, return NULL.
2488  */
2489  copyTuple = EvalPlanQualFetch(estate, relation, lockmode, LockWaitBlock,
2490  tid, priorXmax);
2491 
2492  if (copyTuple == NULL)
2493  return NULL;
2494 
2495  /*
2496  * For UPDATE/DELETE we have to return tid of actual row we're executing
2497  * PQ for.
2498  */
2499  *tid = copyTuple->t_self;
2500 
2501  /*
2502  * Need to run a recheck subquery. Initialize or reinitialize EPQ state.
2503  */
2504  EvalPlanQualBegin(epqstate, estate);
2505 
2506  /*
2507  * Free old test tuple, if any, and store new tuple where relation's scan
2508  * node will see it
2509  */
2510  EvalPlanQualSetTuple(epqstate, rti, copyTuple);
2511 
2512  /*
2513  * Fetch any non-locked source rows
2514  */
2515  EvalPlanQualFetchRowMarks(epqstate);
2516 
2517  /*
2518  * Run the EPQ query. We assume it will return at most one tuple.
2519  */
2520  slot = EvalPlanQualNext(epqstate);
2521 
2522  /*
2523  * If we got a tuple, force the slot to materialize the tuple so that it
2524  * is not dependent on any local state in the EPQ query (in particular,
2525  * it's highly likely that the slot contains references to any pass-by-ref
2526  * datums that may be present in copyTuple). As with the next step, this
2527  * is to guard against early re-use of the EPQ query.
2528  */
2529  if (!TupIsNull(slot))
2530  (void) ExecMaterializeSlot(slot);
2531 
2532  /*
2533  * Clear out the test tuple. This is needed in case the EPQ query is
2534  * re-used to test a tuple for a different relation. (Not clear that can
2535  * really happen, but let's be safe.)
2536  */
2537  EvalPlanQualSetTuple(epqstate, rti, NULL);
2538 
2539  return slot;
2540 }
void EvalPlanQualSetTuple(EPQState *epqstate, Index rti, HeapTuple tuple)
Definition: execMain.c:2826
HeapTuple EvalPlanQualFetch(EState *estate, Relation relation, int lockmode, LockWaitPolicy wait_policy, ItemPointer tid, TransactionId priorXmax)
Definition: execMain.c:2564
void EvalPlanQualFetchRowMarks(EPQState *epqstate)
Definition: execMain.c:2861
void EvalPlanQualBegin(EPQState *epqstate, EState *parentestate)
Definition: execMain.c:3012
TupleTableSlot * EvalPlanQualNext(EPQState *epqstate)
Definition: execMain.c:2996
ItemPointerData t_self
Definition: htup.h:65
#define TupIsNull(slot)
Definition: tuptable.h:138
#define Assert(condition)
Definition: c.h:681
HeapTuple ExecMaterializeSlot(TupleTableSlot *slot)
Definition: execTuples.c:725
void EvalPlanQualBegin ( EPQState epqstate,
EState parentestate 
)

Definition at line 3012 of file execMain.c.

References bms_add_member(), PlanState::chgParam, EPQState::epqParam, EState::es_epqScanDone, EState::es_param_exec_vals, EState::es_plannedstmt, EState::es_range_table, EPQState::estate, EvalPlanQualStart(), i, ParamExecData::isnull, list_length(), MemSet, PlannedStmt::nParamExec, EPQState::plan, EPQState::planstate, and ParamExecData::value.

Referenced by EvalPlanQual(), and ExecLockRows().

3013 {
3014  EState *estate = epqstate->estate;
3015 
3016  if (estate == NULL)
3017  {
3018  /* First time through, so create a child EState */
3019  EvalPlanQualStart(epqstate, parentestate, epqstate->plan);
3020  }
3021  else
3022  {
3023  /*
3024  * We already have a suitable child EPQ tree, so just reset it.
3025  */
3026  int rtsize = list_length(parentestate->es_range_table);
3027  PlanState *planstate = epqstate->planstate;
3028 
3029  MemSet(estate->es_epqScanDone, 0, rtsize * sizeof(bool));
3030 
3031  /* Recopy current values of parent parameters */
3032  if (parentestate->es_plannedstmt->nParamExec > 0)
3033  {
3034  int i = parentestate->es_plannedstmt->nParamExec;
3035 
3036  while (--i >= 0)
3037  {
3038  /* copy value if any, but not execPlan link */
3039  estate->es_param_exec_vals[i].value =
3040  parentestate->es_param_exec_vals[i].value;
3041  estate->es_param_exec_vals[i].isnull =
3042  parentestate->es_param_exec_vals[i].isnull;
3043  }
3044  }
3045 
3046  /*
3047  * Mark child plan tree as needing rescan at all scan nodes. The
3048  * first ExecProcNode will take care of actually doing the rescan.
3049  */
3050  planstate->chgParam = bms_add_member(planstate->chgParam,
3051  epqstate->epqParam);
3052  }
3053 }
PlannedStmt * es_plannedstmt
Definition: execnodes.h:432
#define MemSet(start, val, len)
Definition: c.h:863
List * es_range_table
Definition: execnodes.h:431
PlanState * planstate
Definition: execnodes.h:915
int nParamExec
Definition: plannodes.h:92
ParamExecData * es_param_exec_vals
Definition: execnodes.h:466
bool isnull
Definition: params.h:101
static void EvalPlanQualStart(EPQState *epqstate, EState *parentestate, Plan *planTree)
Definition: execMain.c:3062
Bitmapset * chgParam
Definition: execnodes.h:875
Plan * plan
Definition: execnodes.h:917
static int list_length(const List *l)
Definition: pg_list.h:89
Bitmapset * bms_add_member(Bitmapset *a, int x)
Definition: bitmapset.c:698
int i
bool * es_epqScanDone
Definition: execnodes.h:508
Datum value
Definition: params.h:100
int epqParam
Definition: execnodes.h:919
EState * estate
Definition: execnodes.h:914
void EvalPlanQualEnd ( EPQState epqstate)

Definition at line 3202 of file execMain.c.

References EState::es_query_cxt, EState::es_subplanstates, EState::es_tupleTable, EPQState::estate, ExecCleanUpTriggerState(), ExecEndNode(), ExecResetTupleTable(), FreeExecutorState(), lfirst, MemoryContextSwitchTo(), EPQState::origslot, and EPQState::planstate.

Referenced by apply_handle_delete(), apply_handle_update(), EvalPlanQualSetPlan(), ExecEndLockRows(), and ExecEndModifyTable().

3203 {
3204  EState *estate = epqstate->estate;
3205  MemoryContext oldcontext;
3206  ListCell *l;
3207 
3208  if (estate == NULL)
3209  return; /* idle, so nothing to do */
3210 
3211  oldcontext = MemoryContextSwitchTo(estate->es_query_cxt);
3212 
3213  ExecEndNode(epqstate->planstate);
3214 
3215  foreach(l, estate->es_subplanstates)
3216  {
3217  PlanState *subplanstate = (PlanState *) lfirst(l);
3218 
3219  ExecEndNode(subplanstate);
3220  }
3221 
3222  /* throw away the per-estate tuple table */
3223  ExecResetTupleTable(estate->es_tupleTable, false);
3224 
3225  /* close any trigger target relations attached to this EState */
3226  ExecCleanUpTriggerState(estate);
3227 
3228  MemoryContextSwitchTo(oldcontext);
3229 
3230  FreeExecutorState(estate);
3231 
3232  /* Mark EPQState idle */
3233  epqstate->estate = NULL;
3234  epqstate->planstate = NULL;
3235  epqstate->origslot = NULL;
3236 }
void ExecEndNode(PlanState *node)
Definition: execProcnode.c:523
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:109
PlanState * planstate
Definition: execnodes.h:915
void FreeExecutorState(EState *estate)
Definition: execUtils.c:183
MemoryContext es_query_cxt
Definition: execnodes.h:471
TupleTableSlot * origslot
Definition: execnodes.h:916
List * es_tupleTable
Definition: execnodes.h:473
void ExecResetTupleTable(List *tupleTable, bool shouldFree)
Definition: execTuples.c:156
#define lfirst(lc)
Definition: pg_list.h:106
List * es_subplanstates
Definition: execnodes.h:486
void ExecCleanUpTriggerState(EState *estate)
Definition: execMain.c:1468
EState * estate
Definition: execnodes.h:914
HeapTuple EvalPlanQualFetch ( EState estate,
Relation  relation,
int  lockmode,
LockWaitPolicy  wait_policy,
ItemPointer  tid,
TransactionId  priorXmax 
)

Definition at line 2564 of file execMain.c.

References Assert, buffer, ConditionalXactLockTableWait(), HeapUpdateFailureData::ctid, elog, ereport, errcode(), errmsg(), ERROR, EState::es_output_cid, heap_copytuple(), heap_fetch(), heap_lock_tuple(), HeapTupleHeaderGetCmin(), HeapTupleHeaderGetUpdateXid, HeapTupleHeaderIsSpeculative, HeapTupleInvisible, HeapTupleMayBeUpdated, HeapTupleSelfUpdated, HeapTupleUpdated, HeapTupleUpdateXmaxMatchesXmin(), HeapTupleWouldBlock, InitDirtySnapshot, IsolationUsesXactSnapshot, ItemPointerEquals(), LockWaitBlock, LockWaitError, LockWaitSkip, RelationGetRelationName, ReleaseBuffer(), HeapTupleHeaderData::t_ctid, HeapTupleData::t_data, HeapTupleData::t_self, test(), TransactionIdIsCurrentTransactionId(), TransactionIdIsValid, XactLockTableWait(), XLTW_FetchUpdated, SnapshotData::xmax, HeapUpdateFailureData::xmax, and SnapshotData::xmin.

Referenced by EvalPlanQual(), and ExecLockRows().

2567 {
2568  HeapTuple copyTuple = NULL;
2569  HeapTupleData tuple;
2570  SnapshotData SnapshotDirty;
2571 
2572  /*
2573  * fetch target tuple
2574  *
2575  * Loop here to deal with updated or busy tuples
2576  */
2577  InitDirtySnapshot(SnapshotDirty);
2578  tuple.t_self = *tid;
2579  for (;;)
2580  {
2581  Buffer buffer;
2582 
2583  if (heap_fetch(relation, &SnapshotDirty, &tuple, &buffer, true, NULL))
2584  {
2585  HTSU_Result test;
2586  HeapUpdateFailureData hufd;
2587 
2588  /*
2589  * If xmin isn't what we're expecting, the slot must have been
2590  * recycled and reused for an unrelated tuple. This implies that
2591  * the latest version of the row was deleted, so we need do
2592  * nothing. (Should be safe to examine xmin without getting
2593  * buffer's content lock. We assume reading a TransactionId to be
2594  * atomic, and Xmin never changes in an existing tuple, except to
2595  * invalid or frozen, and neither of those can match priorXmax.)
2596  */
2597  if (!HeapTupleUpdateXmaxMatchesXmin(priorXmax, tuple.t_data))
2598  {
2599  ReleaseBuffer(buffer);
2600  return NULL;
2601  }
2602 
2603  /* otherwise xmin should not be dirty... */
2604  if (TransactionIdIsValid(SnapshotDirty.xmin))
2605  elog(ERROR, "t_xmin is uncommitted in tuple to be updated");
2606 
2607  /*
2608  * If tuple is being updated by other transaction then we have to
2609  * wait for its commit/abort, or die trying.
2610  */
2611  if (TransactionIdIsValid(SnapshotDirty.xmax))
2612  {
2613  ReleaseBuffer(buffer);
2614  switch (wait_policy)
2615  {
2616  case LockWaitBlock:
2617  XactLockTableWait(SnapshotDirty.xmax,
2618  relation, &tuple.t_self,
2620  break;
2621  case LockWaitSkip:
2622  if (!ConditionalXactLockTableWait(SnapshotDirty.xmax))
2623  return NULL; /* skip instead of waiting */
2624  break;
2625  case LockWaitError:
2626  if (!ConditionalXactLockTableWait(SnapshotDirty.xmax))
2627  ereport(ERROR,
2628  (errcode(ERRCODE_LOCK_NOT_AVAILABLE),
2629  errmsg("could not obtain lock on row in relation \"%s\"",
2630  RelationGetRelationName(relation))));
2631  break;
2632  }
2633  continue; /* loop back to repeat heap_fetch */
2634  }
2635 
2636  /*
2637  * If tuple was inserted by our own transaction, we have to check
2638  * cmin against es_output_cid: cmin >= current CID means our
2639  * command cannot see the tuple, so we should ignore it. Otherwise
2640  * heap_lock_tuple() will throw an error, and so would any later
2641  * attempt to update or delete the tuple. (We need not check cmax
2642  * because HeapTupleSatisfiesDirty will consider a tuple deleted
2643  * by our transaction dead, regardless of cmax.) We just checked
2644  * that priorXmax == xmin, so we can test that variable instead of
2645  * doing HeapTupleHeaderGetXmin again.
2646  */
2647  if (TransactionIdIsCurrentTransactionId(priorXmax) &&
2648  HeapTupleHeaderGetCmin(tuple.t_data) >= estate->es_output_cid)
2649  {
2650  ReleaseBuffer(buffer);
2651  return NULL;
2652  }
2653 
2654  /*
2655  * This is a live tuple, so now try to lock it.
2656  */
2657  test = heap_lock_tuple(relation, &tuple,
2658  estate->es_output_cid,
2659  lockmode, wait_policy,
2660  false, &buffer, &hufd);
2661  /* We now have two pins on the buffer, get rid of one */
2662  ReleaseBuffer(buffer);
2663 
2664  switch (test)
2665  {
2666  case HeapTupleSelfUpdated:
2667 
2668  /*
2669  * The target tuple was already updated or deleted by the
2670  * current command, or by a later command in the current
2671  * transaction. We *must* ignore the tuple in the former
2672  * case, so as to avoid the "Halloween problem" of
2673  * repeated update attempts. In the latter case it might
2674  * be sensible to fetch the updated tuple instead, but
2675  * doing so would require changing heap_update and
2676  * heap_delete to not complain about updating "invisible"
2677  * tuples, which seems pretty scary (heap_lock_tuple will
2678  * not complain, but few callers expect
2679  * HeapTupleInvisible, and we're not one of them). So for
2680  * now, treat the tuple as deleted and do not process.
2681  */
2682  ReleaseBuffer(buffer);
2683  return NULL;
2684 
2685  case HeapTupleMayBeUpdated:
2686  /* successfully locked */
2687  break;
2688 
2689  case HeapTupleUpdated:
2690  ReleaseBuffer(buffer);
2692  ereport(ERROR,
2693  (errcode(ERRCODE_T_R_SERIALIZATION_FAILURE),
2694  errmsg("could not serialize access due to concurrent update")));
2695 
2696  /* Should not encounter speculative tuple on recheck */
2698  if (!ItemPointerEquals(&hufd.ctid, &tuple.t_self))
2699  {
2700  /* it was updated, so look at the updated version */
2701  tuple.t_self = hufd.ctid;
2702  /* updated row should have xmin matching this xmax */
2703  priorXmax = hufd.xmax;
2704  continue;
2705  }
2706  /* tuple was deleted, so give up */
2707  return NULL;
2708 
2709  case HeapTupleWouldBlock:
2710  ReleaseBuffer(buffer);
2711  return NULL;
2712 
2713  case HeapTupleInvisible:
2714  elog(ERROR, "attempted to lock invisible tuple");
2715 
2716  default:
2717  ReleaseBuffer(buffer);
2718  elog(ERROR, "unrecognized heap_lock_tuple status: %u",
2719  test);
2720  return NULL; /* keep compiler quiet */
2721  }
2722 
2723  /*
2724  * We got tuple - now copy it for use by recheck query.
2725  */
2726  copyTuple = heap_copytuple(&tuple);
2727  ReleaseBuffer(buffer);
2728  break;
2729  }
2730 
2731  /*
2732  * If the referenced slot was actually empty, the latest version of
2733  * the row must have been deleted, so we need do nothing.
2734  */
2735  if (tuple.t_data == NULL)
2736  {
2737  ReleaseBuffer(buffer);
2738  return NULL;
2739  }
2740 
2741  /*
2742  * As above, if xmin isn't what we're expecting, do nothing.
2743  */
2744  if (!HeapTupleUpdateXmaxMatchesXmin(priorXmax, tuple.t_data))
2745  {
2746  ReleaseBuffer(buffer);
2747  return NULL;
2748  }
2749 
2750  /*
2751  * If we get here, the tuple was found but failed SnapshotDirty.
2752  * Assuming the xmin is either a committed xact or our own xact (as it
2753  * certainly should be if we're trying to modify the tuple), this must
2754  * mean that the row was updated or deleted by either a committed xact
2755  * or our own xact. If it was deleted, we can ignore it; if it was
2756  * updated then chain up to the next version and repeat the whole
2757  * process.
2758  *
2759  * As above, it should be safe to examine xmax and t_ctid without the
2760  * buffer content lock, because they can't be changing.
2761  */
2762  if (ItemPointerEquals(&tuple.t_self, &tuple.t_data->t_ctid))
2763  {
2764  /* deleted, so forget about it */
2765  ReleaseBuffer(buffer);
2766  return NULL;
2767  }
2768 
2769  /* updated, so look at the updated row */
2770  tuple.t_self = tuple.t_data->t_ctid;
2771  /* updated row should have xmin matching this xmax */
2772  priorXmax = HeapTupleHeaderGetUpdateXid(tuple.t_data);
2773  ReleaseBuffer(buffer);
2774  /* loop back to fetch next in chain */
2775  }
2776 
2777  /*
2778  * Return the copied tuple
2779  */
2780  return copyTuple;
2781 }
#define HeapTupleHeaderGetUpdateXid(tup)
Definition: htup_details.h:359
HeapTuple heap_copytuple(HeapTuple tuple)
Definition: heaptuple.c:611
CommandId es_output_cid
Definition: execnodes.h:438
static void test(void)
bool TransactionIdIsCurrentTransactionId(TransactionId xid)
Definition: xact.c:766
HTSU_Result heap_lock_tuple(Relation relation, HeapTuple tuple, CommandId cid, LockTupleMode mode, LockWaitPolicy wait_policy, bool follow_updates, Buffer *buffer, HeapUpdateFailureData *hufd)
Definition: heapam.c:4603
CommandId HeapTupleHeaderGetCmin(HeapTupleHeader tup)
Definition: combocid.c:105
bool heap_fetch(Relation relation, Snapshot snapshot, HeapTuple tuple, Buffer *userbuf, bool keep_buf, Relation stats_relation)
Definition: heapam.c:1876
#define IsolationUsesXactSnapshot()
Definition: xact.h:43
#define HeapTupleHeaderIsSpeculative(tup)
Definition: htup_details.h:423
int errcode(int sqlerrcode)
Definition: elog.c:575
void ReleaseBuffer(Buffer buffer)
Definition: bufmgr.c:3309
bool ConditionalXactLockTableWait(TransactionId xid)
Definition: lmgr.c:607
HeapTupleHeader t_data
Definition: htup.h:67
#define ERROR
Definition: elog.h:43
#define InitDirtySnapshot(snapshotdata)
Definition: tqual.h:103
ItemPointerData t_ctid
Definition: htup_details.h:150
ItemPointerData t_self
Definition: htup.h:65
HTSU_Result
Definition: snapshot.h:121
#define RelationGetRelationName(relation)
Definition: rel.h:436
TransactionId xmax
Definition: snapshot.h:69
TransactionId xmin
Definition: snapshot.h:68
#define ereport(elevel, rest)
Definition: elog.h:122
TransactionId xmax
Definition: heapam.h:71
bool HeapTupleUpdateXmaxMatchesXmin(TransactionId xmax, HeapTupleHeader htup)
Definition: heapam.c:2304
void XactLockTableWait(TransactionId xid, Relation rel, ItemPointer ctid, XLTW_Oper oper)
Definition: lmgr.c:554
#define Assert(condition)
Definition: c.h:681
WalTimeSample buffer[LAG_TRACKER_BUFFER_SIZE]
Definition: walsender.c:214
bool ItemPointerEquals(ItemPointer pointer1, ItemPointer pointer2)
Definition: itemptr.c:29
int errmsg(const char *fmt,...)
Definition: elog.c:797
ItemPointerData ctid
Definition: heapam.h:70
#define elog
Definition: elog.h:219
#define TransactionIdIsValid(xid)
Definition: transam.h:41
int Buffer
Definition: buf.h:23
void EvalPlanQualFetchRowMarks ( EPQState epqstate)

Definition at line 2861 of file execMain.c.

References EPQState::arowMarks, Assert, buffer, ExecAuxRowMark::ctidAttNo, DatumGetHeapTupleHeader, DatumGetObjectId, DatumGetPointer, elog, ereport, errcode(), errmsg(), ERROR, EPQState::estate, EvalPlanQualSetTuple(), ExecGetJunkAttribute(), GetFdwRoutineForRelation(), heap_copytuple(), heap_fetch(), HeapTupleHeaderGetDatumLength, lfirst, ExecRowMark::markType, OidIsValid, EPQState::origslot, ExecRowMark::prti, RelationData::rd_rel, FdwRoutine::RefetchForeignRow, ExecRowMark::relation, RelationGetRelationName, ReleaseBuffer(), ExecRowMark::relid, RELKIND_FOREIGN_TABLE, ROW_MARK_COPY, ROW_MARK_REFERENCE, ExecAuxRowMark::rowmark, RowMarkRequiresRowShareLock, ExecRowMark::rti, SnapshotAny, HeapTupleHeaderData::t_ctid, HeapTupleData::t_data, HeapTupleData::t_len, HeapTupleData::t_self, HeapTupleData::t_tableOid, ExecAuxRowMark::toidAttNo, and ExecAuxRowMark::wholeAttNo.

Referenced by EvalPlanQual(), and ExecLockRows().

2862 {
2863  ListCell *l;
2864 
2865  Assert(epqstate->origslot != NULL);
2866 
2867  foreach(l, epqstate->arowMarks)
2868  {
2869  ExecAuxRowMark *aerm = (ExecAuxRowMark *) lfirst(l);
2870  ExecRowMark *erm = aerm->rowmark;
2871  Datum datum;
2872  bool isNull;
2873  HeapTupleData tuple;
2874 
2876  elog(ERROR, "EvalPlanQual doesn't support locking rowmarks");
2877 
2878  /* clear any leftover test tuple for this rel */
2879  EvalPlanQualSetTuple(epqstate, erm->rti, NULL);
2880 
2881  /* if child rel, must check whether it produced this row */
2882  if (erm->rti != erm->prti)
2883  {
2884  Oid tableoid;
2885 
2886  datum = ExecGetJunkAttribute(epqstate->origslot,
2887  aerm->toidAttNo,
2888  &isNull);
2889  /* non-locked rels could be on the inside of outer joins */
2890  if (isNull)
2891  continue;
2892  tableoid = DatumGetObjectId(datum);
2893 
2894  Assert(OidIsValid(erm->relid));
2895  if (tableoid != erm->relid)
2896  {
2897  /* this child is inactive right now */
2898  continue;
2899  }
2900  }
2901 
2902  if (erm->markType == ROW_MARK_REFERENCE)
2903  {
2904  HeapTuple copyTuple;
2905 
2906  Assert(erm->relation != NULL);
2907 
2908  /* fetch the tuple's ctid */
2909  datum = ExecGetJunkAttribute(epqstate->origslot,
2910  aerm->ctidAttNo,
2911  &isNull);
2912  /* non-locked rels could be on the inside of outer joins */
2913  if (isNull)
2914  continue;
2915 
2916  /* fetch requests on foreign tables must be passed to their FDW */
2917  if (erm->relation->rd_rel->relkind == RELKIND_FOREIGN_TABLE)
2918  {
2919  FdwRoutine *fdwroutine;
2920  bool updated = false;
2921 
2922  fdwroutine = GetFdwRoutineForRelation(erm->relation, false);
2923  /* this should have been checked already, but let's be safe */
2924  if (fdwroutine->RefetchForeignRow == NULL)
2925  ereport(ERROR,
2926  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2927  errmsg("cannot lock rows in foreign table \"%s\"",
2929  copyTuple = fdwroutine->RefetchForeignRow(epqstate->estate,
2930  erm,
2931  datum,
2932  &updated);
2933  if (copyTuple == NULL)
2934  elog(ERROR, "failed to fetch tuple for EvalPlanQual recheck");
2935 
2936  /*
2937  * Ideally we'd insist on updated == false here, but that
2938  * assumes that FDWs can track that exactly, which they might
2939  * not be able to. So just ignore the flag.
2940  */
2941  }
2942  else
2943  {
2944  /* ordinary table, fetch the tuple */
2945  Buffer buffer;
2946 
2947  tuple.t_self = *((ItemPointer) DatumGetPointer(datum));
2948  if (!heap_fetch(erm->relation, SnapshotAny, &tuple, &buffer,
2949  false, NULL))
2950  elog(ERROR, "failed to fetch tuple for EvalPlanQual recheck");
2951 
2952  /* successful, copy tuple */
2953  copyTuple = heap_copytuple(&tuple);
2954  ReleaseBuffer(buffer);
2955  }
2956 
2957  /* store tuple */
2958  EvalPlanQualSetTuple(epqstate, erm->rti, copyTuple);
2959  }
2960  else
2961  {
2962  HeapTupleHeader td;
2963 
2964  Assert(erm->markType == ROW_MARK_COPY);
2965 
2966  /* fetch the whole-row Var for the relation */
2967  datum = ExecGetJunkAttribute(epqstate->origslot,
2968  aerm->wholeAttNo,
2969  &isNull);
2970  /* non-locked rels could be on the inside of outer joins */
2971  if (isNull)
2972  continue;
2973  td = DatumGetHeapTupleHeader(datum);
2974 
2975  /* build a temporary HeapTuple control structure */
2977  tuple.t_data = td;
2978  /* relation might be a foreign table, if so provide tableoid */
2979  tuple.t_tableOid = erm->relid;
2980  /* also copy t_ctid in case there's valid data there */
2981  tuple.t_self = td->t_ctid;
2982 
2983  /* copy and store tuple */
2984  EvalPlanQualSetTuple(epqstate, erm->rti,
2985  heap_copytuple(&tuple));
2986  }
2987  }
2988 }
HeapTuple heap_copytuple(HeapTuple tuple)
Definition: heaptuple.c:611
void EvalPlanQualSetTuple(EPQState *epqstate, Index rti, HeapTuple tuple)
Definition: execMain.c:2826
Relation relation
Definition: execnodes.h:534
bool heap_fetch(Relation relation, Snapshot snapshot, HeapTuple tuple, Buffer *userbuf, bool keep_buf, Relation stats_relation)
Definition: heapam.c:1876
#define DatumGetObjectId(X)
Definition: postgres.h:506
int errcode(int sqlerrcode)
Definition: elog.c:575
void ReleaseBuffer(Buffer buffer)
Definition: bufmgr.c:3309
Form_pg_class rd_rel
Definition: rel.h:114
unsigned int Oid
Definition: postgres_ext.h:31
#define OidIsValid(objectId)
Definition: c.h:532
#define DatumGetHeapTupleHeader(X)
Definition: fmgr.h:259
#define RowMarkRequiresRowShareLock(marktype)
Definition: plannodes.h:969
ItemPointerData * ItemPointer
Definition: itemptr.h:49
ExecRowMark * rowmark
Definition: execnodes.h:561
HeapTupleHeader t_data
Definition: htup.h:67
#define ERROR
Definition: elog.h:43
ItemPointerData t_ctid
Definition: htup_details.h:150
ItemPointerData t_self
Definition: htup.h:65
List * arowMarks
Definition: execnodes.h:918
uint32 t_len
Definition: htup.h:64
Index rti
Definition: execnodes.h:536
AttrNumber wholeAttNo
Definition: execnodes.h:564
Index prti
Definition: execnodes.h:537
#define RelationGetRelationName(relation)
Definition: rel.h:436
Oid t_tableOid
Definition: htup.h:66
#define RELKIND_FOREIGN_TABLE
Definition: pg_class.h:167
TupleTableSlot * origslot
Definition: execnodes.h:916
#define ereport(elevel, rest)
Definition: elog.h:122
uintptr_t Datum
Definition: postgres.h:372
#define SnapshotAny
Definition: tqual.h:28
#define Assert(condition)
Definition: c.h:681
#define lfirst(lc)
Definition: pg_list.h:106
WalTimeSample buffer[LAG_TRACKER_BUFFER_SIZE]
Definition: walsender.c:214
RowMarkType markType
Definition: execnodes.h:539
AttrNumber toidAttNo
Definition: execnodes.h:563
#define DatumGetPointer(X)
Definition: postgres.h:555
int errmsg(const char *fmt,...)
Definition: elog.c:797
FdwRoutine * GetFdwRoutineForRelation(Relation relation, bool makecopy)
Definition: foreign.c:395
Datum ExecGetJunkAttribute(TupleTableSlot *slot, AttrNumber attno, bool *isNull)
Definition: execJunk.c:248
#define elog
Definition: elog.h:219
EState * estate
Definition: execnodes.h:914
int Buffer
Definition: buf.h:23
AttrNumber ctidAttNo
Definition: execnodes.h:562
RefetchForeignRow_function RefetchForeignRow
Definition: fdwapi.h:215
#define HeapTupleHeaderGetDatumLength(tup)
Definition: htup_details.h:439
HeapTuple EvalPlanQualGetTuple ( EPQState epqstate,
Index  rti 
)

Definition at line 2846 of file execMain.c.

References Assert, EState::es_epqTuple, and EPQState::estate.

2847 {
2848  EState *estate = epqstate->estate;
2849 
2850  Assert(rti > 0);
2851 
2852  return estate->es_epqTuple[rti - 1];
2853 }
HeapTuple * es_epqTuple
Definition: execnodes.h:506
#define Assert(condition)
Definition: c.h:681
EState * estate
Definition: execnodes.h:914
void EvalPlanQualInit ( EPQState epqstate,
EState estate,
Plan subplan,
List auxrowmarks,
int  epqParam 
)

Definition at line 2791 of file execMain.c.

References EPQState::arowMarks, EPQState::epqParam, EPQState::estate, EPQState::origslot, EPQState::plan, and EPQState::planstate.

Referenced by apply_handle_delete(), apply_handle_update(), ExecInitLockRows(), and ExecInitModifyTable().

2793 {
2794  /* Mark the EPQ state inactive */
2795  epqstate->estate = NULL;
2796  epqstate->planstate = NULL;
2797  epqstate->origslot = NULL;
2798  /* ... and remember data that EvalPlanQualBegin will need */
2799  epqstate->plan = subplan;
2800  epqstate->arowMarks = auxrowmarks;
2801  epqstate->epqParam = epqParam;
2802 }
PlanState * planstate
Definition: execnodes.h:915
List * arowMarks
Definition: execnodes.h:918
TupleTableSlot * origslot
Definition: execnodes.h:916
Plan * plan
Definition: execnodes.h:917
int epqParam
Definition: execnodes.h:919
EState * estate
Definition: execnodes.h:914
TupleTableSlot* EvalPlanQualNext ( EPQState epqstate)

Definition at line 2996 of file execMain.c.

References EState::es_query_cxt, EPQState::estate, ExecProcNode(), MemoryContextSwitchTo(), and EPQState::planstate.

Referenced by EvalPlanQual(), and ExecLockRows().

2997 {
2998  MemoryContext oldcontext;
2999  TupleTableSlot *slot;
3000 
3001  oldcontext = MemoryContextSwitchTo(epqstate->estate->es_query_cxt);
3002  slot = ExecProcNode(epqstate->planstate);
3003  MemoryContextSwitchTo(oldcontext);
3004 
3005  return slot;
3006 }
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:109
PlanState * planstate
Definition: execnodes.h:915
MemoryContext es_query_cxt
Definition: execnodes.h:471
static TupleTableSlot * ExecProcNode(PlanState *node)
Definition: executor.h:246
EState * estate
Definition: execnodes.h:914
void EvalPlanQualSetPlan ( EPQState epqstate,
Plan subplan,
List auxrowmarks 
)

Definition at line 2810 of file execMain.c.

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

Referenced by ExecInitModifyTable(), and ExecModifyTable().

2811 {
2812  /* If we have a live EPQ query, shut it down */
2813  EvalPlanQualEnd(epqstate);
2814  /* And set/change the plan pointer */
2815  epqstate->plan = subplan;
2816  /* The rowmarks depend on the plan, too */
2817  epqstate->arowMarks = auxrowmarks;
2818 }
void EvalPlanQualEnd(EPQState *epqstate)
Definition: execMain.c:3202
List * arowMarks
Definition: execnodes.h:918
Plan * plan
Definition: execnodes.h:917
void EvalPlanQualSetTuple ( EPQState epqstate,
Index  rti,
HeapTuple  tuple 
)

Definition at line 2826 of file execMain.c.

References Assert, EState::es_epqTuple, EState::es_epqTupleSet, EPQState::estate, and heap_freetuple().

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

2827 {
2828  EState *estate = epqstate->estate;
2829 
2830  Assert(rti > 0);
2831 
2832  /*
2833  * free old test tuple, if any, and store new tuple where relation's scan
2834  * node will see it
2835  */
2836  if (estate->es_epqTuple[rti - 1] != NULL)
2837  heap_freetuple(estate->es_epqTuple[rti - 1]);
2838  estate->es_epqTuple[rti - 1] = tuple;
2839  estate->es_epqTupleSet[rti - 1] = true;
2840 }
HeapTuple * es_epqTuple
Definition: execnodes.h:506
void heap_freetuple(HeapTuple htup)
Definition: heaptuple.c:1373
#define Assert(condition)
Definition: c.h:681
bool * es_epqTupleSet
Definition: execnodes.h:507
EState * estate
Definition: execnodes.h:914
static void EvalPlanQualStart ( EPQState epqstate,
EState parentestate,
Plan planTree 
)
static

Definition at line 3062 of file execMain.c.

References Assert, CreateExecutorState(), EState::es_crosscheck_snapshot, EState::es_direction, EState::es_epqScanDone, EState::es_epqTuple, EState::es_epqTupleSet, EState::es_instrument, EState::es_junkFilter, EState::es_num_result_relations, EState::es_output_cid, EState::es_param_exec_vals, EState::es_param_list_info, EState::es_plannedstmt, EState::es_query_cxt, EState::es_range_table, EState::es_result_relations, EState::es_rowMarks, EState::es_snapshot, EState::es_subplanstates, EState::es_top_eflags, EState::es_tupleTable, EPQState::estate, ExecInitNode(), ForwardScanDirection, i, ParamExecData::isnull, lappend(), lfirst, list_length(), MemoryContextSwitchTo(), NIL, PlannedStmt::nParamExec, palloc(), palloc0(), EPQState::planstate, PlannedStmt::subplans, and ParamExecData::value.

Referenced by EvalPlanQualBegin().

3063 {
3064  EState *estate;
3065  int rtsize;
3066  MemoryContext oldcontext;
3067  ListCell *l;
3068 
3069  rtsize = list_length(parentestate->es_range_table);
3070 
3071  epqstate->estate = estate = CreateExecutorState();
3072 
3073  oldcontext = MemoryContextSwitchTo(estate->es_query_cxt);
3074 
3075  /*
3076  * Child EPQ EStates share the parent's copy of unchanging state such as
3077  * the snapshot, rangetable, result-rel info, and external Param info.
3078  * They need their own copies of local state, including a tuple table,
3079  * es_param_exec_vals, etc.
3080  *
3081  * The ResultRelInfo array management is trickier than it looks. We
3082  * create a fresh array for the child but copy all the content from the
3083  * parent. This is because it's okay for the child to share any
3084  * per-relation state the parent has already created --- but if the child
3085  * sets up any ResultRelInfo fields, such as its own junkfilter, that
3086  * state must *not* propagate back to the parent. (For one thing, the
3087  * pointed-to data is in a memory context that won't last long enough.)
3088  */
3090  estate->es_snapshot = parentestate->es_snapshot;
3091  estate->es_crosscheck_snapshot = parentestate->es_crosscheck_snapshot;
3092  estate->es_range_table = parentestate->es_range_table;
3093  estate->es_plannedstmt = parentestate->es_plannedstmt;
3094  estate->es_junkFilter = parentestate->es_junkFilter;
3095  estate->es_output_cid = parentestate->es_output_cid;
3096  if (parentestate->es_num_result_relations > 0)
3097  {
3098  int numResultRelations = parentestate->es_num_result_relations;
3099  ResultRelInfo *resultRelInfos;
3100 
3101  resultRelInfos = (ResultRelInfo *)
3102  palloc(numResultRelations * sizeof(ResultRelInfo));
3103  memcpy(resultRelInfos, parentestate->es_result_relations,
3104  numResultRelations * sizeof(ResultRelInfo));
3105  estate->es_result_relations = resultRelInfos;
3106  estate->es_num_result_relations = numResultRelations;
3107  }
3108  /* es_result_relation_info must NOT be copied */
3109  /* es_trig_target_relations must NOT be copied */
3110  estate->es_rowMarks = parentestate->es_rowMarks;
3111  estate->es_top_eflags = parentestate->es_top_eflags;
3112  estate->es_instrument = parentestate->es_instrument;
3113  /* es_auxmodifytables must NOT be copied */
3114 
3115  /*
3116  * The external param list is simply shared from parent. The internal
3117  * param workspace has to be local state, but we copy the initial values
3118  * from the parent, so as to have access to any param values that were
3119  * already set from other parts of the parent's plan tree.
3120  */
3121  estate->es_param_list_info = parentestate->es_param_list_info;
3122  if (parentestate->es_plannedstmt->nParamExec > 0)
3123  {
3124  int i = parentestate->es_plannedstmt->nParamExec;
3125 
3126  estate->es_param_exec_vals = (ParamExecData *)
3127  palloc0(i * sizeof(ParamExecData));
3128  while (--i >= 0)
3129  {
3130  /* copy value if any, but not execPlan link */
3131  estate->es_param_exec_vals[i].value =
3132  parentestate->es_param_exec_vals[i].value;
3133  estate->es_param_exec_vals[i].isnull =
3134  parentestate->es_param_exec_vals[i].isnull;
3135  }
3136  }
3137 
3138  /*
3139  * Each EState must have its own es_epqScanDone state, but if we have
3140  * nested EPQ checks they should share es_epqTuple arrays. This allows
3141  * sub-rechecks to inherit the values being examined by an outer recheck.
3142  */
3143  estate->es_epqScanDone = (bool *) palloc0(rtsize * sizeof(bool));
3144  if (parentestate->es_epqTuple != NULL)
3145  {
3146  estate->es_epqTuple = parentestate->es_epqTuple;
3147  estate->es_epqTupleSet = parentestate->es_epqTupleSet;
3148  }
3149  else
3150  {
3151  estate->es_epqTuple = (HeapTuple *)
3152  palloc0(rtsize * sizeof(HeapTuple));
3153  estate->es_epqTupleSet = (bool *)
3154  palloc0(rtsize * sizeof(bool));
3155  }
3156 
3157  /*
3158  * Each estate also has its own tuple table.
3159  */
3160  estate->es_tupleTable = NIL;
3161 
3162  /*
3163  * Initialize private state information for each SubPlan. We must do this
3164  * before running ExecInitNode on the main query tree, since
3165  * ExecInitSubPlan expects to be able to find these entries. Some of the
3166  * SubPlans might not be used in the part of the plan tree we intend to
3167  * run, but since it's not easy to tell which, we just initialize them
3168  * all.
3169  */
3170  Assert(estate->es_subplanstates == NIL);
3171  foreach(l, parentestate->es_plannedstmt->subplans)
3172  {
3173  Plan *subplan = (Plan *) lfirst(l);
3174  PlanState *subplanstate;
3175 
3176  subplanstate = ExecInitNode(subplan, estate, 0);
3177  estate->es_subplanstates = lappend(estate->es_subplanstates,
3178  subplanstate);
3179  }
3180 
3181  /*
3182  * Initialize the private state information for all the nodes in the part
3183  * of the plan tree we need to run. This opens files, allocates storage
3184  * and leaves us ready to start processing tuples.
3185  */
3186  epqstate->planstate = ExecInitNode(planTree, estate, 0);
3187 
3188  MemoryContextSwitchTo(oldcontext);
3189 }
#define NIL
Definition: pg_list.h:69
HeapTuple * es_epqTuple
Definition: execnodes.h:506
JunkFilter * es_junkFilter
Definition: execnodes.h:435
CommandId es_output_cid
Definition: execnodes.h:438
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:109
PlannedStmt * es_plannedstmt
Definition: execnodes.h:432
Snapshot es_crosscheck_snapshot
Definition: execnodes.h:430
Snapshot es_snapshot
Definition: execnodes.h:429
List * es_range_table
Definition: execnodes.h:431
PlanState * planstate
Definition: execnodes.h:915
ScanDirection es_direction
Definition: execnodes.h:428
int nParamExec
Definition: plannodes.h:92
ParamExecData * es_param_exec_vals
Definition: execnodes.h:466
MemoryContext es_query_cxt
Definition: execnodes.h:471
bool isnull
Definition: params.h:101
ResultRelInfo * es_result_relations
Definition: execnodes.h:441
int es_instrument
Definition: execnodes.h:481
EState * CreateExecutorState(void)
Definition: execUtils.c:80
List * lappend(List *list, void *datum)
Definition: list.c:128
List * es_tupleTable
Definition: execnodes.h:473
void * palloc0(Size size)
Definition: mcxt.c:877
int es_num_result_relations
Definition: execnodes.h:442
List * subplans
Definition: plannodes.h:81
#define Assert(condition)
Definition: c.h:681
#define lfirst(lc)
Definition: pg_list.h:106
static int list_length(const List *l)
Definition: pg_list.h:89
bool * es_epqTupleSet
Definition: execnodes.h:507
List * es_subplanstates
Definition: execnodes.h:486
List * es_rowMarks
Definition: execnodes.h:475
void * palloc(Size size)
Definition: mcxt.c:848
int es_top_eflags
Definition: execnodes.h:480
int i
bool * es_epqScanDone
Definition: execnodes.h:508
Datum value
Definition: params.h:100
ParamListInfo es_param_list_info
Definition: execnodes.h:465
EState * estate
Definition: execnodes.h:914
PlanState * ExecInitNode(Plan *node, EState *estate, int eflags)
Definition: execProcnode.c:139
ExecAuxRowMark* ExecBuildAuxRowMark ( ExecRowMark erm,
List targetlist 
)

Definition at line 2406 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().

2407 {
2408  ExecAuxRowMark *aerm = (ExecAuxRowMark *) palloc0(sizeof(ExecAuxRowMark));
2409  char resname[32];
2410 
2411  aerm->rowmark = erm;
2412 
2413  /* Look up the resjunk columns associated with this rowmark */
2414  if (erm->markType != ROW_MARK_COPY)
2415  {
2416  /* need ctid for all methods other than COPY */
2417  snprintf(resname, sizeof(resname), "ctid%u", erm->rowmarkId);
2418  aerm->ctidAttNo = ExecFindJunkAttributeInTlist(targetlist,
2419  resname);
2420  if (!AttributeNumberIsValid(aerm->ctidAttNo))
2421  elog(ERROR, "could not find junk %s column", resname);
2422  }
2423  else
2424  {
2425  /* need wholerow if COPY */
2426  snprintf(resname, sizeof(resname), "wholerow%u", erm->rowmarkId);
2427  aerm->wholeAttNo = ExecFindJunkAttributeInTlist(targetlist,
2428  resname);
2429  if (!AttributeNumberIsValid(aerm->wholeAttNo))
2430  elog(ERROR, "could not find junk %s column", resname);
2431  }
2432 
2433  /* if child rel, need tableoid */
2434  if (erm->rti != erm->prti)
2435  {
2436  snprintf(resname, sizeof(resname), "tableoid%u", erm->rowmarkId);
2437  aerm->toidAttNo = ExecFindJunkAttributeInTlist(targetlist,
2438  resname);
2439  if (!AttributeNumberIsValid(aerm->toidAttNo))
2440  elog(ERROR, "could not find junk %s column", resname);
2441  }
2442 
2443  return aerm;
2444 }
AttrNumber ExecFindJunkAttributeInTlist(List *targetlist, const char *attrName)
Definition: execJunk.c:221
int snprintf(char *str, size_t count, const char *fmt,...) pg_attribute_printf(3
ExecRowMark * rowmark
Definition: execnodes.h:561
#define ERROR
Definition: elog.h:43
Index rti
Definition: execnodes.h:536
AttrNumber wholeAttNo
Definition: execnodes.h:564
Index prti
Definition: execnodes.h:537
Index rowmarkId
Definition: execnodes.h:538
#define AttributeNumberIsValid(attributeNumber)
Definition: attnum.h:34
void * palloc0(Size size)
Definition: mcxt.c:877
RowMarkType markType
Definition: execnodes.h:539
AttrNumber toidAttNo
Definition: execnodes.h:563
#define elog
Definition: elog.h:219
AttrNumber ctidAttNo
Definition: execnodes.h:562
static char * ExecBuildSlotPartitionKeyDescription ( Relation  rel,
Datum values,
bool isnull,
int  maxfieldlen 
)
static

Definition at line 3413 of file execMain.c.

References ACL_SELECT, ACLCHECK_OK, appendBinaryStringInfo(), appendStringInfo(), appendStringInfoChar(), appendStringInfoString(), buf, check_enable_rls(), StringInfoData::data, get_partition_col_attnum(), get_partition_col_typid(), get_partition_natts(), getTypeOutputInfo(), GetUserId(), i, initStringInfo(), InvalidAttrNumber, InvalidOid, OidOutputFunctionCall(), pg_attribute_aclcheck(), pg_class_aclcheck(), pg_get_partkeydef_columns(), pg_mbcliplen(), RelationGetPartitionKey, RelationGetRelid, RLS_ENABLED, and val.

Referenced by ExecFindPartition().

3417 {
3420  int partnatts = get_partition_natts(key);
3421  int i;
3422  Oid relid = RelationGetRelid(rel);
3423  AclResult aclresult;
3424 
3425  if (check_enable_rls(relid, InvalidOid, true) == RLS_ENABLED)
3426  return NULL;
3427 
3428  /* If the user has table-level access, just go build the description. */
3429  aclresult = pg_class_aclcheck(relid, GetUserId(), ACL_SELECT);
3430  if (aclresult != ACLCHECK_OK)
3431  {
3432  /*
3433  * Step through the columns of the partition key and make sure the
3434  * user has SELECT rights on all of them.
3435  */
3436  for (i = 0; i < partnatts; i++)
3437  {
3438  AttrNumber attnum = get_partition_col_attnum(key, i);
3439 
3440  /*
3441  * If this partition key column is an expression, we return no
3442  * detail rather than try to figure out what column(s) the
3443  * expression includes and if the user has SELECT rights on them.
3444  */
3445  if (attnum == InvalidAttrNumber ||
3446  pg_attribute_aclcheck(relid, attnum, GetUserId(),
3447  ACL_SELECT) != ACLCHECK_OK)
3448  return NULL;
3449  }
3450  }
3451 
3452  initStringInfo(&buf);
3453  appendStringInfo(&buf, "(%s) = (",
3454  pg_get_partkeydef_columns(relid, true));
3455 
3456  for (i = 0; i < partnatts; i++)
3457  {
3458  char *val;
3459  int vallen;
3460 
3461  if (isnull[i])
3462  val = "null";
3463  else
3464  {
3465  Oid foutoid;
3466  bool typisvarlena;
3467 
3469  &foutoid, &typisvarlena);
3470  val = OidOutputFunctionCall(foutoid, values[i]);
3471  }
3472 
3473  if (i > 0)
3474  appendStringInfoString(&buf, ", ");
3475 
3476  /* truncate if needed */
3477  vallen = strlen(val);
3478  if (vallen <= maxfieldlen)
3479  appendStringInfoString(&buf, val);
3480  else
3481  {
3482  vallen = pg_mbcliplen(val, vallen, maxfieldlen);
3483  appendBinaryStringInfo(&buf, val, vallen);
3484  appendStringInfoString(&buf, "...");
3485  }
3486  }
3487 
3488  appendStringInfoChar(&buf, ')');
3489 
3490  return buf.data;
3491 }
char * pg_get_partkeydef_columns(Oid relid, bool pretty)
Definition: ruleutils.c:1571
void getTypeOutputInfo(Oid type, Oid *typOutput, bool *typIsVarlena)
Definition: lsyscache.c:2632
AclResult pg_attribute_aclcheck(Oid table_oid, AttrNumber attnum, Oid roleid, AclMode mode)
Definition: aclchk.c:4308
Oid GetUserId(void)
Definition: miscinit.c:284
unsigned int Oid
Definition: postgres_ext.h:31
static int get_partition_natts(PartitionKey key)
Definition: rel.h:596
static int16 get_partition_col_attnum(PartitionKey key, int col)
Definition: rel.h:611
void appendStringInfo(StringInfo str, const char *fmt,...)
Definition: stringinfo.c:78
int pg_mbcliplen(const char *mbstr, int len, int limit)
Definition: mbutils.c:820
void appendStringInfoString(StringInfo str, const char *s)
Definition: stringinfo.c:157
static char * buf
Definition: pg_test_fsync.c:67
void appendStringInfoChar(StringInfo str, char ch)
Definition: stringinfo.c:169
void initStringInfo(StringInfo str)
Definition: stringinfo.c:46
AclResult
Definition: acl.h:178
static Oid get_partition_col_typid(PartitionKey key, int col)
Definition: rel.h:617
#define ACL_SELECT
Definition: parsenodes.h:73
#define InvalidOid
Definition: postgres_ext.h:36
int check_enable_rls(Oid relid, Oid checkAsUser, bool noError)
Definition: rls.c:53
#define RelationGetPartitionKey(relation)
Definition: rel.h:584
#define InvalidAttrNumber
Definition: attnum.h:23
AclResult pg_class_aclcheck(Oid table_oid, Oid roleid, AclMode mode)
Definition: aclchk.c:4422
static Datum values[MAXATTR]
Definition: bootstrap.c:164
char * OidOutputFunctionCall(Oid functionId, Datum val)
Definition: fmgr.c:1742
int i
int16 AttrNumber
Definition: attnum.h:21
#define RelationGetRelid(relation)
Definition: rel.h:416
void appendBinaryStringInfo(StringInfo str, const char *data, int datalen)
Definition: stringinfo.c:208
long val
Definition: informix.c:689
static char * ExecBuildSlotValueDescription ( Oid  reloid,
TupleTableSlot slot,
TupleDesc  tupdesc,
Bitmapset modifiedCols,
int  maxfieldlen 
)
static

Definition at line 2219 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, NameStr, tupleDesc::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(), ExecPartitionCheck(), and ExecWithCheckOptions().

2224 {
2226  StringInfoData collist;
2227  bool write_comma = false;
2228  bool write_comma_collist = false;
2229  int i;
2230  AclResult aclresult;
2231  bool table_perm = false;
2232  bool any_perm = false;
2233 
2234  /*
2235  * Check if RLS is enabled and should be active for the relation; if so,
2236  * then don't return anything. Otherwise, go through normal permission
2237  * checks.
2238  */
2239  if (check_enable_rls(reloid, InvalidOid, true) == RLS_ENABLED)
2240  return NULL;
2241 
2242  initStringInfo(&buf);
2243 
2244  appendStringInfoChar(&buf, '(');
2245 
2246  /*
2247  * Check if the user has permissions to see the row. Table-level SELECT
2248  * allows access to all columns. If the user does not have table-level
2249  * SELECT then we check each column and include those the user has SELECT
2250  * rights on. Additionally, we always include columns the user provided
2251  * data for.
2252  */
2253  aclresult = pg_class_aclcheck(reloid, GetUserId(), ACL_SELECT);
2254  if (aclresult != ACLCHECK_OK)
2255  {
2256  /* Set up the buffer for the column list */
2257  initStringInfo(&collist);
2258  appendStringInfoChar(&collist, '(');
2259  }
2260  else
2261  table_perm = any_perm = true;
2262 
2263  /* Make sure the tuple is fully deconstructed */
2264  slot_getallattrs(slot);
2265 
2266  for (i = 0; i < tupdesc->natts; i++)
2267  {
2268  bool column_perm = false;
2269  char *val;
2270  int vallen;
2271  Form_pg_attribute att = TupleDescAttr(tupdesc, i);
2272 
2273  /* ignore dropped columns */
2274  if (att->attisdropped)
2275  continue;
2276 
2277  if (!table_perm)
2278  {
2279  /*
2280  * No table-level SELECT, so need to make sure they either have
2281  * SELECT rights on the column or that they have provided the data
2282  * for the column. If not, omit this column from the error
2283  * message.
2284  */
2285  aclresult = pg_attribute_aclcheck(reloid, att->attnum,
2286  GetUserId(), ACL_SELECT);
2288  modifiedCols) || aclresult == ACLCHECK_OK)
2289  {
2290  column_perm = any_perm = true;
2291 
2292  if (write_comma_collist)
2293  appendStringInfoString(&collist, ", ");
2294  else
2295  write_comma_collist = true;
2296 
2297  appendStringInfoString(&collist, NameStr(att->attname));
2298  }
2299  }
2300 
2301  if (table_perm || column_perm)
2302  {
2303  if (slot->tts_isnull[i])
2304  val = "null";
2305  else
2306  {
2307  Oid foutoid;
2308  bool typisvarlena;
2309 
2310  getTypeOutputInfo(att->atttypid,
2311  &foutoid, &typisvarlena);
2312  val = OidOutputFunctionCall(foutoid, slot->tts_values[i]);
2313  }
2314 
2315  if (write_comma)
2316  appendStringInfoString(&buf, ", ");
2317  else
2318  write_comma = true;
2319 
2320  /* truncate if needed */
2321  vallen = strlen(val);
2322  if (vallen <= maxfieldlen)
2323  appendStringInfoString(&buf, val);
2324  else
2325  {
2326  vallen = pg_mbcliplen(val, vallen, maxfieldlen);
2327  appendBinaryStringInfo(&buf, val, vallen);
2328  appendStringInfoString(&buf, "...");
2329  }
2330  }
2331  }
2332 
2333  /* If we end up with zero columns being returned, then return NULL. */
2334  if (!any_perm)
2335  return NULL;
2336 
2337  appendStringInfoChar(&buf, ')');
2338 
2339  if (!table_perm)
2340  {
2341  appendStringInfoString(&collist, ") = ");
2342  appendStringInfoString(&collist, buf.data);
2343 
2344  return collist.data;
2345  }
2346 
2347  return buf.data;
2348 }
void getTypeOutputInfo(Oid type, Oid *typOutput, bool *typIsVarlena)
Definition: lsyscache.c:2632
AclResult pg_attribute_aclcheck(Oid table_oid, AttrNumber attnum, Oid roleid, AclMode mode)
Definition: aclchk.c:4308
Oid GetUserId(void)
Definition: miscinit.c:284
#define TupleDescAttr(tupdesc, i)
Definition: tupdesc.h:84
Datum * tts_values
Definition: tuptable.h:125
#define FirstLowInvalidHeapAttributeNumber
Definition: sysattr.h:28
unsigned int Oid
Definition: postgres_ext.h:31
int natts
Definition: tupdesc.h:73
int pg_mbcliplen(const char *mbstr, int len, int limit)
Definition: mbutils.c:820
void appendStringInfoString(StringInfo str, const char *s)
Definition: stringinfo.c:157
static char * buf
Definition: pg_test_fsync.c:67
bool * tts_isnull
Definition: tuptable.h:126
FormData_pg_attribute * Form_pg_attribute
Definition: pg_attribute.h:187
void slot_getallattrs(TupleTableSlot *slot)
Definition: heaptuple.c:1238
void appendStringInfoChar(StringInfo str, char ch)
Definition: stringinfo.c:169
void initStringInfo(StringInfo str)
Definition: stringinfo.c:46
AclResult
Definition: acl.h:178
#define ACL_SELECT
Definition: parsenodes.h:73
#define InvalidOid
Definition: postgres_ext.h:36
int check_enable_rls(Oid relid, Oid checkAsUser, bool noError)
Definition: rls.c:53
AclResult pg_class_aclcheck(Oid table_oid, Oid roleid, AclMode mode)
Definition: aclchk.c:4422
char * OidOutputFunctionCall(Oid functionId, Datum val)
Definition: fmgr.c:1742
int i
#define NameStr(name)
Definition: c.h:493
bool bms_is_member(int x, const Bitmapset *a)
Definition: bitmapset.c:420
void appendBinaryStringInfo(StringInfo str, const char *data, int datalen)
Definition: stringinfo.c:208
long val
Definition: informix.c:689
static bool ExecCheckRTEPerms ( RangeTblEntry rte)
static

Definition at line 601 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().

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

Definition at line 721 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().

723 {
724  int col = -1;
725 
726  /*
727  * When the query doesn't explicitly update any columns, allow the query
728  * if we have permission on any column of the rel. This is to handle
729  * SELECT FOR UPDATE as well as possible corner cases in UPDATE.
730  */
731  if (bms_is_empty(modifiedCols))
732  {
733  if (pg_attribute_aclcheck_all(relOid, userid, requiredPerms,
735  return false;
736  }
737 
738  while ((col = bms_next_member(modifiedCols, col)) >= 0)
739  {
740  /* bit #s are offset by FirstLowInvalidHeapAttributeNumber */
742 
743  if (attno == InvalidAttrNumber)
744  {
745  /* whole-row reference can't happen here */
746  elog(ERROR, "whole-row update is not implemented");
747  }
748  else
749  {
750  if (pg_attribute_aclcheck(relOid, attno, userid,
751  requiredPerms) != ACLCHECK_OK)
752  return false;
753  }
754  }
755  return true;
756 }
AclResult pg_attribute_aclcheck(Oid table_oid, AttrNumber attnum, Oid roleid, AclMode mode)
Definition: aclchk.c:4308
int bms_next_member(const Bitmapset *a, int prevbit)
Definition: bitmapset.c:937
#define FirstLowInvalidHeapAttributeNumber
Definition: sysattr.h:28
#define ERROR
Definition: elog.h:43
bool bms_is_empty(const Bitmapset *a)
Definition: bitmapset.c:663
AclResult pg_attribute_aclcheck_all(Oid table_oid, Oid roleid, AclMode mode, AclMaskHow how)
Definition: aclchk.c:4337
#define InvalidAttrNumber
Definition: attnum.h:23
#define elog
Definition: elog.h:219
int16 AttrNumber
Definition: attnum.h:21
bool ExecCheckRTPerms ( List rangeTable,
bool  ereport_on_violation 
)

Definition at line 570 of file execMain.c.

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

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

571 {
572  ListCell *l;
573  bool result = true;
574 
575  foreach(l, rangeTable)
576  {
577  RangeTblEntry *rte = (RangeTblEntry *) lfirst(l);
578 
579  result = ExecCheckRTEPerms(rte);
580  if (!result)
581  {
582  Assert(rte->rtekind == RTE_RELATION);
583  if (ereport_on_violation)
585  get_rel_name(rte->relid));
586  return false;
587  }
588  }
589 
591  result = (*ExecutorCheckPerms_hook) (rangeTable,
592  ereport_on_violation);
593  return result;
594 }
void aclcheck_error(AclResult aclerr, AclObjectKind objectkind, const char *objectname)
Definition: aclchk.c:3399
static bool ExecCheckRTEPerms(RangeTblEntry *rte)
Definition: execMain.c:601
ExecutorCheckPerms_hook_type ExecutorCheckPerms_hook
Definition: execMain.c:76
#define Assert(condition)
Definition: c.h:681
#define lfirst(lc)
Definition: pg_list.h:106
RTEKind rtekind
Definition: parsenodes.h:945
char * get_rel_name(Oid relid)
Definition: lsyscache.c:1726
static void ExecCheckXactReadOnly ( PlannedStmt plannedstmt)
static

Definition at line 768 of file execMain.c.

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

Referenced by standard_ExecutorStart().

769 {
770  ListCell *l;
771 
772  /*
773  * Fail if write permissions are requested in parallel mode for table
774  * (temp or non-temp), otherwise fail for any non-temp table.
775  */
776  foreach(l, plannedstmt->rtable)
777  {
778  RangeTblEntry *rte = (RangeTblEntry *) lfirst(l);
779 
780  if (rte->rtekind != RTE_RELATION)
781  continue;
782 
783  if ((rte->requiredPerms & (~ACL_SELECT)) == 0)
784  continue;
785 
787  continue;
788 
790  }
791 
792  if (plannedstmt->commandType != CMD_SELECT || plannedstmt->hasModifyingCTE)
794 }
void PreventCommandIfParallelMode(const char *cmdname)
Definition: utility.c:254
Oid get_rel_namespace(Oid relid)
Definition: lsyscache.c:1750
Definition: nodes.h:510
AclMode requiredPerms
Definition: parsenodes.h:1053
bool isTempNamespace(Oid namespaceId)
Definition: namespace.c:3118
const char * CreateCommandTag(Node *parsetree)
Definition: utility.c:2036
CmdType commandType
Definition: plannodes.h:45
#define ACL_SELECT
Definition: parsenodes.h:73
#define lfirst(lc)
Definition: pg_list.h:106
bool hasModifyingCTE
Definition: plannodes.h:51
List * rtable
Definition: plannodes.h:63
void PreventCommandIfReadOnly(const char *cmdname)
Definition: utility.c:236
RTEKind rtekind
Definition: parsenodes.h:945
void ExecCleanUpTriggerState ( EState estate)

Definition at line 1468 of file execMain.c.

References EState::es_trig_target_relations, ExecCloseIndices(), heap_close, lfirst, NoLock, and ResultRelInfo::ri_RelationDesc.

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

1469 {
1470  ListCell *l;
1471 
1472  foreach(l, estate->es_trig_target_relations)
1473  {
1474  ResultRelInfo *resultRelInfo = (ResultRelInfo *) lfirst(l);
1475 
1476  /* Close indices and then the relation itself */
1477  ExecCloseIndices(resultRelInfo);
1478  heap_close(resultRelInfo->ri_RelationDesc, NoLock);
1479  }
1480 }
Relation ri_RelationDesc
Definition: execnodes.h:354
#define heap_close(r, l)
Definition: heapam.h:97
#define NoLock
Definition: lockdefs.h:34
List * es_trig_target_relations
Definition: execnodes.h:459
#define lfirst(lc)
Definition: pg_list.h:106
void ExecCloseIndices(ResultRelInfo *resultRelInfo)
Definition: execIndexing.c:224
void ExecConstraints ( ResultRelInfo resultRelInfo,
TupleTableSlot slot,
EState estate 
)

Definition at line 1940 of file execMain.c.

References Assert, bms_union(), tupleDesc::constr, convert_tuples_by_name(), do_convert_tuple(), ereport, errcode(), errdetail(), errmsg(), ERROR, errtablecol(), errtableconstraint(), ExecBuildSlotValueDescription(), ExecFetchSlotTuple(), ExecPartitionCheck(), ExecRelCheck(), ExecSetSlotDescriptor(), ExecStoreTuple(), GetInsertedColumns, gettext_noop, GetUpdatedColumns, tupleConstr::has_not_null, InvalidBuffer, NameStr, tupleDesc::natts, tupleConstr::num_check, RelationGetDescr, RelationGetRelationName, RelationGetRelid, ResultRelInfo::ri_PartitionCheck, ResultRelInfo::ri_PartitionRoot, ResultRelInfo::ri_RelationDesc, slot_attisnull(), and TupleDescAttr.

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

1942 {
1943  Relation rel = resultRelInfo->ri_RelationDesc;
1944  TupleDesc tupdesc = RelationGetDescr(rel);
1945  TupleConstr *constr = tupdesc->constr;
1946  Bitmapset *modifiedCols;
1947  Bitmapset *insertedCols;
1948  Bitmapset *updatedCols;
1949 
1950  Assert(constr || resultRelInfo->ri_PartitionCheck);
1951 
1952  if (constr && constr->has_not_null)
1953  {
1954  int natts = tupdesc->natts;
1955  int attrChk;
1956 
1957  for (attrChk = 1; attrChk <= natts; attrChk++)
1958  {
1959  Form_pg_attribute att = TupleDescAttr(tupdesc, attrChk - 1);
1960 
1961  if (att->attnotnull && slot_attisnull(slot, attrChk))
1962  {
1963  char *val_desc;
1964  Relation orig_rel = rel;
1965  TupleDesc orig_tupdesc = RelationGetDescr(rel);
1966 
1967  /*
1968  * If the tuple has been routed, it's been converted to the
1969  * partition's rowtype, which might differ from the root
1970  * table's. We must convert it back to the root table's
1971  * rowtype so that val_desc shown error message matches the
1972  * input tuple.
1973  */
1974  if (resultRelInfo->ri_PartitionRoot)
1975  {
1976  HeapTuple tuple = ExecFetchSlotTuple(slot);
1977  TupleConversionMap *map;
1978 
1979  rel = resultRelInfo->ri_PartitionRoot;
1980  tupdesc = RelationGetDescr(rel);
1981  /* a reverse map */
1982  map = convert_tuples_by_name(orig_tupdesc, tupdesc,
1983  gettext_noop("could not convert row type"));
1984  if (map != NULL)
1985  {
1986  tuple = do_convert_tuple(tuple, map);
1987  ExecSetSlotDescriptor(slot, tupdesc);
1988  ExecStoreTuple(tuple, slot, InvalidBuffer, false);
1989  }
1990  }
1991 
1992  insertedCols = GetInsertedColumns(resultRelInfo, estate);
1993  updatedCols = GetUpdatedColumns(resultRelInfo, estate);
1994  modifiedCols = bms_union(insertedCols, updatedCols);
1996  slot,
1997  tupdesc,
1998  modifiedCols,
1999  64);
2000 
2001  ereport(ERROR,
2002  (errcode(ERRCODE_NOT_NULL_VIOLATION),
2003  errmsg("null value in column \"%s\" violates not-null constraint",
2004  NameStr(att->attname)),
2005  val_desc ? errdetail("Failing row contains %s.", val_desc) : 0,
2006  errtablecol(orig_rel, attrChk)));
2007  }
2008  }
2009  }
2010 
2011  if (constr && constr->num_check > 0)
2012  {
2013  const char *failed;
2014 
2015  if ((failed = ExecRelCheck(resultRelInfo, slot, estate)) != NULL)
2016  {
2017  char *val_desc;
2018  Relation orig_rel = rel;
2019 
2020  /* See the comment above. */
2021  if (resultRelInfo->ri_PartitionRoot)
2022  {
2023  HeapTuple tuple = ExecFetchSlotTuple(slot);
2024  TupleDesc old_tupdesc = RelationGetDescr(rel);
2025  TupleConversionMap *map;
2026 
2027  rel = resultRelInfo->ri_PartitionRoot;
2028  tupdesc = RelationGetDescr(rel);
2029  /* a reverse map */
2030  map = convert_tuples_by_name(old_tupdesc, tupdesc,
2031  gettext_noop("could not convert row type"));
2032  if (map != NULL)
2033  {
2034  tuple = do_convert_tuple(tuple, map);
2035  ExecSetSlotDescriptor(slot, tupdesc);
2036  ExecStoreTuple(tuple, slot, InvalidBuffer, false);
2037  }
2038  }
2039 
2040  insertedCols = GetInsertedColumns(resultRelInfo, estate);
2041  updatedCols = GetUpdatedColumns(resultRelInfo, estate);
2042  modifiedCols = bms_union(insertedCols, updatedCols);
2044  slot,
2045  tupdesc,
2046  modifiedCols,
2047  64);
2048  ereport(ERROR,
2049  (errcode(ERRCODE_CHECK_VIOLATION),
2050  errmsg("new row for relation \"%s\" violates check constraint \"%s\"",
2051  RelationGetRelationName(orig_rel), failed),
2052  val_desc ? errdetail("Failing row contains %s.", val_desc) : 0,
2053  errtableconstraint(orig_rel, failed)));
2054  }
2055  }
2056 
2057  if (resultRelInfo->ri_PartitionCheck)
2058  ExecPartitionCheck(resultRelInfo, slot, estate);
2059 }
#define GetUpdatedColumns(relinfo, estate)
Definition: execMain.c:118
TupleTableSlot * ExecStoreTuple(HeapTuple tuple, TupleTableSlot *slot, Buffer buffer, bool shouldFree)
Definition: execTuples.c:320
Relation ri_RelationDesc
Definition: execnodes.h:354
#define RelationGetDescr(relation)
Definition: rel.h:428
#define TupleDescAttr(tupdesc, i)
Definition: tupdesc.h:84
Relation ri_PartitionRoot
Definition: execnodes.h:414
#define InvalidBuffer
Definition: buf.h:25
#define gettext_noop(x)
Definition: c.h:139
int errcode(int sqlerrcode)
Definition: elog.c:575
int natts
Definition: tupdesc.h:73
int errtableconstraint(Relation rel, const char *conname)
Definition: relcache.c:5309
#define ERROR
Definition: elog.h:43
static char * ExecBuildSlotValueDescription(Oid reloid, TupleTableSlot *slot, TupleDesc tupdesc, Bitmapset *modifiedCols, int maxfieldlen)
Definition: execMain.c:2219
int errdetail(const char *fmt,...)
Definition: elog.c:873
#define RelationGetRelationName(relation)
Definition: rel.h:436
FormData_pg_attribute * Form_pg_attribute
Definition: pg_attribute.h:187
#define ereport(elevel, rest)
Definition: elog.h:122
bool has_not_null
Definition: tupdesc.h:43
TupleConversionMap * convert_tuples_by_name(TupleDesc indesc, TupleDesc outdesc, const char *msg)
Definition: tupconvert.c:210
void ExecSetSlotDescriptor(TupleTableSlot *slot, TupleDesc tupdesc)
Definition: execTuples.c:247
List * ri_PartitionCheck
Definition: execnodes.h:408
static const char * ExecRelCheck(ResultRelInfo *resultRelInfo, TupleTableSlot *slot, EState *estate)
Definition: execMain.c:1791
bool slot_attisnull(TupleTableSlot *slot, int attnum)
Definition: heaptuple.c:1329
#define Assert(condition)
Definition: c.h:681
int errtablecol(Relation rel, int attnum)
Definition: relcache.c:5272
TupleConstr * constr
Definition: tupdesc.h:78
Bitmapset * bms_union(const Bitmapset *a, const Bitmapset *b)
Definition: bitmapset.c:218
HeapTuple do_convert_tuple(HeapTuple tuple, TupleConversionMap *map)
Definition: tupconvert.c:354
HeapTuple ExecFetchSlotTuple(TupleTableSlot *slot)
Definition: execTuples.c:618
int errmsg(const char *fmt,...)
Definition: elog.c:797
#define NameStr(name)
Definition: c.h:493
uint16 num_check
Definition: tupdesc.h:42
#define RelationGetRelid(relation)
Definition: rel.h:416
#define GetInsertedColumns(relinfo, estate)
Definition: execMain.c:116
static void ExecPartitionCheck(ResultRelInfo *resultRelInfo, TupleTableSlot *slot, EState *estate)
Definition: execMain.c:1853
bool ExecContextForcesOids ( PlanState planstate,
bool hasoids 
)

Definition at line 1515 of file execMain.c.

References EState::es_result_relation_info, EState::es_top_eflags, EXEC_FLAG_WITH_OIDS, EXEC_FLAG_WITHOUT_OIDS, RelationData::rd_rel, ResultRelInfo::ri_RelationDesc, and PlanState::state.

Referenced by ExecAssignResultTypeFromTL(), ExecInitGather(), ExecInitGatherMerge(), and tlist_matches_tupdesc().

1516 {
1517  ResultRelInfo *ri = planstate->state->es_result_relation_info;
1518 
1519  if (ri != NULL)
1520  {
1521  Relation rel = ri->ri_RelationDesc;
1522 
1523  if (rel != NULL)
1524  {
1525  *hasoids = rel->rd_rel->relhasoids;
1526  return true;
1527  }
1528  }
1529 
1530  if (planstate->state->es_top_eflags & EXEC_FLAG_WITH_OIDS)
1531  {
1532  *hasoids = true;
1533  return true;
1534  }
1535  if (planstate->state->es_top_eflags & EXEC_FLAG_WITHOUT_OIDS)
1536  {
1537  *hasoids = false;
1538  return true;
1539  }
1540 
1541  return false;
1542 }
Relation ri_RelationDesc
Definition: execnodes.h:354
EState * state
Definition: execnodes.h:849
Form_pg_class rd_rel
Definition: rel.h:114
#define EXEC_FLAG_WITHOUT_OIDS
Definition: executor.h:64
#define EXEC_FLAG_WITH_OIDS
Definition: executor.h:63
int es_top_eflags
Definition: execnodes.h:480
ResultRelInfo * es_result_relation_info
Definition: execnodes.h:443
static void ExecEndPlan ( PlanState planstate,
EState estate 
)
static

Definition at line 1597 of file execMain.c.

References EState::es_num_result_relations, EState::es_num_root_result_relations, EState::es_result_relations, EState::es_root_result_relations, EState::es_rowMarks, EState::es_subplanstates, EState::es_tupleTable, ExecCleanUpTriggerState(), ExecCloseIndices(), ExecEndNode(), ExecResetTupleTable(), heap_close, i, lfirst, NoLock, ExecRowMark::relation, and ResultRelInfo::ri_RelationDesc.

Referenced by standard_ExecutorEnd().

1598 {
1599  ResultRelInfo *resultRelInfo;
1600  int i;
1601  ListCell *l;
1602 
1603  /*
1604  * shut down the node-type-specific query processing
1605  */
1606  ExecEndNode(planstate);
1607 
1608  /*
1609  * for subplans too
1610  */
1611  foreach(l, estate->es_subplanstates)
1612  {
1613  PlanState *subplanstate = (PlanState *) lfirst(l);
1614 
1615  ExecEndNode(subplanstate);
1616  }
1617 
1618  /*
1619  * destroy the executor's tuple table. Actually we only care about
1620  * releasing buffer pins and tupdesc refcounts; there's no need to pfree
1621  * the TupleTableSlots, since the containing memory context is about to go
1622  * away anyway.
1623  */
1624  ExecResetTupleTable(estate->es_tupleTable, false);
1625 
1626  /*
1627  * close the result relation(s) if any, but hold locks until xact commit.
1628  */
1629  resultRelInfo = estate->es_result_relations;
1630  for (i = estate->es_num_result_relations; i > 0; i--)
1631  {
1632  /* Close indices and then the relation itself */
1633  ExecCloseIndices(resultRelInfo);
1634  heap_close(resultRelInfo->ri_RelationDesc, NoLock);
1635  resultRelInfo++;
1636  }
1637 
1638  /* Close the root target relation(s). */
1639  resultRelInfo = estate->es_root_result_relations;
1640  for (i = estate->es_num_root_result_relations; i > 0; i--)
1641  {
1642  heap_close(resultRelInfo->ri_RelationDesc, NoLock);
1643  resultRelInfo++;
1644  }
1645 
1646  /* likewise close any trigger target relations */
1647  ExecCleanUpTriggerState(estate);
1648 
1649  /*
1650  * close any relations selected FOR [KEY] UPDATE/SHARE, again keeping
1651  * locks
1652  */
1653  foreach(l, estate->es_rowMarks)
1654  {
1655  ExecRowMark *erm = (ExecRowMark *) lfirst(l);
1656 
1657  if (erm->relation)
1658  heap_close(erm->relation, NoLock);
1659  }
1660 }
Relation ri_RelationDesc
Definition: execnodes.h:354
void ExecEndNode(PlanState *node)
Definition: execProcnode.c:523
Relation relation
Definition: execnodes.h:534
#define heap_close(r, l)
Definition: heapam.h:97
#define NoLock
Definition: lockdefs.h:34
ResultRelInfo * es_result_relations
Definition: execnodes.h:441
int es_num_root_result_relations
Definition: execnodes.h:453
List * es_tupleTable
Definition: execnodes.h:473
void ExecResetTupleTable(List *tupleTable, bool shouldFree)
Definition: execTuples.c:156
int es_num_result_relations
Definition: execnodes.h:442
#define lfirst(lc)
Definition: pg_list.h:106
List * es_subplanstates
Definition: execnodes.h:486
List * es_rowMarks
Definition: execnodes.h:475
void ExecCleanUpTriggerState(EState *estate)
Definition: execMain.c:1468
ResultRelInfo * es_root_result_relations
Definition: execnodes.h:452
int i
void ExecCloseIndices(ResultRelInfo *resultRelInfo)
Definition: execIndexing.c:224
int ExecFindPartition ( ResultRelInfo resultRelInfo,
PartitionDispatch pd,
TupleTableSlot slot,
EState estate 
)

Definition at line 3362 of file execMain.c.

References Assert, ExprContext::ecxt_scantuple, ereport, errcode(), errdetail(), errmsg(), ERROR, ExecBuildSlotPartitionKeyDescription(), ExecPartitionCheck(), FormPartitionKeyDatum(), get_partition_for_tuple(), GetPerTupleExprContext, OidIsValid, PARTITION_MAX_KEYS, RelationGetRelationName, RelationGetRelid, PartitionDispatchData::reldesc, and ResultRelInfo::ri_PartitionCheck.

Referenced by CopyFrom(), and ExecInsert().

3364 {
3365  int result;
3366  PartitionDispatchData *failed_at;
3367  TupleTableSlot *failed_slot;
3368 
3369  /*
3370  * First check the root table's partition constraint, if any. No point in
3371  * routing the tuple if it doesn't belong in the root table itself.
3372  */
3373  if (resultRelInfo->ri_PartitionCheck)
3374  ExecPartitionCheck(resultRelInfo, slot, estate);
3375 
3376  result = get_partition_for_tuple(pd, slot, estate,
3377  &failed_at, &failed_slot);
3378  if (result < 0)
3379  {
3380  Relation failed_rel;
3381  Datum key_values[PARTITION_MAX_KEYS];
3382  bool key_isnull[PARTITION_MAX_KEYS];
3383  char *val_desc;
3384  ExprContext *ecxt = GetPerTupleExprContext(estate);
3385 
3386  failed_rel = failed_at->reldesc;
3387  ecxt->ecxt_scantuple = failed_slot;
3388  FormPartitionKeyDatum(failed_at, failed_slot, estate,
3389  key_values, key_isnull);
3390  val_desc = ExecBuildSlotPartitionKeyDescription(failed_rel,
3391  key_values,
3392  key_isnull,
3393  64);
3394  Assert(OidIsValid(RelationGetRelid(failed_rel)));
3395  ereport(ERROR,
3396  (errcode(ERRCODE_CHECK_VIOLATION),
3397  errmsg("no partition of relation \"%s\" found for row",
3398  RelationGetRelationName(failed_rel)),
3399  val_desc ? errdetail("Partition key of the failing row contains %s.", val_desc) : 0));
3400  }
3401 
3402  return result;
3403 }
int errcode(int sqlerrcode)
Definition: elog.c:575
#define PARTITION_MAX_KEYS
int get_partition_for_tuple(PartitionDispatch *pd, TupleTableSlot *slot, EState *estate, PartitionDispatchData **failed_at, TupleTableSlot **failed_slot)
Definition: partition.c:2359
#define OidIsValid(objectId)
Definition: c.h:532
#define GetPerTupleExprContext(estate)
Definition: executor.h:477
#define ERROR
Definition: elog.h:43
static char * ExecBuildSlotPartitionKeyDescription(Relation rel, Datum *values, bool *isnull, int maxfieldlen)
Definition: execMain.c:3413
void FormPartitionKeyDatum(PartitionDispatch pd, TupleTableSlot *slot, EState *estate, Datum *values, bool *isnull)
Definition: partition.c:2300
int errdetail(const char *fmt,...)
Definition: elog.c:873
#define RelationGetRelationName(relation)
Definition: rel.h:436
#define ereport(elevel, rest)
Definition: elog.h:122
uintptr_t Datum
Definition: postgres.h:372
List * ri_PartitionCheck
Definition: execnodes.h:408
#define Assert(condition)
Definition: c.h:681
TupleTableSlot * ecxt_scantuple
Definition: execnodes.h:197
int errmsg(const char *fmt,...)
Definition: elog.c:797
#define RelationGetRelid(relation)
Definition: rel.h:416
static void ExecPartitionCheck(ResultRelInfo *resultRelInfo, TupleTableSlot *slot, EState *estate)
Definition: execMain.c:1853
ExecRowMark* ExecFindRowMark ( EState estate,
Index  rti,
bool  missing_ok 
)

Definition at line 2382 of file execMain.c.

References elog, ERROR, EState::es_rowMarks, lfirst, and ExecRowMark::rti.

Referenced by ExecInitLockRows(), ExecInitModifyTable(), and ExecOpenScanRelation().

2383 {
2384  ListCell *lc;
2385 
2386  foreach(lc, estate->es_rowMarks)
2387  {
2388  ExecRowMark *erm = (ExecRowMark *) lfirst(lc);
2389 
2390  if (erm->rti == rti)
2391  return erm;
2392  }
2393  if (!missing_ok)
2394  elog(ERROR, "failed to find ExecRowMark for rangetable index %u", rti);
2395  return NULL;
2396 }
#define ERROR
Definition: elog.h:43
Index rti
Definition: execnodes.h:536
#define lfirst(lc)
Definition: pg_list.h:106
List * es_rowMarks
Definition: execnodes.h:475
#define elog
Definition: elog.h:219
ResultRelInfo* ExecGetTriggerResultRel ( EState estate,
Oid  relid 
)

Definition at line 1390 of file execMain.c.

References EState::es_instrument, EState::es_leaf_result_relations, EState::es_num_result_relations, EState::es_num_root_result_relations, EState::es_query_cxt, EState::es_result_relations, EState::es_root_result_relations, EState::es_trig_target_relations, heap_open(), InitResultRelInfo(), lappend(), lfirst, makeNode, MemoryContextSwitchTo(), NoLock, RelationGetRelid, and ResultRelInfo::ri_RelationDesc.

Referenced by afterTriggerInvokeEvents().

1391 {
1392  ResultRelInfo *rInfo;
1393  int nr;
1394  ListCell *l;
1395  Relation rel;
1396  MemoryContext oldcontext;
1397 
1398  /* First, search through the query result relations */
1399  rInfo = estate->es_result_relations;
1400  nr = estate->es_num_result_relations;
1401  while (nr > 0)
1402  {
1403  if (RelationGetRelid(rInfo->ri_RelationDesc) == relid)
1404  return rInfo;
1405  rInfo++;
1406  nr--;
1407  }
1408  /* Second, search through the root result relations, if any */
1409  rInfo = estate->es_root_result_relations;
1410  nr = estate->es_num_root_result_relations;
1411  while (nr > 0)
1412  {
1413  if (RelationGetRelid(rInfo->ri_RelationDesc) == relid)
1414  return rInfo;
1415  rInfo++;
1416  nr--;
1417  }
1418  /* Third, search through the leaf result relations, if any */
1419  foreach(l, estate->es_leaf_result_relations)
1420  {
1421  rInfo = (ResultRelInfo *) lfirst(l);
1422  if (RelationGetRelid(rInfo->ri_RelationDesc) == relid)
1423  return rInfo;
1424  }
1425  /* Nope, but maybe we already made an extra ResultRelInfo for it */
1426  foreach(l, estate->es_trig_target_relations)
1427  {
1428  rInfo = (ResultRelInfo *) lfirst(l);
1429  if (RelationGetRelid(rInfo->ri_RelationDesc) == relid)
1430  return rInfo;
1431  }
1432  /* Nope, so we need a new one */
1433 
1434  /*
1435  * Open the target relation's relcache entry. We assume that an
1436  * appropriate lock is still held by the backend from whenever the trigger
1437  * event got queued, so we need take no new lock here. Also, we need not
1438  * recheck the relkind, so no need for CheckValidResultRel.
1439  */
1440  rel = heap_open(relid, NoLock);
1441 
1442  /*
1443  * Make the new entry in the right context.
1444  */
1445  oldcontext = MemoryContextSwitchTo(estate->es_query_cxt);
1446  rInfo = makeNode(ResultRelInfo);
1447  InitResultRelInfo(rInfo,
1448  rel,
1449  0, /* dummy rangetable index */
1450  NULL,
1451  estate->es_instrument);
1452  estate->es_trig_target_relations =
1453  lappend(estate->es_trig_target_relations, rInfo);
1454  MemoryContextSwitchTo(oldcontext);
1455 
1456  /*
1457  * Currently, we don't need any index information in ResultRelInfos used
1458  * only for triggers, so no need to call ExecOpenIndices.
1459  */
1460 
1461  return rInfo;
1462 }
void InitResultRelInfo(ResultRelInfo *resultRelInfo, Relation resultRelationDesc, Index resultRelationIndex, Relation partition_root, int instrument_options)
Definition: execMain.c:1308
Relation ri_RelationDesc
Definition: execnodes.h:354
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:109
MemoryContext es_query_cxt
Definition: execnodes.h:471
#define NoLock
Definition: lockdefs.h:34
ResultRelInfo * es_result_relations
Definition: execnodes.h:441
int es_instrument
Definition: execnodes.h:481
List * es_leaf_result_relations
Definition: execnodes.h:456
List * lappend(List *list, void *datum)
Definition: list.c:128
int es_num_root_result_relations
Definition: execnodes.h:453
List * es_trig_target_relations
Definition: execnodes.h:459
Relation heap_open(Oid relationId, LOCKMODE lockmode)
Definition: heapam.c:1290
int es_num_result_relations
Definition: execnodes.h:442
#define makeNode(_type_)
Definition: nodes.h:558
#define lfirst(lc)
Definition: pg_list.h:106
ResultRelInfo * es_root_result_relations
Definition: execnodes.h:452
#define RelationGetRelid(relation)
Definition: rel.h:416
static void ExecPartitionCheck ( ResultRelInfo resultRelInfo,
TupleTableSlot slot,
EState estate 
)
static

Definition at line 1853 of file execMain.c.

References bms_union(), convert_tuples_by_name(), do_convert_tuple(), ExprContext::ecxt_scantuple, ereport, errcode(), errdetail(), errmsg(), ERROR, ExecBuildSlotValueDescription(), ExecCheck(), ExecFetchSlotTuple(), ExecPrepareCheck(), ExecSetSlotDescriptor(), ExecStoreTuple(), GetInsertedColumns, GetPerTupleExprContext, gettext_noop, GetUpdatedColumns, InvalidBuffer, RelationGetDescr, RelationGetRelationName, RelationGetRelid, ResultRelInfo::ri_PartitionCheck, ResultRelInfo::ri_PartitionCheckExpr, ResultRelInfo::ri_PartitionRoot, and ResultRelInfo::ri_RelationDesc.

Referenced by ExecConstraints(), and ExecFindPartition().

1855 {
1856  Relation rel = resultRelInfo->ri_RelationDesc;
1857  TupleDesc tupdesc = RelationGetDescr(rel);
1858  Bitmapset *modifiedCols;
1859  Bitmapset *insertedCols;
1860  Bitmapset *updatedCols;
1861  ExprContext *econtext;
1862 
1863  /*
1864  * If first time through, build expression state tree for the partition
1865  * check expression. Keep it in the per-query memory context so they'll
1866  * survive throughout the query.
1867  */
1868  if (resultRelInfo->ri_PartitionCheckExpr == NULL)
1869  {
1870  List *qual = resultRelInfo->ri_PartitionCheck;
1871 
1872  resultRelInfo->ri_PartitionCheckExpr = ExecPrepareCheck(qual, estate);
1873  }
1874 
1875  /*
1876  * We will use the EState's per-tuple context for evaluating constraint
1877  * expressions (creating it if it's not already there).
1878  */
1879  econtext = GetPerTupleExprContext(estate);
1880 
1881  /* Arrange for econtext's scan tuple to be the tuple under test */
1882  econtext->ecxt_scantuple = slot;
1883 
1884  /*
1885  * As in case of the catalogued constraints, we treat a NULL result as
1886  * success here, not a failure.
1887  */
1888  if (!ExecCheck(resultRelInfo->ri_PartitionCheckExpr, econtext))
1889  {
1890  char *val_desc;
1891  Relation orig_rel = rel;
1892 
1893  /* See the comment above. */
1894  if (resultRelInfo->ri_PartitionRoot)
1895  {
1896  HeapTuple tuple = ExecFetchSlotTuple(slot);
1897  TupleDesc old_tupdesc = RelationGetDescr(rel);
1898  TupleConversionMap *map;
1899 
1900  rel = resultRelInfo->ri_PartitionRoot;
1901  tupdesc = RelationGetDescr(rel);
1902  /* a reverse map */
1903  map = convert_tuples_by_name(old_tupdesc, tupdesc,
1904  gettext_noop("could not convert row type"));
1905  if (map != NULL)
1906  {
1907  tuple = do_convert_tuple(tuple, map);
1908  ExecSetSlotDescriptor(slot, tupdesc);
1909  ExecStoreTuple(tuple, slot, InvalidBuffer, false);
1910  }
1911  }
1912 
1913  insertedCols = GetInsertedColumns(resultRelInfo, estate);
1914  updatedCols = GetUpdatedColumns(resultRelInfo, estate);
1915  modifiedCols = bms_union(insertedCols, updatedCols);
1917  slot,
1918  tupdesc,
1919  modifiedCols,
1920  64);
1921  ereport(ERROR,
1922  (errcode(ERRCODE_CHECK_VIOLATION),
1923  errmsg("new row for relation \"%s\" violates partition constraint",
1924  RelationGetRelationName(orig_rel)),
1925  val_desc ? errdetail("Failing row contains %s.", val_desc) : 0));
1926  }
1927 }
#define GetUpdatedColumns(relinfo, estate)
Definition: execMain.c:118
TupleTableSlot * ExecStoreTuple(HeapTuple tuple, TupleTableSlot *slot, Buffer buffer, bool shouldFree)
Definition: execTuples.c:320
Relation ri_RelationDesc
Definition: execnodes.h:354
#define RelationGetDescr(relation)
Definition: rel.h:428
ExprState * ExecPrepareCheck(List *qual, EState *estate)
Definition: execExpr.c:488
Relation ri_PartitionRoot
Definition: execnodes.h:414
ExprState * ri_PartitionCheckExpr
Definition: execnodes.h:411
#define InvalidBuffer
Definition: buf.h:25
#define gettext_noop(x)
Definition: c.h:139
int errcode(int sqlerrcode)
Definition: elog.c:575
#define GetPerTupleExprContext(estate)
Definition: executor.h:477
#define ERROR
Definition: elog.h:43
static char * ExecBuildSlotValueDescription(Oid reloid, TupleTableSlot *slot, TupleDesc tupdesc, Bitmapset *modifiedCols, int maxfieldlen)
Definition: execMain.c:2219
int errdetail(const char *fmt,...)
Definition: elog.c:873
#define RelationGetRelationName(relation)
Definition: rel.h:436
#define ereport(elevel, rest)
Definition: elog.h:122
TupleConversionMap * convert_tuples_by_name(TupleDesc indesc, TupleDesc outdesc, const char *msg)
Definition: tupconvert.c:210
void ExecSetSlotDescriptor(TupleTableSlot *slot, TupleDesc tupdesc)
Definition: execTuples.c:247
List * ri_PartitionCheck
Definition: execnodes.h:408
Bitmapset * bms_union(const Bitmapset *a, const Bitmapset *b)
Definition: bitmapset.c:218
TupleTableSlot * ecxt_scantuple
Definition: execnodes.h:197
HeapTuple do_convert_tuple(HeapTuple tuple, TupleConversionMap *map)
Definition: tupconvert.c:354
HeapTuple ExecFetchSlotTuple(TupleTableSlot *slot)
Definition: execTuples.c:618
int errmsg(const char *fmt,...)
Definition: elog.c:797
bool ExecCheck(ExprState *state, ExprContext *econtext)
Definition: execExpr.c:544
Definition: pg_list.h:45
#define RelationGetRelid(relation)
Definition: rel.h:416
#define GetInsertedColumns(relinfo, estate)
Definition: execMain.c:116
static void ExecPostprocessPlan ( EState estate)
static

Definition at line 1551 of file execMain.c.

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

Referenced by standard_ExecutorFinish().

1552 {
1553  ListCell *lc;
1554 
1555  /*
1556  * Make sure nodes run forward.
1557  */
1559 
1560  /*
1561  * Run any secondary ModifyTable nodes to completion, in case the main
1562  * query did not fetch all rows from them. (We do this to ensure that
1563  * such nodes have predictable results.)
1564  */
1565  foreach(lc, estate->es_auxmodifytables)
1566  {
1567  PlanState *ps = (PlanState *) lfirst(lc);
1568 
1569  for (;;)
1570  {
1571  TupleTableSlot *slot;
1572 
1573  /* Reset the per-output-tuple exprcontext each time */
1574  ResetPerTupleExprContext(estate);
1575 
1576  slot = ExecProcNode(ps);
1577 
1578  if (TupIsNull(slot))
1579  break;
1580  }
1581  }
1582 }
#define ResetPerTupleExprContext(estate)
Definition: executor.h:486
ScanDirection es_direction
Definition: execnodes.h:428
#define TupIsNull(slot)
Definition: tuptable.h:138
List * es_auxmodifytables
Definition: execnodes.h:488
static TupleTableSlot * ExecProcNode(PlanState *node)
Definition: executor.h:246
#define lfirst(lc)
Definition: pg_list.h:106
static const char* ExecRelCheck ( ResultRelInfo resultRelInfo,
TupleTableSlot slot,
EState estate 
)
static

Definition at line 1791 of file execMain.c.

References constrCheck::ccname, tupleConstr::check, tupleDesc::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().

1793 {
1794  Relation rel = resultRelInfo->ri_RelationDesc;
1795  int ncheck = rel->rd_att->constr->num_check;
1796  ConstrCheck *check = rel->rd_att->constr->check;
1797  ExprContext *econtext;
1798  MemoryContext oldContext;
1799  int i;
1800 
1801  /*
1802  * If first time through for this result relation, build expression
1803  * nodetrees for rel's constraint expressions. Keep them in the per-query
1804  * memory context so they'll survive throughout the query.
1805  */
1806  if (resultRelInfo->ri_ConstraintExprs == NULL)
1807  {
1808  oldContext = MemoryContextSwitchTo(estate->es_query_cxt);
1809  resultRelInfo->ri_ConstraintExprs =
1810  (ExprState **) palloc(ncheck * sizeof(ExprState *));
1811  for (i = 0; i < ncheck; i++)
1812  {
1813  Expr *checkconstr;
1814 
1815  checkconstr = stringToNode(check[i].ccbin);
1816  resultRelInfo->ri_ConstraintExprs[i] =
1817  ExecPrepareExpr(checkconstr, estate);
1818  }
1819  MemoryContextSwitchTo(oldContext);
1820  }
1821 
1822  /*
1823  * We will use the EState's per-tuple context for evaluating constraint
1824  * expressions (creating it if it's not already there).
1825  */
1826  econtext = GetPerTupleExprContext(estate);
1827 
1828  /* Arrange for econtext's scan tuple to be the tuple under test */
1829  econtext->ecxt_scantuple = slot;
1830 
1831  /* And evaluate the constraints */
1832  for (i = 0; i < ncheck; i++)
1833  {
1834  ExprState *checkconstr = resultRelInfo->ri_ConstraintExprs[i];
1835 
1836  /*
1837  * NOTE: SQL specifies that a NULL result from a constraint expression
1838  * is not to be treated as a failure. Therefore, use ExecCheck not
1839  * ExecQual.
1840  */
1841  if (!ExecCheck(checkconstr, econtext))
1842  return check[i].ccname;
1843  }
1844 
1845  /* NULL result means no error */
1846  return NULL;
1847 }
void * stringToNode(char *str)
Definition: read.c:38
Relation ri_RelationDesc
Definition: execnodes.h:354
char * ccname
Definition: tupdesc.h:30
ConstrCheck * check
Definition: tupdesc.h:40
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:109
ExprState * ExecPrepareExpr(Expr *node, EState *estate)
Definition: execExpr.c:437
#define GetPerTupleExprContext(estate)
Definition: executor.h:477
MemoryContext es_query_cxt
Definition: execnodes.h:471
ExprState ** ri_ConstraintExprs
Definition: execnodes.h:393
TupleDesc rd_att
Definition: rel.h:115
TupleConstr * constr
Definition: tupdesc.h:78
TupleTableSlot * ecxt_scantuple
Definition: execnodes.h:197
void * palloc(Size size)
Definition: mcxt.c:848
int i
bool ExecCheck(ExprState *state, ExprContext *econtext)
Definition: execExpr.c:544
uint16 num_check
Definition: tupdesc.h:42
void ExecSetupPartitionTupleRouting ( Relation  rel,
Index  resultRTindex,
EState estate,
PartitionDispatch **  pd,
ResultRelInfo ***  partitions,
TupleConversionMap ***  tup_conv_maps,
TupleTableSlot **  partition_tuple_slot,
int *  num_parted,
int *  num_partitions 
)

Definition at line 3264 of file execMain.c.

References CheckValidResultRel(), CMD_INSERT, convert_tuples_by_name(), EState::es_instrument, EState::es_leaf_result_relations, ExecOpenIndices(), find_all_inheritors(), gettext_noop, heap_open(), i, InitResultRelInfo(), lappend(), lfirst_oid, list_length(), MakeTupleTableSlot(), NoLock, palloc(), palloc0(), RelationData::rd_rel, RelationGetDescr, RelationGetPartitionDispatchInfo(), RelationGetRelid, ResultRelInfo::ri_IndexRelationDescs, ResultRelInfo::ri_RelationDesc, and RowExclusiveLock.

Referenced by CopyFrom(), and ExecInitModifyTable().

3272 {
3273  TupleDesc tupDesc = RelationGetDescr(rel);
3274  List *leaf_parts;
3275  ListCell *cell;
3276  int i;
3277  ResultRelInfo *leaf_part_rri;
3278 
3279  /*
3280  * Get the information about the partition tree after locking all the
3281  * partitions.
3282  */
3284  *pd = RelationGetPartitionDispatchInfo(rel, num_parted, &leaf_parts);
3285  *num_partitions = list_length(leaf_parts);
3286  *partitions = (ResultRelInfo **) palloc(*num_partitions *
3287  sizeof(ResultRelInfo *));
3288  *tup_conv_maps = (TupleConversionMap **) palloc0(*num_partitions *
3289  sizeof(TupleConversionMap *));
3290 
3291  /*
3292  * Initialize an empty slot that will be used to manipulate tuples of any
3293  * given partition's rowtype. It is attached to the caller-specified node
3294  * (such as ModifyTableState) and released when the node finishes
3295  * processing.
3296  */
3297  *partition_tuple_slot = MakeTupleTableSlot();
3298 
3299  leaf_part_rri = (ResultRelInfo *) palloc0(*num_partitions *
3300  sizeof(ResultRelInfo));
3301  i = 0;
3302  foreach(cell, leaf_parts)
3303  {
3304  Relation partrel;
3305  TupleDesc part_tupdesc;
3306 
3307  /*
3308  * We locked all the partitions above including the leaf partitions.
3309  * Note that each of the relations in *partitions are eventually
3310  * closed by the caller.
3311  */
3312  partrel = heap_open(lfirst_oid(cell), NoLock);
3313  part_tupdesc = RelationGetDescr(partrel);
3314 
3315  /*
3316  * Save a tuple conversion map to convert a tuple routed to this
3317  * partition from the parent's type to the partition's.
3318  */
3319  (*tup_conv_maps)[i] = convert_tuples_by_name(tupDesc, part_tupdesc,
3320  gettext_noop("could not convert row type"));
3321 
3322  InitResultRelInfo(leaf_part_rri,
3323  partrel,
3324  resultRTindex,
3325  rel,
3326  estate->es_instrument);
3327 
3328  /*
3329  * Verify result relation is a valid target for INSERT.
3330  */
3331  CheckValidResultRel(leaf_part_rri, CMD_INSERT);
3332 
3333  /*
3334  * Open partition indices (remember we do not support ON CONFLICT in
3335  * case of partitioned tables, so we do not need support information
3336  * for speculative insertion)
3337  */
3338  if (leaf_part_rri->ri_RelationDesc->rd_rel->relhasindex &&
3339  leaf_part_rri->ri_IndexRelationDescs == NULL)
3340  ExecOpenIndices(leaf_part_rri, false);
3341 
3342  estate->es_leaf_result_relations =
3343  lappend(estate->es_leaf_result_relations, leaf_part_rri);
3344 
3345  (*partitions)[i] = leaf_part_rri++;
3346  i++;
3347  }
3348 }
void InitResultRelInfo(ResultRelInfo *resultRelInfo, Relation resultRelationDesc, Index resultRelationIndex, Relation partition_root, int instrument_options)
Definition: execMain.c:1308
Relation ri_RelationDesc
Definition: execnodes.h:354
#define RelationGetDescr(relation)
Definition: rel.h:428
TupleTableSlot * MakeTupleTableSlot(void)
Definition: execTuples.c:111
#define gettext_noop(x)
Definition: c.h:139
Form_pg_class rd_rel
Definition: rel.h:114
void ExecOpenIndices(ResultRelInfo *resultRelInfo, bool speculative)
Definition: execIndexing.c:149
void CheckValidResultRel(ResultRelInfo *resultRelInfo, CmdType operation)
Definition: execMain.c:1100
#define NoLock
Definition: lockdefs.h:34
#define RowExclusiveLock
Definition: lockdefs.h:38
int es_instrument
Definition: execnodes.h:481
List * es_leaf_result_relations
Definition: execnodes.h:456
TupleConversionMap * convert_tuples_by_name(TupleDesc indesc, TupleDesc outdesc, const char *msg)
Definition: tupconvert.c:210
List * lappend(List *list, void *datum)
Definition: list.c:128
void * palloc0(Size size)
Definition: mcxt.c:877
Relation heap_open(Oid relationId, LOCKMODE lockmode)
Definition: heapam.c:1290
static int list_length(const List *l)
Definition: pg_list.h:89
List * find_all_inheritors(Oid parentrelId, LOCKMODE lockmode, List **numparents)
Definition: pg_inherits.c:167
void * palloc(Size size)
Definition: mcxt.c:848
int i
Definition: pg_list.h:45
#define RelationGetRelid(relation)
Definition: rel.h:416
RelationPtr ri_IndexRelationDescs
Definition: execnodes.h:360
PartitionDispatch * RelationGetPartitionDispatchInfo(Relation rel, int *num_parted, List **leaf_part_oids)
Definition: partition.c:1295
#define lfirst_oid(lc)
Definition: pg_list.h:108
LockTupleMode ExecUpdateLockMode ( EState estate,
ResultRelInfo relinfo 
)

Definition at line 2356 of file execMain.c.

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

Referenced by ExecBRUpdateTriggers(), and ExecOnConflictUpdate().

2357 {
2358  Bitmapset *keyCols;
2359  Bitmapset *updatedCols;
2360 
2361  /*
2362  * Compute lock mode to use. If columns that are part of the key have not
2363  * been modified, then we can use a weaker lock, allowing for better
2364  * concurrency.
2365  */
2366  updatedCols = GetUpdatedColumns(relinfo, estate);
2367  keyCols = RelationGetIndexAttrBitmap(relinfo->ri_RelationDesc,
2369 
2370  if (bms_overlap(keyCols, updatedCols))
2371  return LockTupleExclusive;
2372 
2373  return LockTupleNoKeyExclusive;
2374 }
#define GetUpdatedColumns(relinfo, estate)
Definition: execMain.c:118
Relation ri_RelationDesc
Definition: execnodes.h:354
bool bms_overlap(const Bitmapset *a, const Bitmapset *b)
Definition: bitmapset.c:443
Bitmapset * RelationGetIndexAttrBitmap(Relation relation, IndexAttrBitmapKind attrKind)
Definition: relcache.c:4859
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 1675 of file execMain.c.

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

Referenced by standard_ExecutorRun().

1684 {
1685  TupleTableSlot *slot;
1686  uint64 current_tuple_count;
1687 
1688  /*
1689  * initialize local variables
1690  */
1691  current_tuple_count = 0;
1692 
1693  /*
1694  * Set the direction.
1695  */
1696  estate->es_direction = direction;
1697 
1698  /*
1699  * If the plan might potentially be executed multiple times, we must force
1700  * it to run without parallelism, because we might exit early.
1701  */
1702  if (!execute_once)
1703  use_parallel_mode = false;
1704 
1705  if (use_parallel_mode)
1707 
1708  /*
1709  * Loop until we've processed the proper number of tuples from the plan.
1710  */
1711  for (;;)
1712  {
1713  /* Reset the per-output-tuple exprcontext */
1714  ResetPerTupleExprContext(estate);
1715 
1716  /*
1717  * Execute the plan and obtain a tuple
1718  */
1719  slot = ExecProcNode(planstate);
1720 
1721  /*
1722  * if the tuple is null, then we assume there is nothing more to
1723  * process so we just end the loop...
1724  */
1725  if (TupIsNull(slot))
1726  {
1727  /* Allow nodes to release or shut down resources. */
1728  (void) ExecShutdownNode(planstate);
1729  break;
1730  }
1731 
1732  /*
1733  * If we have a junk filter, then project a new tuple with the junk
1734  * removed.
1735  *
1736  * Store this new "clean" tuple in the junkfilter's resultSlot.
1737  * (Formerly, we stored it back over the "dirty" tuple, which is WRONG
1738  * because that tuple slot has the wrong descriptor.)
1739  */
1740  if (estate->es_junkFilter != NULL)
1741  slot = ExecFilterJunk(estate->es_junkFilter, slot);
1742 
1743  /*
1744  * If we are supposed to send the tuple somewhere, do so. (In
1745  * practice, this is probably always the case at this point.)
1746  */
1747  if (sendTuples)
1748  {
1749  /*
1750  * If we are not able to send the tuple, we assume the destination
1751  * has closed and no more tuples can be sent. If that's the case,
1752  * end the loop.
1753  */
1754  if (!dest->receiveSlot(slot, dest))
1755  break;
1756  }
1757 
1758  /*
1759  * Count tuples processed, if this is a SELECT. (For other operation
1760  * types, the ModifyTable plan node must count the appropriate
1761  * events.)
1762  */
1763  if (operation == CMD_SELECT)
1764  (estate->es_processed)++;
1765 
1766  /*
1767  * check our tuple count.. if we've processed the proper number then
1768  * quit, else loop again and process more tuples. Zero numberTuples
1769  * means no limit.
1770  */
1771  current_tuple_count++;
1772  if (numberTuples && numberTuples == current_tuple_count)
1773  {
1774  /* Allow nodes to release or shut down resources. */
1775  (void) ExecShutdownNode(planstate);
1776  break;
1777  }
1778  }
1779 
1780  if (use_parallel_mode)
1781  ExitParallelMode();
1782 }
JunkFilter * es_junkFilter
Definition: execnodes.h:435
#define ResetPerTupleExprContext(estate)
Definition: executor.h:486
bool ExecShutdownNode(PlanState *node)
Definition: execProcnode.c:731
ScanDirection es_direction
Definition: execnodes.h:428
void ExitParallelMode(void)
Definition: xact.c:886
#define TupIsNull(slot)
Definition: tuptable.h:138
TupleTableSlot * ExecFilterJunk(JunkFilter *junkfilter, TupleTableSlot *slot)
Definition: execJunk.c:262
static TupleTableSlot * ExecProcNode(PlanState *node)
Definition: executor.h:246
uint64 es_processed
Definition: execnodes.h:477
void EnterParallelMode(void)
Definition: xact.c:873
bool(* receiveSlot)(TupleTableSlot *slot, DestReceiver *self)
Definition: dest.h:118
void ExecutorEnd ( QueryDesc queryDesc)

Definition at line 461 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().

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

Definition at line 401 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().

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

Definition at line 527 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().

528 {
529  EState *estate;
530  MemoryContext oldcontext;
531 
532  /* sanity checks */
533  Assert(queryDesc != NULL);
534 
535  estate = queryDesc->estate;
536 
537  Assert(estate != NULL);
538 
539  /* It's probably not sensible to rescan updating queries */
540  Assert(queryDesc->operation == CMD_SELECT);
541 
542  /*
543  * Switch into per-query memory context
544  */
545  oldcontext = MemoryContextSwitchTo(estate->es_query_cxt);
546 
547  /*
548  * rescan plan
549  */
550  ExecReScan(queryDesc->planstate);
551 
552  MemoryContextSwitchTo(oldcontext);
553 }
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:471
PlanState * planstate
Definition: execdesc.h:49
CmdType operation
Definition: execdesc.h:36
#define Assert(condition)
Definition: c.h:681
void ExecutorRun ( QueryDesc queryDesc,
ScanDirection  direction,
uint64  count,
bool  execute_once 
)

Definition at line 299 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().

302 {
303  if (ExecutorRun_hook)
304  (*ExecutorRun_hook) (queryDesc, direction, count, execute_once);
305  else
306  standard_ExecutorRun(queryDesc, direction, count, execute_once);
307 }
void standard_ExecutorRun(QueryDesc *queryDesc, ScanDirection direction, uint64 count, bool execute_once)
Definition: execMain.c:310
ExecutorRun_hook_type ExecutorRun_hook
Definition: execMain.c:71
void ExecutorStart ( QueryDesc queryDesc,
int  eflags 
)

Definition at line 147 of file execMain.c.

References ExecutorStart_hook, and standard_ExecutorStart().

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

148 {
149  if (ExecutorStart_hook)
150  (*ExecutorStart_hook) (queryDesc, eflags);
151  else
152  standard_ExecutorStart(queryDesc, eflags);
153 }
void standard_ExecutorStart(QueryDesc *queryDesc, int eflags)
Definition: execMain.c:156
ExecutorStart_hook_type ExecutorStart_hook
Definition: execMain.c:70
void ExecWithCheckOptions ( WCOKind  kind,
ResultRelInfo resultRelInfo,
TupleTableSlot slot,
EState estate 
)

Definition at line 2072 of file execMain.c.

References bms_union(), convert_tuples_by_name(), do_convert_tuple(), ExprContext::ecxt_scantuple, elog, ereport, errcode(), errdetail(), errmsg(), ERROR, ExecBuildSlotValueDescription(), ExecFetchSlotTuple(), ExecQual(), ExecSetSlotDescriptor(), ExecStoreTuple(), forboth, GetInsertedColumns, GetPerTupleExprContext, gettext_noop, GetUpdatedColumns, InvalidBuffer, WithCheckOption::kind, lfirst, WithCheckOption::polname, RelationGetDescr, RelationGetRelid, WithCheckOption::relname, ResultRelInfo::ri_PartitionRoot, ResultRelInfo::ri_RelationDesc, ResultRelInfo::ri_WithCheckOptionExprs, ResultRelInfo::ri_WithCheckOptions, WCO_RLS_CONFLICT_CHECK, WCO_RLS_INSERT_CHECK, WCO_RLS_UPDATE_CHECK, and WCO_VIEW_CHECK.

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

2074 {
2075  Relation rel = resultRelInfo->ri_RelationDesc;
2076  TupleDesc tupdesc = RelationGetDescr(rel);
2077  ExprContext *econtext;
2078  ListCell *l1,
2079  *l2;
2080 
2081  /*
2082  * We will use the EState's per-tuple context for evaluating constraint
2083  * expressions (creating it if it's not already there).
2084  */
2085  econtext = GetPerTupleExprContext(estate);
2086 
2087  /* Arrange for econtext's scan tuple to be the tuple under test */
2088  econtext->ecxt_scantuple = slot;
2089 
2090  /* Check each of the constraints */
2091  forboth(l1, resultRelInfo->ri_WithCheckOptions,
2092  l2, resultRelInfo->ri_WithCheckOptionExprs)
2093  {
2094  WithCheckOption *wco = (WithCheckOption *) lfirst(l1);
2095  ExprState *wcoExpr = (ExprState *) lfirst(l2);
2096 
2097  /*
2098  * Skip any WCOs which are not the kind we are looking for at this
2099  * time.
2100  */
2101  if (wco->kind != kind)
2102  continue;
2103 
2104  /*
2105  * WITH CHECK OPTION checks are intended to ensure that the new tuple
2106  * is visible (in the case of a view) or that it passes the
2107  * 'with-check' policy (in the case of row security). If the qual
2108  * evaluates to NULL or FALSE, then the new tuple won't be included in
2109  * the view or doesn't pass the 'with-check' policy for the table.
2110  */
2111  if (!ExecQual(wcoExpr, econtext))
2112  {
2113  char *val_desc;
2114  Bitmapset *modifiedCols;
2115  Bitmapset *insertedCols;
2116  Bitmapset *updatedCols;
2117 
2118  switch (wco->kind)
2119  {
2120  /*
2121  * For WITH CHECK OPTIONs coming from views, we might be
2122  * able to provide the details on the row, depending on
2123  * the permissions on the relation (that is, if the user
2124  * could view it directly anyway). For RLS violations, we
2125  * don't include the data since we don't know if the user
2126  * should be able to view the tuple as that depends on the
2127  * USING policy.
2128  */
2129  case WCO_VIEW_CHECK:
2130  /* See the comment in ExecConstraints(). */
2131  if (resultRelInfo->ri_PartitionRoot)
2132  {
2133  HeapTuple tuple = ExecFetchSlotTuple(slot);
2134  TupleDesc old_tupdesc = RelationGetDescr(rel);
2135  TupleConversionMap *map;
2136 
2137  rel = resultRelInfo->ri_PartitionRoot;
2138  tupdesc = RelationGetDescr(rel);
2139  /* a reverse map */
2140  map = convert_tuples_by_name(old_tupdesc, tupdesc,
2141  gettext_noop("could not convert row type"));
2142  if (map != NULL)
2143  {
2144  tuple = do_convert_tuple(tuple, map);
2145  ExecSetSlotDescriptor(slot, tupdesc);
2146  ExecStoreTuple(tuple, slot, InvalidBuffer, false);
2147  }
2148  }
2149 
2150  insertedCols = GetInsertedColumns(resultRelInfo, estate);
2151  updatedCols = GetUpdatedColumns(resultRelInfo, estate);
2152  modifiedCols = bms_union(insertedCols, updatedCols);
2154  slot,
2155  tupdesc,
2156  modifiedCols,
2157  64);
2158 
2159  ereport(ERROR,
2160  (errcode(ERRCODE_WITH_CHECK_OPTION_VIOLATION),
2161  errmsg("new row violates check option for view \"%s\"",
2162  wco->relname),
2163  val_desc ? errdetail("Failing row contains %s.",
2164  val_desc) : 0));
2165  break;
2166  case WCO_RLS_INSERT_CHECK:
2167  case WCO_RLS_UPDATE_CHECK:
2168  if (wco->polname != NULL)
2169  ereport(ERROR,
2170  (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
2171  errmsg("new row violates row-level security policy \"%s\" for table \"%s\"",
2172  wco->polname, wco->relname)));
2173  else
2174  ereport(ERROR,
2175  (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
2176  errmsg("new row violates row-level security policy for table \"%s\"",
2177  wco->relname)));
2178  break;
2180  if (wco->polname != NULL)
2181  ereport(ERROR,
2182  (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
2183  errmsg("new row violates row-level security policy \"%s\" (USING expression) for table \"%s\"",
2184  wco->polname, wco->relname)));
2185  else
2186  ereport(ERROR,
2187  (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
2188  errmsg("new row violates row-level security policy (USING expression) for table \"%s\"",
2189  wco->relname)));
2190  break;
2191  default:
2192  elog(ERROR, "unrecognized WCO kind: %u", wco->kind);
2193  break;
2194  }
2195  }
2196  }
2197 }
#define GetUpdatedColumns(relinfo, estate)
Definition: execMain.c:118
TupleTableSlot * ExecStoreTuple(HeapTuple tuple, TupleTableSlot *slot, Buffer buffer, bool shouldFree)
Definition: execTuples.c:320
Relation ri_RelationDesc
Definition: execnodes.h:354
#define forboth(cell1, list1, cell2, list2)
Definition: pg_list.h:180
#define RelationGetDescr(relation)
Definition: rel.h:428
Relation ri_PartitionRoot
Definition: execnodes.h:414
#define InvalidBuffer
Definition: buf.h:25
#define gettext_noop(x)
Definition: c.h:139
int errcode(int sqlerrcode)
Definition: elog.c:575
static bool ExecQual(ExprState *state, ExprContext *econtext)
Definition: executor.h:366
List * ri_WithCheckOptionExprs
Definition: execnodes.h:390
#define GetPerTupleExprContext(estate)
Definition: executor.h:477
#define ERROR
Definition: elog.h:43
static char * ExecBuildSlotValueDescription(Oid reloid, TupleTableSlot *slot, TupleDesc tupdesc, Bitmapset *modifiedCols, int maxfieldlen)
Definition: execMain.c:2219
int errdetail(const char *fmt,...)
Definition: elog.c:873
#define ereport(elevel, rest)
Definition: elog.h:122
TupleConversionMap * convert_tuples_by_name(TupleDesc indesc, TupleDesc outdesc, const char *msg)
Definition: tupconvert.c:210
void ExecSetSlotDescriptor(TupleTableSlot *slot, TupleDesc tupdesc)
Definition: execTuples.c:247
List * ri_WithCheckOptions
Definition: execnodes.h:387
#define lfirst(lc)
Definition: pg_list.h:106
Bitmapset * bms_union(const Bitmapset *a, const Bitmapset *b)
Definition: bitmapset.c:218
TupleTableSlot * ecxt_scantuple
Definition: execnodes.h:197
HeapTuple do_convert_tuple(HeapTuple tuple, TupleConversionMap *map)
Definition: tupconvert.c:354
HeapTuple ExecFetchSlotTuple(TupleTableSlot *slot)
Definition: execTuples.c:618
int errmsg(const char *fmt,...)
Definition: elog.c:797
#define elog
Definition: elog.h:219
#define RelationGetRelid(relation)
Definition: rel.h:416
#define GetInsertedColumns(relinfo, estate)
Definition: execMain.c:116
static void InitPlan ( QueryDesc queryDesc,
int  eflags 
)
static

Definition at line 805 of file execMain.c.

References AccessShareLock, Assert, bms_is_member(), CheckValidRowMarkRel(), CMD_SELECT, ExecRowMark::curCtid, elog, ExecRowMark::ermActive, ExecRowMark::ermExtra, ERROR, EState::es_epqScanDone, EState::es_epqTuple, EState::es_epqTupleSet, EState::es_instrument, EState::es_junkFilter, EState::es_num_result_relations, EState::es_num_root_result_relations, EState::es_plannedstmt, EState::es_range_table, EState::es_result_relation_info, EState::es_result_relations, EState::es_root_result_relations, EState::es_rowMarks, EState::es_subplanstates, EState::es_trig_newtup_slot, EState::es_trig_oldtup_slot, EState::es_trig_tuple_slot, EState::es_tupleTable, QueryDesc::estate, EXEC_FLAG_EXPLAIN_ONLY, EXEC_FLAG_REWIND, EXEC_FLAG_WITH_NO_DATA, ExecCheckRTPerms(), ExecGetResultType(), ExecInitExtraTupleSlot(), ExecInitJunkFilter(), ExecInitNode(), getrelid, heap_open(), i, InitResultRelInfo(), PlanRowMark::isParent, ItemPointerSetInvalid, JunkFilter::jf_cleanTupType, lappend(), lfirst, lfirst_int, list_length(), list_member_int(), LockRelationOid(), ExecRowMark::markType, PlanRowMark::markType, NIL, PlannedStmt::nonleafResultRelations, QueryDesc::operation, palloc(), PlanState::plan, QueryDesc::plannedstmt, QueryDesc::planstate, PlannedStmt::planTree, ExecRowMark::prti, PlanRowMark::prti, ExecRowMark::relation, ExecRowMark::relid, TargetEntry::resjunk, PlannedStmt::resultRelations, PlannedStmt::rewindPlanIDs, PlannedStmt::rootResultRelations, ROW_MARK_COPY, ROW_MARK_EXCLUSIVE, ROW_MARK_KEYSHARE, ROW_MARK_NOKEYEXCLUSIVE, ROW_MARK_REFERENCE, ROW_MARK_SHARE, RowExclusiveLock, ExecRowMark::rowmarkId, PlanRowMark::rowmarkId, PlannedStmt::rowMarks, RowShareLock, PlannedStmt::rtable, ExecRowMark::rti, PlanRowMark::rti, ExecRowMark::strength, PlanRowMark::strength, PlannedStmt::subplans, Plan::targetlist, tupleDesc::tdhasoid, QueryDesc::tupDesc, ExecRowMark::waitPolicy, and PlanRowMark::waitPolicy.

Referenced by standard_ExecutorStart().

806 {
807  CmdType operation = queryDesc->operation;
808  PlannedStmt *plannedstmt = queryDesc->plannedstmt;
809  Plan *plan = plannedstmt->planTree;
810  List *rangeTable = plannedstmt->rtable;
811  EState *estate = queryDesc->estate;
812  PlanState *planstate;
813  TupleDesc tupType;
814  ListCell *l;
815  int i;
816 
817  /*
818  * Do permissions checks
819  */
820  ExecCheckRTPerms(rangeTable, true);
821 
822  /*
823  * initialize the node's execution state
824  */
825  estate->es_range_table = rangeTable;
826  estate->es_plannedstmt = plannedstmt;
827 
828  /*
829  * initialize result relation stuff, and open/lock the result rels.
830  *
831  * We must do this before initializing the plan tree, else we might try to
832  * do a lock upgrade if a result rel is also a source rel.
833  */
834  if (plannedstmt->resultRelations)
835  {
836  List *resultRelations = plannedstmt->resultRelations;
837  int numResultRelations = list_length(resultRelations);
838  ResultRelInfo *resultRelInfos;
839  ResultRelInfo *resultRelInfo;
840 
841  resultRelInfos = (ResultRelInfo *)
842  palloc(numResultRelations * sizeof(ResultRelInfo));
843  resultRelInfo = resultRelInfos;
844  foreach(l, resultRelations)
845  {
846  Index resultRelationIndex = lfirst_int(l);
847  Oid resultRelationOid;
848  Relation resultRelation;
849 
850  resultRelationOid = getrelid(resultRelationIndex, rangeTable);
851  resultRelation = heap_open(resultRelationOid, RowExclusiveLock);
852 
853  InitResultRelInfo(resultRelInfo,
854  resultRelation,
855  resultRelationIndex,
856  NULL,
857  estate->es_instrument);
858  resultRelInfo++;
859  }
860  estate->es_result_relations = resultRelInfos;
861  estate->es_num_result_relations = numResultRelations;
862  /* es_result_relation_info is NULL except when within ModifyTable */
863  estate->es_result_relation_info = NULL;
864 
865  /*
866  * In the partitioned result relation case, lock the non-leaf result
867  * relations too. A subset of these are the roots of respective
868  * partitioned tables, for which we also allocate ResulRelInfos.
869  */
870  estate->es_root_result_relations = NULL;
871  estate->es_num_root_result_relations = 0;
872  if (plannedstmt->nonleafResultRelations)
873  {
874  int num_roots = list_length(plannedstmt->rootResultRelations);
875 
876  /*
877  * Firstly, build ResultRelInfos for all the partitioned table
878  * roots, because we will need them to fire the statement-level
879  * triggers, if any.
880  */
881  resultRelInfos = (ResultRelInfo *)
882  palloc(num_roots * sizeof(ResultRelInfo));
883  resultRelInfo = resultRelInfos;
884  foreach(l, plannedstmt->rootResultRelations)
885  {
886  Index resultRelIndex = lfirst_int(l);
887  Oid resultRelOid;
888  Relation resultRelDesc;
889 
890  resultRelOid = getrelid(resultRelIndex, rangeTable);
891  resultRelDesc = heap_open(resultRelOid, RowExclusiveLock);
892  InitResultRelInfo(resultRelInfo,
893  resultRelDesc,
894  lfirst_int(l),
895  NULL,
896  estate->es_instrument);
897  resultRelInfo++;
898  }
899 
900  estate->es_root_result_relations = resultRelInfos;
901  estate->es_num_root_result_relations = num_roots;
902 
903  /* Simply lock the rest of them. */
904  foreach(l, plannedstmt->nonleafResultRelations)
905  {
906  Index resultRelIndex = lfirst_int(l);
907 
908  /* We locked the roots above. */
909  if (!list_member_int(plannedstmt->rootResultRelations,
910  resultRelIndex))
911  LockRelationOid(getrelid(resultRelIndex, rangeTable),
913  }
914  }
915  }
916  else
917  {
918  /*
919  * if no result relation, then set state appropriately
920  */
921  estate->es_result_relations = NULL;
922  estate->es_num_result_relations = 0;
923  estate->es_result_relation_info = NULL;
924  estate->es_root_result_relations = NULL;
925  estate->es_num_root_result_relations = 0;
926  }
927 
928  /*
929  * Similarly, we have to lock relations selected FOR [KEY] UPDATE/SHARE
930  * before we initialize the plan tree, else we'd be risking lock upgrades.
931  * While we are at it, build the ExecRowMark list. Any partitioned child
932  * tables are ignored here (because isParent=true) and will be locked by
933  * the first Append or MergeAppend node that references them. (Note that
934  * the RowMarks corresponding to partitioned child tables are present in
935  * the same list as the rest, i.e., plannedstmt->rowMarks.)
936  */
937  estate->es_rowMarks = NIL;
938  foreach(l, plannedstmt->rowMarks)
939  {
940  PlanRowMark *rc = (PlanRowMark *) lfirst(l);
941  Oid relid;
942  Relation relation;
943  ExecRowMark *erm;
944 
945  /* ignore "parent" rowmarks; they are irrelevant at runtime */
946  if (rc->isParent)
947  continue;
948 
949  /* get relation's OID (will produce InvalidOid if subquery) */
950  relid = getrelid(rc->rti, rangeTable);
951 
952  /*
953  * If you change the conditions under which rel locks are acquired
954  * here, be sure to adjust ExecOpenScanRelation to match.
955  */
956  switch (rc->markType)
957  {
958  case ROW_MARK_EXCLUSIVE:
960  case ROW_MARK_SHARE:
961  case ROW_MARK_KEYSHARE:
962  relation = heap_open(relid, RowShareLock);
963  break;
964  case ROW_MARK_REFERENCE:
965  relation = heap_open(relid, AccessShareLock);
966  break;
967  case ROW_MARK_COPY:
968  /* no physical table access is required */
969  relation = NULL;
970  break;
971  default:
972  elog(ERROR, "unrecognized markType: %d", rc->markType);
973  relation = NULL; /* keep compiler quiet */
974  break;
975  }
976 
977  /* Check that relation is a legal target for marking */
978  if (relation)
979  CheckValidRowMarkRel(relation, rc->markType);
980 
981  erm = (ExecRowMark *) palloc(sizeof(ExecRowMark));
982  erm->relation = relation;
983  erm->relid = relid;
984  erm->rti = rc->rti;
985  erm->prti = rc->prti;
986  erm->rowmarkId = rc->rowmarkId;
987  erm->markType = rc->markType;
988  erm->strength = rc->strength;
989  erm->waitPolicy = rc->waitPolicy;
990  erm->ermActive = false;
992  erm->ermExtra = NULL;
993  estate->es_rowMarks = lappend(estate->es_rowMarks, erm);
994  }
995 
996  /*
997  * Initialize the executor's tuple table to empty.
998  */
999  estate->es_tupleTable = NIL;
1000  estate->es_trig_tuple_slot = NULL;
1001  estate->es_trig_oldtup_slot = NULL;
1002  estate->es_trig_newtup_slot = NULL;
1003 
1004  /* mark EvalPlanQual not active */
1005  estate->es_epqTuple = NULL;
1006  estate->es_epqTupleSet = NULL;
1007  estate->es_epqScanDone = NULL;
1008 
1009  /*
1010  * Initialize private state information for each SubPlan. We must do this
1011  * before running ExecInitNode on the main query tree, since
1012  * ExecInitSubPlan expects to be able to find these entries.
1013  */
1014  Assert(estate->es_subplanstates == NIL);
1015  i = 1; /* subplan indices count from 1 */
1016  foreach(l, plannedstmt->subplans)
1017  {
1018  Plan *subplan = (Plan *) lfirst(l);
1019  PlanState *subplanstate;
1020  int sp_eflags;
1021 
1022  /*
1023  * A subplan will never need to do BACKWARD scan nor MARK/RESTORE. If
1024  * it is a parameterless subplan (not initplan), we suggest that it be
1025  * prepared to handle REWIND efficiently; otherwise there is no need.
1026  */
1027  sp_eflags = eflags
1029  if (bms_is_member(i, plannedstmt->rewindPlanIDs))
1030  sp_eflags |= EXEC_FLAG_REWIND;
1031 
1032  subplanstate = ExecInitNode(subplan, estate, sp_eflags);
1033 
1034  estate->es_subplanstates = lappend(estate->es_subplanstates,
1035  subplanstate);
1036 
1037  i++;
1038  }
1039 
1040  /*
1041  * Initialize the private state information for all the nodes in the query
1042  * tree. This opens files, allocates storage and leaves us ready to start
1043  * processing tuples.
1044  */
1045  planstate = ExecInitNode(plan, estate, eflags);
1046 
1047  /*
1048  * Get the tuple descriptor describing the type of tuples to return.
1049  */
1050  tupType = ExecGetResultType(planstate);
1051 
1052  /*
1053  * Initialize the junk filter if needed. SELECT queries need a filter if
1054  * there are any junk attrs in the top-level tlist.
1055  */
1056  if (operation == CMD_SELECT)
1057  {
1058  bool junk_filter_needed = false;
1059  ListCell *tlist;
1060 
1061  foreach(tlist, plan->targetlist)
1062  {
1063  TargetEntry *tle = (TargetEntry *) lfirst(tlist);
1064 
1065  if (tle->resjunk)
1066  {
1067  junk_filter_needed = true;
1068  break;
1069  }
1070  }
1071 
1072  if (junk_filter_needed)
1073  {
1074  JunkFilter *j;
1075 
1076  j = ExecInitJunkFilter(planstate->plan->targetlist,
1077  tupType->tdhasoid,
1078  ExecInitExtraTupleSlot(estate));
1079  estate->es_junkFilter = j;
1080 
1081  /* Want to return the cleaned tuple type */
1082  tupType = j->jf_cleanTupType;
1083  }
1084  }
1085 
1086  queryDesc->tupDesc = tupType;
1087  queryDesc->planstate = planstate;
1088 }
#define NIL
Definition: pg_list.h:69
HeapTuple * es_epqTuple
Definition: execnodes.h:506
JunkFilter * es_junkFilter
Definition: execnodes.h:435
void InitResultRelInfo(ResultRelInfo *resultRelInfo, Relation resultRelationDesc, Index resultRelationIndex, Relation partition_root, int instrument_options)
Definition: execMain.c:1308
TupleTableSlot * ExecInitExtraTupleSlot(EState *estate)
Definition: execTuples.c:852
RowMarkType markType
Definition: plannodes.h:1016
EState * estate
Definition: execdesc.h:48
bool tdhasoid
Definition: tupdesc.h:76
List * nonleafResultRelations
Definition: plannodes.h:72
TupleTableSlot * es_trig_newtup_slot
Definition: execnodes.h:462
Relation relation
Definition: execnodes.h:534
#define AccessShareLock
Definition: lockdefs.h:36
PlannedStmt * es_plannedstmt
Definition: execnodes.h:432
bool ermActive
Definition: execnodes.h:542
Index prti
Definition: plannodes.h:1014
LockWaitPolicy waitPolicy
Definition: execnodes.h:541
#define EXEC_FLAG_WITH_NO_DATA
Definition: executor.h:65
LockClauseStrength strength
Definition: execnodes.h:540
List * es_range_table
Definition: execnodes.h:431
unsigned int Oid
Definition: postgres_ext.h:31
Index rowmarkId
Definition: plannodes.h:1015
LockWaitPolicy waitPolicy
Definition: plannodes.h:1019
static void CheckValidRowMarkRel(Relation rel, RowMarkType markType)
Definition: execMain.c:1243
struct Plan * planTree
Definition: plannodes.h:61
ItemPointerData curCtid
Definition: execnodes.h:543
bool resjunk
Definition: primnodes.h:1375
#define ERROR
Definition: elog.h:43
PlanState * planstate
Definition: execdesc.h:49
#define lfirst_int(lc)
Definition: pg_list.h:107
bool list_member_int(const List *list, int datum)
Definition: list.c:485
Index rti
Definition: execnodes.h:536
void * ermExtra
Definition: execnodes.h:544
TupleDesc jf_cleanTupType
Definition: execnodes.h:333
ResultRelInfo * es_result_relations
Definition: execnodes.h:441
#define RowExclusiveLock
Definition: lockdefs.h:38
Index prti
Definition: execnodes.h:537
JunkFilter * ExecInitJunkFilter(List *targetList, bool hasoid, TupleTableSlot *slot)
Definition: execJunk.c:61
List * rootResultRelations
Definition: plannodes.h:79
TupleTableSlot * es_trig_oldtup_slot
Definition: execnodes.h:461
int es_instrument
Definition: execnodes.h:481
TupleTableSlot * es_trig_tuple_slot
Definition: execnodes.h:460
#define EXEC_FLAG_REWIND
Definition: executor.h:59
Index rowmarkId
Definition: execnodes.h:538
List * lappend(List *list, void *datum)
Definition: list.c:128
int es_num_root_result_relations
Definition: execnodes.h:453
TupleDesc tupDesc
Definition: execdesc.h:47
CmdType operation
Definition: execdesc.h:36
List * es_tupleTable
Definition: execnodes.h:473
#define RowShareLock
Definition: lockdefs.h:37
Relation heap_open(Oid relationId, LOCKMODE lockmode)
Definition: heapam.c:1290
int es_num_result_relations
Definition: execnodes.h:442
unsigned int Index
Definition: c.h:359
List * rowMarks
Definition: plannodes.h:86
Plan * plan
Definition: execnodes.h:847
List * subplans
Definition: plannodes.h:81
#define Assert(condition)
Definition: c.h:681
#define lfirst(lc)
Definition: pg_list.h:106
Bitmapset * rewindPlanIDs
Definition: plannodes.h:84
RowMarkType markType
Definition: execnodes.h:539
LockClauseStrength strength
Definition: plannodes.h:1018
static int list_length(const List *l)
Definition: pg_list.h:89
bool * es_epqTupleSet
Definition: execnodes.h:507
List * es_subplanstates
Definition: execnodes.h:486
List * es_rowMarks
Definition: execnodes.h:475
List * rtable
Definition: plannodes.h:63
TupleDesc ExecGetResultType(PlanState *planstate)
Definition: execUtils.c:474
List * targetlist
Definition: plannodes.h:144
#define ItemPointerSetInvalid(pointer)
Definition: itemptr.h:150
void * palloc(Size size)
Definition: mcxt.c:848
#define getrelid(rangeindex, rangetable)
Definition: parsetree.h:41
List * resultRelations
Definition: plannodes.h:66
ResultRelInfo * es_root_result_relations
Definition: execnodes.h:452
int i
bool * es_epqScanDone
Definition: execnodes.h:508
bool ExecCheckRTPerms(List *rangeTable, bool ereport_on_violation)
Definition: execMain.c:570
bool isParent
Definition: plannodes.h:1020
#define elog
Definition: elog.h:219
PlannedStmt * plannedstmt
Definition: execdesc.h:37
void LockRelationOid(Oid relid, LOCKMODE lockmode)
Definition: lmgr.c:105
PlanState * ExecInitNode(Plan *node, EState *estate, int eflags)
Definition: execProcnode.c:139
Definition: pg_list.h:45
bool bms_is_member(int x, const Bitmapset *a)
Definition: bitmapset.c:420
#define EXEC_FLAG_EXPLAIN_ONLY
Definition: executor.h:58
CmdType
Definition: nodes.h:650
ResultRelInfo * es_result_relation_info
Definition: execnodes.h:443
void InitResultRelInfo ( ResultRelInfo resultRelInfo,
Relation  resultRelationDesc,
Index  resultRelationIndex,
Relation  partition_root,
int  instrument_options 
)

Definition at line 1308 of file execMain.c.

References CopyTriggerDesc(), GetFdwRoutineForRelation(), InstrAlloc(), MemSet, NIL, TriggerDesc::numtriggers, palloc0(), RelationData::rd_rel, RelationGetPartitionQual(), RELKIND_FOREIGN_TABLE, ResultRelInfo::ri_ConstraintExprs, ResultRelInfo::ri_FdwRoutine, ResultRelInfo::ri_FdwState, ResultRelInfo::ri_IndexRelationDescs, ResultRelInfo::ri_IndexRelationInfo, ResultRelInfo::ri_junkFilter, ResultRelInfo::ri_NumIndices, ResultRelInfo::ri_PartitionCheck, ResultRelInfo::ri_PartitionRoot, ResultRelInfo::ri_projectReturning, ResultRelInfo::ri_RangeTableIndex, ResultRelInfo::ri_RelationDesc, ResultRelInfo::ri_TrigDesc, ResultRelInfo::ri_TrigFunctions, ResultRelInfo::ri_TrigInstrument, ResultRelInfo::ri_TrigWhenExprs, ResultRelInfo::ri_usesFdwDirectModify, T_ResultRelInfo, RelationData::trigdesc, and ResultRelInfo::type.

Referenced by CopyFrom(), create_estate_for_relation(), ExecGetTriggerResultRel(), ExecSetupPartitionTupleRouting(), ExecuteTruncate(), and InitPlan().

1313 {
1314  List *partition_check = NIL;
1315 
1316  MemSet(resultRelInfo, 0, sizeof(ResultRelInfo));
1317  resultRelInfo->type = T_ResultRelInfo;
1318  resultRelInfo->ri_RangeTableIndex = resultRelationIndex;
1319  resultRelInfo->ri_RelationDesc = resultRelationDesc;
1320  resultRelInfo->ri_NumIndices = 0;
1321  resultRelInfo->ri_IndexRelationDescs = NULL;
1322  resultRelInfo->ri_IndexRelationInfo = NULL;
1323  /* make a copy so as not to depend on relcache info not changing... */
1324  resultRelInfo->ri_TrigDesc = CopyTriggerDesc(resultRelationDesc->trigdesc);
1325  if (resultRelInfo->ri_TrigDesc)
1326  {
1327  int n = resultRelInfo->ri_TrigDesc->numtriggers;
1328 
1329  resultRelInfo->ri_TrigFunctions = (FmgrInfo *)
1330  palloc0(n * sizeof(FmgrInfo));
1331  resultRelInfo->ri_TrigWhenExprs = (ExprState **)
1332  palloc0(n * sizeof(ExprState *));
1333  if (instrument_options)
1334  resultRelInfo->ri_TrigInstrument = InstrAlloc(n, instrument_options);
1335  }
1336  else
1337  {
1338  resultRelInfo->ri_TrigFunctions = NULL;
1339  resultRelInfo->ri_TrigWhenExprs = NULL;
1340  resultRelInfo->ri_TrigInstrument = NULL;
1341  }
1342  if (resultRelationDesc->rd_rel->relkind == RELKIND_FOREIGN_TABLE)
1343  resultRelInfo->ri_FdwRoutine = GetFdwRoutineForRelation(resultRelationDesc, true);
1344  else
1345  resultRelInfo->ri_FdwRoutine = NULL;
1346  resultRelInfo->ri_FdwState = NULL;
1347  resultRelInfo->ri_usesFdwDirectModify = false;
1348  resultRelInfo->ri_ConstraintExprs = NULL;
1349  resultRelInfo->ri_junkFilter = NULL;
1350  resultRelInfo->ri_projectReturning = NULL;
1351 
1352  /*
1353  * Partition constraint, which also includes the partition constraint of
1354  * all the ancestors that are partitions. Note that it will be checked
1355  * even in the case of tuple-routing where this table is the target leaf
1356  * partition, if there any BR triggers defined on the table. Although
1357  * tuple-routing implicitly preserves the partition constraint of the
1358  * target partition for a given row, the BR triggers may change the row
1359  * such that the constraint is no longer satisfied, which we must fail for
1360  * by checking it explicitly.
1361  *
1362  * If this is a partitioned table, the partition constraint (if any) of a
1363  * given row will be checked just before performing tuple-routing.
1364  */
1365  partition_check = RelationGetPartitionQual(resultRelationDesc);
1366 
1367  resultRelInfo->ri_PartitionCheck = partition_check;
1368  resultRelInfo->ri_PartitionRoot = partition_root;
1369 }
int ri_NumIndices
Definition: execnodes.h:357
#define NIL
Definition: pg_list.h:69
JunkFilter * ri_junkFilter
Definition: execnodes.h:396
Definition: fmgr.h:56
Relation ri_RelationDesc
Definition: execnodes.h:354
Relation ri_PartitionRoot
Definition: execnodes.h:414
Instrumentation * ri_TrigInstrument
Definition: execnodes.h:375
Instrumentation * InstrAlloc(int n, int instrument_options)
Definition: instrument.c:30
#define MemSet(start, val, len)
Definition: c.h:863
Form_pg_class rd_rel
Definition: rel.h:114
Index ri_RangeTableIndex
Definition: execnodes.h:351
NodeTag type
Definition: execnodes.h:348
TriggerDesc * trigdesc
Definition: rel.h:120
bool ri_usesFdwDirectModify
Definition: execnodes.h:384
ExprState ** ri_TrigWhenExprs
Definition: execnodes.h:372
ProjectionInfo * ri_projectReturning
Definition: execnodes.h:399
struct FdwRoutine * ri_FdwRoutine
Definition: execnodes.h:378
#define RELKIND_FOREIGN_TABLE
Definition: pg_class.h:167
ExprState ** ri_ConstraintExprs
Definition: execnodes.h:393
TriggerDesc * ri_TrigDesc
Definition: execnodes.h:366
int numtriggers
Definition: reltrigger.h:49
List * RelationGetPartitionQual(Relation rel)
Definition: partition.c:1240
void * palloc0(Size size)
Definition: mcxt.c:877
List * ri_PartitionCheck
Definition: execnodes.h:408
void * ri_FdwState
Definition: execnodes.h:381
TriggerDesc * CopyTriggerDesc(TriggerDesc *trigdesc)
Definition: trigger.c:1911
FdwRoutine * GetFdwRoutineForRelation(Relation relation, bool makecopy)
Definition: foreign.c:395
IndexInfo ** ri_IndexRelationInfo
Definition: execnodes.h:363
Definition: pg_list.h:45
RelationPtr ri_IndexRelationDescs
Definition: execnodes.h:360
FmgrInfo * ri_TrigFunctions
Definition: execnodes.h:369
void standard_ExecutorEnd ( QueryDesc queryDesc)

Definition at line 470 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().

471 {
472  EState *estate;
473  MemoryContext oldcontext;
474 
475  /* sanity checks */
476  Assert(queryDesc != NULL);
477 
478  estate = queryDesc->estate;
479 
480  Assert(estate != NULL);
481 
482  /*
483  * Check that ExecutorFinish was called, unless in EXPLAIN-only mode. This
484  * Assert is needed because ExecutorFinish is new as of 9.1, and callers
485  * might forget to call it.
486  */
487  Assert(estate->es_finished ||
489 
490  /*
491  * Switch into per-query memory context to run ExecEndPlan
492  */
493  oldcontext = MemoryContextSwitchTo(estate->es_query_cxt);
494 
495  ExecEndPlan(queryDesc->planstate, estate);
496 
497  /* do away with our snapshots */
500 
501  /*
502  * Must switch out of context before destroying it
503  */
504  MemoryContextSwitchTo(oldcontext);
505 
506  /*
507  * Release EState and per-query memory context. This should release
508  * everything the executor has allocated.
509  */
510  FreeExecutorState(estate);
511 
512  /* Reset queryDesc fields that no longer point to anything */
513  queryDesc->tupDesc = NULL;
514  queryDesc->estate = NULL;
515  queryDesc->planstate = NULL;
516  queryDesc->totaltime = NULL;
517 }
EState * estate
Definition: execdesc.h:48
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:109
Snapshot es_crosscheck_snapshot
Definition: execnodes.h:430
Snapshot es_snapshot
Definition: execnodes.h:429
void FreeExecutorState(EState *estate)
Definition: execUtils.c:183
MemoryContext es_query_cxt
Definition: execnodes.h:471
PlanState * planstate
Definition: execdesc.h:49
void UnregisterSnapshot(Snapshot snapshot)
Definition: snapmgr.c:905
TupleDesc tupDesc
Definition: execdesc.h:47
bool es_finished
Definition: execnodes.h:482
struct Instrumentation * totaltime
Definition: execdesc.h:55
#define Assert(condition)
Definition: c.h:681
static void ExecEndPlan(PlanState *planstate, EState *estate)
Definition: execMain.c:1597
int es_top_eflags
Definition: execnodes.h:480
#define EXEC_FLAG_EXPLAIN_ONLY
Definition: executor.h:58
void standard_ExecutorFinish ( QueryDesc queryDesc)

Definition at line 410 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().

411 {
412  EState *estate;
413  MemoryContext oldcontext;
414 
415  /* sanity checks */
416  Assert(queryDesc != NULL);
417 
418  estate = queryDesc->estate;
419 
420  Assert(estate != NULL);
422 
423  /* This should be run once and only once per Executor instance */
424  Assert(!estate->es_finished);
425 
426  /* Switch into per-query memory context */
427  oldcontext = MemoryContextSwitchTo(estate->es_query_cxt);
428 
429  /* Allow instrumentation of Executor overall runtime */
430  if (queryDesc->totaltime)
431  InstrStartNode(queryDesc->totaltime);
432 
433  /* Run ModifyTable nodes to completion */
434  ExecPostprocessPlan(estate);
435 
436  /* Execute queued AFTER triggers, unless told not to */
437  if (!(estate->es_top_eflags & EXEC_FLAG_SKIP_TRIGGERS))
438  AfterTriggerEndQuery(estate);
439 
440  if (queryDesc->totaltime)
441  InstrStopNode(queryDesc->totaltime, 0);
442 
443  MemoryContextSwitchTo(oldcontext);
444 
445  estate->es_finished = true;
446 }
void InstrStopNode(Instrumentation *instr, double nTuples)
Definition: instrument.c:80
static void ExecPostprocessPlan(EState *estate)
Definition: execMain.c:1551
EState * estate
Definition: execdesc.h:48
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:109
MemoryContext es_query_cxt
Definition: execnodes.h:471
void InstrStartNode(Instrumentation *instr)
Definition: instrument.c:63
bool es_finished
Definition: execnodes.h:482
struct Instrumentation * totaltime
Definition: execdesc.h:55
#define Assert(condition)
Definition: c.h:681
#define EXEC_FLAG_SKIP_TRIGGERS
Definition: executor.h:62
void AfterTriggerEndQuery(EState *estate)
Definition: trigger.c:4546
int es_top_eflags
Definition: execnodes.h:480
#define EXEC_FLAG_EXPLAIN_ONLY
Definition: executor.h:58
void standard_ExecutorRun ( QueryDesc queryDesc,
ScanDirection  direction,
uint64  count,
bool  execute_once 
)

Definition at line 310 of file execMain.c.

References QueryDesc::already_executed, Assert, CMD_SELECT, QueryDesc::dest, elog, ERROR, EState::es_lastoid, EState::es_processed, EState::es_query_cxt, EState::es_top_eflags, QueryDesc::estate, EXEC_FLAG_EXPLAIN_ONLY, ExecutePlan(), PlannedStmt::hasReturning, InstrStartNode(), InstrStopNode(), InvalidOid, 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().

312 {
313  EState *estate;
314  CmdType operation;
315  DestReceiver *dest;
316  bool sendTuples;
317  MemoryContext oldcontext;
318 
319  /* sanity checks */
320  Assert(queryDesc != NULL);
321 
322  estate = queryDesc->estate;
323 
324  Assert(estate != NULL);
326 
327  /*
328  * Switch into per-query memory context
329  */
330  oldcontext = MemoryContextSwitchTo(estate->es_query_cxt);
331 
332  /* Allow instrumentation of Executor overall runtime */
333  if (queryDesc->totaltime)
334  InstrStartNode(queryDesc->totaltime);
335 
336  /*
337  * extract information from the query descriptor and the query feature.
338  */
339  operation = queryDesc->operation;
340  dest = queryDesc->dest;
341 
342  /*
343  * startup tuple receiver, if we will be emitting tuples
344  */
345  estate->es_processed = 0;
346  estate->es_lastoid = InvalidOid;
347 
348  sendTuples = (operation == CMD_SELECT ||
349  queryDesc->plannedstmt->hasReturning);
350 
351  if (sendTuples)
352  dest->rStartup(dest, operation, queryDesc->tupDesc);
353 
354  /*
355  * run plan
356  */
357  if (!ScanDirectionIsNoMovement(direction))
358  {
359  if (execute_once && queryDesc->already_executed)
360  elog(ERROR, "can't re-execute query flagged for single execution");
361  queryDesc->already_executed = true;
362 
363  ExecutePlan(estate,
364  queryDesc->planstate,
365  queryDesc->plannedstmt->parallelModeNeeded,
366  operation,
367  sendTuples,
368  count,
369  direction,
370  dest,
371  execute_once);
372  }
373 
374  /*
375  * shutdown tuple receiver, if we started it
376  */
377  if (sendTuples)
378  dest->rShutdown(dest);
379 
380  if (queryDesc->totaltime)
381  InstrStopNode(queryDesc->totaltime, estate->es_processed);
382 
383  MemoryContextSwitchTo(oldcontext);
384 }
void InstrStopNode(Instrumentation *instr, double nTuples)
Definition: instrument.c:80
void(* rShutdown)(DestReceiver *self)
Definition: dest.h:124
void(* rStartup)(DestReceiver *self, int operation, TupleDesc typeinfo)
Definition: dest.h:121
EState * estate
Definition: execdesc.h:48
Oid es_lastoid
Definition: execnodes.h:478
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:109
#define ScanDirectionIsNoMovement(direction)
Definition: sdir.h:48
MemoryContext es_query_cxt
Definition: execnodes.h:471
#define ERROR
Definition: elog.h:43
PlanState * planstate
Definition: execdesc.h:49
void InstrStartNode(Instrumentation *instr)
Definition: instrument.c:63
bool hasReturning
Definition: plannodes.h:49
TupleDesc tupDesc
Definition: execdesc.h:47
CmdType operation
Definition: execdesc.h:36
bool already_executed
Definition: execdesc.h:52
#define InvalidOid
Definition: postgres_ext.h:36
struct Instrumentation * totaltime
Definition: execdesc.h:55
#define Assert(condition)
Definition: c.h:681
uint64 es_processed
Definition: execnodes.h:477
DestReceiver * dest
Definition: execdesc.h:41
int es_top_eflags
Definition: execnodes.h:480
bool parallelModeNeeded
Definition: plannodes.h:59
#define elog
Definition: elog.h:219
PlannedStmt * plannedstmt
Definition: execdesc.h:37
#define EXEC_FLAG_EXPLAIN_ONLY
Definition: executor.h:58
CmdType
Definition: nodes.h:650
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:1675
void standard_ExecutorStart ( QueryDesc queryDesc,
int  eflags 
)

Definition at line 156 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_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(), MemoryContextSwitchTo(), NIL, PlannedStmt::nParamExec, QueryDesc::operation, palloc0(), QueryDesc::params, QueryDesc::plannedstmt, QueryDesc::queryEnv, RegisterSnapshot(), PlannedStmt::rowMarks, QueryDesc::snapshot, QueryDesc::sourceText, and XactReadOnly.

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

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

Variable Documentation

ExecutorCheckPerms_hook_type ExecutorCheckPerms_hook = NULL

Definition at line 76 of file execMain.c.

Referenced by _PG_init(), and ExecCheckRTPerms().

ExecutorEnd_hook_type ExecutorEnd_hook = NULL

Definition at line 73 of file execMain.c.

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

ExecutorFinish_hook_type ExecutorFinish_hook = NULL

Definition at line 72 of file execMain.c.

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

ExecutorRun_hook_type ExecutorRun_hook = NULL

Definition at line 71 of file execMain.c.

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

ExecutorStart_hook_type ExecutorStart_hook = NULL

Definition at line 70 of file execMain.c.

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