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

Go to the source code of this file.

Macros

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

Functions

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

Variables

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

Macro Definition Documentation

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

Definition at line 113 of file execMain.c.

Referenced by ExecConstraints(), and ExecWithCheckOptions().

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

Definition at line 115 of file execMain.c.

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

Function Documentation

void CheckValidResultRel ( Relation  resultRel,
CmdType  operation 
)

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

1061 {
1062  TriggerDesc *trigDesc = resultRel->trigdesc;
1063  FdwRoutine *fdwroutine;
1064 
1065  switch (resultRel->rd_rel->relkind)
1066  {
1067  case RELKIND_RELATION:
1069  CheckCmdReplicaIdentity(resultRel, operation);
1070  break;
1071  case RELKIND_SEQUENCE:
1072  ereport(ERROR,
1073  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1074  errmsg("cannot change sequence \"%s\"",
1075  RelationGetRelationName(resultRel))));
1076  break;
1077  case RELKIND_TOASTVALUE:
1078  ereport(ERROR,
1079  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1080  errmsg("cannot change TOAST relation \"%s\"",
1081  RelationGetRelationName(resultRel))));
1082  break;
1083  case RELKIND_VIEW:
1084 
1085  /*
1086  * Okay only if there's a suitable INSTEAD OF trigger. Messages
1087  * here should match rewriteHandler.c's rewriteTargetView, except
1088  * that we omit errdetail because we haven't got the information
1089  * handy (and given that we really shouldn't get here anyway, it's
1090  * not worth great exertion to get).
1091  */
1092  switch (operation)
1093  {
1094  case CMD_INSERT:
1095  if (!trigDesc || !trigDesc->trig_insert_instead_row)
1096  ereport(ERROR,
1097  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
1098  errmsg("cannot insert into view \"%s\"",
1099  RelationGetRelationName(resultRel)),
1100  errhint("To enable inserting into the view, provide an INSTEAD OF INSERT trigger or an unconditional ON INSERT DO INSTEAD rule.")));
1101  break;
1102  case CMD_UPDATE:
1103  if (!trigDesc || !trigDesc->trig_update_instead_row)
1104  ereport(ERROR,
1105  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
1106  errmsg("cannot update view \"%s\"",
1107  RelationGetRelationName(resultRel)),
1108  errhint("To enable updating the view, provide an INSTEAD OF UPDATE trigger or an unconditional ON UPDATE DO INSTEAD rule.")));
1109  break;
1110  case CMD_DELETE:
1111  if (!trigDesc || !trigDesc->trig_delete_instead_row)
1112  ereport(ERROR,
1113  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
1114  errmsg("cannot delete from view \"%s\"",
1115  RelationGetRelationName(resultRel)),
1116  errhint("To enable deleting from the view, provide an INSTEAD OF DELETE trigger or an unconditional ON DELETE DO INSTEAD rule.")));
1117  break;
1118  default:
1119  elog(ERROR, "unrecognized CmdType: %d", (int) operation);
1120  break;
1121  }
1122  break;
1123  case RELKIND_MATVIEW:
1125  ereport(ERROR,
1126  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1127  errmsg("cannot change materialized view \"%s\"",
1128  RelationGetRelationName(resultRel))));
1129  break;
1130  case RELKIND_FOREIGN_TABLE:
1131  /* Okay only if the FDW supports it */
1132  fdwroutine = GetFdwRoutineForRelation(resultRel, false);
1133  switch (operation)
1134  {
1135  case CMD_INSERT:
1136  if (fdwroutine->ExecForeignInsert == NULL)
1137  ereport(ERROR,
1138  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1139  errmsg("cannot insert into foreign table \"%s\"",
1140  RelationGetRelationName(resultRel))));
1141  if (fdwroutine->IsForeignRelUpdatable != NULL &&
1142  (fdwroutine->IsForeignRelUpdatable(resultRel) & (1 << CMD_INSERT)) == 0)
1143  ereport(ERROR,
1144  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
1145  errmsg("foreign table \"%s\" does not allow inserts",
1146  RelationGetRelationName(resultRel))));
1147  break;
1148  case CMD_UPDATE:
1149  if (fdwroutine->ExecForeignUpdate == NULL)
1150  ereport(ERROR,
1151  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1152  errmsg("cannot update foreign table \"%s\"",
1153  RelationGetRelationName(resultRel))));
1154  if (fdwroutine->IsForeignRelUpdatable != NULL &&
1155  (fdwroutine->IsForeignRelUpdatable(resultRel) & (1 << CMD_UPDATE)) == 0)
1156  ereport(ERROR,
1157  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
1158  errmsg("foreign table \"%s\" does not allow updates",
1159  RelationGetRelationName(resultRel))));
1160  break;
1161  case CMD_DELETE:
1162  if (fdwroutine->ExecForeignDelete == NULL)
1163  ereport(ERROR,
1164  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1165  errmsg("cannot delete from foreign table \"%s\"",
1166  RelationGetRelationName(resultRel))));
1167  if (fdwroutine->IsForeignRelUpdatable != NULL &&
1168  (fdwroutine->IsForeignRelUpdatable(resultRel) & (1 << CMD_DELETE)) == 0)
1169  ereport(ERROR,
1170  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
1171  errmsg("foreign table \"%s\" does not allow deletes",
1172  RelationGetRelationName(resultRel))));
1173  break;
1174  default:
1175  elog(ERROR, "unrecognized CmdType: %d", (int) operation);
1176  break;
1177  }
1178  break;
1179  default:
1180  ereport(ERROR,
1181  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1182  errmsg("cannot change relation \"%s\"",
1183  RelationGetRelationName(resultRel))));
1184  break;
1185  }
1186 }
ExecForeignDelete_function ExecForeignDelete
Definition: fdwapi.h:199
int errhint(const char *fmt,...)
Definition: elog.c:987
bool MatViewIncrementalMaintenanceIsEnabled(void)
Definition: matview.c:860
ExecForeignInsert_function ExecForeignInsert
Definition: fdwapi.h:197
#define RELKIND_MATVIEW
Definition: pg_class.h:165
int errcode(int sqlerrcode)
Definition: elog.c:575
Form_pg_class rd_rel
Definition: rel.h:114
bool trig_insert_instead_row
Definition: reltrigger.h:57
#define ERROR
Definition: elog.h:43
TriggerDesc * trigdesc
Definition: rel.h:120
#define RelationGetRelationName(relation)
Definition: rel.h:437
#define RELKIND_FOREIGN_TABLE
Definition: pg_class.h:167
void CheckCmdReplicaIdentity(Relation rel, CmdType cmd)
#define ereport(elevel, rest)
Definition: elog.h:122
bool trig_update_instead_row
Definition: reltrigger.h:62
#define RELKIND_PARTITIONED_TABLE
Definition: pg_class.h:168
bool trig_delete_instead_row
Definition: reltrigger.h:67
#define RELKIND_TOASTVALUE
Definition: pg_class.h:163
ExecForeignUpdate_function ExecForeignUpdate
Definition: fdwapi.h:198
#define NULL
Definition: c.h:229
int errmsg(const char *fmt,...)
Definition: elog.c:797
FdwRoutine * GetFdwRoutineForRelation(Relation relation, bool makecopy)
Definition: foreign.c:395
#define RELKIND_VIEW
Definition: pg_class.h:164
IsForeignRelUpdatable_function IsForeignRelUpdatable
Definition: fdwapi.h:201
#define elog
Definition: elog.h:219
#define RELKIND_RELATION
Definition: pg_class.h:160
#define RELKIND_SEQUENCE
Definition: pg_class.h:162
static void CheckValidRowMarkRel ( Relation  rel,
RowMarkType  markType 
)
static

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

1196 {
1197  FdwRoutine *fdwroutine;
1198 
1199  switch (rel->rd_rel->relkind)
1200  {
1201  case RELKIND_RELATION:
1203  /* OK */
1204  break;
1205  case RELKIND_SEQUENCE:
1206  /* Must disallow this because we don't vacuum sequences */
1207  ereport(ERROR,
1208  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1209  errmsg("cannot lock rows in sequence \"%s\"",
1210  RelationGetRelationName(rel))));
1211  break;
1212  case RELKIND_TOASTVALUE:
1213  /* We could allow this, but there seems no good reason to */
1214  ereport(ERROR,
1215  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1216  errmsg("cannot lock rows in TOAST relation \"%s\"",
1217  RelationGetRelationName(rel))));
1218  break;
1219  case RELKIND_VIEW:
1220  /* Should not get here; planner should have expanded the view */
1221  ereport(ERROR,
1222  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1223  errmsg("cannot lock rows in view \"%s\"",
1224  RelationGetRelationName(rel))));
1225  break;
1226  case RELKIND_MATVIEW:
1227  /* Allow referencing a matview, but not actual locking clauses */
1228  if (markType != ROW_MARK_REFERENCE)
1229  ereport(ERROR,
1230  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1231  errmsg("cannot lock rows in materialized view \"%s\"",
1232  RelationGetRelationName(rel))));
1233  break;
1234  case RELKIND_FOREIGN_TABLE:
1235  /* Okay only if the FDW supports it */
1236  fdwroutine = GetFdwRoutineForRelation(rel, false);
1237  if (fdwroutine->RefetchForeignRow == NULL)
1238  ereport(ERROR,
1239  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1240  errmsg("cannot lock rows in foreign table \"%s\"",
1241  RelationGetRelationName(rel))));
1242  break;
1243  default:
1244  ereport(ERROR,
1245  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1246  errmsg("cannot lock rows in relation \"%s\"",
1247  RelationGetRelationName(rel))));
1248  break;
1249  }
1250 }
#define RELKIND_MATVIEW
Definition: pg_class.h:165
int errcode(int sqlerrcode)
Definition: elog.c:575
Form_pg_class rd_rel
Definition: rel.h:114
#define ERROR
Definition: elog.h:43
#define RelationGetRelationName(relation)
Definition: rel.h:437
#define RELKIND_FOREIGN_TABLE
Definition: pg_class.h:167
#define ereport(elevel, rest)
Definition: elog.h:122
#define RELKIND_PARTITIONED_TABLE
Definition: pg_class.h:168
#define RELKIND_TOASTVALUE
Definition: pg_class.h:163
#define NULL
Definition: c.h:229
int errmsg(const char *fmt,...)
Definition: elog.c:797
FdwRoutine * GetFdwRoutineForRelation(Relation relation, bool makecopy)
Definition: foreign.c:395
#define RELKIND_VIEW
Definition: pg_class.h:164
#define RELKIND_RELATION
Definition: pg_class.h:160
#define RELKIND_SEQUENCE
Definition: pg_class.h:162
RefetchForeignRow_function RefetchForeignRow
Definition: fdwapi.h:209
TupleTableSlot* EvalPlanQual ( EState estate,
EPQState epqstate,
Relation  relation,
Index  rti,
int  lockmode,
ItemPointer  tid,
TransactionId  priorXmax 
)

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

2383 {
2384  TupleTableSlot *slot;
2385  HeapTuple copyTuple;
2386 
2387  Assert(rti > 0);
2388 
2389  /*
2390  * Get and lock the updated version of the row; if fail, return NULL.
2391  */
2392  copyTuple = EvalPlanQualFetch(estate, relation, lockmode, LockWaitBlock,
2393  tid, priorXmax);
2394 
2395  if (copyTuple == NULL)
2396  return NULL;
2397 
2398  /*
2399  * For UPDATE/DELETE we have to return tid of actual row we're executing
2400  * PQ for.
2401  */
2402  *tid = copyTuple->t_self;
2403 
2404  /*
2405  * Need to run a recheck subquery. Initialize or reinitialize EPQ state.
2406  */
2407  EvalPlanQualBegin(epqstate, estate);
2408 
2409  /*
2410  * Free old test tuple, if any, and store new tuple where relation's scan
2411  * node will see it
2412  */
2413  EvalPlanQualSetTuple(epqstate, rti, copyTuple);
2414 
2415  /*
2416  * Fetch any non-locked source rows
2417  */
2418  EvalPlanQualFetchRowMarks(epqstate);
2419 
2420  /*
2421  * Run the EPQ query. We assume it will return at most one tuple.
2422  */
2423  slot = EvalPlanQualNext(epqstate);
2424 
2425  /*
2426  * If we got a tuple, force the slot to materialize the tuple so that it
2427  * is not dependent on any local state in the EPQ query (in particular,
2428  * it's highly likely that the slot contains references to any pass-by-ref
2429  * datums that may be present in copyTuple). As with the next step, this
2430  * is to guard against early re-use of the EPQ query.
2431  */
2432  if (!TupIsNull(slot))
2433  (void) ExecMaterializeSlot(slot);
2434 
2435  /*
2436  * Clear out the test tuple. This is needed in case the EPQ query is
2437  * re-used to test a tuple for a different relation. (Not clear that can
2438  * really happen, but let's be safe.)
2439  */
2440  EvalPlanQualSetTuple(epqstate, rti, NULL);
2441 
2442  return slot;
2443 }
void EvalPlanQualSetTuple(EPQState *epqstate, Index rti, HeapTuple tuple)
Definition: execMain.c:2731
HeapTuple EvalPlanQualFetch(EState *estate, Relation relation, int lockmode, LockWaitPolicy wait_policy, ItemPointer tid, TransactionId priorXmax)
Definition: execMain.c:2467
void EvalPlanQualFetchRowMarks(EPQState *epqstate)
Definition: execMain.c:2766
void EvalPlanQualBegin(EPQState *epqstate, EState *parentestate)
Definition: execMain.c:2917
TupleTableSlot * EvalPlanQualNext(EPQState *epqstate)
Definition: execMain.c:2901
ItemPointerData t_self
Definition: htup.h:65
#define TupIsNull(slot)
Definition: tuptable.h:138
#define NULL
Definition: c.h:229
#define Assert(condition)
Definition: c.h:675
HeapTuple ExecMaterializeSlot(TupleTableSlot *slot)
Definition: execTuples.c:725
void EvalPlanQualBegin ( EPQState epqstate,
EState parentestate 
)

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

