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_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)
 
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 (Relation resultRel, 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)
 
static bool ExecPartitionCheck (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, 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 113 of file execMain.c.

Referenced by ExecConstraints(), and ExecWithCheckOptions().

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

Definition at line 115 of file execMain.c.

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

Function Documentation

void CheckValidResultRel ( Relation  resultRel,
CmdType  operation 
)

Definition at line 1097 of file execMain.c.

References CheckCmdReplicaIdentity(), CMD_DELETE, CMD_INSERT, CMD_UPDATE, elog, ereport, errcode(), errhint(), errmsg(), ERROR, FdwRoutine::ExecForeignDelete, FdwRoutine::ExecForeignInsert, FdwRoutine::ExecForeignUpdate, GetFdwRoutineForRelation(), FdwRoutine::IsForeignRelUpdatable, MatViewIncrementalMaintenanceIsEnabled(), NULL, RelationData::rd_rel, RelationGetRelationName, RELKIND_FOREIGN_TABLE, RELKIND_MATVIEW, RELKIND_PARTITIONED_TABLE, RELKIND_RELATION, RELKIND_SEQUENCE, RELKIND_TOASTVALUE, RELKIND_VIEW, TriggerDesc::trig_delete_instead_row, TriggerDesc::trig_insert_instead_row, TriggerDesc::trig_update_instead_row, and RelationData::trigdesc.

Referenced by ExecInitModifyTable(), and ExecSetupPartitionTupleRouting().

1098 {
1099  TriggerDesc *trigDesc = resultRel->trigdesc;
1100  FdwRoutine *fdwroutine;
1101 
1102  switch (resultRel->rd_rel->relkind)
1103  {
1104  case RELKIND_RELATION:
1106  CheckCmdReplicaIdentity(resultRel, operation);
1107  break;
1108  case RELKIND_SEQUENCE:
1109  ereport(ERROR,
1110  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1111  errmsg("cannot change sequence \"%s\"",
1112  RelationGetRelationName(resultRel))));
1113  break;
1114  case RELKIND_TOASTVALUE:
1115  ereport(ERROR,
1116  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1117  errmsg("cannot change TOAST relation \"%s\"",
1118  RelationGetRelationName(resultRel))));
1119  break;
1120  case RELKIND_VIEW:
1121 
1122  /*
1123  * Okay only if there's a suitable INSTEAD OF trigger. Messages
1124  * here should match rewriteHandler.c's rewriteTargetView, except
1125  * that we omit errdetail because we haven't got the information
1126  * handy (and given that we really shouldn't get here anyway, it's
1127  * not worth great exertion to get).
1128  */
1129  switch (operation)
1130  {
1131  case CMD_INSERT:
1132  if (!trigDesc || !trigDesc->trig_insert_instead_row)
1133  ereport(ERROR,
1134  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
1135  errmsg("cannot insert into view \"%s\"",
1136  RelationGetRelationName(resultRel)),
1137  errhint("To enable inserting into the view, provide an INSTEAD OF INSERT trigger or an unconditional ON INSERT DO INSTEAD rule.")));
1138  break;
1139  case CMD_UPDATE:
1140  if (!trigDesc || !trigDesc->trig_update_instead_row)
1141  ereport(ERROR,
1142  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
1143  errmsg("cannot update view \"%s\"",
1144  RelationGetRelationName(resultRel)),
1145  errhint("To enable updating the view, provide an INSTEAD OF UPDATE trigger or an unconditional ON UPDATE DO INSTEAD rule.")));
1146  break;
1147  case CMD_DELETE:
1148  if (!trigDesc || !trigDesc->trig_delete_instead_row)
1149  ereport(ERROR,
1150  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
1151  errmsg("cannot delete from view \"%s\"",
1152  RelationGetRelationName(resultRel)),
1153  errhint("To enable deleting from the view, provide an INSTEAD OF DELETE trigger or an unconditional ON DELETE DO INSTEAD rule.")));
1154  break;
1155  default:
1156  elog(ERROR, "unrecognized CmdType: %d", (int) operation);
1157  break;
1158  }
1159  break;
1160  case RELKIND_MATVIEW:
1162  ereport(ERROR,
1163  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1164  errmsg("cannot change materialized view \"%s\"",
1165  RelationGetRelationName(resultRel))));
1166  break;
1167  case RELKIND_FOREIGN_TABLE:
1168  /* Okay only if the FDW supports it */
1169  fdwroutine = GetFdwRoutineForRelation(resultRel, false);
1170  switch (operation)
1171  {
1172  case CMD_INSERT:
1173  if (fdwroutine->ExecForeignInsert == NULL)
1174  ereport(ERROR,
1175  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1176  errmsg("cannot insert into foreign table \"%s\"",
1177  RelationGetRelationName(resultRel))));
1178  if (fdwroutine->IsForeignRelUpdatable != NULL &&
1179  (fdwroutine->IsForeignRelUpdatable(resultRel) & (1 << CMD_INSERT)) == 0)
1180  ereport(ERROR,
1181  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
1182  errmsg("foreign table \"%s\" does not allow inserts",
1183  RelationGetRelationName(resultRel))));
1184  break;
1185  case CMD_UPDATE:
1186  if (fdwroutine->ExecForeignUpdate == NULL)
1187  ereport(ERROR,
1188  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1189  errmsg("cannot update foreign table \"%s\"",
1190  RelationGetRelationName(resultRel))));
1191  if (fdwroutine->IsForeignRelUpdatable != NULL &&
1192  (fdwroutine->IsForeignRelUpdatable(resultRel) & (1 << CMD_UPDATE)) == 0)
1193  ereport(ERROR,
1194  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
1195  errmsg("foreign table \"%s\" does not allow updates",
1196  RelationGetRelationName(resultRel))));
1197  break;
1198  case CMD_DELETE:
1199  if (fdwroutine->ExecForeignDelete == NULL)
1200  ereport(ERROR,
1201  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1202  errmsg("cannot delete from foreign table \"%s\"",
1203  RelationGetRelationName(resultRel))));
1204  if (fdwroutine->IsForeignRelUpdatable != NULL &&
1205  (fdwroutine->IsForeignRelUpdatable(resultRel) & (1 << CMD_DELETE)) == 0)
1206  ereport(ERROR,
1207  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
1208  errmsg("foreign table \"%s\" does not allow deletes",
1209  RelationGetRelationName(resultRel))));
1210  break;
1211  default:
1212  elog(ERROR, "unrecognized CmdType: %d", (int) operation);
1213  break;
1214  }
1215  break;
1216  default:
1217  ereport(ERROR,
1218  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1219  errmsg("cannot change relation \"%s\"",
1220  RelationGetRelationName(resultRel))));
1221  break;
1222  }
1223 }
ExecForeignDelete_function ExecForeignDelete
Definition: fdwapi.h:199
int errhint(const char *fmt,...)
Definition: elog.c:987
bool MatViewIncrementalMaintenanceIsEnabled(void)
Definition: matview.c:860
ExecForeignInsert_function ExecForeignInsert
Definition: fdwapi.h:197
#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:437
#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:198
#define NULL
Definition: c.h:229
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
IsForeignRelUpdatable_function IsForeignRelUpdatable
Definition: fdwapi.h:201
#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 1232 of file execMain.c.

References ereport, errcode(), errmsg(), ERROR, GetFdwRoutineForRelation(), NULL, 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().

1233 {
1234  FdwRoutine *fdwroutine;
1235 
1236  switch (rel->rd_rel->relkind)
1237  {
1238  case RELKIND_RELATION:
1240  /* OK */
1241  break;
1242  case RELKIND_SEQUENCE:
1243  /* Must disallow this because we don't vacuum sequences */
1244  ereport(ERROR,
1245  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1246  errmsg("cannot lock rows in sequence \"%s\"",
1247  RelationGetRelationName(rel))));
1248  break;
1249  case RELKIND_TOASTVALUE:
1250  /* We could allow this, but there seems no good reason to */
1251  ereport(ERROR,
1252  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1253  errmsg("cannot lock rows in TOAST relation \"%s\"",
1254  RelationGetRelationName(rel))));
1255  break;
1256  case RELKIND_VIEW:
1257  /* Should not get here; planner should have expanded the view */
1258  ereport(ERROR,
1259  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1260  errmsg("cannot lock rows in view \"%s\"",
1261  RelationGetRelationName(rel))));
1262  break;
1263  case RELKIND_MATVIEW:
1264  /* Allow referencing a matview, but not actual locking clauses */
1265  if (markType != ROW_MARK_REFERENCE)
1266  ereport(ERROR,
1267  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1268  errmsg("cannot lock rows in materialized view \"%s\"",
1269  RelationGetRelationName(rel))));
1270  break;
1271  case RELKIND_FOREIGN_TABLE:
1272  /* Okay only if the FDW supports it */
1273  fdwroutine = GetFdwRoutineForRelation(rel, false);
1274  if (fdwroutine->RefetchForeignRow == NULL)
1275  ereport(ERROR,
1276  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1277  errmsg("cannot lock rows in foreign table \"%s\"",
1278  RelationGetRelationName(rel))));
1279  break;
1280  default:
1281  ereport(ERROR,
1282  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1283  errmsg("cannot lock rows in relation \"%s\"",
1284  RelationGetRelationName(rel))));
1285  break;
1286  }
1287 }
#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:437
#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
#define NULL
Definition: c.h:229
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:209
TupleTableSlot* EvalPlanQual ( EState estate,
EPQState epqstate,
Relation  relation,
Index  rti,
int  lockmode,
ItemPointer  tid,
TransactionId  priorXmax 
)

Definition at line 2435 of file execMain.c.

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

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

2438 {
2439  TupleTableSlot *slot;
2440  HeapTuple copyTuple;
2441 
2442  Assert(rti > 0);
2443 
2444  /*
2445  * Get and lock the updated version of the row; if fail, return NULL.
2446  */
2447  copyTuple = EvalPlanQualFetch(estate, relation, lockmode, LockWaitBlock,
2448  tid, priorXmax);
2449 
2450  if (copyTuple == NULL)
2451  return NULL;
2452 
2453  /*
2454  * For UPDATE/DELETE we have to return tid of actual row we're executing
2455  * PQ for.
2456  */
2457  *tid = copyTuple->t_self;
2458 
2459  /*
2460  * Need to run a recheck subquery. Initialize or reinitialize EPQ state.
2461  */
2462  EvalPlanQualBegin(epqstate, estate);
2463 
2464  /*
2465  * Free old test tuple, if any, and store new tuple where relation's scan
2466  * node will see it
2467  */
2468  EvalPlanQualSetTuple(epqstate, rti, copyTuple);
2469 
2470  /*
2471  * Fetch any non-locked source rows
2472  */
2473  EvalPlanQualFetchRowMarks(epqstate);
2474 
2475  /*
2476  * Run the EPQ query. We assume it will return at most one tuple.
2477  */
2478  slot = EvalPlanQualNext(epqstate);
2479 
2480  /*
2481  * If we got a tuple, force the slot to materialize the tuple so that it
2482  * is not dependent on any local state in the EPQ query (in particular,
2483  * it's highly likely that the slot contains references to any pass-by-ref
2484  * datums that may be present in copyTuple). As with the next step, this
2485  * is to guard against early re-use of the EPQ query.
2486  */
2487  if (!TupIsNull(slot))
2488  (void) ExecMaterializeSlot(slot);
2489 
2490  /*
2491  * Clear out the test tuple. This is needed in case the EPQ query is
2492  * re-used to test a tuple for a different relation. (Not clear that can
2493  * really happen, but let's be safe.)
2494  */
2495  EvalPlanQualSetTuple(epqstate, rti, NULL);
2496 
2497  return slot;
2498 }
void EvalPlanQualSetTuple(EPQState *epqstate, Index rti, HeapTuple tuple)
Definition: execMain.c:2786
HeapTuple EvalPlanQualFetch(EState *estate, Relation relation, int lockmode, LockWaitPolicy wait_policy, ItemPointer tid, TransactionId priorXmax)
Definition: execMain.c:2522
void EvalPlanQualFetchRowMarks(EPQState *epqstate)
Definition: execMain.c:2821
void EvalPlanQualBegin(EPQState *epqstate, EState *parentestate)
Definition: execMain.c:2972
TupleTableSlot * EvalPlanQualNext(EPQState *epqstate)
Definition: execMain.c:2956
ItemPointerData t_self
Definition: htup.h:65
#define TupIsNull(slot)
Definition: tuptable.h:138
#define NULL
Definition: c.h:229
#define Assert(condition)
Definition: c.h:675
HeapTuple ExecMaterializeSlot(TupleTableSlot *slot)
Definition: execTuples.c:725
void EvalPlanQualBegin ( EPQState epqstate,
EState parentestate 
)

Definition at line 2972 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, NULL, EPQState::plan, EPQState::planstate, and ParamExecData::value.

Referenced by EvalPlanQual(), and ExecLockRows().

