PostgreSQL Source Code  git master
 All Data Structures Namespaces Files Functions Variables Typedefs Enumerations Enumerator Macros
execMain.c File Reference
#include "postgres.h"
#include "access/htup_details.h"
#include "access/sysattr.h"
#include "access/transam.h"
#include "access/xact.h"
#include "catalog/namespace.h"
#include "catalog/partition.h"
#include "catalog/pg_inherits_fn.h"
#include "catalog/pg_publication.h"
#include "commands/matview.h"
#include "commands/trigger.h"
#include "executor/execdebug.h"
#include "foreign/fdwapi.h"
#include "mb/pg_wchar.h"
#include "miscadmin.h"
#include "optimizer/clauses.h"
#include "parser/parsetree.h"
#include "rewrite/rewriteManip.h"
#include "storage/bufmgr.h"
#include "storage/lmgr.h"
#include "tcop/utility.h"
#include "utils/acl.h"
#include "utils/lsyscache.h"
#include "utils/memutils.h"
#include "utils/rls.h"
#include "utils/ruleutils.h"
#include "utils/snapmgr.h"
#include "utils/tqual.h"
Include dependency graph for execMain.c:

Go to the source code of this file.

Macros

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

Functions

static void InitPlan (QueryDesc *queryDesc, int eflags)
 
static void CheckValidRowMarkRel (Relation rel, RowMarkType markType)
 
static void ExecPostprocessPlan (EState *estate)
 
static void ExecEndPlan (PlanState *planstate, EState *estate)
 
static void ExecutePlan (EState *estate, PlanState *planstate, bool use_parallel_mode, CmdType operation, bool sendTuples, uint64 numberTuples, ScanDirection direction, DestReceiver *dest, bool execute_once)
 
static bool ExecCheckRTEPerms (RangeTblEntry *rte)
 
static bool ExecCheckRTEPermsModified (Oid relOid, Oid userid, Bitmapset *modifiedCols, AclMode requiredPerms)
 
static void ExecCheckXactReadOnly (PlannedStmt *plannedstmt)
 
static char * ExecBuildSlotValueDescription (Oid reloid, TupleTableSlot *slot, TupleDesc tupdesc, Bitmapset *modifiedCols, int maxfieldlen)
 
static char * ExecBuildSlotPartitionKeyDescription (Relation rel, Datum *values, bool *isnull, int maxfieldlen)
 
static void EvalPlanQualStart (EPQState *epqstate, EState *parentestate, Plan *planTree)
 
static void ExecPartitionCheck (ResultRelInfo *resultRelInfo, TupleTableSlot *slot, EState *estate)
 
void ExecutorStart (QueryDesc *queryDesc, int eflags)
 
void standard_ExecutorStart (QueryDesc *queryDesc, int eflags)
 
void ExecutorRun (QueryDesc *queryDesc, ScanDirection direction, uint64 count, bool execute_once)
 
void standard_ExecutorRun (QueryDesc *queryDesc, ScanDirection direction, uint64 count, bool execute_once)
 
void ExecutorFinish (QueryDesc *queryDesc)
 
void standard_ExecutorFinish (QueryDesc *queryDesc)
 
void ExecutorEnd (QueryDesc *queryDesc)
 
void standard_ExecutorEnd (QueryDesc *queryDesc)
 
void ExecutorRewind (QueryDesc *queryDesc)
 
bool ExecCheckRTPerms (List *rangeTable, bool ereport_on_violation)
 
void CheckValidResultRel (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)
 
void ExecConstraints (ResultRelInfo *resultRelInfo, TupleTableSlot *slot, EState *estate)
 
void ExecWithCheckOptions (WCOKind kind, ResultRelInfo *resultRelInfo, TupleTableSlot *slot, EState *estate)
 
LockTupleMode ExecUpdateLockMode (EState *estate, ResultRelInfo *relinfo)
 
ExecRowMarkExecFindRowMark (EState *estate, Index rti, bool missing_ok)
 
ExecAuxRowMarkExecBuildAuxRowMark (ExecRowMark *erm, List *targetlist)
 
TupleTableSlotEvalPlanQual (EState *estate, EPQState *epqstate, Relation relation, Index rti, int lockmode, ItemPointer tid, TransactionId priorXmax)
 