2918 {
2919  EState *estate = epqstate->estate;
2920 
2921  if (estate == NULL)
2922  {
2923  /* First time through, so create a child EState */
2924  EvalPlanQualStart(epqstate, parentestate, epqstate->plan);
2925  }
2926  else
2927  {
2928  /*
2929  * We already have a suitable child EPQ tree, so just reset it.
2930  */
2931  int rtsize = list_length(parentestate->es_range_table);
2932  PlanState *planstate = epqstate->planstate;
2933 
2934  MemSet(estate->es_epqScanDone, 0, rtsize * sizeof(bool));
2935 
2936  /* Recopy current values of parent parameters */
2937  if (parentestate->es_plannedstmt->nParamExec > 0)
2938  {
2939  int i = parentestate->es_plannedstmt->nParamExec;
2940 
2941  while (--i >= 0)
2942  {
2943  /* copy value if any, but not execPlan link */
2944  estate->es_param_exec_vals[i].value =
2945  parentestate->es_param_exec_vals[i].value;
2946  estate->es_param_exec_vals[i].isnull =
2947  parentestate->es_param_exec_vals[i].isnull;
2948  }
2949  }
2950 
2951  /*
2952  * Mark child plan tree as needing rescan at all scan nodes. The
2953  * first ExecProcNode will take care of actually doing the rescan.
2954  */
2955  planstate->chgParam = bms_add_member(planstate->chgParam,
2956  epqstate->epqParam);
2957  }
2958 }
PlannedStmt * es_plannedstmt
Definition: execnodes.h:412
#define MemSet(start, val, len)
Definition: c.h:857
List * es_range_table
Definition: execnodes.h:411
PlanState * planstate
Definition: execnodes.h:867
int nParamExec
Definition: plannodes.h:82
ParamExecData * es_param_exec_vals
Definition: execnodes.h:433
bool isnull
Definition: params.h:101
static void EvalPlanQualStart(EPQState *epqstate, EState *parentestate, Plan *planTree)
Definition: execMain.c:2967
Bitmapset * chgParam
Definition: execnodes.h:827
Plan * plan
Definition: execnodes.h:869
#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:475
Datum value
Definition: params.h:100
int epqParam
Definition: execnodes.h:871
EState * estate
Definition: execnodes.h:866
void EvalPlanQualEnd ( EPQState epqstate)

Definition at line 3107 of file execMain.c.

References EState::es_query_cxt, EState::es_subplanstates, EState::es_trig_target_relations, EState::es_tupleTable, EPQState::estate, ExecCloseIndices(), ExecEndNode(), ExecResetTupleTable(), FreeExecutorState(), heap_close, lfirst, MemoryContextSwitchTo(), NoLock, NULL, EPQState::origslot, EPQState::planstate, and ResultRelInfo::ri_RelationDesc.

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

3108 {
3109  EState *estate = epqstate->estate;
3110  MemoryContext oldcontext;
3111  ListCell *l;
3112 
3113  if (estate == NULL)
3114  return; /* idle, so nothing to do */
3115 
3116  oldcontext = MemoryContextSwitchTo(estate->es_query_cxt);
3117 
3118  ExecEndNode(epqstate->planstate);
3119 
3120  foreach(l, estate->es_subplanstates)
3121  {
3122  PlanState *subplanstate = (PlanState *) lfirst(l);
3123 
3124  ExecEndNode(subplanstate);
3125  }
3126 
3127  /* throw away the per-estate tuple table */
3128  ExecResetTupleTable(estate->es_tupleTable, false);
3129 
3130  /* close any trigger target relations attached to this EState */
3131  foreach(l, estate->es_trig_target_relations)
3132  {
3133  ResultRelInfo *resultRelInfo = (ResultRelInfo *) lfirst(l);
3134 
3135  /* Close indices and then the relation itself */
3136  ExecCloseIndices(resultRelInfo);
3137  heap_close(resultRelInfo->ri_RelationDesc, NoLock);
3138  }
3139 
3140  MemoryContextSwitchTo(oldcontext);
3141 
3142  FreeExecutorState(estate);
3143 
3144  /* Mark EPQState idle */
3145  epqstate->estate = NULL;
3146  epqstate->planstate = NULL;
3147  epqstate->origslot = NULL;
3148 }
Relation ri_RelationDesc
Definition: execnodes.h:374
void ExecEndNode(PlanState *node)
Definition: execProcnode.c:654
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:109
#define heap_close(r, l)
Definition: heapam.h:97
PlanState * planstate
Definition: execnodes.h:867
void FreeExecutorState(EState *estate)
Definition: execUtils.c:178
MemoryContext es_query_cxt
Definition: execnodes.h:438
#define NoLock
Definition: lockdefs.h:34
TupleTableSlot * origslot
Definition: execnodes.h:868
List * es_trig_target_relations
Definition: execnodes.h:426
List * es_tupleTable
Definition: execnodes.h:440
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:453
EState * estate
Definition: execnodes.h:866
void ExecCloseIndices(ResultRelInfo *resultRelInfo)
Definition: execIndexing.c:224
HeapTuple EvalPlanQualFetch ( EState estate,
Relation  relation,
int  lockmode,
LockWaitPolicy  wait_policy,
ItemPointer  tid,
TransactionId  priorXmax 
)

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

2470 {
2471  HeapTuple copyTuple = NULL;
2472  HeapTupleData tuple;
2473  SnapshotData SnapshotDirty;
2474 
2475  /*
2476  * fetch target tuple
2477  *
2478  * Loop here to deal with updated or busy tuples
2479  */
2480  InitDirtySnapshot(SnapshotDirty);
2481  tuple.t_self = *tid;
2482  for (;;)
2483  {
2484  Buffer buffer;
2485 
2486  if (heap_fetch(relation, &SnapshotDirty, &tuple, &buffer, true, NULL))
2487  {
2488  HTSU_Result test;
2489  HeapUpdateFailureData hufd;
2490 
2491  /*
2492  * If xmin isn't what we're expecting, the slot must have been
2493  * recycled and reused for an unrelated tuple. This implies that
2494  * the latest version of the row was deleted, so we need do
2495  * nothing. (Should be safe to examine xmin without getting
2496  * buffer's content lock. We assume reading a TransactionId to be
2497  * atomic, and Xmin never changes in an existing tuple, except to
2498  * invalid or frozen, and neither of those can match priorXmax.)
2499  */
2501  priorXmax))
2502  {
2503  ReleaseBuffer(buffer);
2504  return NULL;
2505  }
2506 
2507  /* otherwise xmin should not be dirty... */
2508  if (TransactionIdIsValid(SnapshotDirty.xmin))
2509  elog(ERROR, "t_xmin is uncommitted in tuple to be updated");
2510 
2511  /*
2512  * If tuple is being updated by other transaction then we have to
2513  * wait for its commit/abort, or die trying.
2514  */
2515  if (TransactionIdIsValid(SnapshotDirty.xmax))
2516  {
2517  ReleaseBuffer(buffer);
2518  switch (wait_policy)
2519  {
2520  case LockWaitBlock:
2521  XactLockTableWait(SnapshotDirty.xmax,
2522  relation, &tuple.t_self,
2524  break;
2525  case LockWaitSkip:
2526  if (!ConditionalXactLockTableWait(SnapshotDirty.xmax))
2527  return NULL; /* skip instead of waiting */
2528  break;
2529  case LockWaitError:
2530  if (!ConditionalXactLockTableWait(SnapshotDirty.xmax))
2531  ereport(ERROR,
2532  (errcode(ERRCODE_LOCK_NOT_AVAILABLE),
2533  errmsg("could not obtain lock on row in relation \"%s\"",
2534  RelationGetRelationName(relation))));
2535  break;
2536  }
2537  continue; /* loop back to repeat heap_fetch */
2538  }
2539 
2540  /*
2541  * If tuple was inserted by our own transaction, we have to check
2542  * cmin against es_output_cid: cmin >= current CID means our
2543  * command cannot see the tuple, so we should ignore it. Otherwise
2544  * heap_lock_tuple() will throw an error, and so would any later
2545  * attempt to update or delete the tuple. (We need not check cmax
2546  * because HeapTupleSatisfiesDirty will consider a tuple deleted
2547  * by our transaction dead, regardless of cmax.) We just checked
2548  * that priorXmax == xmin, so we can test that variable instead of
2549  * doing HeapTupleHeaderGetXmin again.
2550  */
2551  if (TransactionIdIsCurrentTransactionId(priorXmax) &&
2552  HeapTupleHeaderGetCmin(tuple.t_data) >= estate->es_output_cid)
2553  {
2554  ReleaseBuffer(buffer);
2555  return NULL;
2556  }
2557 
2558  /*
2559  * This is a live tuple, so now try to lock it.
2560  */
2561  test = heap_lock_tuple(relation, &tuple,
2562  estate->es_output_cid,
2563  lockmode, wait_policy,
2564  false, &buffer, &hufd);
2565  /* We now have two pins on the buffer, get rid of one */
2566  ReleaseBuffer(buffer);
2567 
2568  switch (test)
2569  {
2570  case HeapTupleSelfUpdated:
2571 
2572  /*
2573  * The target tuple was already updated or deleted by the
2574  * current command, or by a later command in the current
2575  * transaction. We *must* ignore the tuple in the former
2576  * case, so as to avoid the "Halloween problem" of
2577  * repeated update attempts. In the latter case it might
2578  * be sensible to fetch the updated tuple instead, but
2579  * doing so would require changing heap_update and
2580  * heap_delete to not complain about updating "invisible"
2581  * tuples, which seems pretty scary (heap_lock_tuple will
2582  * not complain, but few callers expect
2583  * HeapTupleInvisible, and we're not one of them). So for
2584  * now, treat the tuple as deleted and do not process.
2585  */
2586  ReleaseBuffer(buffer);
2587  return NULL;
2588 
2589  case HeapTupleMayBeUpdated:
2590  /* successfully locked */
2591  break;
2592 
2593  case HeapTupleUpdated:
2594  ReleaseBuffer(buffer);
2596  ereport(ERROR,
2597  (errcode(ERRCODE_T_R_SERIALIZATION_FAILURE),
2598  errmsg("could not serialize access due to concurrent update")));
2599 
2600  /* Should not encounter speculative tuple on recheck */
2602  if (!ItemPointerEquals(&hufd.ctid, &tuple.t_self))
2603  {
2604  /* it was updated, so look at the updated version */
2605  tuple.t_self = hufd.ctid;
2606  /* updated row should have xmin matching this xmax */
2607  priorXmax = hufd.xmax;
2608  continue;
2609  }
2610  /* tuple was deleted, so give up */
2611  return NULL;
2612 
2613  case HeapTupleWouldBlock:
2614  ReleaseBuffer(buffer);
2615  return NULL;
2616 
2617  case HeapTupleInvisible:
2618  elog(ERROR, "attempted to lock invisible tuple");
2619 
2620  default:
2621  ReleaseBuffer(buffer);
2622  elog(ERROR, "unrecognized heap_lock_tuple status: %u",
2623  test);
2624  return NULL; /* keep compiler quiet */
2625  }
2626 
2627  /*
2628  * We got tuple - now copy it for use by recheck query.
2629  */
2630  copyTuple = heap_copytuple(&tuple);
2631  ReleaseBuffer(buffer);
2632  break;
2633  }
2634 
2635  /*
2636  * If the referenced slot was actually empty, the latest version of
2637  * the row must have been deleted, so we need do nothing.
2638  */
2639  if (tuple.t_data == NULL)
2640  {
2641  ReleaseBuffer(buffer);
2642  return NULL;
2643  }
2644 
2645  /*
2646  * As above, if xmin isn't what we're expecting, do nothing.
2647  */
2649  priorXmax))
2650  {
2651  ReleaseBuffer(buffer);
2652  return NULL;
2653  }
2654 
2655  /*
2656  * If we get here, the tuple was found but failed SnapshotDirty.
2657  * Assuming the xmin is either a committed xact or our own xact (as it
2658  * certainly should be if we're trying to modify the tuple), this must
2659  * mean that the row was updated or deleted by either a committed xact
2660  * or our own xact. If it was deleted, we can ignore it; if it was
2661  * updated then chain up to the next version and repeat the whole
2662  * process.
2663  *
2664  * As above, it should be safe to examine xmax and t_ctid without the
2665  * buffer content lock, because they can't be changing.
2666  */
2667  if (ItemPointerEquals(&tuple.t_self, &tuple.t_data->t_ctid))
2668  {
2669  /* deleted, so forget about it */
2670  ReleaseBuffer(buffer);
2671  return NULL;
2672  }
2673 
2674  /* updated, so look at the updated row */
2675  tuple.t_self = tuple.t_data->t_ctid;
2676  /* updated row should have xmin matching this xmax */
2677  priorXmax = HeapTupleHeaderGetUpdateXid(tuple.t_data);
2678  ReleaseBuffer(buffer);
2679  /* loop back to fetch next in chain */
2680  }
2681 
2682  /*
2683  * Return the copied tuple
2684  */
2685  return copyTuple;
2686 }
#define HeapTupleHeaderGetUpdateXid(tup)
Definition: htup_details.h:359
HeapTuple heap_copytuple(HeapTuple tuple)
Definition: heaptuple.c:608
CommandId es_output_cid
Definition: execnodes.h:418
static void test(void)
#define TransactionIdEquals(id1, id2)
Definition: transam.h:43
bool TransactionIdIsCurrentTransactionId(TransactionId xid)
Definition: xact.c:773
HTSU_Result heap_lock_tuple(Relation relation, HeapTuple tuple, CommandId cid, LockTupleMode mode, LockWaitPolicy wait_policy, bool follow_updates, Buffer *buffer, HeapUpdateFailureData *hufd)
Definition: heapam.c:4539
CommandId HeapTupleHeaderGetCmin(HeapTupleHeader tup)
Definition: combocid.c:105
bool heap_fetch(Relation relation, Snapshot snapshot, HeapTuple tuple, Buffer *userbuf, bool keep_buf, Relation stats_relation)
Definition: heapam.c:1862
#define IsolationUsesXactSnapshot()
Definition: xact.h:43
#define HeapTupleHeaderIsSpeculative(tup)
Definition: htup_details.h:423
int errcode(int sqlerrcode)
Definition: elog.c:575
void ReleaseBuffer(Buffer buffer)
Definition: bufmgr.c:3309
bool ConditionalXactLockTableWait(TransactionId xid)
Definition: lmgr.c:607
HeapTupleHeader t_data
Definition: htup.h:67
#define ERROR
Definition: elog.h:43
#define InitDirtySnapshot(snapshotdata)
Definition: tqual.h:100
ItemPointerData t_ctid
Definition: htup_details.h:150
ItemPointerData t_self
Definition: htup.h:65
HTSU_Result
Definition: snapshot.h:119
#define RelationGetRelationName(relation)
Definition: rel.h:437
TransactionId xmax
Definition: snapshot.h:67
TransactionId xmin
Definition: snapshot.h:66
#define ereport(elevel, rest)
Definition: elog.h:122
TransactionId xmax
Definition: heapam.h:71
void XactLockTableWait(TransactionId xid, Relation rel, ItemPointer ctid, XLTW_Oper oper)
Definition: lmgr.c:554
#define NULL
Definition: c.h:229
#define Assert(condition)
Definition: c.h:675
WalTimeSample buffer[LAG_TRACKER_BUFFER_SIZE]
Definition: walsender.c:207
#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 2766 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().