2973 {
2974  EState *estate = epqstate->estate;
2975 
2976  if (estate == NULL)
2977  {
2978  /* First time through, so create a child EState */
2979  EvalPlanQualStart(epqstate, parentestate, epqstate->plan);
2980  }
2981  else
2982  {
2983  /*
2984  * We already have a suitable child EPQ tree, so just reset it.
2985  */
2986  int rtsize = list_length(parentestate->es_range_table);
2987  PlanState *planstate = epqstate->planstate;
2988 
2989  MemSet(estate->es_epqScanDone, 0, rtsize * sizeof(bool));
2990 
2991  /* Recopy current values of parent parameters */
2992  if (parentestate->es_plannedstmt->nParamExec > 0)
2993  {
2994  int i = parentestate->es_plannedstmt->nParamExec;
2995 
2996  while (--i >= 0)
2997  {
2998  /* copy value if any, but not execPlan link */
2999  estate->es_param_exec_vals[i].value =
3000  parentestate->es_param_exec_vals[i].value;
3001  estate->es_param_exec_vals[i].isnull =
3002  parentestate->es_param_exec_vals[i].isnull;
3003  }
3004  }
3005 
3006  /*
3007  * Mark child plan tree as needing rescan at all scan nodes. The
3008  * first ExecProcNode will take care of actually doing the rescan.
3009  */
3010  planstate->chgParam = bms_add_member(planstate->chgParam,
3011  epqstate->epqParam);
3012  }
3013 }
PlannedStmt * es_plannedstmt
Definition: execnodes.h:412
#define MemSet(start, val, len)
Definition: c.h:857
List * es_range_table
Definition: execnodes.h:411
PlanState * planstate
Definition: execnodes.h:877
int nParamExec
Definition: plannodes.h:92
ParamExecData * es_param_exec_vals
Definition: execnodes.h:443
bool isnull
Definition: params.h:101
static void EvalPlanQualStart(EPQState *epqstate, EState *parentestate, Plan *planTree)
Definition: execMain.c:3022
Bitmapset * chgParam
Definition: execnodes.h:837
Plan * plan
Definition: execnodes.h:879
#define NULL
Definition: c.h:229
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:485
Datum value
Definition: params.h:100
int epqParam
Definition: execnodes.h:881
EState * estate
Definition: execnodes.h:876
void EvalPlanQualEnd ( EPQState epqstate)

Definition at line 3162 of file execMain.c.

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

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

3163 {
3164  EState *estate = epqstate->estate;
3165  MemoryContext oldcontext;
3166  ListCell *l;
3167 
3168  if (estate == NULL)
3169  return; /* idle, so nothing to do */
3170 
3171  oldcontext = MemoryContextSwitchTo(estate->es_query_cxt);
3172 
3173  ExecEndNode(epqstate->planstate);
3174 
3175  foreach(l, estate->es_subplanstates)
3176  {
3177  PlanState *subplanstate = (PlanState *) lfirst(l);
3178 
3179  ExecEndNode(subplanstate);
3180  }
3181 
3182  /* throw away the per-estate tuple table */
3183  ExecResetTupleTable(estate->es_tupleTable, false);
3184 
3185  /* close any trigger target relations attached to this EState */
3186  ExecCleanUpTriggerState(estate);
3187 
3188  MemoryContextSwitchTo(oldcontext);
3189 
3190  FreeExecutorState(estate);
3191 
3192  /* Mark EPQState idle */
3193  epqstate->estate = NULL;
3194  epqstate->planstate = NULL;
3195  epqstate->origslot = NULL;
3196 }
void ExecEndNode(PlanState *node)
Definition: execProcnode.c:654
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:109
PlanState * planstate
Definition: execnodes.h:877
void FreeExecutorState(EState *estate)
Definition: execUtils.c:178
MemoryContext es_query_cxt
Definition: execnodes.h:448
TupleTableSlot * origslot
Definition: execnodes.h:878
List * es_tupleTable
Definition: execnodes.h:450
void ExecResetTupleTable(List *tupleTable, bool shouldFree)
Definition: execTuples.c:156
#define NULL
Definition: c.h:229
#define lfirst(lc)
Definition: pg_list.h:106
List * es_subplanstates
Definition: execnodes.h:463
void ExecCleanUpTriggerState(EState *estate)
Definition: execMain.c:1453
EState * estate
Definition: execnodes.h:876
HeapTuple EvalPlanQualFetch ( EState estate,
Relation  relation,
int  lockmode,
LockWaitPolicy  wait_policy,
ItemPointer  tid,
TransactionId  priorXmax 
)

Definition at line 2522 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, HeapTupleHeaderGetXmin, HeapTupleHeaderIsSpeculative, HeapTupleInvisible, HeapTupleMayBeUpdated, HeapTupleSelfUpdated, HeapTupleUpdated, HeapTupleWouldBlock, InitDirtySnapshot, IsolationUsesXactSnapshot, ItemPointerEquals(), LockWaitBlock, LockWaitError, LockWaitSkip, NULL, RelationGetRelationName, ReleaseBuffer(), HeapTupleHeaderData::t_ctid, HeapTupleData::t_data, HeapTupleData::t_self, test(), TransactionIdEquals, TransactionIdIsCurrentTransactionId(), TransactionIdIsValid, XactLockTableWait(), XLTW_FetchUpdated, SnapshotData::xmax, HeapUpdateFailureData::xmax, and SnapshotData::xmin.

Referenced by EvalPlanQual(), and ExecLockRows().

2525 {
2526  HeapTuple copyTuple = NULL;
2527  HeapTupleData tuple;
2528  SnapshotData SnapshotDirty;
2529 
2530  /*
2531  * fetch target tuple
2532  *
2533  * Loop here to deal with updated or busy tuples
2534  */
2535  InitDirtySnapshot(SnapshotDirty);
2536  tuple.t_self = *tid;
2537  for (;;)
2538  {
2539  Buffer buffer;
2540 
2541  if (heap_fetch(relation, &SnapshotDirty, &tuple, &buffer, true, NULL))
2542  {
2543  HTSU_Result test;
2544  HeapUpdateFailureData hufd;
2545 
2546  /*
2547  * If xmin isn't what we're expecting, the slot must have been
2548  * recycled and reused for an unrelated tuple. This implies that
2549  * the latest version of the row was deleted, so we need do
2550  * nothing. (Should be safe to examine xmin without getting
2551  * buffer's content lock. We assume reading a TransactionId to be
2552  * atomic, and Xmin never changes in an existing tuple, except to
2553  * invalid or frozen, and neither of those can match priorXmax.)
2554  */
2556  priorXmax))
2557  {
2558  ReleaseBuffer(buffer);
2559  return NULL;
2560  }
2561 
2562  /* otherwise xmin should not be dirty... */
2563  if (TransactionIdIsValid(SnapshotDirty.xmin))
2564  elog(ERROR, "t_xmin is uncommitted in tuple to be updated");
2565 
2566  /*
2567  * If tuple is being updated by other transaction then we have to
2568  * wait for its commit/abort, or die trying.
2569  */
2570  if (TransactionIdIsValid(SnapshotDirty.xmax))
2571  {
2572  ReleaseBuffer(buffer);
2573  switch (wait_policy)
2574  {
2575  case LockWaitBlock:
2576  XactLockTableWait(SnapshotDirty.xmax,
2577  relation, &tuple.t_self,
2579  break;
2580  case LockWaitSkip:
2581  if (!ConditionalXactLockTableWait(SnapshotDirty.xmax))
2582  return NULL; /* skip instead of waiting */
2583  break;
2584  case LockWaitError:
2585  if (!ConditionalXactLockTableWait(SnapshotDirty.xmax))
2586  ereport(ERROR,
2587  (errcode(ERRCODE_LOCK_NOT_AVAILABLE),
2588  errmsg("could not obtain lock on row in relation \"%s\"",
2589  RelationGetRelationName(relation))));
2590  break;
2591  }
2592  continue; /* loop back to repeat heap_fetch */
2593  }
2594 
2595  /*
2596  * If tuple was inserted by our own transaction, we have to check
2597  * cmin against es_output_cid: cmin >= current CID means our
2598  * command cannot see the tuple, so we should ignore it. Otherwise
2599  * heap_lock_tuple() will throw an error, and so would any later
2600  * attempt to update or delete the tuple. (We need not check cmax
2601  * because HeapTupleSatisfiesDirty will consider a tuple deleted
2602  * by our transaction dead, regardless of cmax.) We just checked
2603  * that priorXmax == xmin, so we can test that variable instead of
2604  * doing HeapTupleHeaderGetXmin again.
2605  */
2606  if (TransactionIdIsCurrentTransactionId(priorXmax) &&
2607  HeapTupleHeaderGetCmin(tuple.t_data) >= estate->es_output_cid)
2608  {
2609  ReleaseBuffer(buffer);
2610  return NULL;
2611  }
2612 
2613  /*
2614  * This is a live tuple, so now try to lock it.
2615  */
2616  test = heap_lock_tuple(relation, &tuple,
2617  estate->es_output_cid,
2618  lockmode, wait_policy,
2619  false, &buffer, &hufd);
2620  /* We now have two pins on the buffer, get rid of one */
2621  ReleaseBuffer(buffer);
2622 
2623  switch (test)
2624  {
2625  case HeapTupleSelfUpdated:
2626 
2627  /*
2628  * The target tuple was already updated or deleted by the
2629  * current command, or by a later command in the current
2630  * transaction. We *must* ignore the tuple in the former
2631  * case, so as to avoid the "Halloween problem" of
2632  * repeated update attempts. In the latter case it might
2633  * be sensible to fetch the updated tuple instead, but
2634  * doing so would require changing heap_update and
2635  * heap_delete to not complain about updating "invisible"
2636  * tuples, which seems pretty scary (heap_lock_tuple will
2637  * not complain, but few callers expect
2638  * HeapTupleInvisible, and we're not one of them). So for
2639  * now, treat the tuple as deleted and do not process.
2640  */
2641  ReleaseBuffer(buffer);
2642  return NULL;
2643 
2644  case HeapTupleMayBeUpdated:
2645  /* successfully locked */
2646  break;
2647 
2648  case HeapTupleUpdated:
2649  ReleaseBuffer(buffer);
2651  ereport(ERROR,
2652  (errcode(ERRCODE_T_R_SERIALIZATION_FAILURE),
2653  errmsg("could not serialize access due to concurrent update")));
2654 
2655  /* Should not encounter speculative tuple on recheck */
2657  if (!ItemPointerEquals(&hufd.ctid, &tuple.t_self))
2658  {
2659  /* it was updated, so look at the updated version */
2660  tuple.t_self = hufd.ctid;
2661  /* updated row should have xmin matching this xmax */
2662  priorXmax = hufd.xmax;
2663  continue;
2664  }
2665  /* tuple was deleted, so give up */
2666  return NULL;
2667 
2668  case HeapTupleWouldBlock:
2669  ReleaseBuffer(buffer);
2670  return NULL;
2671 
2672  case HeapTupleInvisible:
2673  elog(ERROR, "attempted to lock invisible tuple");
2674 
2675  default:
2676  ReleaseBuffer(buffer);
2677  elog(ERROR, "unrecognized heap_lock_tuple status: %u",
2678  test);
2679  return NULL; /* keep compiler quiet */
2680  }
2681 
2682  /*
2683  * We got tuple - now copy it for use by recheck query.
2684  */
2685  copyTuple = heap_copytuple(&tuple);
2686  ReleaseBuffer(buffer);
2687  break;
2688  }
2689 
2690  /*
2691  * If the referenced slot was actually empty, the latest version of
2692  * the row must have been deleted, so we need do nothing.
2693  */
2694  if (tuple.t_data == NULL)
2695  {
2696  ReleaseBuffer(buffer);
2697  return NULL;
2698  }
2699 
2700  /*
2701  * As above, if xmin isn't what we're expecting, do nothing.
2702  */
2704  priorXmax))
2705  {
2706  ReleaseBuffer(buffer);
2707  return NULL;
2708  }
2709 
2710  /*
2711  * If we get here, the tuple was found but failed SnapshotDirty.
2712  * Assuming the xmin is either a committed xact or our own xact (as it
2713  * certainly should be if we're trying to modify the tuple), this must
2714  * mean that the row was updated or deleted by either a committed xact
2715  * or our own xact. If it was deleted, we can ignore it; if it was
2716  * updated then chain up to the next version and repeat the whole
2717  * process.
2718  *
2719  * As above, it should be safe to examine xmax and t_ctid without the
2720  * buffer content lock, because they can't be changing.
2721  */
2722  if (ItemPointerEquals(&tuple.t_self, &tuple.t_data->t_ctid))
2723  {
2724  /* deleted, so forget about it */
2725  ReleaseBuffer(buffer);
2726  return NULL;
2727  }
2728 
2729  /* updated, so look at the updated row */
2730  tuple.t_self = tuple.t_data->t_ctid;
2731  /* updated row should have xmin matching this xmax */
2732  priorXmax = HeapTupleHeaderGetUpdateXid(tuple.t_data);
2733  ReleaseBuffer(buffer);
2734  /* loop back to fetch next in chain */
2735  }
2736 
2737  /*
2738  * Return the copied tuple
2739  */
2740  return copyTuple;
2741 }
#define HeapTupleHeaderGetUpdateXid(tup)
Definition: htup_details.h:359
HeapTuple heap_copytuple(HeapTuple tuple)
Definition: heaptuple.c:608
CommandId es_output_cid
Definition: execnodes.h:418
static void test(void)
#define TransactionIdEquals(id1, id2)
Definition: transam.h:43
bool TransactionIdIsCurrentTransactionId(TransactionId xid)
Definition: xact.c:773
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:4540
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:1862
#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:100
ItemPointerData t_ctid
Definition: htup_details.h:150
ItemPointerData t_self
Definition: htup.h:65
HTSU_Result
Definition: snapshot.h:119
#define RelationGetRelationName(relation)
Definition: rel.h:437
TransactionId xmax
Definition: snapshot.h:67
TransactionId xmin
Definition: snapshot.h:66
#define ereport(elevel, rest)
Definition: elog.h:122
TransactionId xmax
Definition: heapam.h:71
void XactLockTableWait(TransactionId xid, Relation rel, ItemPointer ctid, XLTW_Oper oper)
Definition: lmgr.c:554
#define NULL
Definition: c.h:229
#define Assert(condition)
Definition: c.h:675
WalTimeSample buffer[LAG_TRACKER_BUFFER_SIZE]
Definition: walsender.c:211
#define HeapTupleHeaderGetXmin(tup)
Definition: htup_details.h:307
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 2821 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, NULL, 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().