HeapTuple EvalPlanQualFetch (EState *estate, Relation relation, int lockmode, LockWaitPolicy wait_policy, ItemPointer tid, TransactionId priorXmax)
 
void EvalPlanQualInit (EPQState *epqstate, EState *estate, Plan *subplan, List *auxrowmarks, int epqParam)
 
void EvalPlanQualSetPlan (EPQState *epqstate, Plan *subplan, List *auxrowmarks)
 
void EvalPlanQualSetTuple (EPQState *epqstate, Index rti, HeapTuple tuple)
 
HeapTuple EvalPlanQualGetTuple (EPQState *epqstate, Index rti)
 
void EvalPlanQualFetchRowMarks (EPQState *epqstate)
 
TupleTableSlotEvalPlanQualNext (EPQState *epqstate)
 
void EvalPlanQualBegin (EPQState *epqstate, EState *parentestate)
 
void EvalPlanQualEnd (EPQState *epqstate)
 
void ExecSetupPartitionTupleRouting (Relation rel, Index resultRTindex, EState *estate, PartitionDispatch **pd, ResultRelInfo **partitions, TupleConversionMap ***tup_conv_maps, TupleTableSlot **partition_tuple_slot, int *num_parted, int *num_partitions)
 
int ExecFindPartition (ResultRelInfo *resultRelInfo, PartitionDispatch *pd, TupleTableSlot *slot, EState *estate)
 

Variables

ExecutorStart_hook_type ExecutorStart_hook = NULL
 
ExecutorRun_hook_type ExecutorRun_hook = NULL
 
ExecutorFinish_hook_type ExecutorFinish_hook = NULL
 
ExecutorEnd_hook_type ExecutorEnd_hook = NULL
 
ExecutorCheckPerms_hook_type ExecutorCheckPerms_hook = NULL
 

Macro Definition Documentation

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

Definition at line 116 of file execMain.c.

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

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

Function Documentation

void CheckValidResultRel ( Relation  resultRel,
CmdType  operation 
)

Definition at line 1100 of file execMain.c.

References CheckCmdReplicaIdentity(), CMD_DELETE, CMD_INSERT, CMD_UPDATE, elog, ereport, errcode(), errhint(), errmsg(), ERROR, FdwRoutine::ExecForeignDelete, FdwRoutine::ExecForeignInsert, FdwRoutine::ExecForeignUpdate, 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().

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

1236 {
1237  FdwRoutine *fdwroutine;
1238 
1239  switch (rel->rd_rel->relkind)
1240  {
1241  case RELKIND_RELATION:
1243  /* OK */
1244  break;
1245  case RELKIND_SEQUENCE:
1246  /* Must disallow this because we don't vacuum sequences */
1247  ereport(ERROR,
1248  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1249  errmsg("cannot lock rows in sequence \"%s\"",
1250  RelationGetRelationName(rel))));
1251  break;
1252  case RELKIND_TOASTVALUE:
1253  /* We could allow this, but there seems no good reason to */
1254  ereport(ERROR,
1255  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1256  errmsg("cannot lock rows in TOAST relation \"%s\"",
1257  RelationGetRelationName(rel))));
1258  break;
1259  case RELKIND_VIEW:
1260  /* Should not get here; planner should have expanded the view */
1261  ereport(ERROR,
1262  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1263  errmsg("cannot lock rows in view \"%s\"",
1264  RelationGetRelationName(rel))));
1265  break;
1266  case RELKIND_MATVIEW:
1267  /* Allow referencing a matview, but not actual locking clauses */
1268  if (markType != ROW_MARK_REFERENCE)
1269  ereport(ERROR,
1270  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1271  errmsg("cannot lock rows in materialized view \"%s\"",
1272  RelationGetRelationName(rel))));
1273  break;
1274  case RELKIND_FOREIGN_TABLE:
1275  /* Okay only if the FDW supports it */
1276  fdwroutine = GetFdwRoutineForRelation(rel, false);
1277  if (fdwroutine->RefetchForeignRow == NULL)
1278  ereport(ERROR,
1279  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1280  errmsg("cannot lock rows in foreign table \"%s\"",
1281  RelationGetRelationName(rel))));
1282  break;
1283  default:
1284  ereport(ERROR,
1285  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1286  errmsg("cannot lock rows in relation \"%s\"",
1287  RelationGetRelationName(rel))));
1288  break;
1289  }
1290 }
#define RELKIND_MATVIEW
Definition: pg_class.h:165
int errcode(int sqlerrcode)
Definition: elog.c:575
Form_pg_class rd_rel
Definition: rel.h:114
#define ERROR
Definition: elog.h:43
#define RelationGetRelationName(relation)
Definition: rel.h:436
#define RELKIND_FOREIGN_TABLE
Definition: pg_class.h:167
#define ereport(elevel, rest)
Definition: elog.h:122
#define RELKIND_PARTITIONED_TABLE
Definition: pg_class.h:168
#define RELKIND_TOASTVALUE
Definition: pg_class.h:163
#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 2469 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().

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

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

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

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

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

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

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

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