2767 {
2768  ListCell *l;
2769 
2770  Assert(epqstate->origslot != NULL);
2771 
2772  foreach(l, epqstate->arowMarks)
2773  {
2774  ExecAuxRowMark *aerm = (ExecAuxRowMark *) lfirst(l);
2775  ExecRowMark *erm = aerm->rowmark;
2776  Datum datum;
2777  bool isNull;
2778  HeapTupleData tuple;
2779 
2781  elog(ERROR, "EvalPlanQual doesn't support locking rowmarks");
2782 
2783  /* clear any leftover test tuple for this rel */
2784  EvalPlanQualSetTuple(epqstate, erm->rti, NULL);
2785 
2786  /* if child rel, must check whether it produced this row */
2787  if (erm->rti != erm->prti)
2788  {
2789  Oid tableoid;
2790 
2791  datum = ExecGetJunkAttribute(epqstate->origslot,
2792  aerm->toidAttNo,
2793  &isNull);
2794  /* non-locked rels could be on the inside of outer joins */
2795  if (isNull)
2796  continue;
2797  tableoid = DatumGetObjectId(datum);
2798 
2799  Assert(OidIsValid(erm->relid));
2800  if (tableoid != erm->relid)
2801  {
2802  /* this child is inactive right now */
2803  continue;
2804  }
2805  }
2806 
2807  if (erm->markType == ROW_MARK_REFERENCE)
2808  {
2809  HeapTuple copyTuple;
2810 
2811  Assert(erm->relation != NULL);
2812 
2813  /* fetch the tuple's ctid */
2814  datum = ExecGetJunkAttribute(epqstate->origslot,
2815  aerm->ctidAttNo,
2816  &isNull);
2817  /* non-locked rels could be on the inside of outer joins */
2818  if (isNull)
2819  continue;
2820 
2821  /* fetch requests on foreign tables must be passed to their FDW */
2822  if (erm->relation->rd_rel->relkind == RELKIND_FOREIGN_TABLE)
2823  {
2824  FdwRoutine *fdwroutine;
2825  bool updated = false;
2826 
2827  fdwroutine = GetFdwRoutineForRelation(erm->relation, false);
2828  /* this should have been checked already, but let's be safe */
2829  if (fdwroutine->RefetchForeignRow == NULL)
2830  ereport(ERROR,
2831  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2832  errmsg("cannot lock rows in foreign table \"%s\"",
2834  copyTuple = fdwroutine->RefetchForeignRow(epqstate->estate,
2835  erm,
2836  datum,
2837  &updated);
2838  if (copyTuple == NULL)
2839  elog(ERROR, "failed to fetch tuple for EvalPlanQual recheck");
2840 
2841  /*
2842  * Ideally we'd insist on updated == false here, but that
2843  * assumes that FDWs can track that exactly, which they might
2844  * not be able to. So just ignore the flag.
2845  */
2846  }
2847  else
2848  {
2849  /* ordinary table, fetch the tuple */
2850  Buffer buffer;
2851 
2852  tuple.t_self = *((ItemPointer) DatumGetPointer(datum));
2853  if (!heap_fetch(erm->relation, SnapshotAny, &tuple, &buffer,
2854  false, NULL))
2855  elog(ERROR, "failed to fetch tuple for EvalPlanQual recheck");
2856 
2857  /* successful, copy tuple */
2858  copyTuple = heap_copytuple(&tuple);
2859  ReleaseBuffer(buffer);
2860  }
2861 
2862  /* store tuple */
2863  EvalPlanQualSetTuple(epqstate, erm->rti, copyTuple);
2864  }
2865  else
2866  {
2867  HeapTupleHeader td;
2868 
2869  Assert(erm->markType == ROW_MARK_COPY);
2870 
2871  /* fetch the whole-row Var for the relation */
2872  datum = ExecGetJunkAttribute(epqstate->origslot,
2873  aerm->wholeAttNo,
2874  &isNull);
2875  /* non-locked rels could be on the inside of outer joins */
2876  if (isNull)
2877  continue;
2878  td = DatumGetHeapTupleHeader(datum);
2879 
2880  /* build a temporary HeapTuple control structure */
2882  tuple.t_data = td;
2883  /* relation might be a foreign table, if so provide tableoid */
2884  tuple.t_tableOid = erm->relid;
2885  /* also copy t_ctid in case there's valid data there */
2886  tuple.t_self = td->t_ctid;
2887 
2888  /* copy and store tuple */
2889  EvalPlanQualSetTuple(epqstate, erm->rti,
2890  heap_copytuple(&tuple));
2891  }
2892  }
2893 }
HeapTuple heap_copytuple(HeapTuple tuple)
Definition: heaptuple.c:608
void EvalPlanQualSetTuple(EPQState *epqstate, Index rti, HeapTuple tuple)
Definition: execMain.c:2731
Relation relation
Definition: execnodes.h:501
bool heap_fetch(Relation relation, Snapshot snapshot, HeapTuple tuple, Buffer *userbuf, bool keep_buf, Relation stats_relation)
Definition: heapam.c:1862
#define DatumGetObjectId(X)
Definition: postgres.h:506
int errcode(int sqlerrcode)
Definition: elog.c:575
void ReleaseBuffer(Buffer buffer)
Definition: bufmgr.c:3309
Form_pg_class rd_rel
Definition: rel.h:114
unsigned int Oid
Definition: postgres_ext.h:31
#define OidIsValid(objectId)
Definition: c.h:538
#define DatumGetHeapTupleHeader(X)
Definition: fmgr.h:259
#define RowMarkRequiresRowShareLock(marktype)
Definition: plannodes.h:954
ItemPointerData * ItemPointer
Definition: itemptr.h:48
ExecRowMark * rowmark
Definition: execnodes.h:528
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:870
uint32 t_len
Definition: htup.h:64
Index rti
Definition: execnodes.h:503
AttrNumber wholeAttNo
Definition: execnodes.h:531
Index prti
Definition: execnodes.h:504
#define RelationGetRelationName(relation)
Definition: rel.h:437
Oid t_tableOid
Definition: htup.h:66
#define RELKIND_FOREIGN_TABLE
Definition: pg_class.h:167
TupleTableSlot * origslot
Definition: execnodes.h:868
#define ereport(elevel, rest)
Definition: elog.h:122
uintptr_t Datum
Definition: postgres.h:372
#define SnapshotAny
Definition: tqual.h:28
#define NULL
Definition: c.h:229
#define Assert(condition)
Definition: c.h:675
#define lfirst(lc)
Definition: pg_list.h:106
WalTimeSample buffer[LAG_TRACKER_BUFFER_SIZE]
Definition: walsender.c:207
RowMarkType markType
Definition: execnodes.h:506
AttrNumber toidAttNo
Definition: execnodes.h:530
#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:866
int Buffer
Definition: buf.h:23
AttrNumber ctidAttNo
Definition: execnodes.h:529
RefetchForeignRow_function RefetchForeignRow
Definition: fdwapi.h:209
#define HeapTupleHeaderGetDatumLength(tup)
Definition: htup_details.h:439
HeapTuple EvalPlanQualGetTuple ( EPQState epqstate,
Index  rti 
)

Definition at line 2751 of file execMain.c.

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

2752 {
2753  EState *estate = epqstate->estate;
2754 
2755  Assert(rti > 0);
2756 
2757  return estate->es_epqTuple[rti - 1];
2758 }
HeapTuple * es_epqTuple
Definition: execnodes.h:473
#define Assert(condition)
Definition: c.h:675
EState * estate
Definition: execnodes.h:866
void EvalPlanQualInit ( EPQState epqstate,
EState estate,
Plan subplan,
List auxrowmarks,
int  epqParam 
)

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

2698 {
2699  /* Mark the EPQ state inactive */
2700  epqstate->estate = NULL;
2701  epqstate->planstate = NULL;
2702  epqstate->origslot = NULL;
2703  /* ... and remember data that EvalPlanQualBegin will need */
2704  epqstate->plan = subplan;
2705  epqstate->arowMarks = auxrowmarks;
2706  epqstate->epqParam = epqParam;
2707 }
PlanState * planstate
Definition: execnodes.h:867
List * arowMarks
Definition: execnodes.h:870
TupleTableSlot * origslot
Definition: execnodes.h:868
Plan * plan
Definition: execnodes.h:869
#define NULL
Definition: c.h:229
int epqParam
Definition: execnodes.h:871
EState * estate
Definition: execnodes.h:866
TupleTableSlot* EvalPlanQualNext ( EPQState epqstate)

Definition at line 2901 of file execMain.c.

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

Referenced by EvalPlanQual(), and ExecLockRows().

2902 {
2903  MemoryContext oldcontext;
2904  TupleTableSlot *slot;
2905 
2906  oldcontext = MemoryContextSwitchTo(epqstate->estate->es_query_cxt);
2907  slot = ExecProcNode(epqstate->planstate);
2908  MemoryContextSwitchTo(oldcontext);
2909 
2910  return slot;
2911 }
TupleTableSlot * ExecProcNode(PlanState *node)
Definition: execProcnode.c:398
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:109
PlanState * planstate
Definition: execnodes.h:867
MemoryContext es_query_cxt
Definition: execnodes.h:438
EState * estate
Definition: execnodes.h:866
void EvalPlanQualSetPlan ( EPQState epqstate,
Plan subplan,
List auxrowmarks 
)

Definition at line 2715 of file execMain.c.

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

Referenced by ExecInitModifyTable(), and ExecModifyTable().

2716 {
2717  /* If we have a live EPQ query, shut it down */
2718  EvalPlanQualEnd(epqstate);
2719  /* And set/change the plan pointer */
2720  epqstate->plan = subplan;
2721  /* The rowmarks depend on the plan, too */
2722  epqstate->arowMarks = auxrowmarks;
2723 }
void EvalPlanQualEnd(EPQState *epqstate)
Definition: execMain.c:3107
List * arowMarks
Definition: execnodes.h:870
Plan * plan
Definition: execnodes.h:869
void EvalPlanQualSetTuple ( EPQState epqstate,
Index  rti,
HeapTuple  tuple 
)

Definition at line 2731 of file execMain.c.

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

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

2732 {
2733  EState *estate = epqstate->estate;
2734 
2735  Assert(rti > 0);
2736 
2737  /*
2738  * free old test tuple, if any, and store new tuple where relation's scan
2739  * node will see it
2740  */
2741  if (estate->es_epqTuple[rti - 1] != NULL)
2742  heap_freetuple(estate->es_epqTuple[rti - 1]);
2743  estate->es_epqTuple[rti - 1] = tuple;
2744  estate->es_epqTupleSet[rti - 1] = true;
2745 }
HeapTuple * es_epqTuple
Definition: execnodes.h:473
void heap_freetuple(HeapTuple htup)
Definition: heaptuple.c:1374
#define NULL
Definition: c.h:229
#define Assert(condition)
Definition: c.h:675
bool * es_epqTupleSet
Definition: execnodes.h:474
EState * estate
Definition: execnodes.h:866
static void EvalPlanQualStart ( EPQState epqstate,
EState parentestate,
Plan planTree 
)
static

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

2968 {
2969  EState *estate;
2970  int rtsize;
2971  MemoryContext oldcontext;
2972  ListCell *l;
2973 
2974  rtsize = list_length(parentestate->es_range_table);
2975 
2976  epqstate->estate = estate = CreateExecutorState();
2977 
2978  oldcontext = MemoryContextSwitchTo(estate->es_query_cxt);
2979 
2980  /*
2981  * Child EPQ EStates share the parent's copy of unchanging state such as
2982  * the snapshot, rangetable, result-rel info, and external Param info.
2983  * They need their own copies of local state, including a tuple table,
2984  * es_param_exec_vals, etc.
2985  *
2986  * The ResultRelInfo array management is trickier than it looks. We
2987  * create a fresh array for the child but copy all the content from the
2988  * parent. This is because it's okay for the child to share any
2989  * per-relation state the parent has already created --- but if the child
2990  * sets up any ResultRelInfo fields, such as its own junkfilter, that
2991  * state must *not* propagate back to the parent. (For one thing, the
2992  * pointed-to data is in a memory context that won't last long enough.)
2993  */
2995  estate->es_snapshot = parentestate->es_snapshot;
2996  estate->es_crosscheck_snapshot = parentestate->es_crosscheck_snapshot;
2997  estate->es_range_table = parentestate->es_range_table;
2998  estate->es_plannedstmt = parentestate->es_plannedstmt;
2999  estate->es_junkFilter = parentestate->es_junkFilter;
3000  estate->es_output_cid = parentestate->es_output_cid;
3001  if (parentestate->es_num_result_relations > 0)
3002  {
3003  int numResultRelations = parentestate->es_num_result_relations;
3004  ResultRelInfo *resultRelInfos;
3005 
3006  resultRelInfos = (ResultRelInfo *)
3007  palloc(numResultRelations * sizeof(ResultRelInfo));
3008  memcpy(resultRelInfos, parentestate->es_result_relations,
3009  numResultRelations * sizeof(ResultRelInfo));
3010  estate->es_result_relations = resultRelInfos;
3011  estate->es_num_result_relations = numResultRelations;
3012  }
3013  /* es_result_relation_info must NOT be copied */
3014  /* es_trig_target_relations must NOT be copied */
3015  estate->es_rowMarks = parentestate->es_rowMarks;
3016  estate->es_top_eflags = parentestate->es_top_eflags;
3017  estate->es_instrument = parentestate->es_instrument;
3018  /* es_auxmodifytables must NOT be copied */
3019 
3020  /*
3021  * The external param list is simply shared from parent. The internal
3022  * param workspace has to be local state, but we copy the initial values
3023  * from the parent, so as to have access to any param values that were
3024  * already set from other parts of the parent's plan tree.
3025  */
3026  estate->es_param_list_info = parentestate->es_param_list_info;
3027  if (parentestate->es_plannedstmt->nParamExec > 0)
3028  {
3029  int i = parentestate->es_plannedstmt->nParamExec;
3030 
3031  estate->es_param_exec_vals = (ParamExecData *)
3032  palloc0(i * sizeof(ParamExecData));
3033  while (--i >= 0)
3034  {
3035  /* copy value if any, but not execPlan link */
3036  estate->es_param_exec_vals[i].value =
3037  parentestate->es_param_exec_vals[i].value;
3038  estate->es_param_exec_vals[i].isnull =
3039  parentestate->es_param_exec_vals[i].isnull;
3040  }
3041  }
3042 
3043  /*
3044  * Each EState must have its own es_epqScanDone state, but if we have
3045  * nested EPQ checks they should share es_epqTuple arrays. This allows
3046  * sub-rechecks to inherit the values being examined by an outer recheck.
3047  */
3048  estate->es_epqScanDone = (bool *) palloc0(rtsize * sizeof(bool));
3049  if (parentestate->es_epqTuple != NULL)
3050  {
3051  estate->es_epqTuple = parentestate->es_epqTuple;
3052  estate->es_epqTupleSet = parentestate->es_epqTupleSet;
3053  }
3054  else
3055  {
3056  estate->es_epqTuple = (HeapTuple *)
3057  palloc0(rtsize * sizeof(HeapTuple));
3058  estate->es_epqTupleSet = (bool *)
3059  palloc0(rtsize * sizeof(bool));
3060  }
3061 
3062  /*
3063  * Each estate also has its own tuple table.
3064  */
3065  estate->es_tupleTable = NIL;
3066 
3067  /*
3068  * Initialize private state information for each SubPlan. We must do this
3069  * before running ExecInitNode on the main query tree, since
3070  * ExecInitSubPlan expects to be able to find these entries. Some of the
3071  * SubPlans might not be used in the part of the plan tree we intend to
3072  * run, but since it's not easy to tell which, we just initialize them
3073  * all.
3074  */
3075  Assert(estate->es_subplanstates == NIL);
3076  foreach(l, parentestate->es_plannedstmt->subplans)
3077  {
3078  Plan *subplan = (Plan *) lfirst(l);
3079  PlanState *subplanstate;
3080 
3081  subplanstate = ExecInitNode(subplan, estate, 0);
3082  estate->es_subplanstates = lappend(estate->es_subplanstates,
3083  subplanstate);
3084  }
3085 
3086  /*
3087  * Initialize the private state information for all the nodes in the part
3088  * of the plan tree we need to run. This opens files, allocates storage
3089  * and leaves us ready to start processing tuples.
3090  */
3091  epqstate->planstate = ExecInitNode(planTree, estate, 0);
3092 
3093  MemoryContextSwitchTo(oldcontext);
3094 }
#define NIL
Definition: pg_list.h:69
HeapTuple * es_epqTuple
Definition: execnodes.h:473
JunkFilter * es_junkFilter
Definition: execnodes.h:415
CommandId es_output_cid
Definition: execnodes.h:418
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:109
PlannedStmt * es_plannedstmt
Definition: execnodes.h:412
Snapshot es_crosscheck_snapshot
Definition: execnodes.h:410
Snapshot es_snapshot
Definition: execnodes.h:409
List * es_range_table
Definition: execnodes.h:411
PlanState * planstate
Definition: execnodes.h:867
ScanDirection es_direction
Definition: execnodes.h:408
int nParamExec
Definition: plannodes.h:82
ParamExecData * es_param_exec_vals
Definition: execnodes.h:433
MemoryContext es_query_cxt
Definition: execnodes.h:438
bool isnull
Definition: params.h:101
ResultRelInfo * es_result_relations
Definition: execnodes.h:421
int es_instrument
Definition: execnodes.h:448
EState * CreateExecutorState(void)
Definition: execUtils.c:80
List * lappend(List *list, void *datum)
Definition: list.c:128
List * es_tupleTable
Definition: execnodes.h:440
void * palloc0(Size size)
Definition: mcxt.c:878
int es_num_result_relations
Definition: execnodes.h:422
List * subplans
Definition: plannodes.h:71
#define NULL
Definition: c.h:229
#define Assert(condition)
Definition: c.h:675
#define lfirst(lc)
Definition: pg_list.h:106
static int list_length(const List *l)
Definition: pg_list.h:89
bool * es_epqTupleSet
Definition: execnodes.h:474
List * es_subplanstates
Definition: execnodes.h:453
List * es_rowMarks
Definition: execnodes.h:442
void * palloc(Size size)
Definition: mcxt.c:849
int es_top_eflags
Definition: execnodes.h:447
int i
bool * es_epqScanDone
Definition: execnodes.h:475
Datum value
Definition: params.h:100
ParamListInfo es_param_list_info
Definition: execnodes.h:432
EState * estate
Definition: execnodes.h:866
PlanState * ExecInitNode(Plan *node, EState *estate, int eflags)
Definition: execProcnode.c:140
ExecAuxRowMark* ExecBuildAuxRowMark ( ExecRowMark erm,
List targetlist 
)

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

2310 {
2311  ExecAuxRowMark *aerm = (ExecAuxRowMark *) palloc0(sizeof(ExecAuxRowMark));
2312  char resname[32];
2313 
2314  aerm->rowmark = erm;
2315 
2316  /* Look up the resjunk columns associated with this rowmark */
2317  if (erm->markType != ROW_MARK_COPY)
2318  {
2319  /* need ctid for all methods other than COPY */
2320  snprintf(resname, sizeof(resname), "ctid%u", erm->rowmarkId);
2321  aerm->ctidAttNo = ExecFindJunkAttributeInTlist(targetlist,
2322  resname);
2323  if (!AttributeNumberIsValid(aerm->ctidAttNo))
2324  elog(ERROR, "could not find junk %s column", resname);
2325  }
2326  else
2327  {
2328  /* need wholerow if COPY */
2329  snprintf(resname, sizeof(resname), "wholerow%u", erm->rowmarkId);
2330  aerm->wholeAttNo = ExecFindJunkAttributeInTlist(targetlist,
2331  resname);
2332  if (!AttributeNumberIsValid(aerm->wholeAttNo))
2333  elog(ERROR, "could not find junk %s column", resname);
2334  }
2335 
2336  /* if child rel, need tableoid */
2337  if (erm->rti != erm->prti)
2338  {
2339  snprintf(resname, sizeof(resname), "tableoid%u", erm->rowmarkId);
2340  aerm->toidAttNo = ExecFindJunkAttributeInTlist(targetlist,
2341  resname);
2342  if (!AttributeNumberIsValid(aerm->toidAttNo))
2343  elog(ERROR, "could not find junk %s column", resname);
2344  }
2345 
2346  return aerm;
2347 }
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:528
#define ERROR
Definition: elog.h:43
Index rti
Definition: execnodes.h:503
AttrNumber wholeAttNo
Definition: execnodes.h:531
Index prti
Definition: execnodes.h:504
Index rowmarkId
Definition: execnodes.h:505
#define AttributeNumberIsValid(attributeNumber)
Definition: attnum.h:34
void * palloc0(Size size)
Definition: mcxt.c:878
RowMarkType markType
Definition: execnodes.h:506
AttrNumber toidAttNo
Definition: execnodes.h:530
#define elog
Definition: elog.h:219
AttrNumber ctidAttNo
Definition: execnodes.h:529
static char * ExecBuildSlotPartitionKeyDescription ( Relation  rel,
Datum values,
bool isnull,
int  maxfieldlen 
)
static

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

3313 {
3316  int partnatts = get_partition_natts(key);
3317  int i;
3318  Oid relid = RelationGetRelid(rel);
3319  AclResult aclresult;
3320 
3321  if (check_enable_rls(relid, InvalidOid, true) == RLS_ENABLED)
3322  return NULL;
3323 
3324  /* If the user has table-level access, just go build the description. */
3325  aclresult = pg_class_aclcheck(relid, GetUserId(), ACL_SELECT);
3326  if (aclresult != ACLCHECK_OK)
3327  {
3328  /*
3329  * Step through the columns of the partition key and make sure the
3330  * user has SELECT rights on all of them.
3331  */
3332  for (i = 0; i < partnatts; i++)
3333  {
3334  AttrNumber attnum = get_partition_col_attnum(key, i);
3335 
3336  /*
3337  * If this partition key column is an expression, we return no
3338  * detail rather than try to figure out what column(s) the
3339  * expression includes and if the user has SELECT rights on them.
3340  */
3341  if (attnum == InvalidAttrNumber ||
3342  pg_attribute_aclcheck(relid, attnum, GetUserId(),
3343  ACL_SELECT) != ACLCHECK_OK)
3344  return NULL;
3345  }
3346  }
3347 
3348  initStringInfo(&buf);
3349  appendStringInfo(&buf, "(%s) = (",
3350  pg_get_partkeydef_columns(relid, true));
3351 
3352  for (i = 0; i < partnatts; i++)
3353  {
3354  char *val;
3355  int vallen;
3356 
3357  if (isnull[i])
3358  val = "null";
3359  else
3360  {
3361  Oid foutoid;
3362  bool typisvarlena;
3363 
3365  &foutoid, &typisvarlena);
3366  val = OidOutputFunctionCall(foutoid, values[i]);
3367  }
3368 
3369  if (i > 0)
3370  appendStringInfoString(&buf, ", ");
3371 
3372  /* truncate if needed */
3373  vallen = strlen(val);
3374  if (vallen <= maxfieldlen)
3375  appendStringInfoString(&buf, val);
3376  else
3377  {
3378  vallen = pg_mbcliplen(val, vallen, maxfieldlen);
3379  appendBinaryStringInfo(&buf, val, vallen);
3380  appendStringInfoString(&buf, "...");
3381  }
3382  }
3383 
3384  appendStringInfoChar(&buf, ')');
3385 
3386  return buf.data;
3387 }
char * pg_get_partkeydef_columns(Oid relid, bool pretty)
Definition: ruleutils.c:1566
void getTypeOutputInfo(Oid type, Oid *typOutput, bool *typIsVarlena)
Definition: lsyscache.c:2632
AclResult pg_attribute_aclcheck(Oid table_oid, AttrNumber attnum, Oid roleid, AclMode mode)
Definition: aclchk.c:4308
Oid GetUserId(void)
Definition: miscinit.c:283
unsigned int Oid
Definition: postgres_ext.h:31
static int get_partition_natts(PartitionKey key)
Definition: rel.h:597
static int16 get_partition_col_attnum(PartitionKey key, int col)
Definition: rel.h:612
void appendStringInfo(StringInfo str, const char *fmt,...)
Definition: stringinfo.c:110
int pg_mbcliplen(const char *mbstr, int len, int limit)
Definition: mbutils.c:831
void appendStringInfoString(StringInfo str, const char *s)
Definition: stringinfo.c:189
static char * buf
Definition: pg_test_fsync.c:66
void appendStringInfoChar(StringInfo str, char ch)
Definition: stringinfo.c:201
void initStringInfo(StringInfo str)
Definition: stringinfo.c:65
AclResult
Definition: acl.h:170
static Oid get_partition_col_typid(PartitionKey key, int col)
Definition: rel.h:618
#define ACL_SELECT
Definition: parsenodes.h:73
#define InvalidOid
Definition: postgres_ext.h:36
int check_enable_rls(Oid relid, Oid checkAsUser, bool noError)
Definition: rls.c:53
#define NULL
Definition: c.h:229
#define RelationGetPartitionKey(relation)
Definition: rel.h:585
#define InvalidAttrNumber
Definition: attnum.h:23
AclResult pg_class_aclcheck(Oid table_oid, Oid roleid, AclMode mode)
Definition: aclchk.c:4422
static Datum values[MAXATTR]
Definition: bootstrap.c:163
char * OidOutputFunctionCall(Oid functionId, Datum val)
Definition: fmgr.c:1747
int i
int16 AttrNumber
Definition: attnum.h:21
#define RelationGetRelid(relation)
Definition: rel.h:417
void appendBinaryStringInfo(StringInfo str, const char *data, int datalen)
Definition: stringinfo.c:240
long val
Definition: informix.c:689
static char * ExecBuildSlotValueDescription ( Oid  reloid,
TupleTableSlot slot,
TupleDesc  tupdesc,
Bitmapset modifiedCols,
int  maxfieldlen 
)
static

Definition at line 2123 of file execMain.c.

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

Referenced by ExecConstraints(), and ExecWithCheckOptions().

2128 {
2130  StringInfoData collist;
2131  bool write_comma = false;
2132  bool write_comma_collist = false;
2133  int i;
2134  AclResult aclresult;
2135  bool table_perm = false;
2136  bool any_perm = false;
2137 
2138  /*
2139  * Check if RLS is enabled and should be active for the relation; if so,
2140  * then don't return anything. Otherwise, go through normal permission
2141  * checks.
2142  */
2143  if (check_enable_rls(reloid, InvalidOid, true) == RLS_ENABLED)
2144  return NULL;
2145 
2146  initStringInfo(&buf);
2147 
2148  appendStringInfoChar(&buf, '(');
2149 
2150  /*
2151  * Check if the user has permissions to see the row. Table-level SELECT
2152  * allows access to all columns. If the user does not have table-level
2153  * SELECT then we check each column and include those the user has SELECT
2154  * rights on. Additionally, we always include columns the user provided
2155  * data for.
2156  */
2157  aclresult = pg_class_aclcheck(reloid, GetUserId(), ACL_SELECT);
2158  if (aclresult != ACLCHECK_OK)
2159  {
2160  /* Set up the buffer for the column list */
2161  initStringInfo(&collist);
2162  appendStringInfoChar(&collist, '(');
2163  }
2164  else
2165  table_perm = any_perm = true;
2166 
2167  /* Make sure the tuple is fully deconstructed */
2168  slot_getallattrs(slot);
2169 
2170  for (i = 0; i < tupdesc->natts; i++)
2171  {
2172  bool column_perm = false;
2173  char *val;
2174  int vallen;
2175 
2176  /* ignore dropped columns */
2177  if (tupdesc->attrs[i]->attisdropped)
2178  continue;
2179 
2180  if (!table_perm)
2181  {
2182  /*
2183  * No table-level SELECT, so need to make sure they either have
2184  * SELECT rights on the column or that they have provided the data
2185  * for the column. If not, omit this column from the error
2186  * message.
2187  */
2188  aclresult = pg_attribute_aclcheck(reloid, tupdesc->attrs[i]->attnum,
2189  GetUserId(), ACL_SELECT);
2190  if (bms_is_member(tupdesc->attrs[i]->attnum - FirstLowInvalidHeapAttributeNumber,
2191  modifiedCols) || aclresult == ACLCHECK_OK)
2192  {
2193  column_perm = any_perm = true;
2194 
2195  if (write_comma_collist)
2196  appendStringInfoString(&collist, ", ");
2197  else
2198  write_comma_collist = true;
2199 
2200  appendStringInfoString(&collist, NameStr(tupdesc->attrs[i]->attname));
2201  }
2202  }
2203 
2204  if (table_perm || column_perm)
2205  {
2206  if (slot->tts_isnull[i])
2207  val = "null";
2208  else
2209  {
2210  Oid foutoid;
2211  bool typisvarlena;
2212 
2213  getTypeOutputInfo(tupdesc->attrs[i]->atttypid,
2214  &foutoid, &typisvarlena);
2215  val = OidOutputFunctionCall(foutoid, slot->tts_values[i]);
2216  }
2217 
2218  if (write_comma)
2219  appendStringInfoString(&buf, ", ");
2220  else
2221  write_comma = true;
2222 
2223  /* truncate if needed */
2224  vallen = strlen(val);
2225  if (vallen <= maxfieldlen)
2226  appendStringInfoString(&buf, val);
2227  else
2228  {
2229  vallen = pg_mbcliplen(val, vallen, maxfieldlen);
2230  appendBinaryStringInfo(&buf, val, vallen);
2231  appendStringInfoString(&buf, "...");
2232  }
2233  }
2234  }
2235 
2236  /* If we end up with zero columns being returned, then return NULL. */
2237  if (!any_perm)
2238  return NULL;
2239 
2240  appendStringInfoChar(&buf, ')');
2241 
2242  if (!table_perm)
2243  {
2244  appendStringInfoString(&collist, ") = ");
2245  appendStringInfoString(&collist, buf.data);
2246 
2247  return collist.data;
2248  }
2249 
2250  return buf.data;
2251 }
void getTypeOutputInfo(Oid type, Oid *typOutput, bool *typIsVarlena)
Definition: lsyscache.c:2632
AclResult pg_attribute_aclcheck(Oid table_oid, AttrNumber attnum, Oid roleid, AclMode mode)
Definition: aclchk.c:4308
Oid GetUserId(void)
Definition: miscinit.c:283
Form_pg_attribute * attrs
Definition: tupdesc.h:74
Datum * tts_values
Definition: tuptable.h:125
#define FirstLowInvalidHeapAttributeNumber
Definition: sysattr.h:28
unsigned int Oid
Definition: postgres_ext.h:31
int natts
Definition: tupdesc.h:73
int pg_mbcliplen(const char *mbstr, int len, int limit)
Definition: mbutils.c:831
void appendStringInfoString(StringInfo str, const char *s)
Definition: stringinfo.c:189
static char * buf
Definition: pg_test_fsync.c:66
bool * tts_isnull
Definition: tuptable.h:126
void slot_getallattrs(TupleTableSlot *slot)
Definition: heaptuple.c:1239
void appendStringInfoChar(StringInfo str, char ch)
Definition: stringinfo.c:201
void initStringInfo(StringInfo str)
Definition: stringinfo.c:65
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:240
long val
Definition: informix.c:689
static bool ExecCheckRTEPerms ( RangeTblEntry rte)
static

Definition at line 598 of file execMain.c.

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

Referenced by ExecCheckRTPerms().

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

Definition at line 718 of file execMain.c.

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

Referenced by ExecCheckRTEPerms().

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

Definition at line 567 of file execMain.c.

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

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

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

Definition at line 765 of file execMain.c.

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

Referenced by standard_ExecutorStart().

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

Definition at line 1831 of file execMain.c.

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

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

1833 {
1834  Relation rel = resultRelInfo->ri_RelationDesc;
1835  TupleDesc tupdesc = RelationGetDescr(rel);
1836  TupleConstr *constr = tupdesc->constr;
1837  Bitmapset *modifiedCols;
1838  Bitmapset *insertedCols;
1839  Bitmapset *updatedCols;
1840 
1841  Assert(constr || resultRelInfo->ri_PartitionCheck);
1842 
1843  if (constr && constr->has_not_null)
1844  {
1845  int natts = tupdesc->natts;
1846  int attrChk;
1847 
1848  for (attrChk = 1; attrChk <= natts; attrChk++)
1849  {
1850  if (tupdesc->attrs[attrChk - 1]->attnotnull &&
1851  slot_attisnull(slot, attrChk))
1852  {
1853  char *val_desc;
1854  Relation orig_rel = rel;
1855  TupleDesc orig_tupdesc = RelationGetDescr(rel);
1856 
1857  /*
1858  * If the tuple has been routed, it's been converted to the
1859  * partition's rowtype, which might differ from the root
1860  * table's. We must convert it back to the root table's
1861  * rowtype so that val_desc shown error message matches the
1862  * input tuple.
1863  */
1864  if (resultRelInfo->ri_PartitionRoot)
1865  {
1866  HeapTuple tuple = ExecFetchSlotTuple(slot);
1867  TupleConversionMap *map;
1868 
1869  rel = resultRelInfo->ri_PartitionRoot;
1870  tupdesc = RelationGetDescr(rel);
1871  /* a reverse map */
1872  map = convert_tuples_by_name(orig_tupdesc, tupdesc,
1873  gettext_noop("could not convert row type"));
1874  if (map != NULL)
1875  {
1876  tuple = do_convert_tuple(tuple, map);
1877  ExecStoreTuple(tuple, slot, InvalidBuffer, false);
1878  }
1879  }
1880 
1881  insertedCols = GetInsertedColumns(resultRelInfo, estate);
1882  updatedCols = GetUpdatedColumns(resultRelInfo, estate);
1883  modifiedCols = bms_union(insertedCols, updatedCols);
1885  slot,
1886  tupdesc,
1887  modifiedCols,
1888  64);
1889 
1890  ereport(ERROR,
1891  (errcode(ERRCODE_NOT_NULL_VIOLATION),
1892  errmsg("null value in column \"%s\" violates not-null constraint",
1893  NameStr(orig_tupdesc->attrs[attrChk - 1]->attname)),
1894  val_desc ? errdetail("Failing row contains %s.", val_desc) : 0,
1895  errtablecol(orig_rel, attrChk)));
1896  }
1897  }
1898  }
1899 
1900  if (constr && constr->num_check > 0)
1901  {
1902  const char *failed;
1903 
1904  if ((failed = ExecRelCheck(resultRelInfo, slot, estate)) != NULL)
1905  {
1906  char *val_desc;
1907  Relation orig_rel = rel;
1908 
1909  /* See the comment above. */
1910  if (resultRelInfo->ri_PartitionRoot)
1911  {
1912  HeapTuple tuple = ExecFetchSlotTuple(slot);
1913  TupleDesc old_tupdesc = RelationGetDescr(rel);
1914  TupleConversionMap *map;
1915 
1916  rel = resultRelInfo->ri_PartitionRoot;
1917  tupdesc = RelationGetDescr(rel);
1918  /* a reverse map */
1919  map = convert_tuples_by_name(old_tupdesc, tupdesc,
1920  gettext_noop("could not convert row type"));
1921  if (map != NULL)
1922  {
1923  tuple = do_convert_tuple(tuple, map);
1924  ExecStoreTuple(tuple, slot, InvalidBuffer, false);
1925  }
1926  }
1927 
1928  insertedCols = GetInsertedColumns(resultRelInfo, estate);
1929  updatedCols = GetUpdatedColumns(resultRelInfo, estate);
1930  modifiedCols = bms_union(insertedCols, updatedCols);
1932  slot,
1933  tupdesc,
1934  modifiedCols,
1935  64);
1936  ereport(ERROR,
1937  (errcode(ERRCODE_CHECK_VIOLATION),
1938  errmsg("new row for relation \"%s\" violates check constraint \"%s\"",
1939  RelationGetRelationName(orig_rel), failed),
1940  val_desc ? errdetail("Failing row contains %s.", val_desc) : 0,
1941  errtableconstraint(orig_rel, failed)));
1942  }
1943  }
1944 
1945  if (resultRelInfo->ri_PartitionCheck &&
1946  !ExecPartitionCheck(resultRelInfo, slot, estate))
1947  {
1948  char *val_desc;
1949  Relation orig_rel = rel;
1950 
1951  /* See the comment above. */
1952  if (resultRelInfo->ri_PartitionRoot)
1953  {
1954  HeapTuple tuple = ExecFetchSlotTuple(slot);
1955  TupleDesc old_tupdesc = RelationGetDescr(rel);
1956  TupleConversionMap *map;
1957 
1958  rel = resultRelInfo->ri_PartitionRoot;
1959  tupdesc = RelationGetDescr(rel);
1960  /* a reverse map */
1961  map = convert_tuples_by_name(old_tupdesc, tupdesc,
1962  gettext_noop("could not convert row type"));
1963  if (map != NULL)
1964  {
1965  tuple = do_convert_tuple(tuple, map);
1966  ExecStoreTuple(tuple, slot, InvalidBuffer, false);
1967  }
1968  }
1969 
1970  insertedCols = GetInsertedColumns(resultRelInfo, estate);
1971  updatedCols = GetUpdatedColumns(resultRelInfo, estate);
1972  modifiedCols = bms_union(insertedCols, updatedCols);
1974  slot,
1975  tupdesc,
1976  modifiedCols,
1977  64);
1978  ereport(ERROR,
1979  (errcode(ERRCODE_CHECK_VIOLATION),
1980  errmsg("new row for relation \"%s\" violates partition constraint",
1981  RelationGetRelationName(orig_rel)),
1982  val_desc ? errdetail("Failing row contains %s.", val_desc) : 0));
1983  }
1984 }
#define GetUpdatedColumns(relinfo, estate)
Definition: execMain.c:115
TupleTableSlot * ExecStoreTuple(HeapTuple tuple, TupleTableSlot *slot, Buffer buffer, bool shouldFree)
Definition: execTuples.c:320
Relation ri_RelationDesc
Definition: execnodes.h:374
#define RelationGetDescr(relation)
Definition: rel.h:429
Relation ri_PartitionRoot
Definition: execnodes.h:394
Form_pg_attribute * attrs
Definition: tupdesc.h:74
#define InvalidBuffer
Definition: buf.h:25
#define gettext_noop(x)
Definition: c.h:139
int errcode(int sqlerrcode)
Definition: elog.c:575
int natts
Definition: tupdesc.h:73
int errtableconstraint(Relation rel, const char *conname)
Definition: relcache.c:5286
static bool ExecPartitionCheck(ResultRelInfo *resultRelInfo, TupleTableSlot *slot, EState *estate)
Definition: execMain.c:1787
#define ERROR
Definition: elog.h:43
static char * ExecBuildSlotValueDescription(Oid reloid, TupleTableSlot *slot, TupleDesc tupdesc, Bitmapset *modifiedCols, int maxfieldlen)
Definition: execMain.c:2123
int errdetail(const char *fmt,...)
Definition: elog.c:873
#define RelationGetRelationName(relation)
Definition: rel.h:437
#define ereport(elevel, rest)
Definition: elog.h:122
bool has_not_null
Definition: tupdesc.h:43
TupleConversionMap * convert_tuples_by_name(TupleDesc indesc, TupleDesc outdesc, const char *msg)
Definition: tupconvert.c:205
List * ri_PartitionCheck
Definition: execnodes.h:392
static const char * ExecRelCheck(ResultRelInfo *resultRelInfo, TupleTableSlot *slot, EState *estate)
Definition: execMain.c:1723
bool slot_attisnull(TupleTableSlot *slot, int attnum)
Definition: heaptuple.c:1330
#define NULL
Definition: c.h:229
#define Assert(condition)
Definition: c.h:675
int errtablecol(Relation rel, int attnum)
Definition: relcache.c:5249
TupleConstr * constr
Definition: tupdesc.h:76
Bitmapset * bms_union(const Bitmapset *a, const Bitmapset *b)
Definition: bitmapset.c:218
HeapTuple do_convert_tuple(HeapTuple tuple, TupleConversionMap *map)
Definition: tupconvert.c:343
HeapTuple ExecFetchSlotTuple(TupleTableSlot *slot)
Definition: execTuples.c:618
int errmsg(const char *fmt,...)
Definition: elog.c:797
#define NameStr(name)
Definition: c.h:499
uint16 num_check
Definition: tupdesc.h:42
#define RelationGetRelid(relation)
Definition: rel.h:417
#define GetInsertedColumns(relinfo, estate)
Definition: execMain.c:113
bool ExecContextForcesOids ( PlanState planstate,
bool hasoids 
)

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