2822 {
2823  ListCell *l;
2824 
2825  Assert(epqstate->origslot != NULL);
2826 
2827  foreach(l, epqstate->arowMarks)
2828  {
2829  ExecAuxRowMark *aerm = (ExecAuxRowMark *) lfirst(l);
2830  ExecRowMark *erm = aerm->rowmark;
2831  Datum datum;
2832  bool isNull;
2833  HeapTupleData tuple;
2834 
2836  elog(ERROR, "EvalPlanQual doesn't support locking rowmarks");
2837 
2838  /* clear any leftover test tuple for this rel */
2839  EvalPlanQualSetTuple(epqstate, erm->rti, NULL);
2840 
2841  /* if child rel, must check whether it produced this row */
2842  if (erm->rti != erm->prti)
2843  {
2844  Oid tableoid;
2845 
2846  datum = ExecGetJunkAttribute(epqstate->origslot,
2847  aerm->toidAttNo,
2848  &isNull);
2849  /* non-locked rels could be on the inside of outer joins */
2850  if (isNull)
2851  continue;
2852  tableoid = DatumGetObjectId(datum);
2853 
2854  Assert(OidIsValid(erm->relid));
2855  if (tableoid != erm->relid)
2856  {
2857  /* this child is inactive right now */
2858  continue;
2859  }
2860  }
2861 
2862  if (erm->markType == ROW_MARK_REFERENCE)
2863  {
2864  HeapTuple copyTuple;
2865 
2866  Assert(erm->relation != NULL);
2867 
2868  /* fetch the tuple's ctid */
2869  datum = ExecGetJunkAttribute(epqstate->origslot,
2870  aerm->ctidAttNo,
2871  &isNull);
2872  /* non-locked rels could be on the inside of outer joins */
2873  if (isNull)
2874  continue;
2875 
2876  /* fetch requests on foreign tables must be passed to their FDW */
2877  if (erm->relation->rd_rel->relkind == RELKIND_FOREIGN_TABLE)
2878  {
2879  FdwRoutine *fdwroutine;
2880  bool updated = false;
2881 
2882  fdwroutine = GetFdwRoutineForRelation(erm->relation, false);
2883  /* this should have been checked already, but let's be safe */
2884  if (fdwroutine->RefetchForeignRow == NULL)
2885  ereport(ERROR,
2886  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2887  errmsg("cannot lock rows in foreign table \"%s\"",
2889  copyTuple = fdwroutine->RefetchForeignRow(epqstate->estate,
2890  erm,
2891  datum,
2892  &updated);
2893  if (copyTuple == NULL)
2894  elog(ERROR, "failed to fetch tuple for EvalPlanQual recheck");
2895 
2896  /*
2897  * Ideally we'd insist on updated == false here, but that
2898  * assumes that FDWs can track that exactly, which they might
2899  * not be able to. So just ignore the flag.
2900  */
2901  }
2902  else
2903  {
2904  /* ordinary table, fetch the tuple */
2905  Buffer buffer;
2906 
2907  tuple.t_self = *((ItemPointer) DatumGetPointer(datum));
2908  if (!heap_fetch(erm->relation, SnapshotAny, &tuple, &buffer,
2909  false, NULL))
2910  elog(ERROR, "failed to fetch tuple for EvalPlanQual recheck");
2911 
2912  /* successful, copy tuple */
2913  copyTuple = heap_copytuple(&tuple);
2914  ReleaseBuffer(buffer);
2915  }
2916 
2917  /* store tuple */
2918  EvalPlanQualSetTuple(epqstate, erm->rti, copyTuple);
2919  }
2920  else
2921  {
2922  HeapTupleHeader td;
2923 
2924  Assert(erm->markType == ROW_MARK_COPY);
2925 
2926  /* fetch the whole-row Var for the relation */
2927  datum = ExecGetJunkAttribute(epqstate->origslot,
2928  aerm->wholeAttNo,
2929  &isNull);
2930  /* non-locked rels could be on the inside of outer joins */
2931  if (isNull)
2932  continue;
2933  td = DatumGetHeapTupleHeader(datum);
2934 
2935  /* build a temporary HeapTuple control structure */
2937  tuple.t_data = td;
2938  /* relation might be a foreign table, if so provide tableoid */
2939  tuple.t_tableOid = erm->relid;
2940  /* also copy t_ctid in case there's valid data there */
2941  tuple.t_self = td->t_ctid;
2942 
2943  /* copy and store tuple */
2944  EvalPlanQualSetTuple(epqstate, erm->rti,
2945  heap_copytuple(&tuple));
2946  }
2947  }
2948 }
HeapTuple heap_copytuple(HeapTuple tuple)
Definition: heaptuple.c:608
void EvalPlanQualSetTuple(EPQState *epqstate, Index rti, HeapTuple tuple)
Definition: execMain.c:2786
Relation relation
Definition: execnodes.h:511
bool heap_fetch(Relation relation, Snapshot snapshot, HeapTuple tuple, Buffer *userbuf, bool keep_buf, Relation stats_relation)
Definition: heapam.c:1862
#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:538
#define DatumGetHeapTupleHeader(X)
Definition: fmgr.h:259
#define RowMarkRequiresRowShareLock(marktype)
Definition: plannodes.h:962
ItemPointerData * ItemPointer
Definition: itemptr.h:48
ExecRowMark * rowmark
Definition: execnodes.h:538
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:880
uint32 t_len
Definition: htup.h:64
Index rti
Definition: execnodes.h:513
AttrNumber wholeAttNo
Definition: execnodes.h:541
Index prti
Definition: execnodes.h:514
#define RelationGetRelationName(relation)
Definition: rel.h:437
Oid t_tableOid
Definition: htup.h:66
#define RELKIND_FOREIGN_TABLE
Definition: pg_class.h:167
TupleTableSlot * origslot
Definition: execnodes.h:878
#define ereport(elevel, rest)
Definition: elog.h:122
uintptr_t Datum
Definition: postgres.h:372
#define SnapshotAny
Definition: tqual.h:28
#define NULL
Definition: c.h:229
#define Assert(condition)
Definition: c.h:675
#define lfirst(lc)
Definition: pg_list.h:106
WalTimeSample buffer[LAG_TRACKER_BUFFER_SIZE]
Definition: walsender.c:211
RowMarkType markType
Definition: execnodes.h:516
AttrNumber toidAttNo
Definition: execnodes.h:540
#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:876
int Buffer
Definition: buf.h:23
AttrNumber ctidAttNo
Definition: execnodes.h:539
RefetchForeignRow_function RefetchForeignRow
Definition: fdwapi.h:209
#define HeapTupleHeaderGetDatumLength(tup)
Definition: htup_details.h:439
HeapTuple EvalPlanQualGetTuple ( EPQState epqstate,
Index  rti 
)

Definition at line 2806 of file execMain.c.

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

2807 {
2808  EState *estate = epqstate->estate;
2809 
2810  Assert(rti > 0);
2811 
2812  return estate->es_epqTuple[rti - 1];
2813 }
HeapTuple * es_epqTuple
Definition: execnodes.h:483
#define Assert(condition)
Definition: c.h:675
EState * estate
Definition: execnodes.h:876
void EvalPlanQualInit ( EPQState epqstate,
EState estate,
Plan subplan,
List auxrowmarks,
int  epqParam 
)

Definition at line 2751 of file execMain.c.

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

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

2753 {
2754  /* Mark the EPQ state inactive */
2755  epqstate->estate = NULL;
2756  epqstate->planstate = NULL;
2757  epqstate->origslot = NULL;
2758  /* ... and remember data that EvalPlanQualBegin will need */
2759  epqstate->plan = subplan;
2760  epqstate->arowMarks = auxrowmarks;
2761  epqstate->epqParam = epqParam;
2762 }
PlanState * planstate
Definition: execnodes.h:877
List * arowMarks
Definition: execnodes.h:880
TupleTableSlot * origslot
Definition: execnodes.h:878
Plan * plan
Definition: execnodes.h:879
#define NULL
Definition: c.h:229
int epqParam
Definition: execnodes.h:881
EState * estate
Definition: execnodes.h:876
TupleTableSlot* EvalPlanQualNext ( EPQState epqstate)

Definition at line 2956 of file execMain.c.

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

Referenced by EvalPlanQual(), and ExecLockRows().

2957 {
2958  MemoryContext oldcontext;
2959  TupleTableSlot *slot;
2960 
2961  oldcontext = MemoryContextSwitchTo(epqstate->estate->es_query_cxt);
2962  slot = ExecProcNode(epqstate->planstate);
2963  MemoryContextSwitchTo(oldcontext);
2964 
2965  return slot;
2966 }
TupleTableSlot * ExecProcNode(PlanState *node)
Definition: execProcnode.c:398
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:109
PlanState * planstate
Definition: execnodes.h:877
MemoryContext es_query_cxt
Definition: execnodes.h:448
EState * estate
Definition: execnodes.h:876
void EvalPlanQualSetPlan ( EPQState epqstate,
Plan subplan,
List auxrowmarks 
)

Definition at line 2770 of file execMain.c.

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

Referenced by ExecInitModifyTable(), and ExecModifyTable().

2771 {
2772  /* If we have a live EPQ query, shut it down */
2773  EvalPlanQualEnd(epqstate);
2774  /* And set/change the plan pointer */
2775  epqstate->plan = subplan;
2776  /* The rowmarks depend on the plan, too */
2777  epqstate->arowMarks = auxrowmarks;
2778 }
void EvalPlanQualEnd(EPQState *epqstate)
Definition: execMain.c:3162
List * arowMarks
Definition: execnodes.h:880
Plan * plan
Definition: execnodes.h:879
void EvalPlanQualSetTuple ( EPQState epqstate,
Index  rti,
HeapTuple  tuple 
)

Definition at line 2786 of file execMain.c.

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

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

2787 {
2788  EState *estate = epqstate->estate;
2789 
2790  Assert(rti > 0);
2791 
2792  /*
2793  * free old test tuple, if any, and store new tuple where relation's scan
2794  * node will see it
2795  */
2796  if (estate->es_epqTuple[rti - 1] != NULL)
2797  heap_freetuple(estate->es_epqTuple[rti - 1]);
2798  estate->es_epqTuple[rti - 1] = tuple;
2799  estate->es_epqTupleSet[rti - 1] = true;
2800 }
HeapTuple * es_epqTuple
Definition: execnodes.h:483
void heap_freetuple(HeapTuple htup)
Definition: heaptuple.c:1372
#define NULL
Definition: c.h:229
#define Assert(condition)
Definition: c.h:675
bool * es_epqTupleSet
Definition: execnodes.h:484
EState * estate
Definition: execnodes.h:876
static void EvalPlanQualStart ( EPQState epqstate,
EState parentestate,
Plan planTree 
)
static

Definition at line 3022 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, NULL, palloc(), palloc0(), EPQState::planstate, PlannedStmt::subplans, and ParamExecData::value.

Referenced by EvalPlanQualBegin().

3023 {
3024  EState *estate;
3025  int rtsize;
3026  MemoryContext oldcontext;
3027  ListCell *l;
3028 
3029  rtsize = list_length(parentestate->es_range_table);
3030 
3031  epqstate->estate = estate = CreateExecutorState();
3032 
3033  oldcontext = MemoryContextSwitchTo(estate->es_query_cxt);
3034 
3035  /*
3036  * Child EPQ EStates share the parent's copy of unchanging state such as
3037  * the snapshot, rangetable, result-rel info, and external Param info.
3038  * They need their own copies of local state, including a tuple table,
3039  * es_param_exec_vals, etc.
3040  *
3041  * The ResultRelInfo array management is trickier than it looks. We
3042  * create a fresh array for the child but copy all the content from the
3043  * parent. This is because it's okay for the child to share any
3044  * per-relation state the parent has already created --- but if the child
3045  * sets up any ResultRelInfo fields, such as its own junkfilter, that
3046  * state must *not* propagate back to the parent. (For one thing, the
3047  * pointed-to data is in a memory context that won't last long enough.)
3048  */
3050  estate->es_snapshot = parentestate->es_snapshot;
3051  estate->es_crosscheck_snapshot = parentestate->es_crosscheck_snapshot;
3052  estate->es_range_table = parentestate->es_range_table;
3053  estate->es_plannedstmt = parentestate->es_plannedstmt;
3054  estate->es_junkFilter = parentestate->es_junkFilter;
3055  estate->es_output_cid = parentestate->es_output_cid;
3056  if (parentestate->es_num_result_relations > 0)
3057  {
3058  int numResultRelations = parentestate->es_num_result_relations;
3059  ResultRelInfo *resultRelInfos;
3060 
3061  resultRelInfos = (ResultRelInfo *)
3062  palloc(numResultRelations * sizeof(ResultRelInfo));
3063  memcpy(resultRelInfos, parentestate->es_result_relations,
3064  numResultRelations * sizeof(ResultRelInfo));
3065  estate->es_result_relations = resultRelInfos;
3066  estate->es_num_result_relations = numResultRelations;
3067  }
3068  /* es_result_relation_info must NOT be copied */
3069  /* es_trig_target_relations must NOT be copied */
3070  estate->es_rowMarks = parentestate->es_rowMarks;
3071  estate->es_top_eflags = parentestate->es_top_eflags;
3072  estate->es_instrument = parentestate->es_instrument;
3073  /* es_auxmodifytables must NOT be copied */
3074 
3075  /*
3076  * The external param list is simply shared from parent. The internal
3077  * param workspace has to be local state, but we copy the initial values
3078  * from the parent, so as to have access to any param values that were
3079  * already set from other parts of the parent's plan tree.
3080  */
3081  estate->es_param_list_info = parentestate->es_param_list_info;
3082  if (parentestate->es_plannedstmt->nParamExec > 0)
3083  {
3084  int i = parentestate->es_plannedstmt->nParamExec;
3085 
3086  estate->es_param_exec_vals = (ParamExecData *)
3087  palloc0(i * sizeof(ParamExecData));
3088  while (--i >= 0)
3089  {
3090  /* copy value if any, but not execPlan link */
3091  estate->es_param_exec_vals[i].value =
3092  parentestate->es_param_exec_vals[i].value;
3093  estate->es_param_exec_vals[i].isnull =
3094  parentestate->es_param_exec_vals[i].isnull;
3095  }
3096  }
3097 
3098  /*
3099  * Each EState must have its own es_epqScanDone state, but if we have
3100  * nested EPQ checks they should share es_epqTuple arrays. This allows
3101  * sub-rechecks to inherit the values being examined by an outer recheck.
3102  */
3103  estate->es_epqScanDone = (bool *) palloc0(rtsize * sizeof(bool));
3104  if (parentestate->es_epqTuple != NULL)
3105  {
3106  estate->es_epqTuple = parentestate->es_epqTuple;
3107  estate->es_epqTupleSet = parentestate->es_epqTupleSet;
3108  }
3109  else
3110  {
3111  estate->es_epqTuple = (HeapTuple *)
3112  palloc0(rtsize * sizeof(HeapTuple));
3113  estate->es_epqTupleSet = (bool *)
3114  palloc0(rtsize * sizeof(bool));
3115  }
3116 
3117  /*
3118  * Each estate also has its own tuple table.
3119  */
3120  estate->es_tupleTable = NIL;
3121 
3122  /*
3123  * Initialize private state information for each SubPlan. We must do this
3124  * before running ExecInitNode on the main query tree, since
3125  * ExecInitSubPlan expects to be able to find these entries. Some of the
3126  * SubPlans might not be used in the part of the plan tree we intend to
3127  * run, but since it's not easy to tell which, we just initialize them
3128  * all.
3129  */
3130  Assert(estate->es_subplanstates == NIL);
3131  foreach(l, parentestate->es_plannedstmt->subplans)
3132  {
3133  Plan *subplan = (Plan *) lfirst(l);
3134  PlanState *subplanstate;
3135 
3136  subplanstate = ExecInitNode(subplan, estate, 0);
3137  estate->es_subplanstates = lappend(estate->es_subplanstates,
3138  subplanstate);
3139  }
3140 
3141  /*
3142  * Initialize the private state information for all the nodes in the part
3143  * of the plan tree we need to run. This opens files, allocates storage
3144  * and leaves us ready to start processing tuples.
3145  */
3146  epqstate->planstate = ExecInitNode(planTree, estate, 0);
3147 
3148  MemoryContextSwitchTo(oldcontext);
3149 }
#define NIL
Definition: pg_list.h:69
HeapTuple * es_epqTuple
Definition: execnodes.h:483
JunkFilter * es_junkFilter
Definition: execnodes.h:415
CommandId es_output_cid
Definition: execnodes.h:418
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:109
PlannedStmt * es_plannedstmt
Definition: execnodes.h:412
Snapshot es_crosscheck_snapshot
Definition: execnodes.h:410
Snapshot es_snapshot
Definition: execnodes.h:409
List * es_range_table
Definition: execnodes.h:411
PlanState * planstate
Definition: execnodes.h:877
ScanDirection es_direction
Definition: execnodes.h:408
int nParamExec
Definition: plannodes.h:92
ParamExecData * es_param_exec_vals
Definition: execnodes.h:443
MemoryContext es_query_cxt
Definition: execnodes.h:448
bool isnull
Definition: params.h:101
ResultRelInfo * es_result_relations
Definition: execnodes.h:421
int es_instrument
Definition: execnodes.h:458
EState * CreateExecutorState(void)
Definition: execUtils.c:80
List * lappend(List *list, void *datum)
Definition: list.c:128
List * es_tupleTable
Definition: execnodes.h:450
void * palloc0(Size size)
Definition: mcxt.c:878
int es_num_result_relations
Definition: execnodes.h:422
List * subplans
Definition: plannodes.h:81
#define NULL
Definition: c.h:229
#define Assert(condition)
Definition: c.h:675
#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:484
List * es_subplanstates
Definition: execnodes.h:463
List * es_rowMarks
Definition: execnodes.h:452
void * palloc(Size size)
Definition: mcxt.c:849
int es_top_eflags
Definition: execnodes.h:457
int i
bool * es_epqScanDone
Definition: execnodes.h:485
Datum value
Definition: params.h:100
ParamListInfo es_param_list_info
Definition: execnodes.h:442
EState * estate
Definition: execnodes.h:876
PlanState * ExecInitNode(Plan *node, EState *estate, int eflags)
Definition: execProcnode.c:140
ExecAuxRowMark* ExecBuildAuxRowMark ( ExecRowMark erm,
List targetlist 
)

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

2365 {
2366  ExecAuxRowMark *aerm = (ExecAuxRowMark *) palloc0(sizeof(ExecAuxRowMark));
2367  char resname[32];
2368 
2369  aerm->rowmark = erm;
2370 
2371  /* Look up the resjunk columns associated with this rowmark */
2372  if (erm->markType != ROW_MARK_COPY)
2373  {
2374  /* need ctid for all methods other than COPY */
2375  snprintf(resname, sizeof(resname), "ctid%u", erm->rowmarkId);
2376  aerm->ctidAttNo = ExecFindJunkAttributeInTlist(targetlist,
2377  resname);
2378  if (!AttributeNumberIsValid(aerm->ctidAttNo))
2379  elog(ERROR, "could not find junk %s column", resname);
2380  }
2381  else
2382  {
2383  /* need wholerow if COPY */
2384  snprintf(resname, sizeof(resname), "wholerow%u", erm->rowmarkId);
2385  aerm->wholeAttNo = ExecFindJunkAttributeInTlist(targetlist,
2386  resname);
2387  if (!AttributeNumberIsValid(aerm->wholeAttNo))
2388  elog(ERROR, "could not find junk %s column", resname);
2389  }
2390 
2391  /* if child rel, need tableoid */
2392  if (erm->rti != erm->prti)
2393  {
2394  snprintf(resname, sizeof(resname), "tableoid%u", erm->rowmarkId);
2395  aerm->toidAttNo = ExecFindJunkAttributeInTlist(targetlist,
2396  resname);
2397  if (!AttributeNumberIsValid(aerm->toidAttNo))
2398  elog(ERROR, "could not find junk %s column", resname);
2399  }
2400 
2401  return aerm;
2402 }
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:538
#define ERROR
Definition: elog.h:43
Index rti
Definition: execnodes.h:513
AttrNumber wholeAttNo
Definition: execnodes.h:541
Index prti
Definition: execnodes.h:514
Index rowmarkId
Definition: execnodes.h:515
#define AttributeNumberIsValid(attributeNumber)
Definition: attnum.h:34
void * palloc0(Size size)
Definition: mcxt.c:878
RowMarkType markType
Definition: execnodes.h:516
AttrNumber toidAttNo
Definition: execnodes.h:540
#define elog
Definition: elog.h:219
AttrNumber ctidAttNo
Definition: execnodes.h:539
static char * ExecBuildSlotPartitionKeyDescription ( Relation  rel,
Datum values,
bool isnull,
int  maxfieldlen 
)
static

Definition at line 3357 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, NULL, OidOutputFunctionCall(), pg_attribute_aclcheck(), pg_class_aclcheck(), pg_get_partkeydef_columns(), pg_mbcliplen(), RelationGetPartitionKey, RelationGetRelid, RLS_ENABLED, and val.

Referenced by ExecFindPartition().

3361 {
3364  int partnatts = get_partition_natts(key);
3365  int i;
3366  Oid relid = RelationGetRelid(rel);
3367  AclResult aclresult;
3368 
3369  if (check_enable_rls(relid, InvalidOid, true) == RLS_ENABLED)
3370  return NULL;
3371 
3372  /* If the user has table-level access, just go build the description. */
3373  aclresult = pg_class_aclcheck(relid, GetUserId(), ACL_SELECT);
3374  if (aclresult != ACLCHECK_OK)
3375  {
3376  /*
3377  * Step through the columns of the partition key and make sure the
3378  * user has SELECT rights on all of them.
3379  */
3380  for (i = 0; i < partnatts; i++)
3381  {
3382  AttrNumber attnum = get_partition_col_attnum(key, i);
3383 
3384  /*
3385  * If this partition key column is an expression, we return no
3386  * detail rather than try to figure out what column(s) the
3387  * expression includes and if the user has SELECT rights on them.
3388  */
3389  if (attnum == InvalidAttrNumber ||
3390  pg_attribute_aclcheck(relid, attnum, GetUserId(),
3391  ACL_SELECT) != ACLCHECK_OK)
3392  return NULL;
3393  }
3394  }
3395 
3396  initStringInfo(&buf);
3397  appendStringInfo(&buf, "(%s) = (",
3398  pg_get_partkeydef_columns(relid, true));
3399 
3400  for (i = 0; i < partnatts; i++)
3401  {
3402  char *val;
3403  int vallen;
3404 
3405  if (isnull[i])
3406  val = "null";
3407  else
3408  {
3409  Oid foutoid;
3410  bool typisvarlena;
3411 
3413  &foutoid, &typisvarlena);
3414  val = OidOutputFunctionCall(foutoid, values[i]);
3415  }
3416 
3417  if (i > 0)
3418  appendStringInfoString(&buf, ", ");
3419 
3420  /* truncate if needed */
3421  vallen = strlen(val);
3422  if (vallen <= maxfieldlen)
3423  appendStringInfoString(&buf, val);
3424  else
3425  {
3426  vallen = pg_mbcliplen(val, vallen, maxfieldlen);
3427  appendBinaryStringInfo(&buf, val, vallen);
3428  appendStringInfoString(&buf, "...");
3429  }
3430  }
3431 
3432  appendStringInfoChar(&buf, ')');
3433 
3434  return buf.data;
3435 }
char * pg_get_partkeydef_columns(Oid relid, bool pretty)
Definition: ruleutils.c:1569
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:283
unsigned int Oid
Definition: postgres_ext.h:31
static int get_partition_natts(PartitionKey key)
Definition: rel.h:597
static int16 get_partition_col_attnum(PartitionKey key, int col)
Definition: rel.h:612
void appendStringInfo(StringInfo str, const char *fmt,...)
Definition: stringinfo.c:78
int pg_mbcliplen(const char *mbstr, int len, int limit)
Definition: mbutils.c:831
void appendStringInfoString(StringInfo str, const char *s)
Definition: stringinfo.c:157
static char * buf
Definition: pg_test_fsync.c:66
void appendStringInfoChar(StringInfo str, char ch)
Definition: stringinfo.c:169
void initStringInfo(StringInfo str)
Definition: stringinfo.c:46
AclResult
Definition: acl.h:170
static Oid get_partition_col_typid(PartitionKey key, int col)
Definition: rel.h:618
#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 NULL
Definition: c.h:229
#define RelationGetPartitionKey(relation)
Definition: rel.h:585
#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:163
char * OidOutputFunctionCall(Oid functionId, Datum val)
Definition: fmgr.c:1747
int i
int16 AttrNumber
Definition: attnum.h:21
#define RelationGetRelid(relation)
Definition: rel.h:417
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 2178 of file execMain.c.

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

Referenced by ExecConstraints(), and ExecWithCheckOptions().

2183 {
2185  StringInfoData collist;
2186  bool write_comma = false;
2187  bool write_comma_collist = false;
2188  int i;
2189  AclResult aclresult;
2190  bool table_perm = false;
2191  bool any_perm = false;
2192 
2193  /*
2194  * Check if RLS is enabled and should be active for the relation; if so,
2195  * then don't return anything. Otherwise, go through normal permission
2196  * checks.
2197  */
2198  if (check_enable_rls(reloid, InvalidOid, true) == RLS_ENABLED)
2199  return NULL;
2200 
2201  initStringInfo(&buf);
2202 
2203  appendStringInfoChar(&buf, '(');
2204 
2205  /*
2206  * Check if the user has permissions to see the row. Table-level SELECT
2207  * allows access to all columns. If the user does not have table-level
2208  * SELECT then we check each column and include those the user has SELECT
2209  * rights on. Additionally, we always include columns the user provided
2210  * data for.
2211  */
2212  aclresult = pg_class_aclcheck(reloid, GetUserId(), ACL_SELECT);
2213  if (aclresult != ACLCHECK_OK)
2214  {
2215  /* Set up the buffer for the column list */
2216  initStringInfo(&collist);
2217  appendStringInfoChar(&collist, '(');
2218  }
2219  else
2220  table_perm = any_perm = true;
2221 
2222  /* Make sure the tuple is fully deconstructed */
2223  slot_getallattrs(slot);
2224 
2225  for (i = 0; i < tupdesc->natts; i++)
2226  {
2227  bool column_perm = false;
2228  char *val;
2229  int vallen;
2230 
2231  /* ignore dropped columns */
2232  if (tupdesc->attrs[i]->attisdropped)
2233  continue;
2234 
2235  if (!table_perm)
2236  {
2237  /*
2238  * No table-level SELECT, so need to make sure they either have
2239  * SELECT rights on the column or that they have provided the data
2240  * for the column. If not, omit this column from the error
2241  * message.
2242  */
2243  aclresult = pg_attribute_aclcheck(reloid, tupdesc->attrs[i]->attnum,
2244  GetUserId(), ACL_SELECT);
2245  if (bms_is_member(tupdesc->attrs[i]->attnum - FirstLowInvalidHeapAttributeNumber,
2246  modifiedCols) || aclresult == ACLCHECK_OK)
2247  {
2248  column_perm = any_perm = true;
2249 
2250  if (write_comma_collist)
2251  appendStringInfoString(&collist, ", ");
2252  else
2253  write_comma_collist = true;
2254 
2255  appendStringInfoString(&collist, NameStr(tupdesc->attrs[i]->attname));
2256  }
2257  }
2258 
2259  if (table_perm || column_perm)
2260  {
2261  if (slot->tts_isnull[i])
2262  val = "null";
2263  else
2264  {
2265  Oid foutoid;
2266  bool typisvarlena;
2267 
2268  getTypeOutputInfo(tupdesc->attrs[i]->atttypid,
2269  &foutoid, &typisvarlena);
2270  val = OidOutputFunctionCall(foutoid, slot->tts_values[i]);
2271  }
2272 
2273  if (write_comma)
2274  appendStringInfoString(&buf, ", ");
2275  else
2276  write_comma = true;
2277 
2278  /* truncate if needed */
2279  vallen = strlen(val);
2280  if (vallen <= maxfieldlen)
2281  appendStringInfoString(&buf, val);
2282  else
2283  {
2284  vallen = pg_mbcliplen(val, vallen, maxfieldlen);
2285  appendBinaryStringInfo(&buf, val, vallen);
2286  appendStringInfoString(&buf, "...");
2287  }
2288  }
2289  }
2290 
2291  /* If we end up with zero columns being returned, then return NULL. */
2292  if (!any_perm)
2293  return NULL;
2294 
2295  appendStringInfoChar(&buf, ')');
2296 
2297  if (!table_perm)
2298  {
2299  appendStringInfoString(&collist, ") = ");
2300  appendStringInfoString(&collist, buf.data);
2301 
2302  return collist.data;
2303  }
2304 
2305  return buf.data;
2306 }
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:283
Form_pg_attribute * attrs
Definition: tupdesc.h:74
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:831
void appendStringInfoString(StringInfo str, const char *s)
Definition: stringinfo.c:157
static char * buf
Definition: pg_test_fsync.c:66
bool * tts_isnull
Definition: tuptable.h:126
void slot_getallattrs(TupleTableSlot *slot)
Definition: heaptuple.c:1237
void appendStringInfoChar(StringInfo str, char ch)
Definition: stringinfo.c:169
void initStringInfo(StringInfo str)
Definition: stringinfo.c:46
AclResult
Definition: acl.h:170
#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 NULL
Definition: c.h:229
AclResult pg_class_aclcheck(Oid table_oid, Oid roleid, AclMode mode)
Definition: aclchk.c:4422
char * OidOutputFunctionCall(Oid functionId, Datum val)
Definition: fmgr.c:1747
int i
#define NameStr(name)
Definition: c.h:499
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 598 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().

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

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

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

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

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

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

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

766 {
767  ListCell *l;
768 
769  /*
770  * Fail if write permissions are requested in parallel mode for table
771  * (temp or non-temp), otherwise fail for any non-temp table.
772  */
773  foreach(l, plannedstmt->rtable)
774  {
775  RangeTblEntry *rte = (RangeTblEntry *) lfirst(l);
776 
777  if (rte->rtekind != RTE_RELATION)
778  continue;
779 
780  if ((rte->requiredPerms & (~ACL_SELECT)) == 0)
781  continue;
782 
784  continue;
785 
787  }
788 
789  if (plannedstmt->commandType != CMD_SELECT || plannedstmt->hasModifyingCTE)
791 }
void PreventCommandIfParallelMode(const char *cmdname)
Definition: utility.c:254
Oid get_rel_namespace(Oid relid)
Definition: lsyscache.c:1750
Definition: nodes.h:509
AclMode requiredPerms
Definition: parsenodes.h:1020
bool isTempNamespace(Oid namespaceId)
Definition: namespace.c:3075
const char * CreateCommandTag(Node *parsetree)
Definition: utility.c:2035
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:929
void ExecCleanUpTriggerState ( EState estate)

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

1454 {
1455  ListCell *l;
1456 
1457  foreach(l, estate->es_trig_target_relations)
1458  {
1459  ResultRelInfo *resultRelInfo = (ResultRelInfo *) lfirst(l);
1460 
1461  /* Close indices and then the relation itself */
1462  ExecCloseIndices(resultRelInfo);
1463  heap_close(resultRelInfo->ri_RelationDesc, NoLock);
1464  }
1465 }
Relation ri_RelationDesc
Definition: execnodes.h:374
#define heap_close(r, l)
Definition: heapam.h:97
#define NoLock
Definition: lockdefs.h:34
List * es_trig_target_relations
Definition: execnodes.h:436
#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 1886 of file execMain.c.

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

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

1888 {
1889  Relation rel = resultRelInfo->ri_RelationDesc;
1890  TupleDesc tupdesc = RelationGetDescr(rel);
1891  TupleConstr *constr = tupdesc->constr;
1892  Bitmapset *modifiedCols;
1893  Bitmapset *insertedCols;
1894  Bitmapset *updatedCols;
1895 
1896  Assert(constr || resultRelInfo->ri_PartitionCheck);
1897 
1898  if (constr && constr->has_not_null)
1899  {
1900  int natts = tupdesc->natts;
1901  int attrChk;
1902 
1903  for (attrChk = 1; attrChk <= natts; attrChk++)
1904  {
1905  if (tupdesc->attrs[attrChk - 1]->attnotnull &&
1906  slot_attisnull(slot, attrChk))
1907  {
1908  char *val_desc;
1909  Relation orig_rel = rel;
1910  TupleDesc orig_tupdesc = RelationGetDescr(rel);
1911 
1912  /*
1913  * If the tuple has been routed, it's been converted to the
1914  * partition's rowtype, which might differ from the root
1915  * table's. We must convert it back to the root table's
1916  * rowtype so that val_desc shown error message matches the
1917  * input tuple.
1918  */
1919  if (resultRelInfo->ri_PartitionRoot)
1920  {
1921  HeapTuple tuple = ExecFetchSlotTuple(slot);
1922  TupleConversionMap *map;
1923 
1924  rel = resultRelInfo->ri_PartitionRoot;
1925  tupdesc = RelationGetDescr(rel);
1926  /* a reverse map */
1927  map = convert_tuples_by_name(orig_tupdesc, tupdesc,
1928  gettext_noop("could not convert row type"));
1929  if (map != NULL)
1930  {
1931  tuple = do_convert_tuple(tuple, map);
1932  ExecStoreTuple(tuple, slot, InvalidBuffer, false);
1933  }
1934  }
1935 
1936  insertedCols = GetInsertedColumns(resultRelInfo, estate);
1937  updatedCols = GetUpdatedColumns(resultRelInfo, estate);
1938  modifiedCols = bms_union(insertedCols, updatedCols);
1940  slot,
1941  tupdesc,
1942  modifiedCols,
1943  64);
1944 
1945  ereport(ERROR,
1946  (errcode(ERRCODE_NOT_NULL_VIOLATION),
1947  errmsg("null value in column \"%s\" violates not-null constraint",
1948  NameStr(orig_tupdesc->attrs[attrChk - 1]->attname)),
1949  val_desc ? errdetail("Failing row contains %s.", val_desc) : 0,
1950  errtablecol(orig_rel, attrChk)));
1951  }
1952  }
1953  }
1954 
1955  if (constr && constr->num_check > 0)
1956  {
1957  const char *failed;
1958 
1959  if ((failed = ExecRelCheck(resultRelInfo, slot, estate)) != NULL)
1960  {
1961  char *val_desc;
1962  Relation orig_rel = rel;
1963 
1964  /* See the comment above. */
1965  if (resultRelInfo->ri_PartitionRoot)
1966  {
1967  HeapTuple tuple = ExecFetchSlotTuple(slot);
1968  TupleDesc old_tupdesc = RelationGetDescr(rel);
1969  TupleConversionMap *map;
1970 
1971  rel = resultRelInfo->ri_PartitionRoot;
1972  tupdesc = RelationGetDescr(rel);
1973  /* a reverse map */
1974  map = convert_tuples_by_name(old_tupdesc, tupdesc,
1975  gettext_noop("could not convert row type"));
1976  if (map != NULL)
1977  {
1978  tuple = do_convert_tuple(tuple, map);
1979  ExecStoreTuple(tuple, slot, InvalidBuffer, false);
1980  }
1981  }
1982 
1983  insertedCols = GetInsertedColumns(resultRelInfo, estate);
1984  updatedCols = GetUpdatedColumns(resultRelInfo, estate);
1985  modifiedCols = bms_union(insertedCols, updatedCols);
1987  slot,
1988  tupdesc,
1989  modifiedCols,
1990  64);
1991  ereport(ERROR,
1992  (errcode(ERRCODE_CHECK_VIOLATION),
1993  errmsg("new row for relation \"%s\" violates check constraint \"%s\"",
1994  RelationGetRelationName(orig_rel), failed),
1995  val_desc ? errdetail("Failing row contains %s.", val_desc) : 0,
1996  errtableconstraint(orig_rel, failed)));
1997  }
1998  }
1999 
2000  if (resultRelInfo->ri_PartitionCheck &&
2001  !ExecPartitionCheck(resultRelInfo, slot, estate))
2002  {
2003  char *val_desc;
2004  Relation orig_rel = rel;
2005 
2006  /* See the comment above. */
2007  if (resultRelInfo->ri_PartitionRoot)
2008  {
2009  HeapTuple tuple = ExecFetchSlotTuple(slot);
2010  TupleDesc old_tupdesc = RelationGetDescr(rel);
2011  TupleConversionMap *map;
2012 
2013  rel = resultRelInfo->ri_PartitionRoot;
2014  tupdesc = RelationGetDescr(rel);
2015  /* a reverse map */
2016  map = convert_tuples_by_name(old_tupdesc, tupdesc,
2017  gettext_noop("could not convert row type"));
2018  if (map != NULL)
2019  {
2020  tuple = do_convert_tuple(tuple, map);
2021  ExecStoreTuple(tuple, slot, InvalidBuffer, false);
2022  }
2023  }
2024 
2025  insertedCols = GetInsertedColumns(resultRelInfo, estate);
2026  updatedCols = GetUpdatedColumns(resultRelInfo, estate);
2027  modifiedCols = bms_union(insertedCols, updatedCols);
2029  slot,
2030  tupdesc,
2031  modifiedCols,
2032  64);
2033  ereport(ERROR,
2034  (errcode(ERRCODE_CHECK_VIOLATION),
2035  errmsg("new row for relation \"%s\" violates partition constraint",
2036  RelationGetRelationName(orig_rel)),
2037  val_desc ? errdetail("Failing row contains %s.", val_desc) : 0));
2038  }
2039 }
#define GetUpdatedColumns(relinfo, estate)
Definition: execMain.c:115
TupleTableSlot * ExecStoreTuple(HeapTuple tuple, TupleTableSlot *slot, Buffer buffer, bool shouldFree)
Definition: execTuples.c:320
Relation ri_RelationDesc
Definition: execnodes.h:374
#define RelationGetDescr(relation)
Definition: rel.h:429
Relation ri_PartitionRoot
Definition: execnodes.h:394
Form_pg_attribute * attrs
Definition: tupdesc.h:74
#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:5297
static bool ExecPartitionCheck(ResultRelInfo *resultRelInfo, TupleTableSlot *slot, EState *estate)
Definition: execMain.c:1842
#define ERROR
Definition: elog.h:43
static char * ExecBuildSlotValueDescription(Oid reloid, TupleTableSlot *slot, TupleDesc tupdesc, Bitmapset *modifiedCols, int maxfieldlen)
Definition: execMain.c:2178
int errdetail(const char *fmt,...)
Definition: elog.c:873
#define RelationGetRelationName(relation)
Definition: rel.h:437
#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:205
List * ri_PartitionCheck
Definition: execnodes.h:392
static const char * ExecRelCheck(ResultRelInfo *resultRelInfo, TupleTableSlot *slot, EState *estate)
Definition: execMain.c:1778
bool slot_attisnull(TupleTableSlot *slot, int attnum)
Definition: heaptuple.c:1328
#define NULL
Definition: c.h:229
#define Assert(condition)
Definition: c.h:675
int errtablecol(Relation rel, int attnum)
Definition: relcache.c:5260
TupleConstr * constr
Definition: tupdesc.h:76
Bitmapset * bms_union(const Bitmapset *a, const Bitmapset *b)
Definition: bitmapset.c:218
HeapTuple do_convert_tuple(HeapTuple tuple, TupleConversionMap *map)
Definition: tupconvert.c:343
HeapTuple ExecFetchSlotTuple(TupleTableSlot *slot)
Definition: execTuples.c:618
int errmsg(const char *fmt,...)
Definition: elog.c:797
#define NameStr(name)
Definition: c.h:499
uint16 num_check
Definition: tupdesc.h:42
#define RelationGetRelid(relation)
Definition: rel.h:417
#define GetInsertedColumns(relinfo, estate)
Definition: execMain.c:113
bool ExecContextForcesOids ( PlanState planstate,
bool hasoids 
)