Definition at line 2840 of file execMain.c.

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

2841 {
2842  EState *estate = epqstate->estate;
2843 
2844  Assert(rti > 0);
2845 
2846  return estate->es_epqTuple[rti - 1];
2847 }
HeapTuple * es_epqTuple
Definition: execnodes.h:506
#define Assert(condition)
Definition: c.h:676
EState * estate
Definition: execnodes.h:914
void EvalPlanQualInit ( EPQState epqstate,
EState estate,
Plan subplan,
List auxrowmarks,
int  epqParam 
)

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

2787 {
2788  /* Mark the EPQ state inactive */
2789  epqstate->estate = NULL;
2790  epqstate->planstate = NULL;
2791  epqstate->origslot = NULL;
2792  /* ... and remember data that EvalPlanQualBegin will need */
2793  epqstate->plan = subplan;
2794  epqstate->arowMarks = auxrowmarks;
2795  epqstate->epqParam = epqParam;
2796 }
PlanState * planstate
Definition: execnodes.h:915
List * arowMarks
Definition: execnodes.h:918
TupleTableSlot * origslot
Definition: execnodes.h:916
Plan * plan
Definition: execnodes.h:917
#define NULL
Definition: c.h:229
int epqParam
Definition: execnodes.h:919
EState * estate
Definition: execnodes.h:914
TupleTableSlot* EvalPlanQualNext ( EPQState epqstate)

Definition at line 2990 of file execMain.c.

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

Referenced by EvalPlanQual(), and ExecLockRows().

2991 {
2992  MemoryContext oldcontext;
2993  TupleTableSlot *slot;
2994 
2995  oldcontext = MemoryContextSwitchTo(epqstate->estate->es_query_cxt);
2996  slot = ExecProcNode(epqstate->planstate);
2997  MemoryContextSwitchTo(oldcontext);
2998 
2999  return slot;
3000 }
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:109
PlanState * planstate
Definition: execnodes.h:915
MemoryContext es_query_cxt
Definition: execnodes.h:471
static TupleTableSlot * ExecProcNode(PlanState *node)
Definition: executor.h:245
EState * estate
Definition: execnodes.h:914
void EvalPlanQualSetPlan ( EPQState epqstate,
Plan subplan,
List auxrowmarks 
)

Definition at line 2804 of file execMain.c.

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

Referenced by ExecInitModifyTable(), and ExecModifyTable().

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

Definition at line 2820 of file execMain.c.

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

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

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

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

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

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

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

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

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

Definition at line 2212 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(), ExecPartitionCheck(), and ExecWithCheckOptions().

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

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

Referenced by ExecCheckRTPerms().

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

Definition at line 721 of file execMain.c.

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

Referenced by ExecCheckRTEPerms().

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

Definition at line 570 of file execMain.c.

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

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

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

Definition at line 768 of file execMain.c.

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

Referenced by standard_ExecutorStart().

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

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

1461 {
1462  ListCell *l;
1463 
1464  foreach(l, estate->es_trig_target_relations)
1465  {
1466  ResultRelInfo *resultRelInfo = (ResultRelInfo *) lfirst(l);
1467 
1468  /* Close indices and then the relation itself */
1469  ExecCloseIndices(resultRelInfo);
1470  heap_close(resultRelInfo->ri_RelationDesc, NoLock);
1471  }
1472 }
Relation ri_RelationDesc
Definition: execnodes.h:354
#define heap_close(r, l)
Definition: heapam.h:97
#define NoLock
Definition: lockdefs.h:34
List * es_trig_target_relations
Definition: execnodes.h:459
#define lfirst(lc)
Definition: pg_list.h:106
void ExecCloseIndices(ResultRelInfo *resultRelInfo)
Definition: execIndexing.c:224
void ExecConstraints ( ResultRelInfo resultRelInfo,
TupleTableSlot slot,
EState estate 
)