1446 {
1447  ResultRelInfo *ri = planstate->state->es_result_relation_info;
1448 
1449  if (ri != NULL)
1450  {
1451  Relation rel = ri->ri_RelationDesc;
1452 
1453  if (rel != NULL)
1454  {
1455  *hasoids = rel->rd_rel->relhasoids;
1456  return true;
1457  }
1458  }
1459 
1460  if (planstate->state->es_top_eflags & EXEC_FLAG_WITH_OIDS)
1461  {
1462  *hasoids = true;
1463  return true;
1464  }
1465  if (planstate->state->es_top_eflags & EXEC_FLAG_WITHOUT_OIDS)
1466  {
1467  *hasoids = false;
1468  return true;
1469  }
1470 
1471  return false;
1472 }
Relation ri_RelationDesc
Definition: execnodes.h:374
EState * state
Definition: execnodes.h:805
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:447
ResultRelInfo * es_result_relation_info
Definition: execnodes.h:423
static void ExecEndPlan ( PlanState planstate,
EState estate 
)
static

Definition at line 1527 of file execMain.c.

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

Referenced by standard_ExecutorEnd().

1528 {
1529  ResultRelInfo *resultRelInfo;
1530  int i;
1531  ListCell *l;
1532 
1533  /*
1534  * shut down the node-type-specific query processing
1535  */
1536  ExecEndNode(planstate);
1537 
1538  /*
1539  * for subplans too
1540  */
1541  foreach(l, estate->es_subplanstates)
1542  {
1543  PlanState *subplanstate = (PlanState *) lfirst(l);
1544 
1545  ExecEndNode(subplanstate);
1546  }
1547 
1548  /*
1549  * destroy the executor's tuple table. Actually we only care about
1550  * releasing buffer pins and tupdesc refcounts; there's no need to pfree
1551  * the TupleTableSlots, since the containing memory context is about to go
1552  * away anyway.
1553  */
1554  ExecResetTupleTable(estate->es_tupleTable, false);
1555 
1556  /*
1557  * close the result relation(s) if any, but hold locks until xact commit.
1558  */
1559  resultRelInfo = estate->es_result_relations;
1560  for (i = estate->es_num_result_relations; i > 0; i--)
1561  {
1562  /* Close indices and then the relation itself */
1563  ExecCloseIndices(resultRelInfo);
1564  heap_close(resultRelInfo->ri_RelationDesc, NoLock);
1565  resultRelInfo++;
1566  }
1567 
1568  /*
1569  * likewise close any trigger target relations
1570  */
1571  foreach(l, estate->es_trig_target_relations)
1572  {
1573  resultRelInfo = (ResultRelInfo *) lfirst(l);
1574  /* Close indices and then the relation itself */
1575  ExecCloseIndices(resultRelInfo);
1576  heap_close(resultRelInfo->ri_RelationDesc, NoLock);
1577  }
1578 
1579  /*
1580  * close any relations selected FOR [KEY] UPDATE/SHARE, again keeping
1581  * locks
1582  */
1583  foreach(l, estate->es_rowMarks)
1584  {
1585  ExecRowMark *erm = (ExecRowMark *) lfirst(l);
1586 
1587  if (erm->relation)
1588  heap_close(erm->relation, NoLock);
1589  }
1590 }
Relation ri_RelationDesc
Definition: execnodes.h:374
void ExecEndNode(PlanState *node)
Definition: execProcnode.c:654
Relation relation
Definition: execnodes.h:501
#define heap_close(r, l)
Definition: heapam.h:97
#define NoLock
Definition: lockdefs.h:34
ResultRelInfo * es_result_relations
Definition: execnodes.h:421
List * es_trig_target_relations
Definition: execnodes.h:426
List * es_tupleTable
Definition: execnodes.h:440
void ExecResetTupleTable(List *tupleTable, bool shouldFree)
Definition: execTuples.c:156
int es_num_result_relations
Definition: execnodes.h:422
#define lfirst(lc)
Definition: pg_list.h:106
List * es_subplanstates
Definition: execnodes.h:453
List * es_rowMarks
Definition: execnodes.h:442
int i
void ExecCloseIndices(ResultRelInfo *resultRelInfo)
Definition: execIndexing.c:224
int ExecFindPartition ( ResultRelInfo resultRelInfo,
PartitionDispatch pd,
TupleTableSlot slot,
EState estate 
)