Definition at line 1500 of file execMain.c.

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

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

1501 {
1502  ResultRelInfo *ri = planstate->state->es_result_relation_info;
1503 
1504  if (ri != NULL)
1505  {
1506  Relation rel = ri->ri_RelationDesc;
1507 
1508  if (rel != NULL)
1509  {
1510  *hasoids = rel->rd_rel->relhasoids;
1511  return true;
1512  }
1513  }
1514 
1515  if (planstate->state->es_top_eflags & EXEC_FLAG_WITH_OIDS)
1516  {
1517  *hasoids = true;
1518  return true;
1519  }
1520  if (planstate->state->es_top_eflags & EXEC_FLAG_WITHOUT_OIDS)
1521  {
1522  *hasoids = false;
1523  return true;
1524  }
1525 
1526  return false;
1527 }
Relation ri_RelationDesc
Definition: execnodes.h:374
EState * state
Definition: execnodes.h:815
Form_pg_class rd_rel
Definition: rel.h:114
#define EXEC_FLAG_WITHOUT_OIDS
Definition: executor.h:64
#define NULL
Definition: c.h:229
#define EXEC_FLAG_WITH_OIDS
Definition: executor.h:63
int es_top_eflags
Definition: execnodes.h:457
ResultRelInfo * es_result_relation_info
Definition: execnodes.h:423
static void ExecEndPlan ( PlanState planstate,
EState estate 
)
static

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