Definition at line 1934 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(), ExecSetSlotDescriptor(), 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().

1936 {
1937  Relation rel = resultRelInfo->ri_RelationDesc;
1938  TupleDesc tupdesc = RelationGetDescr(rel);
1939  TupleConstr *constr = tupdesc->constr;
1940  Bitmapset *modifiedCols;
1941  Bitmapset *insertedCols;
1942  Bitmapset *updatedCols;
1943 
1944  Assert(constr || resultRelInfo->ri_PartitionCheck);
1945 
1946  if (constr && constr->has_not_null)
1947  {
1948  int natts = tupdesc->natts;
1949  int attrChk;
1950 
1951  for (attrChk = 1; attrChk <= natts; attrChk++)
1952  {
1953  if (tupdesc->attrs[attrChk - 1]->attnotnull &&
1954  slot_attisnull(slot, attrChk))
1955  {
1956  char *val_desc;
1957  Relation orig_rel = rel;
1958  TupleDesc orig_tupdesc = RelationGetDescr(rel);
1959 
1960  /*
1961  * If the tuple has been routed, it's been converted to the
1962  * partition's rowtype, which might differ from the root
1963  * table's. We must convert it back to the root table's
1964  * rowtype so that val_desc shown error message matches the
1965  * input tuple.
1966  */
1967  if (resultRelInfo->ri_PartitionRoot)
1968  {
1969  HeapTuple tuple = ExecFetchSlotTuple(slot);
1970  TupleConversionMap *map;
1971 
1972  rel = resultRelInfo->ri_PartitionRoot;
1973  tupdesc = RelationGetDescr(rel);
1974  /* a reverse map */
1975  map = convert_tuples_by_name(orig_tupdesc, tupdesc,
1976  gettext_noop("could not convert row type"));
1977  if (map != NULL)
1978  {
1979  tuple = do_convert_tuple(tuple, map);
1980  ExecSetSlotDescriptor(slot, tupdesc);
1981  ExecStoreTuple(tuple, slot, InvalidBuffer, false);
1982  }
1983  }
1984 
1985  insertedCols = GetInsertedColumns(resultRelInfo, estate);
1986  updatedCols = GetUpdatedColumns(resultRelInfo, estate);
1987  modifiedCols = bms_union(insertedCols, updatedCols);
1989  slot,
1990  tupdesc,
1991  modifiedCols,
1992  64);
1993 
1994  ereport(ERROR,
1995  (errcode(ERRCODE_NOT_NULL_VIOLATION),
1996  errmsg("null value in column \"%s\" violates not-null constraint",
1997  NameStr(orig_tupdesc->attrs[attrChk - 1]->attname)),
1998  val_desc ? errdetail("Failing row contains %s.", val_desc) : 0,
1999  errtablecol(orig_rel, attrChk)));
2000  }
2001  }
2002  }
2003 
2004  if (constr && constr->num_check > 0)
2005  {
2006  const char *failed;
2007 
2008  if ((failed = ExecRelCheck(resultRelInfo, slot, estate)) != NULL)
2009  {
2010  char *val_desc;
2011  Relation orig_rel = rel;
2012 
2013  /* See the comment above. */
2014  if (resultRelInfo->ri_PartitionRoot)
2015  {
2016  HeapTuple tuple = ExecFetchSlotTuple(slot);
2017  TupleDesc old_tupdesc = RelationGetDescr(rel);
2018  TupleConversionMap *map;
2019 
2020  rel = resultRelInfo->ri_PartitionRoot;
2021  tupdesc = RelationGetDescr(rel);
2022  /* a reverse map */
2023  map = convert_tuples_by_name(old_tupdesc, tupdesc,
2024  gettext_noop("could not convert row type"));
2025  if (map != NULL)
2026  {
2027  tuple = do_convert_tuple(tuple, map);
2028  ExecSetSlotDescriptor(slot, tupdesc);
2029  ExecStoreTuple(tuple, slot, InvalidBuffer, false);
2030  }
2031  }
2032 
2033  insertedCols = GetInsertedColumns(resultRelInfo, estate);
2034  updatedCols = GetUpdatedColumns(resultRelInfo, estate);
2035  modifiedCols = bms_union(insertedCols, updatedCols);
2037  slot,
2038  tupdesc,
2039  modifiedCols,
2040  64);
2041  ereport(ERROR,
2042  (errcode(ERRCODE_CHECK_VIOLATION),
2043  errmsg("new row for relation \"%s\" violates check constraint \"%s\"",
2044  RelationGetRelationName(orig_rel), failed),
2045  val_desc ? errdetail("Failing row contains %s.", val_desc) : 0,
2046  errtableconstraint(orig_rel, failed)));
2047  }
2048  }
2049 
2050  if (resultRelInfo->ri_PartitionCheck)
2051  ExecPartitionCheck(resultRelInfo, slot, estate);
2052 }
#define GetUpdatedColumns(relinfo, estate)
Definition: execMain.c:118
TupleTableSlot * ExecStoreTuple(HeapTuple tuple, TupleTableSlot *slot, Buffer buffer, bool shouldFree)
Definition: execTuples.c:320
Relation ri_RelationDesc
Definition: execnodes.h:354
#define RelationGetDescr(relation)
Definition: rel.h:428
Relation ri_PartitionRoot
Definition: execnodes.h:414
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:5303
#define ERROR
Definition: elog.h:43
static char * ExecBuildSlotValueDescription(Oid reloid, TupleTableSlot *slot, TupleDesc tupdesc, Bitmapset *modifiedCols, int maxfieldlen)
Definition: execMain.c:2212
int errdetail(const char *fmt,...)
Definition: elog.c:873
#define RelationGetRelationName(relation)
Definition: rel.h:436
#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
void ExecSetSlotDescriptor(TupleTableSlot *slot, TupleDesc tupdesc)
Definition: execTuples.c:247
List * ri_PartitionCheck
Definition: execnodes.h:408
static const char * ExecRelCheck(ResultRelInfo *resultRelInfo, TupleTableSlot *slot, EState *estate)
Definition: execMain.c:1785
bool slot_attisnull(TupleTableSlot *slot, int attnum)
Definition: heaptuple.c:1328
#define NULL
Definition: c.h:229
#define Assert(condition)
Definition: c.h:676
int errtablecol(Relation rel, int attnum)
Definition: relcache.c:5266
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:416
#define GetInsertedColumns(relinfo, estate)
Definition: execMain.c:116
static void ExecPartitionCheck(ResultRelInfo *resultRelInfo, TupleTableSlot *slot, EState *estate)
Definition: execMain.c:1847
bool ExecContextForcesOids ( PlanState planstate,
bool hasoids 
)

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

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

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

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