Definition at line 3265 of file execMain.c.

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

Referenced by CopyFrom(), and ExecInsert().

3267 {
3268  int result;
3269  PartitionDispatchData *failed_at;
3270  TupleTableSlot *failed_slot;
3271 
3272  result = get_partition_for_tuple(pd, slot, estate,
3273  &failed_at, &failed_slot);
3274  if (result < 0)
3275  {
3276  Relation failed_rel;
3277  Datum key_values[PARTITION_MAX_KEYS];
3278  bool key_isnull[PARTITION_MAX_KEYS];
3279  char *val_desc;
3280  ExprContext *ecxt = GetPerTupleExprContext(estate);
3281 
3282  failed_rel = failed_at->reldesc;
3283  ecxt->ecxt_scantuple = failed_slot;
3284  FormPartitionKeyDatum(failed_at, failed_slot, estate,
3285  key_values, key_isnull);
3286  val_desc = ExecBuildSlotPartitionKeyDescription(failed_rel,
3287  key_values,
3288  key_isnull,
3289  64);
3290  Assert(OidIsValid(RelationGetRelid(failed_rel)));
3291  ereport(ERROR,
3292  (errcode(ERRCODE_CHECK_VIOLATION),
3293  errmsg("no partition of relation \"%s\" found for row",
3294  RelationGetRelationName(failed_rel)),
3295  val_desc ? errdetail("Partition key of the failing row contains %s.", val_desc) : 0));
3296  }
3297 
3298  return result;
3299 }
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:1668
return result
Definition: formatting.c:1618
#define OidIsValid(objectId)
Definition: c.h:538
#define GetPerTupleExprContext(estate)
Definition: executor.h:455
#define ERROR
Definition: elog.h:43
static char * ExecBuildSlotPartitionKeyDescription(Relation rel, Datum *values, bool *isnull, int maxfieldlen)
Definition: execMain.c:3309
void FormPartitionKeyDatum(PartitionDispatch pd, TupleTableSlot *slot, EState *estate, Datum *values, bool *isnull)
Definition: partition.c:1609
int errdetail(const char *fmt,...)
Definition: elog.c:873
#define RelationGetRelationName(relation)
Definition: rel.h:437
#define ereport(elevel, rest)
Definition: elog.h:122
uintptr_t Datum
Definition: postgres.h:372
#define Assert(condition)
Definition: c.h:675
TupleTableSlot * ecxt_scantuple
Definition: execnodes.h:197
int errmsg(const char *fmt,...)
Definition: elog.c:797
#define RelationGetRelid(relation)
Definition: rel.h:417
ExecRowMark* ExecFindRowMark ( EState estate,
Index  rti,
bool  missing_ok 
)