1583 {
1584  ResultRelInfo *resultRelInfo;
1585  int i;
1586  ListCell *l;
1587 
1588  /*
1589  * shut down the node-type-specific query processing
1590  */
1591  ExecEndNode(planstate);
1592 
1593  /*
1594  * for subplans too
1595  */
1596  foreach(l, estate->es_subplanstates)
1597  {
1598  PlanState *subplanstate = (PlanState *) lfirst(l);
1599 
1600  ExecEndNode(subplanstate);
1601  }
1602 
1603  /*
1604  * destroy the executor's tuple table. Actually we only care about
1605  * releasing buffer pins and tupdesc refcounts; there's no need to pfree
1606  * the TupleTableSlots, since the containing memory context is about to go
1607  * away anyway.
1608  */
1609  ExecResetTupleTable(estate->es_tupleTable, false);
1610 
1611  /*
1612  * close the result relation(s) if any, but hold locks until xact commit.
1613  */
1614  resultRelInfo = estate->es_result_relations;
1615  for (i = estate->es_num_result_relations; i > 0; i--)
1616  {
1617  /* Close indices and then the relation itself */
1618  ExecCloseIndices(resultRelInfo);
1619  heap_close(resultRelInfo->ri_RelationDesc, NoLock);
1620  resultRelInfo++;
1621  }
1622 
1623  /* Close the root target relation(s). */
1624  resultRelInfo = estate->es_root_result_relations;
1625  for (i = estate->es_num_root_result_relations; i > 0; i--)
1626  {
1627  heap_close(resultRelInfo->ri_RelationDesc, NoLock);
1628  resultRelInfo++;
1629  }
1630 
1631  /* likewise close any trigger target relations */
1632  ExecCleanUpTriggerState(estate);
1633 
1634  /*
1635  * close any relations selected FOR [KEY] UPDATE/SHARE, again keeping
1636  * locks
1637  */
1638  foreach(l, estate->es_rowMarks)
1639  {
1640  ExecRowMark *erm = (ExecRowMark *) lfirst(l);
1641 
1642  if (erm->relation)
1643  heap_close(erm->relation, NoLock);
1644  }
1645 }
Relation ri_RelationDesc
Definition: execnodes.h:374
void ExecEndNode(PlanState *node)
Definition: execProcnode.c:654
Relation relation
Definition: execnodes.h:511
#define heap_close(r, l)
Definition: heapam.h:97
#define NoLock
Definition: lockdefs.h:34
ResultRelInfo * es_result_relations
Definition: execnodes.h:421
int es_num_root_result_relations
Definition: execnodes.h:433
List * es_tupleTable
Definition: execnodes.h:450
void ExecResetTupleTable(List *tupleTable, bool shouldFree)
Definition: execTuples.c:156
int es_num_result_relations
Definition: execnodes.h:422
#define lfirst(lc)
Definition: pg_list.h:106
List * es_subplanstates
Definition: execnodes.h:463
List * es_rowMarks
Definition: execnodes.h:452
void ExecCleanUpTriggerState(EState *estate)
Definition: execMain.c:1453
ResultRelInfo * es_root_result_relations
Definition: execnodes.h:432
int i
void ExecCloseIndices(ResultRelInfo *resultRelInfo)
Definition: execIndexing.c:224
int ExecFindPartition ( ResultRelInfo resultRelInfo,
PartitionDispatch pd,
TupleTableSlot slot,
EState estate 
)