Definition at line 3355 of file execMain.c.

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

Referenced by CopyFrom(), and ExecInsert().

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

Definition at line 2374 of file execMain.c.

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

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

2375 {
2376  ListCell *lc;
2377 
2378  foreach(lc, estate->es_rowMarks)
2379  {
2380  ExecRowMark *erm = (ExecRowMark *) lfirst(lc);
2381 
2382  if (erm->rti == rti)
2383  return erm;
2384  }
2385  if (!missing_ok)
2386  elog(ERROR, "failed to find ExecRowMark for rangetable index %u", rti);
2387  return NULL;
2388 }
#define ERROR
Definition: elog.h:43
Index rti
Definition: execnodes.h:536
#define NULL
Definition: c.h:229
#define lfirst(lc)
Definition: pg_list.h:106
List * es_rowMarks
Definition: execnodes.h:475
#define elog
Definition: elog.h:219
ResultRelInfo* ExecGetTriggerResultRel ( EState estate,
Oid  relid 
)

Definition at line 1382 of file execMain.c.

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

Referenced by afterTriggerInvokeEvents().

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

Definition at line 1847 of file execMain.c.

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

Referenced by ExecConstraints(), and ExecFindPartition().

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

Definition at line 1543 of file execMain.c.

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

Referenced by standard_ExecutorFinish().

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

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

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

Definition at line 3258 of file execMain.c.

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