Definition at line 2285 of file execMain.c.

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

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

2286 {
2287  ListCell *lc;
2288 
2289  foreach(lc, estate->es_rowMarks)
2290  {
2291  ExecRowMark *erm = (ExecRowMark *) lfirst(lc);
2292 
2293  if (erm->rti == rti)
2294  return erm;
2295  }
2296  if (!missing_ok)
2297  elog(ERROR, "failed to find ExecRowMark for rangetable index %u", rti);
2298  return NULL;
2299 }
#define ERROR
Definition: elog.h:43
Index rti
Definition: execnodes.h:503
#define NULL
Definition: c.h:229
#define lfirst(lc)
Definition: pg_list.h:106
List * es_rowMarks
Definition: execnodes.h:442
#define elog
Definition: elog.h:219
ResultRelInfo* ExecGetTriggerResultRel ( EState estate,
Oid  relid 
)

Definition at line 1355 of file execMain.c.

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

Referenced by afterTriggerInvokeEvents().

1356 {
1357  ResultRelInfo *rInfo;
1358  int nr;
1359  ListCell *l;
1360  Relation rel;
1361  MemoryContext oldcontext;
1362 
1363  /* First, search through the query result relations */
1364  rInfo = estate->es_result_relations;
1365  nr = estate->es_num_result_relations;
1366  while (nr > 0)
1367  {
1368  if (RelationGetRelid(rInfo->ri_RelationDesc) == relid)
1369  return rInfo;
1370  rInfo++;
1371  nr--;
1372  }
1373  /* Nope, but maybe we already made an extra ResultRelInfo for it */
1374  foreach(l, estate->es_trig_target_relations)
1375  {
1376  rInfo = (ResultRelInfo *) lfirst(l);
1377  if (RelationGetRelid(rInfo->ri_RelationDesc) == relid)
1378  return rInfo;
1379  }
1380  /* Nope, so we need a new one */
1381 
1382  /*
1383  * Open the target relation's relcache entry. We assume that an
1384  * appropriate lock is still held by the backend from whenever the trigger
1385  * event got queued, so we need take no new lock here. Also, we need not
1386  * recheck the relkind, so no need for CheckValidResultRel.
1387  */
1388  rel = heap_open(relid, NoLock);
1389 
1390  /*
1391  * Make the new entry in the right context.
1392  */
1393  oldcontext = MemoryContextSwitchTo(estate->es_query_cxt);
1394  rInfo = makeNode(ResultRelInfo);
1395  InitResultRelInfo(rInfo,
1396  rel,
1397  0, /* dummy rangetable index */
1398  NULL,
1399  estate->es_instrument);
1400  estate->es_trig_target_relations =
1401  lappend(estate->es_trig_target_relations, rInfo);
1402  MemoryContextSwitchTo(oldcontext);
1403 
1404  /*
1405  * Currently, we don't need any index information in ResultRelInfos used
1406  * only for triggers, so no need to call ExecOpenIndices.
1407  */
1408 
1409  return rInfo;
1410 }
void InitResultRelInfo(ResultRelInfo *resultRelInfo, Relation resultRelationDesc, Index resultRelationIndex, Relation partition_root, int instrument_options)
Definition: execMain.c:1260
Relation ri_RelationDesc
Definition: execnodes.h:374
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:109
MemoryContext es_query_cxt
Definition: execnodes.h:438
#define NoLock
Definition: lockdefs.h:34
ResultRelInfo * es_result_relations
Definition: execnodes.h:421
int es_instrument
Definition: execnodes.h:448
List * lappend(List *list, void *datum)
Definition: list.c:128
List * es_trig_target_relations
Definition: execnodes.h:426
Relation heap_open(Oid relationId, LOCKMODE lockmode)
Definition: heapam.c:1284
int es_num_result_relations
Definition: execnodes.h:422
#define makeNode(_type_)
Definition: nodes.h:557
#define NULL
Definition: c.h:229
#define lfirst(lc)
Definition: pg_list.h:106
#define RelationGetRelid(relation)
Definition: rel.h:417
static bool ExecPartitionCheck ( ResultRelInfo resultRelInfo,
TupleTableSlot slot,
EState estate 
)
static

Definition at line 1787 of file execMain.c.

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

Referenced by ExecConstraints().

1789 {
1790  ExprContext *econtext;
1791 
1792  /*
1793  * If first time through, build expression state tree for the partition
1794  * check expression. Keep it in the per-query memory context so they'll
1795  * survive throughout the query.
1796  */
1797  if (resultRelInfo->ri_PartitionCheckExpr == NULL)
1798  {
1799  List *qual = resultRelInfo->ri_PartitionCheck;
1800 
1801  resultRelInfo->ri_PartitionCheckExpr = ExecPrepareCheck(qual, estate);
1802  }
1803 
1804  /*
1805  * We will use the EState's per-tuple context for evaluating constraint
1806  * expressions (creating it if it's not already there).
1807  */
1808  econtext = GetPerTupleExprContext(estate);
1809 
1810  /* Arrange for econtext's scan tuple to be the tuple under test */
1811  econtext->ecxt_scantuple = slot;
1812 
1813  /*
1814  * As in case of the catalogued constraints, we treat a NULL result as
1815  * success here, not a failure.
1816  */
1817  return ExecCheck(resultRelInfo->ri_PartitionCheckExpr, econtext);
1818 }
ExprState * ExecPrepareCheck(List *qual, EState *estate)
Definition: execExpr.c:488
ExprState * ri_PartitionCheckExpr
Definition: execnodes.h:393
#define GetPerTupleExprContext(estate)
Definition: executor.h:455
List * ri_PartitionCheck
Definition: execnodes.h:392
#define NULL
Definition: c.h:229
TupleTableSlot * ecxt_scantuple
Definition: execnodes.h:197
bool ExecCheck(ExprState *state, ExprContext *econtext)
Definition: execExpr.c:544
Definition: pg_list.h:45
static void ExecPostprocessPlan ( EState estate)
static

Definition at line 1481 of file execMain.c.

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

Referenced by standard_ExecutorFinish().

1482 {
1483  ListCell *lc;
1484 
1485  /*
1486  * Make sure nodes run forward.
1487  */
1489 
1490  /*
1491  * Run any secondary ModifyTable nodes to completion, in case the main
1492  * query did not fetch all rows from them. (We do this to ensure that
1493  * such nodes have predictable results.)
1494  */
1495  foreach(lc, estate->es_auxmodifytables)
1496  {
1497  PlanState *ps = (PlanState *) lfirst(lc);
1498 
1499  for (;;)
1500  {
1501  TupleTableSlot *slot;
1502 
1503  /* Reset the per-output-tuple exprcontext each time */
1504  ResetPerTupleExprContext(estate);
1505 
1506  slot = ExecProcNode(ps);
1507 
1508  if (TupIsNull(slot))
1509  break;
1510  }
1511  }
1512 }
TupleTableSlot * ExecProcNode(PlanState *node)
Definition: execProcnode.c:398
#define ResetPerTupleExprContext(estate)
Definition: executor.h:464
ScanDirection es_direction
Definition: execnodes.h:408
#define TupIsNull(slot)
Definition: tuptable.h:138
List * es_auxmodifytables
Definition: execnodes.h:455
#define lfirst(lc)
Definition: pg_list.h:106
static const char* ExecRelCheck ( ResultRelInfo resultRelInfo,
TupleTableSlot slot,
EState estate 
)
static

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