Definition at line 3313 of file execMain.c.

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

Referenced by CopyFrom(), and ExecInsert().

3315 {
3316  int result;
3317  PartitionDispatchData *failed_at;
3318  TupleTableSlot *failed_slot;
3319 
3320  result = get_partition_for_tuple(pd, slot, estate,
3321  &failed_at, &failed_slot);
3322  if (result < 0)
3323  {
3324  Relation failed_rel;
3325  Datum key_values[PARTITION_MAX_KEYS];
3326  bool key_isnull[PARTITION_MAX_KEYS];
3327  char *val_desc;
3328  ExprContext *ecxt = GetPerTupleExprContext(estate);
3329 
3330  failed_rel = failed_at->reldesc;
3331  ecxt->ecxt_scantuple = failed_slot;
3332  FormPartitionKeyDatum(failed_at, failed_slot, estate,
3333  key_values, key_isnull);
3334  val_desc = ExecBuildSlotPartitionKeyDescription(failed_rel,
3335  key_values,
3336  key_isnull,
3337  64);
3338  Assert(OidIsValid(RelationGetRelid(failed_rel)));
3339  ereport(ERROR,
3340  (errcode(ERRCODE_CHECK_VIOLATION),
3341  errmsg("no partition of relation \"%s\" found for row",
3342  RelationGetRelationName(failed_rel)),
3343  val_desc ? errdetail("Partition key of the failing row contains %s.", val_desc) : 0));
3344  }
3345 
3346  return result;
3347 }
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:1917
return result
Definition: formatting.c:1632
#define OidIsValid(objectId)
Definition: c.h:538
#define GetPerTupleExprContext(estate)
Definition: executor.h:456
#define ERROR
Definition: elog.h:43
static char * ExecBuildSlotPartitionKeyDescription(Relation rel, Datum *values, bool *isnull, int maxfieldlen)
Definition: execMain.c:3357
void FormPartitionKeyDatum(PartitionDispatch pd, TupleTableSlot *slot, EState *estate, Datum *values, bool *isnull)
Definition: partition.c:1858
int errdetail(const char *fmt,...)
Definition: elog.c:873
#define RelationGetRelationName(relation)
Definition: rel.h:437
#define ereport(elevel, rest)
Definition: elog.h:122
uintptr_t Datum
Definition: postgres.h:372
#define Assert(condition)
Definition: c.h:675
TupleTableSlot * ecxt_scantuple
Definition: execnodes.h:197
int errmsg(const char *fmt,...)
Definition: elog.c:797
#define RelationGetRelid(relation)
Definition: rel.h:417
ExecRowMark* ExecFindRowMark ( EState estate,
Index  rti,
bool  missing_ok 
)

Definition at line 2340 of file execMain.c.

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

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

2341 {
2342  ListCell *lc;
2343 
2344  foreach(lc, estate->es_rowMarks)
2345  {
2346  ExecRowMark *erm = (ExecRowMark *) lfirst(lc);
2347 
2348  if (erm->rti == rti)
2349  return erm;
2350  }
2351  if (!missing_ok)
2352  elog(ERROR, "failed to find ExecRowMark for rangetable index %u", rti);
2353  return NULL;
2354 }
#define ERROR
Definition: elog.h:43
Index rti
Definition: execnodes.h:513
#define NULL
Definition: c.h:229
#define lfirst(lc)
Definition: pg_list.h:106
List * es_rowMarks
Definition: execnodes.h:452
#define elog
Definition: elog.h:219
ResultRelInfo* ExecGetTriggerResultRel ( EState estate,
Oid  relid 
)

Definition at line 1392 of file execMain.c.

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

Referenced by afterTriggerInvokeEvents().

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

Definition at line 1842 of file execMain.c.

References ExprContext::ecxt_scantuple, ExecCheck(), ExecPrepareCheck(), GetPerTupleExprContext, NULL, ResultRelInfo::ri_PartitionCheck, and ResultRelInfo::ri_PartitionCheckExpr.

Referenced by ExecConstraints().

1844 {
1845  ExprContext *econtext;
1846 
1847  /*
1848  * If first time through, build expression state tree for the partition
1849  * check expression. Keep it in the per-query memory context so they'll
1850  * survive throughout the query.
1851  */
1852  if (resultRelInfo->ri_PartitionCheckExpr == NULL)
1853  {
1854  List *qual = resultRelInfo->ri_PartitionCheck;
1855 
1856  resultRelInfo->ri_PartitionCheckExpr = ExecPrepareCheck(qual, estate);
1857  }
1858 
1859  /*
1860  * We will use the EState's per-tuple context for evaluating constraint
1861  * expressions (creating it if it's not already there).
1862  */
1863  econtext = GetPerTupleExprContext(estate);
1864 
1865  /* Arrange for econtext's scan tuple to be the tuple under test */
1866  econtext->ecxt_scantuple = slot;
1867 
1868  /*
1869  * As in case of the catalogued constraints, we treat a NULL result as
1870  * success here, not a failure.
1871  */
1872  return ExecCheck(resultRelInfo->ri_PartitionCheckExpr, econtext);
1873 }
ExprState * ExecPrepareCheck(List *qual, EState *estate)
Definition: execExpr.c:488
ExprState * ri_PartitionCheckExpr
Definition: execnodes.h:393
#define GetPerTupleExprContext(estate)
Definition: executor.h:456
List * ri_PartitionCheck
Definition: execnodes.h:392
#define NULL
Definition: c.h:229
TupleTableSlot * ecxt_scantuple
Definition: execnodes.h:197
bool ExecCheck(ExprState *state, ExprContext *econtext)
Definition: execExpr.c:544
Definition: pg_list.h:45
static void ExecPostprocessPlan ( EState estate)
static