Referenced by CopyFrom(), and ExecInitModifyTable().

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

Definition at line 2348 of file execMain.c.

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

Referenced by ExecBRUpdateTriggers(), and ExecOnConflictUpdate().

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

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

Definition at line 461 of file execMain.c.

References ExecutorEnd_hook, and standard_ExecutorEnd().

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

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

Definition at line 401 of file execMain.c.

References ExecutorFinish_hook, and standard_ExecutorFinish().

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

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

Definition at line 527 of file execMain.c.

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

Referenced by DoPortalRewind(), and PersistHoldablePortal().

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

Definition at line 299 of file execMain.c.

References ExecutorRun_hook, and standard_ExecutorRun().

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

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

Definition at line 147 of file execMain.c.

References ExecutorStart_hook, and standard_ExecutorStart().

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

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

Definition at line 2065 of file execMain.c.

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

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

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

Definition at line 805 of file execMain.c.

References AccessShareLock, Assert, bms_is_member(), CheckValidRowMarkRel(), CMD_SELECT, ExecRowMark::curCtid, elog, ExecRowMark::ermActive, ExecRowMark::ermExtra, ERROR, EState::es_epqScanDone, EState::es_epqTuple, EState::es_epqTupleSet, EState::es_instrument, EState::es_junkFilter, EState::es_num_result_relations, EState::es_num_root_result_relations, EState::es_plannedstmt, EState::es_range_table, EState::es_result_relation_info, EState::es_result_relations, EState::es_root_result_relations, EState::es_rowMarks, EState::es_subplanstates, EState::es_trig_newtup_slot, EState::es_trig_oldtup_slot, EState::es_trig_tuple_slot, EState::es_tupleTable, QueryDesc::estate, EXEC_FLAG_EXPLAIN_ONLY, EXEC_FLAG_REWIND, EXEC_FLAG_WITH_NO_DATA, ExecCheckRTPerms(), ExecGetResultType(), ExecInitExtraTupleSlot(), ExecInitJunkFilter(), ExecInitNode(), getrelid, heap_open(), i, InitResultRelInfo(), PlanRowMark::isParent, ItemPointerSetInvalid, JunkFilter::jf_cleanTupType, lappend(), lfirst, lfirst_int, list_length(), list_member_int(), LockRelationOid(), ExecRowMark::markType, PlanRowMark::markType, NIL, PlannedStmt::nonleafResultRelations, 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().

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

Definition at line 1300 of file execMain.c.

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

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

Definition at line 470 of file execMain.c.

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

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

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

Definition at line 410 of file execMain.c.

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

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

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

Definition at line 310 of file execMain.c.

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

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

Definition at line 156 of file execMain.c.

References AfterTriggerBeginQuery(), Assert, CMD_DELETE, CMD_INSERT, CMD_SELECT, CMD_UPDATE, CreateExecutorState(), QueryDesc::crosscheck_snapshot, elog, ERROR, EState::es_crosscheck_snapshot, EState::es_instrument, EState::es_output_cid, EState::es_param_exec_vals, EState::es_param_list_info, EState::es_query_cxt, EState::es_queryEnv, EState::es_snapshot, EState::es_sourceText, EState::es_top_eflags, QueryDesc::estate, EXEC_FLAG_EXPLAIN_ONLY, EXEC_FLAG_SKIP_TRIGGERS, ExecCheckXactReadOnly(), GetCurrentCommandId(), PlannedStmt::hasModifyingCTE, InitPlan(), QueryDesc::instrument_options, IsInParallelMode(), MemoryContextSwitchTo(), NIL, PlannedStmt::nParamExec, 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().

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

Variable Documentation

ExecutorCheckPerms_hook_type ExecutorCheckPerms_hook = NULL

Definition at line 76 of file execMain.c.

Referenced by _PG_init(), and ExecCheckRTPerms().

ExecutorEnd_hook_type ExecutorEnd_hook = NULL

Definition at line 73 of file execMain.c.

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

ExecutorFinish_hook_type ExecutorFinish_hook = NULL

Definition at line 72 of file execMain.c.

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

ExecutorRun_hook_type ExecutorRun_hook = NULL

Definition at line 71 of file execMain.c.

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

ExecutorStart_hook_type ExecutorStart_hook = NULL

Definition at line 70 of file execMain.c.

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