1725 {
1726  Relation rel = resultRelInfo->ri_RelationDesc;
1727  int ncheck = rel->rd_att->constr->num_check;
1728  ConstrCheck *check = rel->rd_att->constr->check;
1729  ExprContext *econtext;
1730  MemoryContext oldContext;
1731  int i;
1732 
1733  /*
1734  * If first time through for this result relation, build expression
1735  * nodetrees for rel's constraint expressions. Keep them in the per-query
1736  * memory context so they'll survive throughout the query.
1737  */
1738  if (resultRelInfo->ri_ConstraintExprs == NULL)
1739  {
1740  oldContext = MemoryContextSwitchTo(estate->es_query_cxt);
1741  resultRelInfo->ri_ConstraintExprs =
1742  (ExprState **) palloc(ncheck * sizeof(ExprState *));
1743  for (i = 0; i < ncheck; i++)
1744  {
1745  Expr *checkconstr;
1746 
1747  checkconstr = stringToNode(check[i].ccbin);
1748  resultRelInfo->ri_ConstraintExprs[i] =
1749  ExecPrepareExpr(checkconstr, estate);
1750  }
1751  MemoryContextSwitchTo(oldContext);
1752  }
1753 
1754  /*
1755  * We will use the EState's per-tuple context for evaluating constraint
1756  * expressions (creating it if it's not already there).
1757  */
1758  econtext = GetPerTupleExprContext(estate);
1759 
1760  /* Arrange for econtext's scan tuple to be the tuple under test */
1761  econtext->ecxt_scantuple = slot;
1762 
1763  /* And evaluate the constraints */
1764  for (i = 0; i < ncheck; i++)
1765  {
1766  ExprState *checkconstr = resultRelInfo->ri_ConstraintExprs[i];
1767 
1768  /*
1769  * NOTE: SQL specifies that a NULL result from a constraint expression
1770  * is not to be treated as a failure. Therefore, use ExecCheck not
1771  * ExecQual.
1772  */
1773  if (!ExecCheck(checkconstr, econtext))
1774  return check[i].ccname;
1775  }
1776 
1777  /* NULL result means no error */
1778  return NULL;
1779 }
void * stringToNode(char *str)
Definition: read.c:38
Relation ri_RelationDesc
Definition: execnodes.h:374
char * ccname
Definition: tupdesc.h:30
ConstrCheck * check
Definition: tupdesc.h:40
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:109
ExprState * ExecPrepareExpr(Expr *node, EState *estate)
Definition: execExpr.c:437
#define GetPerTupleExprContext(estate)
Definition: executor.h:455
MemoryContext es_query_cxt
Definition: execnodes.h:438
ExprState ** ri_ConstraintExprs
Definition: execnodes.h:387
TupleDesc rd_att
Definition: rel.h:115
#define NULL
Definition: c.h:229
TupleConstr * constr
Definition: tupdesc.h:76
TupleTableSlot * ecxt_scantuple
Definition: execnodes.h:197
void * palloc(Size size)
Definition: mcxt.c:849
int i
bool ExecCheck(ExprState *state, ExprContext *econtext)
Definition: execExpr.c:544
uint16 num_check
Definition: tupdesc.h:42
void ExecSetupPartitionTupleRouting ( Relation  rel,
PartitionDispatch **  pd,
ResultRelInfo **  partitions,
TupleConversionMap ***  tup_conv_maps,
TupleTableSlot **  partition_tuple_slot,
int *  num_parted,
int *  num_partitions 
)

Definition at line 3176 of file execMain.c.

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

Referenced by BeginCopy(), and ExecInitModifyTable().

3182 {
3183  TupleDesc tupDesc = RelationGetDescr(rel);
3184  List *leaf_parts;
3185  ListCell *cell;
3186  int i;
3187  ResultRelInfo *leaf_part_rri;
3188 
3189  /* Get the tuple-routing information and lock partitions */
3190  *pd = RelationGetPartitionDispatchInfo(rel, RowExclusiveLock, num_parted,
3191  &leaf_parts);
3192  *num_partitions = list_length(leaf_parts);
3193  *partitions = (ResultRelInfo *) palloc(*num_partitions *
3194  sizeof(ResultRelInfo));
3195  *tup_conv_maps = (TupleConversionMap **) palloc0(*num_partitions *
3196  sizeof(TupleConversionMap *));
3197 
3198  /*
3199  * Initialize an empty slot that will be used to manipulate tuples of any
3200  * given partition's rowtype. It is attached to the caller-specified node
3201  * (such as ModifyTableState) and released when the node finishes
3202  * processing.
3203  */
3204  *partition_tuple_slot = MakeTupleTableSlot();
3205 
3206  leaf_part_rri = *partitions;
3207  i = 0;
3208  foreach(cell, leaf_parts)
3209  {
3210  Relation partrel;
3211  TupleDesc part_tupdesc;
3212 
3213  /*
3214  * We locked all the partitions above including the leaf partitions.
3215  * Note that each of the relations in *partitions are eventually
3216  * closed by the caller.
3217  */
3218  partrel = heap_open(lfirst_oid(cell), NoLock);
3219  part_tupdesc = RelationGetDescr(partrel);
3220 
3221  /*
3222  * Verify result relation is a valid target for the current operation.
3223  */
3224  CheckValidResultRel(partrel, CMD_INSERT);
3225 
3226  /*
3227  * Save a tuple conversion map to convert a tuple routed to this
3228  * partition from the parent's type to the partition's.
3229  */
3230  (*tup_conv_maps)[i] = convert_tuples_by_name(tupDesc, part_tupdesc,
3231  gettext_noop("could not convert row type"));
3232 
3233  InitResultRelInfo(leaf_part_rri,
3234  partrel,
3235  1, /* dummy */
3236  rel,
3237  0);
3238 
3239  /*
3240  * Open partition indices (remember we do not support ON CONFLICT in
3241  * case of partitioned tables, so we do not need support information
3242  * for speculative insertion)
3243  */
3244  if (leaf_part_rri->ri_RelationDesc->rd_rel->relhasindex &&
3245  leaf_part_rri->ri_IndexRelationDescs == NULL)
3246  ExecOpenIndices(leaf_part_rri, false);
3247 
3248  leaf_part_rri++;
3249  i++;
3250  }
3251 }
void InitResultRelInfo(ResultRelInfo *resultRelInfo, Relation resultRelationDesc, Index resultRelationIndex, Relation partition_root, int instrument_options)
Definition: execMain.c:1260
Relation ri_RelationDesc
Definition: execnodes.h:374
#define RelationGetDescr(relation)
Definition: rel.h:429
TupleTableSlot * MakeTupleTableSlot(void)
Definition: execTuples.c:111
#define gettext_noop(x)
Definition: c.h:139
Form_pg_class rd_rel
Definition: rel.h:114
void ExecOpenIndices(ResultRelInfo *resultRelInfo, bool speculative)
Definition: execIndexing.c:149
#define NoLock
Definition: lockdefs.h:34
#define RowExclusiveLock
Definition: lockdefs.h:38
void CheckValidResultRel(Relation resultRel, CmdType operation)
Definition: execMain.c:1060
TupleConversionMap * convert_tuples_by_name(TupleDesc indesc, TupleDesc outdesc, const char *msg)
Definition: tupconvert.c:205
void * palloc0(Size size)
Definition: mcxt.c:878
Relation heap_open(Oid relationId, LOCKMODE lockmode)
Definition: heapam.c:1284
#define NULL
Definition: c.h:229
static int list_length(const List *l)
Definition: pg_list.h:89
PartitionDispatch * RelationGetPartitionDispatchInfo(Relation rel, int lockmode, int *num_parted, List **leaf_part_oids)
Definition: partition.c:995
void * palloc(Size size)
Definition: mcxt.c:849
int i
Definition: pg_list.h:45
RelationPtr ri_IndexRelationDescs
Definition: execnodes.h:376
#define lfirst_oid(lc)
Definition: pg_list.h:108
LockTupleMode ExecUpdateLockMode ( EState estate,
ResultRelInfo relinfo 
)

Definition at line 2259 of file execMain.c.

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

Referenced by ExecBRUpdateTriggers(), and ExecOnConflictUpdate().