Definition at line 1536 of file execMain.c.

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

Referenced by standard_ExecutorFinish().

1537 {
1538  ListCell *lc;
1539 
1540  /*
1541  * Make sure nodes run forward.
1542  */
1544 
1545  /*
1546  * Run any secondary ModifyTable nodes to completion, in case the main
1547  * query did not fetch all rows from them. (We do this to ensure that
1548  * such nodes have predictable results.)
1549  */
1550  foreach(lc, estate->es_auxmodifytables)
1551  {
1552  PlanState *ps = (PlanState *) lfirst(lc);
1553 
1554  for (;;)
1555  {
1556  TupleTableSlot *slot;
1557 
1558  /* Reset the per-output-tuple exprcontext each time */
1559  ResetPerTupleExprContext(estate);
1560 
1561  slot = ExecProcNode(ps);
1562 
1563  if (TupIsNull(slot))
1564  break;
1565  }
1566  }
1567 }
TupleTableSlot * ExecProcNode(PlanState *node)
Definition: execProcnode.c:398
#define ResetPerTupleExprContext(estate)
Definition: executor.h:465
ScanDirection es_direction
Definition: execnodes.h:408
#define TupIsNull(slot)
Definition: tuptable.h:138
List * es_auxmodifytables
Definition: execnodes.h:465
#define lfirst(lc)
Definition: pg_list.h:106
static const char* ExecRelCheck ( ResultRelInfo resultRelInfo,
TupleTableSlot slot,
EState estate 
)
static

Definition at line 1778 of file execMain.c.

References constrCheck::ccname, tupleConstr::check, tupleDesc::constr, ExprContext::ecxt_scantuple, EState::es_query_cxt, ExecCheck(), ExecPrepareExpr(), GetPerTupleExprContext, i, MemoryContextSwitchTo(), NULL, tupleConstr::num_check, palloc(), RelationData::rd_att, ResultRelInfo::ri_ConstraintExprs, ResultRelInfo::ri_RelationDesc, and stringToNode().

Referenced by ExecConstraints().

1780 {
1781  Relation rel = resultRelInfo->ri_RelationDesc;
1782  int ncheck = rel->rd_att->constr->num_check;
1783  ConstrCheck *check = rel->rd_att->constr->check;
1784  ExprContext *econtext;
1785  MemoryContext oldContext;
1786  int i;
1787 
1788  /*
1789  * If first time through for this result relation, build expression
1790  * nodetrees for rel's constraint expressions. Keep them in the per-query
1791  * memory context so they'll survive throughout the query.
1792  */
1793  if (resultRelInfo->ri_ConstraintExprs == NULL)
1794  {
1795  oldContext = MemoryContextSwitchTo(estate->es_query_cxt);
1796  resultRelInfo->ri_ConstraintExprs =
1797  (ExprState **) palloc(ncheck * sizeof(ExprState *));
1798  for (i = 0; i < ncheck; i++)
1799  {
1800  Expr *checkconstr;
1801 
1802  checkconstr = stringToNode(check[i].ccbin);
1803  resultRelInfo->ri_ConstraintExprs[i] =
1804  ExecPrepareExpr(checkconstr, estate);
1805  }
1806  MemoryContextSwitchTo(oldContext);
1807  }
1808 
1809  /*
1810  * We will use the EState's per-tuple context for evaluating constraint
1811  * expressions (creating it if it's not already there).
1812  */
1813  econtext = GetPerTupleExprContext(estate);
1814 
1815  /* Arrange for econtext's scan tuple to be the tuple under test */
1816  econtext->ecxt_scantuple = slot;
1817 
1818  /* And evaluate the constraints */
1819  for (i = 0; i < ncheck; i++)
1820  {
1821  ExprState *checkconstr = resultRelInfo->ri_ConstraintExprs[i];
1822 
1823  /*
1824  * NOTE: SQL specifies that a NULL result from a constraint expression
1825  * is not to be treated as a failure. Therefore, use ExecCheck not
1826  * ExecQual.
1827  */
1828  if (!ExecCheck(checkconstr, econtext))
1829  return check[i].ccname;
1830  }
1831 
1832  /* NULL result means no error */
1833  return NULL;
1834 }
void * stringToNode(char *str)
Definition: read.c:38
Relation ri_RelationDesc
Definition: execnodes.h:374
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:456
MemoryContext es_query_cxt
Definition: execnodes.h:448
ExprState ** ri_ConstraintExprs
Definition: execnodes.h:387
TupleDesc rd_att
Definition: rel.h:115
#define NULL
Definition: c.h:229
TupleConstr * constr
Definition: tupdesc.h:76
TupleTableSlot * ecxt_scantuple
Definition: execnodes.h:197
void * palloc(Size size)
Definition: mcxt.c:849
int i
bool ExecCheck(ExprState *state, ExprContext *econtext)
Definition: execExpr.c:544
uint16 num_check
Definition: tupdesc.h:42
void ExecSetupPartitionTupleRouting ( Relation  rel,
PartitionDispatch **  pd,
ResultRelInfo **  partitions,
TupleConversionMap ***  tup_conv_maps,
TupleTableSlot **  partition_tuple_slot,
int *  num_parted,
int *  num_partitions 
)

Definition at line 3224 of file execMain.c.

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

Referenced by BeginCopy(), and ExecInitModifyTable().

3230 {
3231  TupleDesc tupDesc = RelationGetDescr(rel);
3232  List *leaf_parts;
3233  ListCell *cell;
3234  int i;
3235  ResultRelInfo *leaf_part_rri;
3236 
3237  /* Get the tuple-routing information and lock partitions */
3238  *pd = RelationGetPartitionDispatchInfo(rel, RowExclusiveLock, num_parted,
3239  &leaf_parts);
3240  *num_partitions = list_length(leaf_parts);
3241  *partitions = (ResultRelInfo *) palloc(*num_partitions *
3242  sizeof(ResultRelInfo));
3243  *tup_conv_maps = (TupleConversionMap **) palloc0(*num_partitions *
3244  sizeof(TupleConversionMap *));
3245 
3246  /*
3247  * Initialize an empty slot that will be used to manipulate tuples of any
3248  * given partition's rowtype. It is attached to the caller-specified node
3249  * (such as ModifyTableState) and released when the node finishes
3250  * processing.
3251  */
3252  *partition_tuple_slot = MakeTupleTableSlot();
3253 
3254  leaf_part_rri = *partitions;
3255  i = 0;
3256  foreach(cell, leaf_parts)
3257  {
3258  Relation partrel;
3259  TupleDesc part_tupdesc;
3260 
3261  /*
3262  * We locked all the partitions above including the leaf partitions.
3263  * Note that each of the relations in *partitions are eventually
3264  * closed by the caller.
3265  */
3266  partrel = heap_open(lfirst_oid(cell), NoLock);
3267  part_tupdesc = RelationGetDescr(partrel);
3268 
3269  /*
3270  * Verify result relation is a valid target for the current operation.
3271  */
3272  CheckValidResultRel(partrel, CMD_INSERT);
3273 
3274  /*
3275  * Save a tuple conversion map to convert a tuple routed to this
3276  * partition from the parent's type to the partition's.
3277  */
3278  (*tup_conv_maps)[i] = convert_tuples_by_name(tupDesc, part_tupdesc,
3279  gettext_noop("could not convert row type"));
3280 
3281  InitResultRelInfo(leaf_part_rri,
3282  partrel,
3283  1, /* dummy */
3284  rel,
3285  0);
3286 
3287  /*
3288  * Open partition indices (remember we do not support ON CONFLICT in
3289  * case of partitioned tables, so we do not need support information
3290  * for speculative insertion)
3291  */
3292  if (leaf_part_rri->ri_RelationDesc->rd_rel->relhasindex &&
3293  leaf_part_rri->ri_IndexRelationDescs == NULL)
3294  ExecOpenIndices(leaf_part_rri, false);
3295 
3296  leaf_part_rri++;
3297  i++;
3298  }
3299 }
void InitResultRelInfo(ResultRelInfo *resultRelInfo, Relation resultRelationDesc, Index resultRelationIndex, Relation partition_root, int instrument_options)
Definition: execMain.c:1297
Relation ri_RelationDesc
Definition: execnodes.h:374
#define RelationGetDescr(relation)
Definition: rel.h:429
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
#define NoLock
Definition: lockdefs.h:34
#define RowExclusiveLock
Definition: lockdefs.h:38
void CheckValidResultRel(Relation resultRel, CmdType operation)
Definition: execMain.c:1097
TupleConversionMap * convert_tuples_by_name(TupleDesc indesc, TupleDesc outdesc, const char *msg)
Definition: tupconvert.c:205
void * palloc0(Size size)
Definition: mcxt.c:878
Relation heap_open(Oid relationId, LOCKMODE lockmode)
Definition: heapam.c:1284
#define NULL
Definition: c.h:229
static int list_length(const List *l)
Definition: pg_list.h:89
PartitionDispatch * RelationGetPartitionDispatchInfo(Relation rel, int lockmode, int *num_parted, List **leaf_part_oids)
Definition: partition.c:1024
void * palloc(Size size)
Definition: mcxt.c:849
int i
Definition: pg_list.h:45
RelationPtr ri_IndexRelationDescs
Definition: execnodes.h:376
#define lfirst_oid(lc)
Definition: pg_list.h:108
LockTupleMode ExecUpdateLockMode ( EState estate,
ResultRelInfo relinfo 
)

Definition at line 2314 of file execMain.c.

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

Referenced by ExecBRUpdateTriggers(), and ExecOnConflictUpdate().