2260 {
2261  Bitmapset *keyCols;
2262  Bitmapset *updatedCols;
2263 
2264  /*
2265  * Compute lock mode to use. If columns that are part of the key have not
2266  * been modified, then we can use a weaker lock, allowing for better
2267  * concurrency.
2268  */
2269  updatedCols = GetUpdatedColumns(relinfo, estate);
2270  keyCols = RelationGetIndexAttrBitmap(relinfo->ri_RelationDesc,
2272 
2273  if (bms_overlap(keyCols, updatedCols))
2274  return LockTupleExclusive;
2275 
2276  return LockTupleNoKeyExclusive;
2277 }
#define GetUpdatedColumns(relinfo, estate)
Definition: execMain.c:115
Relation ri_RelationDesc
Definition: execnodes.h:374
bool bms_overlap(const Bitmapset *a, const Bitmapset *b)
Definition: bitmapset.c:443
Bitmapset * RelationGetIndexAttrBitmap(Relation relation, IndexAttrBitmapKind attrKind)
Definition: relcache.c:4836
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 1605 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().

1614 {
1615  TupleTableSlot *slot;
1616  uint64 current_tuple_count;
1617 
1618  /*
1619  * initialize local variables
1620  */
1621  current_tuple_count = 0;
1622 
1623  /*
1624  * Set the direction.
1625  */
1626  estate->es_direction = direction;
1627 
1628  /*
1629  * If the plan might potentially be executed multiple times, we must force
1630  * it to run without parallelism, because we might exit early. Also
1631  * disable parallelism when writing into a relation, because no database
1632  * changes are allowed in parallel mode.
1633  */
1634  if (!execute_once || dest->mydest == DestIntoRel)
1635  use_parallel_mode = false;
1636 
1637  if (use_parallel_mode)
1639 
1640  /*
1641  * Loop until we've processed the proper number of tuples from the plan.
1642  */
1643  for (;;)
1644  {
1645  /* Reset the per-output-tuple exprcontext */
1646  ResetPerTupleExprContext(estate);
1647 
1648  /*
1649  * Execute the plan and obtain a tuple
1650  */
1651  slot = ExecProcNode(planstate);
1652 
1653  /*
1654  * if the tuple is null, then we assume there is nothing more to
1655  * process so we just end the loop...
1656  */
1657  if (TupIsNull(slot))
1658  {
1659  /* Allow nodes to release or shut down resources. */
1660  (void) ExecShutdownNode(planstate);
1661  break;
1662  }
1663 
1664  /*
1665  * If we have a junk filter, then project a new tuple with the junk
1666  * removed.
1667  *
1668  * Store this new "clean" tuple in the junkfilter's resultSlot.
1669  * (Formerly, we stored it back over the "dirty" tuple, which is WRONG
1670  * because that tuple slot has the wrong descriptor.)
1671  */
1672  if (estate->es_junkFilter != NULL)
1673  slot = ExecFilterJunk(estate->es_junkFilter, slot);
1674 
1675  /*
1676  * If we are supposed to send the tuple somewhere, do so. (In
1677  * practice, this is probably always the case at this point.)
1678  */
1679  if (sendTuples)
1680  {
1681  /*
1682  * If we are not able to send the tuple, we assume the destination
1683  * has closed and no more tuples can be sent. If that's the case,
1684  * end the loop.
1685  */
1686  if (!((*dest->receiveSlot) (slot, dest)))
1687  break;
1688  }
1689 
1690  /*
1691  * Count tuples processed, if this is a SELECT. (For other operation
1692  * types, the ModifyTable plan node must count the appropriate
1693  * events.)
1694  */
1695  if (operation == CMD_SELECT)
1696  (estate->es_processed)++;
1697 
1698  /*
1699  * check our tuple count.. if we've processed the proper number then
1700  * quit, else loop again and process more tuples. Zero numberTuples
1701  * means no limit.
1702  */
1703  current_tuple_count++;
1704  if (numberTuples && numberTuples == current_tuple_count)
1705  {
1706  /* Allow nodes to release or shut down resources. */
1707  (void) ExecShutdownNode(planstate);
1708  break;
1709  }
1710  }
1711 
1712  if (use_parallel_mode)
1713  ExitParallelMode();
1714 }
JunkFilter * es_junkFilter
Definition: execnodes.h:415
TupleTableSlot * ExecProcNode(PlanState *node)
Definition: execProcnode.c:398
#define ResetPerTupleExprContext(estate)
Definition: executor.h:464
bool ExecShutdownNode(PlanState *node)
Definition: execProcnode.c:855
CommandDest mydest
Definition: dest.h:128
ScanDirection es_direction
Definition: execnodes.h:408
void ExitParallelMode(void)
Definition: xact.c:893
#define TupIsNull(slot)
Definition: tuptable.h:138
TupleTableSlot * ExecFilterJunk(JunkFilter *junkfilter, TupleTableSlot *slot)
Definition: execJunk.c:262
#define NULL
Definition: c.h:229
uint64 es_processed
Definition: execnodes.h:444
void EnterParallelMode(void)
Definition: xact.c:880
bool(* receiveSlot)(TupleTableSlot *slot, DestReceiver *self)
Definition: dest.h:118
void ExecutorEnd ( QueryDesc queryDesc)

Definition at line 458 of file execMain.c.

References ExecutorEnd_hook, and standard_ExecutorEnd().

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

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

Definition at line 398 of file execMain.c.

References ExecutorFinish_hook, and standard_ExecutorFinish().

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

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

Definition at line 524 of file execMain.c.

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

Referenced by DoPortalRewind(), and PersistHoldablePortal().

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

Definition at line 296 of file execMain.c.

References ExecutorRun_hook, and standard_ExecutorRun().

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

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

Definition at line 144 of file execMain.c.

References ExecutorStart_hook, and standard_ExecutorStart().

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

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

Definition at line 1996 of file execMain.c.

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

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

1998 {
1999  Relation rel = resultRelInfo->ri_RelationDesc;
2000  TupleDesc tupdesc = RelationGetDescr(rel);
2001  ExprContext *econtext;
2002  ListCell *l1,
2003  *l2;
2004 
2005  /*
2006  * We will use the EState's per-tuple context for evaluating constraint
2007  * expressions (creating it if it's not already there).
2008  */
2009  econtext = GetPerTupleExprContext(estate);
2010 
2011  /* Arrange for econtext's scan tuple to be the tuple under test */
2012  econtext->ecxt_scantuple = slot;
2013 
2014  /* Check each of the constraints */
2015  forboth(l1, resultRelInfo->ri_WithCheckOptions,
2016  l2, resultRelInfo->ri_WithCheckOptionExprs)
2017  {
2018  WithCheckOption *wco = (WithCheckOption *) lfirst(l1);
2019  ExprState *wcoExpr = (ExprState *) lfirst(l2);
2020 
2021  /*
2022  * Skip any WCOs which are not the kind we are looking for at this
2023  * time.
2024  */
2025  if (wco->kind != kind)
2026  continue;
2027 
2028  /*
2029  * WITH CHECK OPTION checks are intended to ensure that the new tuple
2030  * is visible (in the case of a view) or that it passes the
2031  * 'with-check' policy (in the case of row security). If the qual
2032  * evaluates to NULL or FALSE, then the new tuple won't be included in
2033  * the view or doesn't pass the 'with-check' policy for the table.
2034  */
2035  if (!ExecQual(wcoExpr, econtext))
2036  {
2037  char *val_desc;
2038  Bitmapset *modifiedCols;
2039  Bitmapset *insertedCols;
2040  Bitmapset *updatedCols;
2041 
2042  switch (wco->kind)
2043  {
2044  /*
2045  * For WITH CHECK OPTIONs coming from views, we might be
2046  * able to provide the details on the row, depending on
2047  * the permissions on the relation (that is, if the user
2048  * could view it directly anyway). For RLS violations, we
2049  * don't include the data since we don't know if the user
2050  * should be able to view the tuple as as that depends on
2051  * the USING policy.
2052  */
2053  case WCO_VIEW_CHECK:
2054  insertedCols = GetInsertedColumns(resultRelInfo, estate);
2055  updatedCols = GetUpdatedColumns(resultRelInfo, estate);
2056  modifiedCols = bms_union(insertedCols, updatedCols);
2058  slot,
2059  tupdesc,
2060  modifiedCols,
2061  64);
2062 
2063  ereport(ERROR,
2064  (errcode(ERRCODE_WITH_CHECK_OPTION_VIOLATION),
2065  errmsg("new row violates check option for view \"%s\"",
2066  wco->relname),
2067  val_desc ? errdetail("Failing row contains %s.",
2068  val_desc) : 0));
2069  break;
2070  case WCO_RLS_INSERT_CHECK:
2071  case WCO_RLS_UPDATE_CHECK:
2072  if (wco->polname != NULL)
2073  ereport(ERROR,
2074  (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
2075  errmsg("new row violates row-level security policy \"%s\" for table \"%s\"",
2076  wco->polname, wco->relname)));
2077  else
2078  ereport(ERROR,
2079  (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
2080  errmsg("new row violates row-level security policy for table \"%s\"",
2081  wco->relname)));
2082  break;
2084  if (wco->polname != NULL)
2085  ereport(ERROR,
2086  (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
2087  errmsg("new row violates row-level security policy \"%s\" (USING expression) for table \"%s\"",
2088  wco->polname, wco->relname)));
2089  else
2090  ereport(ERROR,
2091  (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
2092  errmsg("new row violates row-level security policy (USING expression) for table \"%s\"",
2093  wco->relname)));
2094  break;
2095  default:
2096  elog(ERROR, "unrecognized WCO kind: %u", wco->kind);
2097  break;
2098  }
2099  }
2100  }
2101 }
#define GetUpdatedColumns(relinfo, estate)
Definition: execMain.c:115
Relation ri_RelationDesc
Definition: execnodes.h:374
#define forboth(cell1, list1, cell2, list2)
Definition: pg_list.h:180
#define RelationGetDescr(relation)
Definition: rel.h:429
int errcode(int sqlerrcode)
Definition: elog.c:575
static bool ExecQual(ExprState *state, ExprContext *econtext)
Definition: executor.h:345
List * ri_WithCheckOptionExprs
Definition: execnodes.h:386
#define GetPerTupleExprContext(estate)
Definition: executor.h:455
#define ERROR
Definition: elog.h:43
static char * ExecBuildSlotValueDescription(Oid reloid, TupleTableSlot *slot, TupleDesc tupdesc, Bitmapset *modifiedCols, int maxfieldlen)
Definition: execMain.c:2123
int errdetail(const char *fmt,...)
Definition: elog.c:873
#define ereport(elevel, rest)
Definition: elog.h:122
List * ri_WithCheckOptions
Definition: execnodes.h:385
#define NULL
Definition: c.h:229
#define lfirst(lc)
Definition: pg_list.h:106
Bitmapset * bms_union(const Bitmapset *a, const Bitmapset *b)
Definition: bitmapset.c:218
TupleTableSlot * ecxt_scantuple
Definition: execnodes.h:197
int errmsg(const char *fmt,...)
Definition: elog.c:797
#define elog
Definition: elog.h:219
#define RelationGetRelid(relation)
Definition: rel.h:417
#define GetInsertedColumns(relinfo, estate)
Definition: execMain.c:113
static void InitPlan ( QueryDesc queryDesc,
int  eflags 
)
static

Definition at line 802 of file execMain.c.

References AccessShareLock, Assert, bms_is_member(), CheckValidRowMarkRel(), CMD_SELECT, ExecRowMark::curCtid, elog, ExecRowMark::ermActive, ExecRowMark::ermExtra, ERROR, EState::es_epqScanDone, EState::es_epqTuple, EState::es_epqTupleSet, EState::es_instrument, EState::es_junkFilter, EState::es_num_result_relations, EState::es_plannedstmt, EState::es_range_table, EState::es_result_relation_info, EState::es_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(), 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, ROW_MARK_COPY, ROW_MARK_EXCLUSIVE, ROW_MARK_KEYSHARE, ROW_MARK_NOKEYEXCLUSIVE, ROW_MARK_REFERENCE, ROW_MARK_SHARE, RowExclusiveLock, ExecRowMark::rowmarkId, PlanRowMark::rowmarkId, PlannedStmt::rowMarks, RowShareLock, PlannedStmt::rtable, ExecRowMark::rti, PlanRowMark::rti, ExecRowMark::strength, PlanRowMark::strength, PlannedStmt::subplans, Plan::targetlist, tupleDesc::tdhasoid, QueryDesc::tupDesc, ExecRowMark::waitPolicy, and PlanRowMark::waitPolicy.

Referenced by standard_ExecutorStart().

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

Definition at line 1260 of file execMain.c.

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

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

1265 {
1266  List *partition_check = NIL;
1267 
1268  MemSet(resultRelInfo, 0, sizeof(ResultRelInfo));
1269  resultRelInfo->type = T_ResultRelInfo;
1270  resultRelInfo->ri_RangeTableIndex = resultRelationIndex;
1271  resultRelInfo->ri_RelationDesc = resultRelationDesc;
1272  resultRelInfo->ri_NumIndices = 0;
1273  resultRelInfo->ri_IndexRelationDescs = NULL;
1274  resultRelInfo->ri_IndexRelationInfo = NULL;
1275  /* make a copy so as not to depend on relcache info not changing... */
1276  resultRelInfo->ri_TrigDesc = CopyTriggerDesc(resultRelationDesc->trigdesc);
1277  if (resultRelInfo->ri_TrigDesc)
1278  {
1279  int n = resultRelInfo->ri_TrigDesc->numtriggers;
1280 
1281  resultRelInfo->ri_TrigFunctions = (FmgrInfo *)
1282  palloc0(n * sizeof(FmgrInfo));
1283  resultRelInfo->ri_TrigWhenExprs = (ExprState **)
1284  palloc0(n * sizeof(ExprState *));
1285  if (instrument_options)
1286  resultRelInfo->ri_TrigInstrument = InstrAlloc(n, instrument_options);
1287  }
1288  else
1289  {
1290  resultRelInfo->ri_TrigFunctions = NULL;
1291  resultRelInfo->ri_TrigWhenExprs = NULL;
1292  resultRelInfo->ri_TrigInstrument = NULL;
1293  }
1294  if (resultRelationDesc->rd_rel->relkind == RELKIND_FOREIGN_TABLE)
1295  resultRelInfo->ri_FdwRoutine = GetFdwRoutineForRelation(resultRelationDesc, true);
1296  else
1297  resultRelInfo->ri_FdwRoutine = NULL;
1298  resultRelInfo->ri_FdwState = NULL;
1299  resultRelInfo->ri_usesFdwDirectModify = false;
1300  resultRelInfo->ri_ConstraintExprs = NULL;
1301  resultRelInfo->ri_junkFilter = NULL;
1302  resultRelInfo->ri_projectReturning = NULL;
1303 
1304  /*
1305  * If partition_root has been specified, that means we are building the
1306  * ResultRelationInfo for one of its leaf partitions. In that case, we
1307  * need *not* initialize the leaf partition's constraint, but rather the
1308  * the partition_root's (if any). We must do that explicitly like this,
1309  * because implicit partition constraints are not inherited like user-
1310  * defined constraints and would fail to be enforced by ExecConstraints()
1311  * after a tuple is routed to a leaf partition.
1312  */
1313  if (partition_root)
1314  {
1315  /*
1316  * Root table itself may or may not be a partition; partition_check
1317  * would be NIL in the latter case.
1318  */
1319  partition_check = RelationGetPartitionQual(partition_root);
1320 
1321  /*
1322  * This is not our own partition constraint, but rather an ancestor's.
1323  * So any Vars in it bear the ancestor's attribute numbers. We must
1324  * switch them to our own. (dummy varno = 1)
1325  */
1326  if (partition_check != NIL)
1327  partition_check = map_partition_varattnos(partition_check, 1,
1328  resultRelationDesc,
1329  partition_root);
1330  }
1331  else
1332  partition_check = RelationGetPartitionQual(resultRelationDesc);
1333 
1334  resultRelInfo->ri_PartitionCheck = partition_check;
1335  resultRelInfo->ri_PartitionRoot = partition_root;
1336 }
int ri_NumIndices
Definition: execnodes.h:375
#define NIL
Definition: pg_list.h:69
JunkFilter * ri_junkFilter
Definition: execnodes.h:388
Definition: fmgr.h:56
Relation ri_RelationDesc
Definition: execnodes.h:374
Relation ri_PartitionRoot
Definition: execnodes.h:394
Instrumentation * ri_TrigInstrument
Definition: execnodes.h:381
Instrumentation * InstrAlloc(int n, int instrument_options)
Definition: instrument.c:30
#define MemSet(start, val, len)
Definition: c.h:857
Form_pg_class rd_rel
Definition: rel.h:114
Index ri_RangeTableIndex
Definition: execnodes.h:373
NodeTag type
Definition: execnodes.h:372
TriggerDesc * trigdesc
Definition: rel.h:120
bool ri_usesFdwDirectModify
Definition: execnodes.h:384
ExprState ** ri_TrigWhenExprs
Definition: execnodes.h:380
ProjectionInfo * ri_projectReturning
Definition: execnodes.h:389
struct FdwRoutine * ri_FdwRoutine
Definition: execnodes.h:382
#define RELKIND_FOREIGN_TABLE
Definition: pg_class.h:167
ExprState ** ri_ConstraintExprs
Definition: execnodes.h:387
TriggerDesc * ri_TrigDesc
Definition: execnodes.h:378
int numtriggers
Definition: reltrigger.h:49
List * RelationGetPartitionQual(Relation rel)
Definition: partition.c:962
void * palloc0(Size size)
Definition: mcxt.c:878
List * ri_PartitionCheck
Definition: execnodes.h:392
void * ri_FdwState
Definition: execnodes.h:383
#define NULL
Definition: c.h:229
TriggerDesc * CopyTriggerDesc(TriggerDesc *trigdesc)
Definition: trigger.c:1833
FdwRoutine * GetFdwRoutineForRelation(Relation relation, bool makecopy)
Definition: foreign.c:395
IndexInfo ** ri_IndexRelationInfo
Definition: execnodes.h:377
Definition: pg_list.h:45
RelationPtr ri_IndexRelationDescs
Definition: execnodes.h:376
FmgrInfo * ri_TrigFunctions
Definition: execnodes.h:379
List * map_partition_varattnos(List *expr, int target_varno, Relation partrel, Relation parent)
Definition: partition.c:932
void standard_ExecutorEnd ( QueryDesc queryDesc)

Definition at line 467 of file execMain.c.

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

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

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

Definition at line 407 of file execMain.c.

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

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

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

Definition at line 307 of file execMain.c.

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

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

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

Definition at line 153 of file execMain.c.

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

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

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

Variable Documentation

ExecutorCheckPerms_hook_type ExecutorCheckPerms_hook = NULL

Definition at line 75 of file execMain.c.

Referenced by _PG_init(), and ExecCheckRTPerms().

ExecutorEnd_hook_type ExecutorEnd_hook = NULL

Definition at line 72 of file execMain.c.

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

ExecutorFinish_hook_type ExecutorFinish_hook = NULL

Definition at line 71 of file execMain.c.

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

ExecutorRun_hook_type ExecutorRun_hook = NULL

Definition at line 70 of file execMain.c.

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

ExecutorStart_hook_type ExecutorStart_hook = NULL

Definition at line 69 of file execMain.c.

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