2315 {
2316  Bitmapset *keyCols;
2317  Bitmapset *updatedCols;
2318 
2319  /*
2320  * Compute lock mode to use. If columns that are part of the key have not
2321  * been modified, then we can use a weaker lock, allowing for better
2322  * concurrency.
2323  */
2324  updatedCols = GetUpdatedColumns(relinfo, estate);
2325  keyCols = RelationGetIndexAttrBitmap(relinfo->ri_RelationDesc,
2327 
2328  if (bms_overlap(keyCols, updatedCols))
2329  return LockTupleExclusive;
2330 
2331  return LockTupleNoKeyExclusive;
2332 }
#define GetUpdatedColumns(relinfo, estate)
Definition: execMain.c:115
Relation ri_RelationDesc
Definition: execnodes.h:374
bool bms_overlap(const Bitmapset *a, const Bitmapset *b)
Definition: bitmapset.c:443
Bitmapset * RelationGetIndexAttrBitmap(Relation relation, IndexAttrBitmapKind attrKind)
Definition: relcache.c:4847
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 1660 of file execMain.c.

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

Referenced by standard_ExecutorRun().

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

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

459 {
460  if (ExecutorEnd_hook)
461  (*ExecutorEnd_hook) (queryDesc);
462  else
463  standard_ExecutorEnd(queryDesc);
464 }
void standard_ExecutorEnd(QueryDesc *queryDesc)
Definition: execMain.c:467
ExecutorEnd_hook_type ExecutorEnd_hook
Definition: execMain.c:72
void ExecutorFinish ( QueryDesc queryDesc)

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

399 {
401  (*ExecutorFinish_hook) (queryDesc);
402  else
403  standard_ExecutorFinish(queryDesc);
404 }
void standard_ExecutorFinish(QueryDesc *queryDesc)
Definition: execMain.c:407
ExecutorFinish_hook_type ExecutorFinish_hook
Definition: execMain.c:71
void ExecutorRewind ( QueryDesc queryDesc)

Definition at line 524 of file execMain.c.

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

Referenced by DoPortalRewind(), and PersistHoldablePortal().

525 {
526  EState *estate;
527  MemoryContext oldcontext;
528 
529  /* sanity checks */
530  Assert(queryDesc != NULL);
531 
532  estate = queryDesc->estate;
533 
534  Assert(estate != NULL);
535 
536  /* It's probably not sensible to rescan updating queries */
537  Assert(queryDesc->operation == CMD_SELECT);
538 
539  /*
540  * Switch into per-query memory context
541  */
542  oldcontext = MemoryContextSwitchTo(estate->es_query_cxt);
543 
544  /*
545  * rescan plan
546  */
547  ExecReScan(queryDesc->planstate);
548 
549  MemoryContextSwitchTo(oldcontext);
550 }
EState * estate
Definition: execdesc.h:48
void ExecReScan(PlanState *node)
Definition: execAmi.c:75
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:109
MemoryContext es_query_cxt
Definition: execnodes.h:448
PlanState * planstate
Definition: execdesc.h:49
CmdType operation
Definition: execdesc.h:36
#define NULL
Definition: c.h:229
#define Assert(condition)
Definition: c.h:675
void ExecutorRun ( QueryDesc queryDesc,
ScanDirection  direction,
uint64  count,
bool  execute_once 
)

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

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

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

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

Definition at line 2051 of file execMain.c.

References bms_union(), ExprContext::ecxt_scantuple, elog, ereport, errcode(), errdetail(), errmsg(), ERROR, ExecBuildSlotValueDescription(), ExecQual(), forboth, GetInsertedColumns, GetPerTupleExprContext, GetUpdatedColumns, WithCheckOption::kind, lfirst, NULL, WithCheckOption::polname, RelationGetDescr, RelationGetRelid, WithCheckOption::relname, 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().

2053 {
2054  Relation rel = resultRelInfo->ri_RelationDesc;
2055  TupleDesc tupdesc = RelationGetDescr(rel);
2056  ExprContext *econtext;
2057  ListCell *l1,
2058  *l2;
2059 
2060  /*
2061  * We will use the EState's per-tuple context for evaluating constraint
2062  * expressions (creating it if it's not already there).
2063  */
2064  econtext = GetPerTupleExprContext(estate);
2065 
2066  /* Arrange for econtext's scan tuple to be the tuple under test */
2067  econtext->ecxt_scantuple = slot;
2068 
2069  /* Check each of the constraints */
2070  forboth(l1, resultRelInfo->ri_WithCheckOptions,
2071  l2, resultRelInfo->ri_WithCheckOptionExprs)
2072  {
2073  WithCheckOption *wco = (WithCheckOption *) lfirst(l1);
2074  ExprState *wcoExpr = (ExprState *) lfirst(l2);
2075 
2076  /*
2077  * Skip any WCOs which are not the kind we are looking for at this
2078  * time.
2079  */
2080  if (wco->kind != kind)
2081  continue;
2082 
2083  /*
2084  * WITH CHECK OPTION checks are intended to ensure that the new tuple
2085  * is visible (in the case of a view) or that it passes the
2086  * 'with-check' policy (in the case of row security). If the qual
2087  * evaluates to NULL or FALSE, then the new tuple won't be included in
2088  * the view or doesn't pass the 'with-check' policy for the table.
2089  */
2090  if (!ExecQual(wcoExpr, econtext))
2091  {
2092  char *val_desc;
2093  Bitmapset *modifiedCols;
2094  Bitmapset *insertedCols;
2095  Bitmapset *updatedCols;
2096 
2097  switch (wco->kind)
2098  {
2099  /*
2100  * For WITH CHECK OPTIONs coming from views, we might be
2101  * able to provide the details on the row, depending on
2102  * the permissions on the relation (that is, if the user
2103  * could view it directly anyway). For RLS violations, we
2104  * don't include the data since we don't know if the user
2105  * should be able to view the tuple as as that depends on
2106  * the USING policy.
2107  */
2108  case WCO_VIEW_CHECK:
2109  insertedCols = GetInsertedColumns(resultRelInfo, estate);
2110  updatedCols = GetUpdatedColumns(resultRelInfo, estate);
2111  modifiedCols = bms_union(insertedCols, updatedCols);
2113  slot,
2114  tupdesc,
2115  modifiedCols,
2116  64);
2117 
2118  ereport(ERROR,
2119  (errcode(ERRCODE_WITH_CHECK_OPTION_VIOLATION),
2120  errmsg("new row violates check option for view \"%s\"",
2121  wco->relname),
2122  val_desc ? errdetail("Failing row contains %s.",
2123  val_desc) : 0));
2124  break;
2125  case WCO_RLS_INSERT_CHECK:
2126  case WCO_RLS_UPDATE_CHECK:
2127  if (wco->polname != NULL)
2128  ereport(ERROR,
2129  (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
2130  errmsg("new row violates row-level security policy \"%s\" for table \"%s\"",
2131  wco->polname, wco->relname)));
2132  else
2133  ereport(ERROR,
2134  (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
2135  errmsg("new row violates row-level security policy for table \"%s\"",
2136  wco->relname)));
2137  break;
2139  if (wco->polname != NULL)
2140  ereport(ERROR,
2141  (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
2142  errmsg("new row violates row-level security policy \"%s\" (USING expression) for table \"%s\"",
2143  wco->polname, wco->relname)));
2144  else
2145  ereport(ERROR,
2146  (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
2147  errmsg("new row violates row-level security policy (USING expression) for table \"%s\"",
2148  wco->relname)));
2149  break;
2150  default:
2151  elog(ERROR, "unrecognized WCO kind: %u", wco->kind);
2152  break;
2153  }
2154  }
2155  }
2156 }
#define GetUpdatedColumns(relinfo, estate)
Definition: execMain.c:115
Relation ri_RelationDesc
Definition: execnodes.h:374
#define forboth(cell1, list1, cell2, list2)
Definition: pg_list.h:180
#define RelationGetDescr(relation)
Definition: rel.h:429
int errcode(int sqlerrcode)
Definition: elog.c:575
static bool ExecQual(ExprState *state, ExprContext *econtext)
Definition: executor.h:346
List * ri_WithCheckOptionExprs
Definition: execnodes.h:386
#define GetPerTupleExprContext(estate)
Definition: executor.h:456
#define ERROR
Definition: elog.h:43
static char * ExecBuildSlotValueDescription(Oid reloid, TupleTableSlot *slot, TupleDesc tupdesc, Bitmapset *modifiedCols, int maxfieldlen)
Definition: execMain.c:2178
int errdetail(const char *fmt,...)
Definition: elog.c:873
#define ereport(elevel, rest)
Definition: elog.h:122
List * ri_WithCheckOptions
Definition: execnodes.h:385
#define NULL
Definition: c.h:229
#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
int errmsg(const char *fmt,...)
Definition: elog.c:797
#define elog
Definition: elog.h:219
#define RelationGetRelid(relation)
Definition: rel.h:417
#define GetInsertedColumns(relinfo, estate)
Definition: execMain.c:113
static void InitPlan ( QueryDesc queryDesc,
int  eflags 
)
static

Definition at line 802 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, NULL, 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().

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

Definition at line 1297 of file execMain.c.

References CopyTriggerDesc(), GetFdwRoutineForRelation(), InstrAlloc(), map_partition_varattnos(), MemSet, NIL, NULL, 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().

1302 {
1303  List *partition_check = NIL;
1304 
1305  MemSet(resultRelInfo, 0, sizeof(ResultRelInfo));
1306  resultRelInfo->type = T_ResultRelInfo;
1307  resultRelInfo->ri_RangeTableIndex = resultRelationIndex;
1308  resultRelInfo->ri_RelationDesc = resultRelationDesc;
1309  resultRelInfo->ri_NumIndices = 0;
1310  resultRelInfo->ri_IndexRelationDescs = NULL;
1311  resultRelInfo->ri_IndexRelationInfo = NULL;
1312  /* make a copy so as not to depend on relcache info not changing... */
1313  resultRelInfo->ri_TrigDesc = CopyTriggerDesc(resultRelationDesc->trigdesc);
1314  if (resultRelInfo->ri_TrigDesc)
1315  {
1316  int n = resultRelInfo->ri_TrigDesc->numtriggers;
1317 
1318  resultRelInfo->ri_TrigFunctions = (FmgrInfo *)
1319  palloc0(n * sizeof(FmgrInfo));
1320  resultRelInfo->ri_TrigWhenExprs = (ExprState **)
1321  palloc0(n * sizeof(ExprState *));
1322  if (instrument_options)
1323  resultRelInfo->ri_TrigInstrument = InstrAlloc(n, instrument_options);
1324  }
1325  else
1326  {
1327  resultRelInfo->ri_TrigFunctions = NULL;
1328  resultRelInfo->ri_TrigWhenExprs = NULL;
1329  resultRelInfo->ri_TrigInstrument = NULL;
1330  }
1331  if (resultRelationDesc->rd_rel->relkind == RELKIND_FOREIGN_TABLE)
1332  resultRelInfo->ri_FdwRoutine = GetFdwRoutineForRelation(resultRelationDesc, true);
1333  else
1334  resultRelInfo->ri_FdwRoutine = NULL;
1335  resultRelInfo->ri_FdwState = NULL;
1336  resultRelInfo->ri_usesFdwDirectModify = false;
1337  resultRelInfo->ri_ConstraintExprs = NULL;
1338  resultRelInfo->ri_junkFilter = NULL;
1339  resultRelInfo->ri_projectReturning = NULL;
1340 
1341  /*
1342  * If partition_root has been specified, that means we are building the
1343  * ResultRelInfo for one of its leaf partitions. In that case, we need
1344  * *not* initialize the leaf partition's constraint, but rather the
1345  * partition_root's (if any). We must do that explicitly like this,
1346  * because implicit partition constraints are not inherited like user-
1347  * defined constraints and would fail to be enforced by ExecConstraints()
1348  * after a tuple is routed to a leaf partition.
1349  */
1350  if (partition_root)
1351  {
1352  /*
1353  * Root table itself may or may not be a partition; partition_check
1354  * would be NIL in the latter case.
1355  */
1356  partition_check = RelationGetPartitionQual(partition_root);
1357 
1358  /*
1359  * This is not our own partition constraint, but rather an ancestor's.
1360  * So any Vars in it bear the ancestor's attribute numbers. We must
1361  * switch them to our own. (dummy varno = 1)
1362  */
1363  if (partition_check != NIL)
1364  partition_check = map_partition_varattnos(partition_check, 1,
1365  resultRelationDesc,
1366  partition_root);
1367  }
1368  else
1369  partition_check = RelationGetPartitionQual(resultRelationDesc);
1370 
1371  resultRelInfo->ri_PartitionCheck = partition_check;
1372  resultRelInfo->ri_PartitionRoot = partition_root;
1373 }
int ri_NumIndices
Definition: execnodes.h:375
#define NIL
Definition: pg_list.h:69
JunkFilter * ri_junkFilter
Definition: execnodes.h:388
Definition: fmgr.h:56
Relation ri_RelationDesc
Definition: execnodes.h:374
Relation ri_PartitionRoot
Definition: execnodes.h:394
Instrumentation * ri_TrigInstrument
Definition: execnodes.h:381
Instrumentation * InstrAlloc(int n, int instrument_options)
Definition: instrument.c:30
#define MemSet(start, val, len)
Definition: c.h:857
Form_pg_class rd_rel
Definition: rel.h:114
Index ri_RangeTableIndex
Definition: execnodes.h:373
NodeTag type
Definition: execnodes.h:372
TriggerDesc * trigdesc
Definition: rel.h:120
bool ri_usesFdwDirectModify
Definition: execnodes.h:384
ExprState ** ri_TrigWhenExprs
Definition: execnodes.h:380
ProjectionInfo * ri_projectReturning
Definition: execnodes.h:389
struct FdwRoutine * ri_FdwRoutine
Definition: execnodes.h:382
#define RELKIND_FOREIGN_TABLE
Definition: pg_class.h:167
ExprState ** ri_ConstraintExprs
Definition: execnodes.h:387
TriggerDesc * ri_TrigDesc
Definition: execnodes.h:378
int numtriggers
Definition: reltrigger.h:49
List * RelationGetPartitionQual(Relation rel)
Definition: partition.c:962
void * palloc0(Size size)
Definition: mcxt.c:878
List * ri_PartitionCheck
Definition: execnodes.h:392
void * ri_FdwState
Definition: execnodes.h:383
#define NULL
Definition: c.h:229
TriggerDesc * CopyTriggerDesc(TriggerDesc *trigdesc)
Definition: trigger.c:1852
FdwRoutine * GetFdwRoutineForRelation(Relation relation, bool makecopy)
Definition: foreign.c:395
IndexInfo ** ri_IndexRelationInfo
Definition: execnodes.h:377
Definition: pg_list.h:45
RelationPtr ri_IndexRelationDescs
Definition: execnodes.h:376
FmgrInfo * ri_TrigFunctions
Definition: execnodes.h:379
List * map_partition_varattnos(List *expr, int target_varno, Relation partrel, Relation parent)
Definition: partition.c:932
void standard_ExecutorEnd ( QueryDesc queryDesc)

Definition at line 467 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(), NULL, QueryDesc::planstate, QueryDesc::totaltime, QueryDesc::tupDesc, and UnregisterSnapshot().

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

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

Definition at line 407 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(), NULL, and QueryDesc::totaltime.

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

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

Definition at line 307 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(), NULL, 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().

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

Definition at line 153 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, NULL, 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().

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

Variable Documentation

ExecutorCheckPerms_hook_type ExecutorCheckPerms_hook = NULL

Definition at line 75 of file execMain.c.

Referenced by _PG_init(), and ExecCheckRTPerms().

ExecutorEnd_hook_type ExecutorEnd_hook = NULL

Definition at line 72 of file execMain.c.

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

ExecutorFinish_hook_type ExecutorFinish_hook = NULL

Definition at line 71 of file execMain.c.

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

ExecutorRun_hook_type ExecutorRun_hook = NULL

Definition at line 70 of file execMain.c.

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

ExecutorStart_hook_type ExecutorStart_hook = NULL

Definition at line 69 of file execMain.c.

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