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)
 
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)
 
void standard_ExecutorRun (QueryDesc *queryDesc, ScanDirection direction, uint64 count)
 
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, TupleTableSlot *orig_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 112 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 114 of file execMain.c.

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

Function Documentation

void CheckValidResultRel ( Relation  resultRel,
CmdType  operation 
)

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

1047 {
1048  TriggerDesc *trigDesc = resultRel->trigdesc;
1049  FdwRoutine *fdwroutine;
1050 
1051  switch (resultRel->rd_rel->relkind)
1052  {
1053  case RELKIND_RELATION:
1055  CheckCmdReplicaIdentity(resultRel, operation);
1056  break;
1057  case RELKIND_SEQUENCE:
1058  ereport(ERROR,
1059  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1060  errmsg("cannot change sequence \"%s\"",
1061  RelationGetRelationName(resultRel))));
1062  break;
1063  case RELKIND_TOASTVALUE:
1064  ereport(ERROR,
1065  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1066  errmsg("cannot change TOAST relation \"%s\"",
1067  RelationGetRelationName(resultRel))));
1068  break;
1069  case RELKIND_VIEW:
1070 
1071  /*
1072  * Okay only if there's a suitable INSTEAD OF trigger. Messages
1073  * here should match rewriteHandler.c's rewriteTargetView, except
1074  * that we omit errdetail because we haven't got the information
1075  * handy (and given that we really shouldn't get here anyway, it's
1076  * not worth great exertion to get).
1077  */
1078  switch (operation)
1079  {
1080  case CMD_INSERT:
1081  if (!trigDesc || !trigDesc->trig_insert_instead_row)
1082  ereport(ERROR,
1083  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
1084  errmsg("cannot insert into view \"%s\"",
1085  RelationGetRelationName(resultRel)),
1086  errhint("To enable inserting into the view, provide an INSTEAD OF INSERT trigger or an unconditional ON INSERT DO INSTEAD rule.")));
1087  break;
1088  case CMD_UPDATE:
1089  if (!trigDesc || !trigDesc->trig_update_instead_row)
1090  ereport(ERROR,
1091  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
1092  errmsg("cannot update view \"%s\"",
1093  RelationGetRelationName(resultRel)),
1094  errhint("To enable updating the view, provide an INSTEAD OF UPDATE trigger or an unconditional ON UPDATE DO INSTEAD rule.")));
1095  break;
1096  case CMD_DELETE:
1097  if (!trigDesc || !trigDesc->trig_delete_instead_row)
1098  ereport(ERROR,
1099  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
1100  errmsg("cannot delete from view \"%s\"",
1101  RelationGetRelationName(resultRel)),
1102  errhint("To enable deleting from the view, provide an INSTEAD OF DELETE trigger or an unconditional ON DELETE DO INSTEAD rule.")));
1103  break;
1104  default:
1105  elog(ERROR, "unrecognized CmdType: %d", (int) operation);
1106  break;
1107  }
1108  break;
1109  case RELKIND_MATVIEW:
1111  ereport(ERROR,
1112  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1113  errmsg("cannot change materialized view \"%s\"",
1114  RelationGetRelationName(resultRel))));
1115  break;
1116  case RELKIND_FOREIGN_TABLE:
1117  /* Okay only if the FDW supports it */
1118  fdwroutine = GetFdwRoutineForRelation(resultRel, false);
1119  switch (operation)
1120  {
1121  case CMD_INSERT:
1122  if (fdwroutine->ExecForeignInsert == NULL)
1123  ereport(ERROR,
1124  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1125  errmsg("cannot insert into foreign table \"%s\"",
1126  RelationGetRelationName(resultRel))));
1127  if (fdwroutine->IsForeignRelUpdatable != NULL &&
1128  (fdwroutine->IsForeignRelUpdatable(resultRel) & (1 << CMD_INSERT)) == 0)
1129  ereport(ERROR,
1130  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
1131  errmsg("foreign table \"%s\" does not allow inserts",
1132  RelationGetRelationName(resultRel))));
1133  break;
1134  case CMD_UPDATE:
1135  if (fdwroutine->ExecForeignUpdate == NULL)
1136  ereport(ERROR,
1137  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1138  errmsg("cannot update foreign table \"%s\"",
1139  RelationGetRelationName(resultRel))));
1140  if (fdwroutine->IsForeignRelUpdatable != NULL &&
1141  (fdwroutine->IsForeignRelUpdatable(resultRel) & (1 << CMD_UPDATE)) == 0)
1142  ereport(ERROR,
1143  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
1144  errmsg("foreign table \"%s\" does not allow updates",
1145  RelationGetRelationName(resultRel))));
1146  break;
1147  case CMD_DELETE:
1148  if (fdwroutine->ExecForeignDelete == NULL)
1149  ereport(ERROR,
1150  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1151  errmsg("cannot delete from foreign table \"%s\"",
1152  RelationGetRelationName(resultRel))));
1153  if (fdwroutine->IsForeignRelUpdatable != NULL &&
1154  (fdwroutine->IsForeignRelUpdatable(resultRel) & (1 << CMD_DELETE)) == 0)
1155  ereport(ERROR,
1156  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
1157  errmsg("foreign table \"%s\" does not allow deletes",
1158  RelationGetRelationName(resultRel))));
1159  break;
1160  default:
1161  elog(ERROR, "unrecognized CmdType: %d", (int) operation);
1162  break;
1163  }
1164  break;
1165  default:
1166  ereport(ERROR,
1167  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1168  errmsg("cannot change relation \"%s\"",
1169  RelationGetRelationName(resultRel))));
1170  break;
1171  }
1172 }
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:113
bool trig_insert_instead_row
Definition: reltrigger.h:57
#define ERROR
Definition: elog.h:43
TriggerDesc * trigdesc
Definition: rel.h:119
#define RelationGetRelationName(relation)
Definition: rel.h:433
#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 1181 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().

1182 {
1183  FdwRoutine *fdwroutine;
1184 
1185  switch (rel->rd_rel->relkind)
1186  {
1187  case RELKIND_RELATION:
1189  /* OK */
1190  break;
1191  case RELKIND_SEQUENCE:
1192  /* Must disallow this because we don't vacuum sequences */
1193  ereport(ERROR,
1194  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1195  errmsg("cannot lock rows in sequence \"%s\"",
1196  RelationGetRelationName(rel))));
1197  break;
1198  case RELKIND_TOASTVALUE:
1199  /* We could allow this, but there seems no good reason to */
1200  ereport(ERROR,
1201  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1202  errmsg("cannot lock rows in TOAST relation \"%s\"",
1203  RelationGetRelationName(rel))));
1204  break;
1205  case RELKIND_VIEW:
1206  /* Should not get here; planner should have expanded the view */
1207  ereport(ERROR,
1208  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1209  errmsg("cannot lock rows in view \"%s\"",
1210  RelationGetRelationName(rel))));
1211  break;
1212  case RELKIND_MATVIEW:
1213  /* Allow referencing a matview, but not actual locking clauses */
1214  if (markType != ROW_MARK_REFERENCE)
1215  ereport(ERROR,
1216  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1217  errmsg("cannot lock rows in materialized view \"%s\"",
1218  RelationGetRelationName(rel))));
1219  break;
1220  case RELKIND_FOREIGN_TABLE:
1221  /* Okay only if the FDW supports it */
1222  fdwroutine = GetFdwRoutineForRelation(rel, false);
1223  if (fdwroutine->RefetchForeignRow == NULL)
1224  ereport(ERROR,
1225  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1226  errmsg("cannot lock rows in foreign table \"%s\"",
1227  RelationGetRelationName(rel))));
1228  break;
1229  default:
1230  ereport(ERROR,
1231  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1232  errmsg("cannot lock rows in relation \"%s\"",
1233  RelationGetRelationName(rel))));
1234  break;
1235  }
1236 }
#define RELKIND_MATVIEW
Definition: pg_class.h:165
int errcode(int sqlerrcode)
Definition: elog.c:575
Form_pg_class rd_rel
Definition: rel.h:113
#define ERROR
Definition: elog.h:43
#define RelationGetRelationName(relation)
Definition: rel.h:433
#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 2328 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().

2331 {
2332  TupleTableSlot *slot;
2333  HeapTuple copyTuple;
2334 
2335  Assert(rti > 0);
2336 
2337  /*
2338  * Get and lock the updated version of the row; if fail, return NULL.
2339  */
2340  copyTuple = EvalPlanQualFetch(estate, relation, lockmode, LockWaitBlock,
2341  tid, priorXmax);
2342 
2343  if (copyTuple == NULL)
2344  return NULL;
2345 
2346  /*
2347  * For UPDATE/DELETE we have to return tid of actual row we're executing
2348  * PQ for.
2349  */
2350  *tid = copyTuple->t_self;
2351 
2352  /*
2353  * Need to run a recheck subquery. Initialize or reinitialize EPQ state.
2354  */
2355  EvalPlanQualBegin(epqstate, estate);
2356 
2357  /*
2358  * Free old test tuple, if any, and store new tuple where relation's scan
2359  * node will see it
2360  */
2361  EvalPlanQualSetTuple(epqstate, rti, copyTuple);
2362 
2363  /*
2364  * Fetch any non-locked source rows
2365  */
2366  EvalPlanQualFetchRowMarks(epqstate);
2367 
2368  /*
2369  * Run the EPQ query. We assume it will return at most one tuple.
2370  */
2371  slot = EvalPlanQualNext(epqstate);
2372 
2373  /*
2374  * If we got a tuple, force the slot to materialize the tuple so that it
2375  * is not dependent on any local state in the EPQ query (in particular,
2376  * it's highly likely that the slot contains references to any pass-by-ref
2377  * datums that may be present in copyTuple). As with the next step, this
2378  * is to guard against early re-use of the EPQ query.
2379  */
2380  if (!TupIsNull(slot))
2381  (void) ExecMaterializeSlot(slot);
2382 
2383  /*
2384  * Clear out the test tuple. This is needed in case the EPQ query is
2385  * re-used to test a tuple for a different relation. (Not clear that can
2386  * really happen, but let's be safe.)
2387  */
2388  EvalPlanQualSetTuple(epqstate, rti, NULL);
2389 
2390  return slot;
2391 }
void EvalPlanQualSetTuple(EPQState *epqstate, Index rti, HeapTuple tuple)
Definition: execMain.c:2679
HeapTuple EvalPlanQualFetch(EState *estate, Relation relation, int lockmode, LockWaitPolicy wait_policy, ItemPointer tid, TransactionId priorXmax)
Definition: execMain.c:2415
void EvalPlanQualFetchRowMarks(EPQState *epqstate)
Definition: execMain.c:2714
void EvalPlanQualBegin(EPQState *epqstate, EState *parentestate)
Definition: execMain.c:2865
TupleTableSlot * EvalPlanQualNext(EPQState *epqstate)
Definition: execMain.c:2849
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 2865 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().

2866 {
2867  EState *estate = epqstate->estate;
2868 
2869  if (estate == NULL)
2870  {
2871  /* First time through, so create a child EState */
2872  EvalPlanQualStart(epqstate, parentestate, epqstate->plan);
2873  }
2874  else
2875  {
2876  /*
2877  * We already have a suitable child EPQ tree, so just reset it.
2878  */
2879  int rtsize = list_length(parentestate->es_range_table);
2880  PlanState *planstate = epqstate->planstate;
2881 
2882  MemSet(estate->es_epqScanDone, 0, rtsize * sizeof(bool));
2883 
2884  /* Recopy current values of parent parameters */
2885  if (parentestate->es_plannedstmt->nParamExec > 0)
2886  {
2887  int i = parentestate->es_plannedstmt->nParamExec;
2888 
2889  while (--i >= 0)
2890  {
2891  /* copy value if any, but not execPlan link */
2892  estate->es_param_exec_vals[i].value =
2893  parentestate->es_param_exec_vals[i].value;
2894  estate->es_param_exec_vals[i].isnull =
2895  parentestate->es_param_exec_vals[i].isnull;
2896  }
2897  }
2898 
2899  /*
2900  * Mark child plan tree as needing rescan at all scan nodes. The
2901  * first ExecProcNode will take care of actually doing the rescan.
2902  */
2903  planstate->chgParam = bms_add_member(planstate->chgParam,
2904  epqstate->epqParam);
2905  }
2906 }
PlannedStmt * es_plannedstmt
Definition: execnodes.h:375
#define MemSet(start, val, len)
Definition: c.h:857
List * es_range_table
Definition: execnodes.h:374
PlanState * planstate
Definition: execnodes.h:1114
int nParamExec
Definition: plannodes.h:81
ParamExecData * es_param_exec_vals
Definition: execnodes.h:396
bool isnull
Definition: params.h:101
static void EvalPlanQualStart(EPQState *epqstate, EState *parentestate, Plan *planTree)
Definition: execMain.c:2915
Bitmapset * chgParam
Definition: execnodes.h:1074
Plan * plan
Definition: execnodes.h:1116
#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:668
int i
bool * es_epqScanDone
Definition: execnodes.h:436
Datum value
Definition: params.h:100
int epqParam
Definition: execnodes.h:1118
EState * estate
Definition: execnodes.h:1113
void EvalPlanQualEnd ( EPQState epqstate)

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

3056 {
3057  EState *estate = epqstate->estate;
3058  MemoryContext oldcontext;
3059  ListCell *l;
3060 
3061  if (estate == NULL)
3062  return; /* idle, so nothing to do */
3063 
3064  oldcontext = MemoryContextSwitchTo(estate->es_query_cxt);
3065 
3066  ExecEndNode(epqstate->planstate);
3067 
3068  foreach(l, estate->es_subplanstates)
3069  {
3070  PlanState *subplanstate = (PlanState *) lfirst(l);
3071 
3072  ExecEndNode(subplanstate);
3073  }
3074 
3075  /* throw away the per-estate tuple table */
3076  ExecResetTupleTable(estate->es_tupleTable, false);
3077 
3078  /* close any trigger target relations attached to this EState */
3079  foreach(l, estate->es_trig_target_relations)
3080  {
3081  ResultRelInfo *resultRelInfo = (ResultRelInfo *) lfirst(l);
3082 
3083  /* Close indices and then the relation itself */
3084  ExecCloseIndices(resultRelInfo);
3085  heap_close(resultRelInfo->ri_RelationDesc, NoLock);
3086  }
3087 
3088  MemoryContextSwitchTo(oldcontext);
3089 
3090  FreeExecutorState(estate);
3091 
3092  /* Mark EPQState idle */
3093  epqstate->estate = NULL;
3094  epqstate->planstate = NULL;
3095  epqstate->origslot = NULL;
3096 }
Relation ri_RelationDesc
Definition: execnodes.h:337
void ExecEndNode(PlanState *node)
Definition: execProcnode.c:644
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:109
#define heap_close(r, l)
Definition: heapam.h:97
PlanState * planstate
Definition: execnodes.h:1114
void FreeExecutorState(EState *estate)
Definition: execUtils.c:169
MemoryContext es_query_cxt
Definition: execnodes.h:399
#define NoLock
Definition: lockdefs.h:34
TupleTableSlot * origslot
Definition: execnodes.h:1115
List * es_trig_target_relations
Definition: execnodes.h:389
List * es_tupleTable
Definition: execnodes.h:401
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:414
EState * estate
Definition: execnodes.h:1113
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 2415 of file execMain.c.

References Assert, 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().

2418 {
2419  HeapTuple copyTuple = NULL;
2420  HeapTupleData tuple;
2421  SnapshotData SnapshotDirty;
2422 
2423  /*
2424  * fetch target tuple
2425  *
2426  * Loop here to deal with updated or busy tuples
2427  */
2428  InitDirtySnapshot(SnapshotDirty);
2429  tuple.t_self = *tid;
2430  for (;;)
2431  {
2432  Buffer buffer;
2433 
2434  if (heap_fetch(relation, &SnapshotDirty, &tuple, &buffer, true, NULL))
2435  {
2436  HTSU_Result test;
2437  HeapUpdateFailureData hufd;
2438 
2439  /*
2440  * If xmin isn't what we're expecting, the slot must have been
2441  * recycled and reused for an unrelated tuple. This implies that
2442  * the latest version of the row was deleted, so we need do
2443  * nothing. (Should be safe to examine xmin without getting
2444  * buffer's content lock. We assume reading a TransactionId to be
2445  * atomic, and Xmin never changes in an existing tuple, except to
2446  * invalid or frozen, and neither of those can match priorXmax.)
2447  */
2449  priorXmax))
2450  {
2451  ReleaseBuffer(buffer);
2452  return NULL;
2453  }
2454 
2455  /* otherwise xmin should not be dirty... */
2456  if (TransactionIdIsValid(SnapshotDirty.xmin))
2457  elog(ERROR, "t_xmin is uncommitted in tuple to be updated");
2458 
2459  /*
2460  * If tuple is being updated by other transaction then we have to
2461  * wait for its commit/abort, or die trying.
2462  */
2463  if (TransactionIdIsValid(SnapshotDirty.xmax))
2464  {
2465  ReleaseBuffer(buffer);
2466  switch (wait_policy)
2467  {
2468  case LockWaitBlock:
2469  XactLockTableWait(SnapshotDirty.xmax,
2470  relation, &tuple.t_self,
2472  break;
2473  case LockWaitSkip:
2474  if (!ConditionalXactLockTableWait(SnapshotDirty.xmax))
2475  return NULL; /* skip instead of waiting */
2476  break;
2477  case LockWaitError:
2478  if (!ConditionalXactLockTableWait(SnapshotDirty.xmax))
2479  ereport(ERROR,
2480  (errcode(ERRCODE_LOCK_NOT_AVAILABLE),
2481  errmsg("could not obtain lock on row in relation \"%s\"",
2482  RelationGetRelationName(relation))));
2483  break;
2484  }
2485  continue; /* loop back to repeat heap_fetch */
2486  }
2487 
2488  /*
2489  * If tuple was inserted by our own transaction, we have to check
2490  * cmin against es_output_cid: cmin >= current CID means our
2491  * command cannot see the tuple, so we should ignore it. Otherwise
2492  * heap_lock_tuple() will throw an error, and so would any later
2493  * attempt to update or delete the tuple. (We need not check cmax
2494  * because HeapTupleSatisfiesDirty will consider a tuple deleted
2495  * by our transaction dead, regardless of cmax.) We just checked
2496  * that priorXmax == xmin, so we can test that variable instead of
2497  * doing HeapTupleHeaderGetXmin again.
2498  */
2499  if (TransactionIdIsCurrentTransactionId(priorXmax) &&
2500  HeapTupleHeaderGetCmin(tuple.t_data) >= estate->es_output_cid)
2501  {
2502  ReleaseBuffer(buffer);
2503  return NULL;
2504  }
2505 
2506  /*
2507  * This is a live tuple, so now try to lock it.
2508  */
2509  test = heap_lock_tuple(relation, &tuple,
2510  estate->es_output_cid,
2511  lockmode, wait_policy,
2512  false, &buffer, &hufd);
2513  /* We now have two pins on the buffer, get rid of one */
2514  ReleaseBuffer(buffer);
2515 
2516  switch (test)
2517  {
2518  case HeapTupleSelfUpdated:
2519 
2520  /*
2521  * The target tuple was already updated or deleted by the
2522  * current command, or by a later command in the current
2523  * transaction. We *must* ignore the tuple in the former
2524  * case, so as to avoid the "Halloween problem" of
2525  * repeated update attempts. In the latter case it might
2526  * be sensible to fetch the updated tuple instead, but
2527  * doing so would require changing heap_update and
2528  * heap_delete to not complain about updating "invisible"
2529  * tuples, which seems pretty scary (heap_lock_tuple will
2530  * not complain, but few callers expect
2531  * HeapTupleInvisible, and we're not one of them). So for
2532  * now, treat the tuple as deleted and do not process.
2533  */
2534  ReleaseBuffer(buffer);
2535  return NULL;
2536 
2537  case HeapTupleMayBeUpdated:
2538  /* successfully locked */
2539  break;
2540 
2541  case HeapTupleUpdated:
2542  ReleaseBuffer(buffer);
2544  ereport(ERROR,
2545  (errcode(ERRCODE_T_R_SERIALIZATION_FAILURE),
2546  errmsg("could not serialize access due to concurrent update")));
2547 
2548  /* Should not encounter speculative tuple on recheck */
2550  if (!ItemPointerEquals(&hufd.ctid, &tuple.t_self))
2551  {
2552  /* it was updated, so look at the updated version */
2553  tuple.t_self = hufd.ctid;
2554  /* updated row should have xmin matching this xmax */
2555  priorXmax = hufd.xmax;
2556  continue;
2557  }
2558  /* tuple was deleted, so give up */
2559  return NULL;
2560 
2561  case HeapTupleWouldBlock:
2562  ReleaseBuffer(buffer);
2563  return NULL;
2564 
2565  case HeapTupleInvisible:
2566  elog(ERROR, "attempted to lock invisible tuple");
2567 
2568  default:
2569  ReleaseBuffer(buffer);
2570  elog(ERROR, "unrecognized heap_lock_tuple status: %u",
2571  test);
2572  return NULL; /* keep compiler quiet */
2573  }
2574 
2575  /*
2576  * We got tuple - now copy it for use by recheck query.
2577  */
2578  copyTuple = heap_copytuple(&tuple);
2579  ReleaseBuffer(buffer);
2580  break;
2581  }
2582 
2583  /*
2584  * If the referenced slot was actually empty, the latest version of
2585  * the row must have been deleted, so we need do nothing.
2586  */
2587  if (tuple.t_data == NULL)
2588  {
2589  ReleaseBuffer(buffer);
2590  return NULL;
2591  }
2592 
2593  /*
2594  * As above, if xmin isn't what we're expecting, do nothing.
2595  */
2597  priorXmax))
2598  {
2599  ReleaseBuffer(buffer);
2600  return NULL;
2601  }
2602 
2603  /*
2604  * If we get here, the tuple was found but failed SnapshotDirty.
2605  * Assuming the xmin is either a committed xact or our own xact (as it
2606  * certainly should be if we're trying to modify the tuple), this must
2607  * mean that the row was updated or deleted by either a committed xact
2608  * or our own xact. If it was deleted, we can ignore it; if it was
2609  * updated then chain up to the next version and repeat the whole
2610  * process.
2611  *
2612  * As above, it should be safe to examine xmax and t_ctid without the
2613  * buffer content lock, because they can't be changing.
2614  */
2615  if (ItemPointerEquals(&tuple.t_self, &tuple.t_data->t_ctid))
2616  {
2617  /* deleted, so forget about it */
2618  ReleaseBuffer(buffer);
2619  return NULL;
2620  }
2621 
2622  /* updated, so look at the updated row */
2623  tuple.t_self = tuple.t_data->t_ctid;
2624  /* updated row should have xmin matching this xmax */
2625  priorXmax = HeapTupleHeaderGetUpdateXid(tuple.t_data);
2626  ReleaseBuffer(buffer);
2627  /* loop back to fetch next in chain */
2628  }
2629 
2630  /*
2631  * Return the copied tuple
2632  */
2633  return copyTuple;
2634 }
#define HeapTupleHeaderGetUpdateXid(tup)
Definition: htup_details.h:359
HeapTuple heap_copytuple(HeapTuple tuple)
Definition: heaptuple.c:608
CommandId es_output_cid
Definition: execnodes.h:381
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:4594
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:1865
#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:433
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
#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 2714 of file execMain.c.

References EPQState::arowMarks, Assert, 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().

2715 {
2716  ListCell *l;
2717 
2718  Assert(epqstate->origslot != NULL);
2719 
2720  foreach(l, epqstate->arowMarks)
2721  {
2722  ExecAuxRowMark *aerm = (ExecAuxRowMark *) lfirst(l);
2723  ExecRowMark *erm = aerm->rowmark;
2724  Datum datum;
2725  bool isNull;
2726  HeapTupleData tuple;
2727 
2729  elog(ERROR, "EvalPlanQual doesn't support locking rowmarks");
2730 
2731  /* clear any leftover test tuple for this rel */
2732  EvalPlanQualSetTuple(epqstate, erm->rti, NULL);
2733 
2734  /* if child rel, must check whether it produced this row */
2735  if (erm->rti != erm->prti)
2736  {
2737  Oid tableoid;
2738 
2739  datum = ExecGetJunkAttribute(epqstate->origslot,
2740  aerm->toidAttNo,
2741  &isNull);
2742  /* non-locked rels could be on the inside of outer joins */
2743  if (isNull)
2744  continue;
2745  tableoid = DatumGetObjectId(datum);
2746 
2747  Assert(OidIsValid(erm->relid));
2748  if (tableoid != erm->relid)
2749  {
2750  /* this child is inactive right now */
2751  continue;
2752  }
2753  }
2754 
2755  if (erm->markType == ROW_MARK_REFERENCE)
2756  {
2757  HeapTuple copyTuple;
2758 
2759  Assert(erm->relation != NULL);
2760 
2761  /* fetch the tuple's ctid */
2762  datum = ExecGetJunkAttribute(epqstate->origslot,
2763  aerm->ctidAttNo,
2764  &isNull);
2765  /* non-locked rels could be on the inside of outer joins */
2766  if (isNull)
2767  continue;
2768 
2769  /* fetch requests on foreign tables must be passed to their FDW */
2770  if (erm->relation->rd_rel->relkind == RELKIND_FOREIGN_TABLE)
2771  {
2772  FdwRoutine *fdwroutine;
2773  bool updated = false;
2774 
2775  fdwroutine = GetFdwRoutineForRelation(erm->relation, false);
2776  /* this should have been checked already, but let's be safe */
2777  if (fdwroutine->RefetchForeignRow == NULL)
2778  ereport(ERROR,
2779  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2780  errmsg("cannot lock rows in foreign table \"%s\"",
2782  copyTuple = fdwroutine->RefetchForeignRow(epqstate->estate,
2783  erm,
2784  datum,
2785  &updated);
2786  if (copyTuple == NULL)
2787  elog(ERROR, "failed to fetch tuple for EvalPlanQual recheck");
2788 
2789  /*
2790  * Ideally we'd insist on updated == false here, but that
2791  * assumes that FDWs can track that exactly, which they might
2792  * not be able to. So just ignore the flag.
2793  */
2794  }
2795  else
2796  {
2797  /* ordinary table, fetch the tuple */
2798  Buffer buffer;
2799 
2800  tuple.t_self = *((ItemPointer) DatumGetPointer(datum));
2801  if (!heap_fetch(erm->relation, SnapshotAny, &tuple, &buffer,
2802  false, NULL))
2803  elog(ERROR, "failed to fetch tuple for EvalPlanQual recheck");
2804 
2805  /* successful, copy tuple */
2806  copyTuple = heap_copytuple(&tuple);
2807  ReleaseBuffer(buffer);
2808  }
2809 
2810  /* store tuple */
2811  EvalPlanQualSetTuple(epqstate, erm->rti, copyTuple);
2812  }
2813  else
2814  {
2815  HeapTupleHeader td;
2816 
2817  Assert(erm->markType == ROW_MARK_COPY);
2818 
2819  /* fetch the whole-row Var for the relation */
2820  datum = ExecGetJunkAttribute(epqstate->origslot,
2821  aerm->wholeAttNo,
2822  &isNull);
2823  /* non-locked rels could be on the inside of outer joins */
2824  if (isNull)
2825  continue;
2826  td = DatumGetHeapTupleHeader(datum);
2827 
2828  /* build a temporary HeapTuple control structure */
2830  tuple.t_data = td;
2831  /* relation might be a foreign table, if so provide tableoid */
2832  tuple.t_tableOid = erm->relid;
2833  /* also copy t_ctid in case there's valid data there */
2834  tuple.t_self = td->t_ctid;
2835 
2836  /* copy and store tuple */
2837  EvalPlanQualSetTuple(epqstate, erm->rti,
2838  heap_copytuple(&tuple));
2839  }
2840  }
2841 }
HeapTuple heap_copytuple(HeapTuple tuple)
Definition: heaptuple.c:608
void EvalPlanQualSetTuple(EPQState *epqstate, Index rti, HeapTuple tuple)
Definition: execMain.c:2679
Relation relation
Definition: execnodes.h:462
bool heap_fetch(Relation relation, Snapshot snapshot, HeapTuple tuple, Buffer *userbuf, bool keep_buf, Relation stats_relation)
Definition: heapam.c:1865
#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:113
unsigned int Oid
Definition: postgres_ext.h:31
#define OidIsValid(objectId)
Definition: c.h:538
#define DatumGetHeapTupleHeader(X)
Definition: fmgr.h:251
#define RowMarkRequiresRowShareLock(marktype)
Definition: plannodes.h:934
ItemPointerData * ItemPointer
Definition: itemptr.h:48
ExecRowMark * rowmark
Definition: execnodes.h:489
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:1117
uint32 t_len
Definition: htup.h:64
Index rti
Definition: execnodes.h:464
AttrNumber wholeAttNo
Definition: execnodes.h:492
Index prti
Definition: execnodes.h:465
#define RelationGetRelationName(relation)
Definition: rel.h:433
Oid t_tableOid
Definition: htup.h:66
#define RELKIND_FOREIGN_TABLE
Definition: pg_class.h:167
TupleTableSlot * origslot
Definition: execnodes.h:1115
#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
RowMarkType markType
Definition: execnodes.h:467
AttrNumber toidAttNo
Definition: execnodes.h:491
#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:1113
int Buffer
Definition: buf.h:23
AttrNumber ctidAttNo
Definition: execnodes.h:490
RefetchForeignRow_function RefetchForeignRow
Definition: fdwapi.h:209
#define HeapTupleHeaderGetDatumLength(tup)
Definition: htup_details.h:439
HeapTuple EvalPlanQualGetTuple ( EPQState epqstate,
Index  rti 
)

Definition at line 2699 of file execMain.c.

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

2700 {
2701  EState *estate = epqstate->estate;
2702 
2703  Assert(rti > 0);
2704 
2705  return estate->es_epqTuple[rti - 1];
2706 }
HeapTuple * es_epqTuple
Definition: execnodes.h:434
#define Assert(condition)
Definition: c.h:675
EState * estate
Definition: execnodes.h:1113
void EvalPlanQualInit ( EPQState epqstate,
EState estate,
Plan subplan,
List auxrowmarks,
int  epqParam 
)

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

2646 {
2647  /* Mark the EPQ state inactive */
2648  epqstate->estate = NULL;
2649  epqstate->planstate = NULL;
2650  epqstate->origslot = NULL;
2651  /* ... and remember data that EvalPlanQualBegin will need */
2652  epqstate->plan = subplan;
2653  epqstate->arowMarks = auxrowmarks;
2654  epqstate->epqParam = epqParam;
2655 }
PlanState * planstate
Definition: execnodes.h:1114
List * arowMarks
Definition: execnodes.h:1117
TupleTableSlot * origslot
Definition: execnodes.h:1115
Plan * plan
Definition: execnodes.h:1116
#define NULL
Definition: c.h:229
int epqParam
Definition: execnodes.h:1118
EState * estate
Definition: execnodes.h:1113
TupleTableSlot* EvalPlanQualNext ( EPQState epqstate)

Definition at line 2849 of file execMain.c.

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

Referenced by EvalPlanQual(), and ExecLockRows().

2850 {
2851  MemoryContext oldcontext;
2852  TupleTableSlot *slot;
2853 
2854  oldcontext = MemoryContextSwitchTo(epqstate->estate->es_query_cxt);
2855  slot = ExecProcNode(epqstate->planstate);
2856  MemoryContextSwitchTo(oldcontext);
2857 
2858  return slot;
2859 }
TupleTableSlot * ExecProcNode(PlanState *node)
Definition: execProcnode.c:392
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:109
PlanState * planstate
Definition: execnodes.h:1114
MemoryContext es_query_cxt
Definition: execnodes.h:399
EState * estate
Definition: execnodes.h:1113
void EvalPlanQualSetPlan ( EPQState epqstate,
Plan subplan,
List auxrowmarks 
)

Definition at line 2663 of file execMain.c.

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

Referenced by ExecInitModifyTable(), and ExecModifyTable().

2664 {
2665  /* If we have a live EPQ query, shut it down */
2666  EvalPlanQualEnd(epqstate);
2667  /* And set/change the plan pointer */
2668  epqstate->plan = subplan;
2669  /* The rowmarks depend on the plan, too */
2670  epqstate->arowMarks = auxrowmarks;
2671 }
void EvalPlanQualEnd(EPQState *epqstate)
Definition: execMain.c:3055
List * arowMarks
Definition: execnodes.h:1117
Plan * plan
Definition: execnodes.h:1116
void EvalPlanQualSetTuple ( EPQState epqstate,
Index  rti,
HeapTuple  tuple 
)

Definition at line 2679 of file execMain.c.

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

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

2680 {
2681  EState *estate = epqstate->estate;
2682 
2683  Assert(rti > 0);
2684 
2685  /*
2686  * free old test tuple, if any, and store new tuple where relation's scan
2687  * node will see it
2688  */
2689  if (estate->es_epqTuple[rti - 1] != NULL)
2690  heap_freetuple(estate->es_epqTuple[rti - 1]);
2691  estate->es_epqTuple[rti - 1] = tuple;
2692  estate->es_epqTupleSet[rti - 1] = true;
2693 }
HeapTuple * es_epqTuple
Definition: execnodes.h:434
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:435
EState * estate
Definition: execnodes.h:1113
static void EvalPlanQualStart ( EPQState epqstate,
EState parentestate,
Plan planTree 
)
static

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

2916 {
2917  EState *estate;
2918  int rtsize;
2919  MemoryContext oldcontext;
2920  ListCell *l;
2921 
2922  rtsize = list_length(parentestate->es_range_table);
2923 
2924  epqstate->estate = estate = CreateExecutorState();
2925 
2926  oldcontext = MemoryContextSwitchTo(estate->es_query_cxt);
2927 
2928  /*
2929  * Child EPQ EStates share the parent's copy of unchanging state such as
2930  * the snapshot, rangetable, result-rel info, and external Param info.
2931  * They need their own copies of local state, including a tuple table,
2932  * es_param_exec_vals, etc.
2933  *
2934  * The ResultRelInfo array management is trickier than it looks. We
2935  * create a fresh array for the child but copy all the content from the
2936  * parent. This is because it's okay for the child to share any
2937  * per-relation state the parent has already created --- but if the child
2938  * sets up any ResultRelInfo fields, such as its own junkfilter, that
2939  * state must *not* propagate back to the parent. (For one thing, the
2940  * pointed-to data is in a memory context that won't last long enough.)
2941  */
2943  estate->es_snapshot = parentestate->es_snapshot;
2944  estate->es_crosscheck_snapshot = parentestate->es_crosscheck_snapshot;
2945  estate->es_range_table = parentestate->es_range_table;
2946  estate->es_plannedstmt = parentestate->es_plannedstmt;
2947  estate->es_junkFilter = parentestate->es_junkFilter;
2948  estate->es_output_cid = parentestate->es_output_cid;
2949  if (parentestate->es_num_result_relations > 0)
2950  {
2951  int numResultRelations = parentestate->es_num_result_relations;
2952  ResultRelInfo *resultRelInfos;
2953 
2954  resultRelInfos = (ResultRelInfo *)
2955  palloc(numResultRelations * sizeof(ResultRelInfo));
2956  memcpy(resultRelInfos, parentestate->es_result_relations,
2957  numResultRelations * sizeof(ResultRelInfo));
2958  estate->es_result_relations = resultRelInfos;
2959  estate->es_num_result_relations = numResultRelations;
2960  }
2961  /* es_result_relation_info must NOT be copied */
2962  /* es_trig_target_relations must NOT be copied */
2963  estate->es_rowMarks = parentestate->es_rowMarks;
2964  estate->es_top_eflags = parentestate->es_top_eflags;
2965  estate->es_instrument = parentestate->es_instrument;
2966  /* es_auxmodifytables must NOT be copied */
2967 
2968  /*
2969  * The external param list is simply shared from parent. The internal
2970  * param workspace has to be local state, but we copy the initial values
2971  * from the parent, so as to have access to any param values that were
2972  * already set from other parts of the parent's plan tree.
2973  */
2974  estate->es_param_list_info = parentestate->es_param_list_info;
2975  if (parentestate->es_plannedstmt->nParamExec > 0)
2976  {
2977  int i = parentestate->es_plannedstmt->nParamExec;
2978 
2979  estate->es_param_exec_vals = (ParamExecData *)
2980  palloc0(i * sizeof(ParamExecData));
2981  while (--i >= 0)
2982  {
2983  /* copy value if any, but not execPlan link */
2984  estate->es_param_exec_vals[i].value =
2985  parentestate->es_param_exec_vals[i].value;
2986  estate->es_param_exec_vals[i].isnull =
2987  parentestate->es_param_exec_vals[i].isnull;
2988  }
2989  }
2990 
2991  /*
2992  * Each EState must have its own es_epqScanDone state, but if we have
2993  * nested EPQ checks they should share es_epqTuple arrays. This allows
2994  * sub-rechecks to inherit the values being examined by an outer recheck.
2995  */
2996  estate->es_epqScanDone = (bool *) palloc0(rtsize * sizeof(bool));
2997  if (parentestate->es_epqTuple != NULL)
2998  {
2999  estate->es_epqTuple = parentestate->es_epqTuple;
3000  estate->es_epqTupleSet = parentestate->es_epqTupleSet;
3001  }
3002  else
3003  {
3004  estate->es_epqTuple = (HeapTuple *)
3005  palloc0(rtsize * sizeof(HeapTuple));
3006  estate->es_epqTupleSet = (bool *)
3007  palloc0(rtsize * sizeof(bool));
3008  }
3009 
3010  /*
3011  * Each estate also has its own tuple table.
3012  */
3013  estate->es_tupleTable = NIL;
3014 
3015  /*
3016  * Initialize private state information for each SubPlan. We must do this
3017  * before running ExecInitNode on the main query tree, since
3018  * ExecInitSubPlan expects to be able to find these entries. Some of the
3019  * SubPlans might not be used in the part of the plan tree we intend to
3020  * run, but since it's not easy to tell which, we just initialize them
3021  * all.
3022  */
3023  Assert(estate->es_subplanstates == NIL);
3024  foreach(l, parentestate->es_plannedstmt->subplans)
3025  {
3026  Plan *subplan = (Plan *) lfirst(l);
3027  PlanState *subplanstate;
3028 
3029  subplanstate = ExecInitNode(subplan, estate, 0);
3030  estate->es_subplanstates = lappend(estate->es_subplanstates,
3031  subplanstate);
3032  }
3033 
3034  /*
3035  * Initialize the private state information for all the nodes in the part
3036  * of the plan tree we need to run. This opens files, allocates storage
3037  * and leaves us ready to start processing tuples.
3038  */
3039  epqstate->planstate = ExecInitNode(planTree, estate, 0);
3040 
3041  MemoryContextSwitchTo(oldcontext);
3042 }
#define NIL
Definition: pg_list.h:69
HeapTuple * es_epqTuple
Definition: execnodes.h:434
JunkFilter * es_junkFilter
Definition: execnodes.h:378
CommandId es_output_cid
Definition: execnodes.h:381
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:109
PlannedStmt * es_plannedstmt
Definition: execnodes.h:375
Snapshot es_crosscheck_snapshot
Definition: execnodes.h:373
Snapshot es_snapshot
Definition: execnodes.h:372
List * es_range_table
Definition: execnodes.h:374
PlanState * planstate
Definition: execnodes.h:1114
ScanDirection es_direction
Definition: execnodes.h:371
int nParamExec
Definition: plannodes.h:81
ParamExecData * es_param_exec_vals
Definition: execnodes.h:396
MemoryContext es_query_cxt
Definition: execnodes.h:399
bool isnull
Definition: params.h:101
ResultRelInfo * es_result_relations
Definition: execnodes.h:384
int es_instrument
Definition: execnodes.h:409
EState * CreateExecutorState(void)
Definition: execUtils.c:73
List * lappend(List *list, void *datum)
Definition: list.c:128
List * es_tupleTable
Definition: execnodes.h:401
void * palloc0(Size size)
Definition: mcxt.c:878
int es_num_result_relations
Definition: execnodes.h:385
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:435
List * es_subplanstates
Definition: execnodes.h:414
List * es_rowMarks
Definition: execnodes.h:403
void * palloc(Size size)
Definition: mcxt.c:849
int es_top_eflags
Definition: execnodes.h:408
int i
bool * es_epqScanDone
Definition: execnodes.h:436
Datum value
Definition: params.h:100
ParamListInfo es_param_list_info
Definition: execnodes.h:395
EState * estate
Definition: execnodes.h:1113
PlanState * ExecInitNode(Plan *node, EState *estate, int eflags)
Definition: execProcnode.c:139
ExecAuxRowMark* ExecBuildAuxRowMark ( ExecRowMark erm,
List targetlist 
)

Definition at line 2257 of file execMain.c.

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

Referenced by ExecInitLockRows(), and ExecInitModifyTable().

2258 {
2259  ExecAuxRowMark *aerm = (ExecAuxRowMark *) palloc0(sizeof(ExecAuxRowMark));
2260  char resname[32];
2261 
2262  aerm->rowmark = erm;
2263 
2264  /* Look up the resjunk columns associated with this rowmark */
2265  if (erm->markType != ROW_MARK_COPY)
2266  {
2267  /* need ctid for all methods other than COPY */
2268  snprintf(resname, sizeof(resname), "ctid%u", erm->rowmarkId);
2269  aerm->ctidAttNo = ExecFindJunkAttributeInTlist(targetlist,
2270  resname);
2271  if (!AttributeNumberIsValid(aerm->ctidAttNo))
2272  elog(ERROR, "could not find junk %s column", resname);
2273  }
2274  else
2275  {
2276  /* need wholerow if COPY */
2277  snprintf(resname, sizeof(resname), "wholerow%u", erm->rowmarkId);
2278  aerm->wholeAttNo = ExecFindJunkAttributeInTlist(targetlist,
2279  resname);
2280  if (!AttributeNumberIsValid(aerm->wholeAttNo))
2281  elog(ERROR, "could not find junk %s column", resname);
2282  }
2283 
2284  /* if child rel, need tableoid */
2285  if (erm->rti != erm->prti)
2286  {
2287  snprintf(resname, sizeof(resname), "tableoid%u", erm->rowmarkId);
2288  aerm->toidAttNo = ExecFindJunkAttributeInTlist(targetlist,
2289  resname);
2290  if (!AttributeNumberIsValid(aerm->toidAttNo))
2291  elog(ERROR, "could not find junk %s column", resname);
2292  }
2293 
2294  return aerm;
2295 }
AttrNumber ExecFindJunkAttributeInTlist(List *targetlist, const char *attrName)
Definition: execJunk.c:221
int snprintf(char *str, size_t count, const char *fmt,...) pg_attribute_printf(3
ExecRowMark * rowmark
Definition: execnodes.h:489
#define ERROR
Definition: elog.h:43
Index rti
Definition: execnodes.h:464
AttrNumber wholeAttNo
Definition: execnodes.h:492
Index prti
Definition: execnodes.h:465
Index rowmarkId
Definition: execnodes.h:466
#define AttributeNumberIsValid(attributeNumber)
Definition: attnum.h:34
void * palloc0(Size size)
Definition: mcxt.c:878
RowMarkType markType
Definition: execnodes.h:467
AttrNumber toidAttNo
Definition: execnodes.h:491
#define elog
Definition: elog.h:219
AttrNumber ctidAttNo
Definition: execnodes.h:490
static char * ExecBuildSlotPartitionKeyDescription ( Relation  rel,
Datum values,
bool isnull,
int  maxfieldlen 
)
static

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

3261 {
3264  int partnatts = get_partition_natts(key);
3265  int i;
3266  Oid relid = RelationGetRelid(rel);
3267  AclResult aclresult;
3268 
3269  if (check_enable_rls(relid, InvalidOid, true) == RLS_ENABLED)
3270  return NULL;
3271 
3272  /* If the user has table-level access, just go build the description. */
3273  aclresult = pg_class_aclcheck(relid, GetUserId(), ACL_SELECT);
3274  if (aclresult != ACLCHECK_OK)
3275  {
3276  /*
3277  * Step through the columns of the partition key and make sure the
3278  * user has SELECT rights on all of them.
3279  */
3280  for (i = 0; i < partnatts; i++)
3281  {
3282  AttrNumber attnum = get_partition_col_attnum(key, i);
3283 
3284  /*
3285  * If this partition key column is an expression, we return no
3286  * detail rather than try to figure out what column(s) the
3287  * expression includes and if the user has SELECT rights on them.
3288  */
3289  if (attnum == InvalidAttrNumber ||
3290  pg_attribute_aclcheck(relid, attnum, GetUserId(),
3291  ACL_SELECT) != ACLCHECK_OK)
3292  return NULL;
3293  }
3294  }
3295 
3296  initStringInfo(&buf);
3297  appendStringInfo(&buf, "(%s) = (",
3298  pg_get_partkeydef_columns(relid, true));
3299 
3300  for (i = 0; i < partnatts; i++)
3301  {
3302  char *val;
3303  int vallen;
3304 
3305  if (isnull[i])
3306  val = "null";
3307  else
3308  {
3309  Oid foutoid;
3310  bool typisvarlena;
3311 
3313  &foutoid, &typisvarlena);
3314  val = OidOutputFunctionCall(foutoid, values[i]);
3315  }
3316 
3317  if (i > 0)
3318  appendStringInfoString(&buf, ", ");
3319 
3320  /* truncate if needed */
3321  vallen = strlen(val);
3322  if (vallen <= maxfieldlen)
3323  appendStringInfoString(&buf, val);
3324  else
3325  {
3326  vallen = pg_mbcliplen(val, vallen, maxfieldlen);
3327  appendBinaryStringInfo(&buf, val, vallen);
3328  appendStringInfoString(&buf, "...");
3329  }
3330  }
3331 
3332  appendStringInfoChar(&buf, ')');
3333 
3334  return buf.data;
3335 }
char * pg_get_partkeydef_columns(Oid relid, bool pretty)
Definition: ruleutils.c:1443
void getTypeOutputInfo(Oid type, Oid *typOutput, bool *typIsVarlena)
Definition: lsyscache.c:2600
AclResult pg_attribute_aclcheck(Oid table_oid, AttrNumber attnum, Oid roleid, AclMode mode)
Definition: aclchk.c:4282
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:593
static int16 get_partition_col_attnum(PartitionKey key, int col)
Definition: rel.h:608
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:65
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:614
#define ACL_SELECT
Definition: parsenodes.h:66
#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:581
#define InvalidAttrNumber
Definition: attnum.h:23
AclResult pg_class_aclcheck(Oid table_oid, Oid roleid, AclMode mode)
Definition: aclchk.c:4396
static Datum values[MAXATTR]
Definition: bootstrap.c:162
char * OidOutputFunctionCall(Oid functionId, Datum val)
Definition: fmgr.c:2056
int i
int16 AttrNumber
Definition: attnum.h:21
#define RelationGetRelid(relation)
Definition: rel.h:413
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 2071 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().

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

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

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

706 {
707  int col = -1;
708 
709  /*
710  * When the query doesn't explicitly update any columns, allow the query
711  * if we have permission on any column of the rel. This is to handle
712  * SELECT FOR UPDATE as well as possible corner cases in UPDATE.
713  */
714  if (bms_is_empty(modifiedCols))
715  {
716  if (pg_attribute_aclcheck_all(relOid, userid, requiredPerms,
718  return false;
719  }
720 
721  while ((col = bms_next_member(modifiedCols, col)) >= 0)
722  {
723  /* bit #s are offset by FirstLowInvalidHeapAttributeNumber */
725 
726  if (attno == InvalidAttrNumber)
727  {
728  /* whole-row reference can't happen here */
729  elog(ERROR, "whole-row update is not implemented");
730  }
731  else
732  {
733  if (pg_attribute_aclcheck(relOid, attno, userid,
734  requiredPerms) != ACLCHECK_OK)
735  return false;
736  }
737  }
738  return true;
739 }
AclResult pg_attribute_aclcheck(Oid table_oid, AttrNumber attnum, Oid roleid, AclMode mode)
Definition: aclchk.c:4282
int bms_next_member(const Bitmapset *a, int prevbit)
Definition: bitmapset.c:907
#define FirstLowInvalidHeapAttributeNumber
Definition: sysattr.h:28
#define ERROR
Definition: elog.h:43
bool bms_is_empty(const Bitmapset *a)
Definition: bitmapset.c:633
AclResult pg_attribute_aclcheck_all(Oid table_oid, Oid roleid, AclMode mode, AclMaskHow how)
Definition: aclchk.c:4311
#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 553 of file execMain.c.

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

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

554 {
555  ListCell *l;
556  bool result = true;
557 
558  foreach(l, rangeTable)
559  {
560  RangeTblEntry *rte = (RangeTblEntry *) lfirst(l);
561 
562  result = ExecCheckRTEPerms(rte);
563  if (!result)
564  {
565  Assert(rte->rtekind == RTE_RELATION);
566  if (ereport_on_violation)
568  get_rel_name(rte->relid));
569  return false;
570  }
571  }
572 
574  result = (*ExecutorCheckPerms_hook) (rangeTable,
575  ereport_on_violation);
576  return result;
577 }
void aclcheck_error(AclResult aclerr, AclObjectKind objectkind, const char *objectname)
Definition: aclchk.c:3377
static bool ExecCheckRTEPerms(RangeTblEntry *rte)
Definition: execMain.c:584
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:916
char * get_rel_name(Oid relid)
Definition: lsyscache.c:1694
static void ExecCheckXactReadOnly ( PlannedStmt plannedstmt)
static

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

752 {
753  ListCell *l;
754 
755  /*
756  * Fail if write permissions are requested in parallel mode for table
757  * (temp or non-temp), otherwise fail for any non-temp table.
758  */
759  foreach(l, plannedstmt->rtable)
760  {
761  RangeTblEntry *rte = (RangeTblEntry *) lfirst(l);
762 
763  if (rte->rtekind != RTE_RELATION)
764  continue;
765 
766  if ((rte->requiredPerms & (~ACL_SELECT)) == 0)
767  continue;
768 
770  continue;
771 
773  }
774 
775  if (plannedstmt->commandType != CMD_SELECT || plannedstmt->hasModifyingCTE)
777 }
void PreventCommandIfParallelMode(const char *cmdname)
Definition: utility.c:253
Oid get_rel_namespace(Oid relid)
Definition: lsyscache.c:1718
Definition: nodes.h:518
AclMode requiredPerms
Definition: parsenodes.h:1004
bool isTempNamespace(Oid namespaceId)
Definition: namespace.c:2952
const char * CreateCommandTag(Node *parsetree)
Definition: utility.c:2013
CmdType commandType
Definition: plannodes.h:45
#define ACL_SELECT
Definition: parsenodes.h:66
#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:235
RTEKind rtekind
Definition: parsenodes.h:916
void ExecConstraints ( ResultRelInfo resultRelInfo,
TupleTableSlot slot,
TupleTableSlot orig_slot,
EState estate 
)

Definition at line 1814 of file execMain.c.

References Assert, tupleDesc::attrs, bms_union(), tupleDesc::constr, ereport, errcode(), errdetail(), errmsg(), ERROR, errtablecol(), errtableconstraint(), ExecBuildSlotValueDescription(), ExecPartitionCheck(), ExecRelCheck(), GetInsertedColumns, GetUpdatedColumns, tupleConstr::has_not_null, 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().

1817 {
1818  Relation rel = resultRelInfo->ri_RelationDesc;
1819  TupleDesc tupdesc = RelationGetDescr(rel);
1820  TupleConstr *constr = tupdesc->constr;
1821  Bitmapset *modifiedCols;
1822  Bitmapset *insertedCols;
1823  Bitmapset *updatedCols;
1824 
1825  Assert(constr || resultRelInfo->ri_PartitionCheck);
1826 
1827  if (constr && constr->has_not_null)
1828  {
1829  int natts = tupdesc->natts;
1830  int attrChk;
1831 
1832  for (attrChk = 1; attrChk <= natts; attrChk++)
1833  {
1834  if (tupdesc->attrs[attrChk - 1]->attnotnull &&
1835  slot_attisnull(slot, attrChk))
1836  {
1837  char *val_desc;
1838  Relation orig_rel = rel;
1839  TupleDesc orig_tupdesc = tupdesc;
1840 
1841  /*
1842  * choose the correct relation to build val_desc from the
1843  * tuple contained in orig_slot
1844  */
1845  if (resultRelInfo->ri_PartitionRoot)
1846  {
1847  rel = resultRelInfo->ri_PartitionRoot;
1848  tupdesc = RelationGetDescr(rel);
1849  }
1850 
1851  insertedCols = GetInsertedColumns(resultRelInfo, estate);
1852  updatedCols = GetUpdatedColumns(resultRelInfo, estate);
1853  modifiedCols = bms_union(insertedCols, updatedCols);
1855  orig_slot,
1856  tupdesc,
1857  modifiedCols,
1858  64);
1859 
1860  ereport(ERROR,
1861  (errcode(ERRCODE_NOT_NULL_VIOLATION),
1862  errmsg("null value in column \"%s\" violates not-null constraint",
1863  NameStr(orig_tupdesc->attrs[attrChk - 1]->attname)),
1864  val_desc ? errdetail("Failing row contains %s.", val_desc) : 0,
1865  errtablecol(orig_rel, attrChk)));
1866  }
1867  }
1868  }
1869 
1870  if (constr && constr->num_check > 0)
1871  {
1872  const char *failed;
1873 
1874  if ((failed = ExecRelCheck(resultRelInfo, slot, estate)) != NULL)
1875  {
1876  char *val_desc;
1877  Relation orig_rel = rel;
1878 
1879  /* See the comment above. */
1880  if (resultRelInfo->ri_PartitionRoot)
1881  {
1882  rel = resultRelInfo->ri_PartitionRoot;
1883  tupdesc = RelationGetDescr(rel);
1884  }
1885 
1886  insertedCols = GetInsertedColumns(resultRelInfo, estate);
1887  updatedCols = GetUpdatedColumns(resultRelInfo, estate);
1888  modifiedCols = bms_union(insertedCols, updatedCols);
1890  orig_slot,
1891  tupdesc,
1892  modifiedCols,
1893  64);
1894  ereport(ERROR,
1895  (errcode(ERRCODE_CHECK_VIOLATION),
1896  errmsg("new row for relation \"%s\" violates check constraint \"%s\"",
1897  RelationGetRelationName(orig_rel), failed),
1898  val_desc ? errdetail("Failing row contains %s.", val_desc) : 0,
1899  errtableconstraint(orig_rel, failed)));
1900  }
1901  }
1902 
1903  if (resultRelInfo->ri_PartitionCheck &&
1904  !ExecPartitionCheck(resultRelInfo, slot, estate))
1905  {
1906  char *val_desc;
1907  Relation orig_rel = rel;
1908 
1909  /* See the comment above. */
1910  if (resultRelInfo->ri_PartitionRoot)
1911  {
1912  rel = resultRelInfo->ri_PartitionRoot;
1913  tupdesc = RelationGetDescr(rel);
1914  }
1915 
1916  insertedCols = GetInsertedColumns(resultRelInfo, estate);
1917  updatedCols = GetUpdatedColumns(resultRelInfo, estate);
1918  modifiedCols = bms_union(insertedCols, updatedCols);
1920  orig_slot,
1921  tupdesc,
1922  modifiedCols,
1923  64);
1924  ereport(ERROR,
1925  (errcode(ERRCODE_CHECK_VIOLATION),
1926  errmsg("new row for relation \"%s\" violates partition constraint",
1927  RelationGetRelationName(orig_rel)),
1928  val_desc ? errdetail("Failing row contains %s.", val_desc) : 0));
1929  }
1930 }
#define GetUpdatedColumns(relinfo, estate)
Definition: execMain.c:114
Relation ri_RelationDesc
Definition: execnodes.h:337
#define RelationGetDescr(relation)
Definition: rel.h:425
Relation ri_PartitionRoot
Definition: execnodes.h:357
Form_pg_attribute * attrs
Definition: tupdesc.h:74
int errcode(int sqlerrcode)
Definition: elog.c:575
int natts
Definition: tupdesc.h:73
int errtableconstraint(Relation rel, const char *conname)
Definition: relcache.c:5209
static bool ExecPartitionCheck(ResultRelInfo *resultRelInfo, TupleTableSlot *slot, EState *estate)
Definition: execMain.c:1768
#define ERROR
Definition: elog.h:43
static char * ExecBuildSlotValueDescription(Oid reloid, TupleTableSlot *slot, TupleDesc tupdesc, Bitmapset *modifiedCols, int maxfieldlen)
Definition: execMain.c:2071
int errdetail(const char *fmt,...)
Definition: elog.c:873
#define RelationGetRelationName(relation)
Definition: rel.h:433
#define ereport(elevel, rest)
Definition: elog.h:122
bool has_not_null
Definition: tupdesc.h:43
List * ri_PartitionCheck
Definition: execnodes.h:355
static const char * ExecRelCheck(ResultRelInfo *resultRelInfo, TupleTableSlot *slot, EState *estate)
Definition: execMain.c:1704
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:5172
TupleConstr * constr
Definition: tupdesc.h:76
Bitmapset * bms_union(const Bitmapset *a, const Bitmapset *b)
Definition: bitmapset.c:217
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:413
#define GetInsertedColumns(relinfo, estate)
Definition: execMain.c:112
bool ExecContextForcesOids ( PlanState planstate,
bool hasoids 
)

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

1432 {
1433  ResultRelInfo *ri = planstate->state->es_result_relation_info;
1434 
1435  if (ri != NULL)
1436  {
1437  Relation rel = ri->ri_RelationDesc;
1438 
1439  if (rel != NULL)
1440  {
1441  *hasoids = rel->rd_rel->relhasoids;
1442  return true;
1443  }
1444  }
1445 
1446  if (planstate->state->es_top_eflags & EXEC_FLAG_WITH_OIDS)
1447  {
1448  *hasoids = true;
1449  return true;
1450  }
1451  if (planstate->state->es_top_eflags & EXEC_FLAG_WITHOUT_OIDS)
1452  {
1453  *hasoids = false;
1454  return true;
1455  }
1456 
1457  return false;
1458 }
Relation ri_RelationDesc
Definition: execnodes.h:337
EState * state
Definition: execnodes.h:1051
Form_pg_class rd_rel
Definition: rel.h:113
#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:408
ResultRelInfo * es_result_relation_info
Definition: execnodes.h:386
static void ExecEndPlan ( PlanState planstate,
EState estate 
)
static

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

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

Definition at line 3213 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, and PartitionDispatchData::reldesc.

Referenced by CopyFrom(), and ExecInsert().

3215 {
3216  int result;
3217  PartitionDispatchData *failed_at;
3218  TupleTableSlot *failed_slot;
3219 
3220  result = get_partition_for_tuple(pd, slot, estate,
3221  &failed_at, &failed_slot);
3222  if (result < 0)
3223  {
3224  Relation failed_rel;
3225  Datum key_values[PARTITION_MAX_KEYS];
3226  bool key_isnull[PARTITION_MAX_KEYS];
3227  char *val_desc;
3228  ExprContext *ecxt = GetPerTupleExprContext(estate);
3229 
3230  failed_rel = failed_at->reldesc;
3231  ecxt->ecxt_scantuple = failed_slot;
3232  FormPartitionKeyDatum(failed_at, failed_slot, estate,
3233  key_values, key_isnull);
3234  val_desc = ExecBuildSlotPartitionKeyDescription(failed_rel,
3235  key_values,
3236  key_isnull,
3237  64);
3238  Assert(OidIsValid(RelationGetRelid(failed_rel)));
3239  ereport(ERROR,
3240  (errcode(ERRCODE_CHECK_VIOLATION),
3241  errmsg("no partition of relation \"%s\" found for row",
3242  RelationGetRelationName(failed_rel)),
3243  val_desc ? errdetail("Partition key of the failing row contains %s.", val_desc) : 0));
3244  }
3245 
3246  return result;
3247 }
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:1665
#define OidIsValid(objectId)
Definition: c.h:538
#define GetPerTupleExprContext(estate)
Definition: executor.h:338
#define ERROR
Definition: elog.h:43
static char * ExecBuildSlotPartitionKeyDescription(Relation rel, Datum *values, bool *isnull, int maxfieldlen)
Definition: execMain.c:3257
void FormPartitionKeyDatum(PartitionDispatch pd, TupleTableSlot *slot, EState *estate, Datum *values, bool *isnull)
Definition: partition.c:1605
int errdetail(const char *fmt,...)
Definition: elog.c:873
#define RelationGetRelationName(relation)
Definition: rel.h:433
#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:130
int errmsg(const char *fmt,...)
Definition: elog.c:797
#define RelationGetRelid(relation)
Definition: rel.h:413
ExecRowMark* ExecFindRowMark ( EState estate,
Index  rti,
bool  missing_ok 
)

Definition at line 2233 of file execMain.c.

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

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

2234 {
2235  ListCell *lc;
2236 
2237  foreach(lc, estate->es_rowMarks)
2238  {
2239  ExecRowMark *erm = (ExecRowMark *) lfirst(lc);
2240 
2241  if (erm->rti == rti)
2242  return erm;
2243  }
2244  if (!missing_ok)
2245  elog(ERROR, "failed to find ExecRowMark for rangetable index %u", rti);
2246  return NULL;
2247 }
#define ERROR
Definition: elog.h:43
Index rti
Definition: execnodes.h:464
#define NULL
Definition: c.h:229
#define lfirst(lc)
Definition: pg_list.h:106
List * es_rowMarks
Definition: execnodes.h:403
#define elog
Definition: elog.h:219
ResultRelInfo* ExecGetTriggerResultRel ( EState estate,
Oid  relid 
)

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

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

Definition at line 1768 of file execMain.c.

References ExprContext::ecxt_scantuple, ExecPrepareExpr(), ExecQual(), GetPerTupleExprContext, NULL, ResultRelInfo::ri_PartitionCheck, and ResultRelInfo::ri_PartitionCheckExpr.

Referenced by ExecConstraints().

1770 {
1771  ExprContext *econtext;
1772 
1773  /*
1774  * If first time through, build expression state tree for the partition
1775  * check expression. Keep it in the per-query memory context so they'll
1776  * survive throughout the query.
1777  */
1778  if (resultRelInfo->ri_PartitionCheckExpr == NULL)
1779  {
1780  List *qual = resultRelInfo->ri_PartitionCheck;
1781 
1782  resultRelInfo->ri_PartitionCheckExpr = (List *)
1783  ExecPrepareExpr((Expr *) qual, estate);
1784  }
1785 
1786  /*
1787  * We will use the EState's per-tuple context for evaluating constraint
1788  * expressions (creating it if it's not already there).
1789  */
1790  econtext = GetPerTupleExprContext(estate);
1791 
1792  /* Arrange for econtext's scan tuple to be the tuple under test */
1793  econtext->ecxt_scantuple = slot;
1794 
1795  /*
1796  * As in case of the catalogued constraints, we treat a NULL result as
1797  * success here, not a failure.
1798  */
1799  return ExecQual(resultRelInfo->ri_PartitionCheckExpr, econtext, true);
1800 }
ExprState * ExecPrepareExpr(Expr *node, EState *estate)
Definition: execQual.c:5005
List * ri_PartitionCheckExpr
Definition: execnodes.h:356
#define GetPerTupleExprContext(estate)
Definition: executor.h:338
bool ExecQual(List *qual, ExprContext *econtext, bool resultForNull)
Definition: execQual.c:5056
List * ri_PartitionCheck
Definition: execnodes.h:355
#define NULL
Definition: c.h:229
TupleTableSlot * ecxt_scantuple
Definition: execnodes.h:130
Definition: pg_list.h:45
static void ExecPostprocessPlan ( EState estate)
static

Definition at line 1467 of file execMain.c.

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

Referenced by standard_ExecutorFinish().

1468 {
1469  ListCell *lc;
1470 
1471  /*
1472  * Make sure nodes run forward.
1473  */
1475 
1476  /*
1477  * Run any secondary ModifyTable nodes to completion, in case the main
1478  * query did not fetch all rows from them. (We do this to ensure that
1479  * such nodes have predictable results.)
1480  */
1481  foreach(lc, estate->es_auxmodifytables)
1482  {
1483  PlanState *ps = (PlanState *) lfirst(lc);
1484 
1485  for (;;)
1486  {
1487  TupleTableSlot *slot;
1488 
1489  /* Reset the per-output-tuple exprcontext each time */
1490  ResetPerTupleExprContext(estate);
1491 
1492  slot = ExecProcNode(ps);
1493 
1494  if (TupIsNull(slot))
1495  break;
1496  }
1497  }
1498 }
TupleTableSlot * ExecProcNode(PlanState *node)
Definition: execProcnode.c:392
#define ResetPerTupleExprContext(estate)
Definition: executor.h:347
ScanDirection es_direction
Definition: execnodes.h:371
#define TupIsNull(slot)
Definition: tuptable.h:138
List * es_auxmodifytables
Definition: execnodes.h:416
#define lfirst(lc)
Definition: pg_list.h:106
static const char* ExecRelCheck ( ResultRelInfo resultRelInfo,
TupleTableSlot slot,
EState estate 
)
static

Definition at line 1704 of file execMain.c.

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

Referenced by ExecConstraints().

1706 {
1707  Relation rel = resultRelInfo->ri_RelationDesc;
1708  int ncheck = rel->rd_att->constr->num_check;
1709  ConstrCheck *check = rel->rd_att->constr->check;
1710  ExprContext *econtext;
1711  MemoryContext oldContext;
1712  List *qual;
1713  int i;
1714 
1715  /*
1716  * If first time through for this result relation, build expression
1717  * nodetrees for rel's constraint expressions. Keep them in the per-query
1718  * memory context so they'll survive throughout the query.
1719  */
1720  if (resultRelInfo->ri_ConstraintExprs == NULL)
1721  {
1722  oldContext = MemoryContextSwitchTo(estate->es_query_cxt);
1723  resultRelInfo->ri_ConstraintExprs =
1724  (List **) palloc(ncheck * sizeof(List *));
1725  for (i = 0; i < ncheck; i++)
1726  {
1727  /* ExecQual wants implicit-AND form */
1728  qual = make_ands_implicit(stringToNode(check[i].ccbin));
1729  resultRelInfo->ri_ConstraintExprs[i] = (List *)
1730  ExecPrepareExpr((Expr *) qual, estate);
1731  }
1732  MemoryContextSwitchTo(oldContext);
1733  }
1734 
1735  /*
1736  * We will use the EState's per-tuple context for evaluating constraint
1737  * expressions (creating it if it's not already there).
1738  */
1739  econtext = GetPerTupleExprContext(estate);
1740 
1741  /* Arrange for econtext's scan tuple to be the tuple under test */
1742  econtext->ecxt_scantuple = slot;
1743 
1744  /* And evaluate the constraints */
1745  for (i = 0; i < ncheck; i++)
1746  {
1747  qual = resultRelInfo->ri_ConstraintExprs[i];
1748 
1749  /*
1750  * NOTE: SQL specifies that a NULL result from a constraint expression
1751  * is not to be treated as a failure. Therefore, tell ExecQual to
1752  * return TRUE for NULL.
1753  */
1754  if (!ExecQual(qual, econtext, true))
1755  return check[i].ccname;
1756  }
1757 
1758  /* NULL result means no error */
1759  return NULL;
1760 }
void * stringToNode(char *str)
Definition: read.c:38
Relation ri_RelationDesc
Definition: execnodes.h:337
ExprState * ExecPrepareExpr(Expr *node, EState *estate)
Definition: execQual.c:5005
char * ccname
Definition: tupdesc.h:30
ConstrCheck * check
Definition: tupdesc.h:40
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:109
#define GetPerTupleExprContext(estate)
Definition: executor.h:338
MemoryContext es_query_cxt
Definition: execnodes.h:399
List * make_ands_implicit(Expr *clause)
Definition: clauses.c:377
List ** ri_ConstraintExprs
Definition: execnodes.h:350
bool ExecQual(List *qual, ExprContext *econtext, bool resultForNull)
Definition: execQual.c:5056
TupleDesc rd_att
Definition: rel.h:114
#define NULL
Definition: c.h:229
TupleConstr * constr
Definition: tupdesc.h:76
TupleTableSlot * ecxt_scantuple
Definition: execnodes.h:130
void * palloc(Size size)
Definition: mcxt.c:849
int i
uint16 num_check
Definition: tupdesc.h:42
Definition: pg_list.h:45
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 3124 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().

3130 {
3131  TupleDesc tupDesc = RelationGetDescr(rel);
3132  List *leaf_parts;
3133  ListCell *cell;
3134  int i;
3135  ResultRelInfo *leaf_part_rri;
3136 
3137  /* Get the tuple-routing information and lock partitions */
3138  *pd = RelationGetPartitionDispatchInfo(rel, RowExclusiveLock, num_parted,
3139  &leaf_parts);
3140  *num_partitions = list_length(leaf_parts);
3141  *partitions = (ResultRelInfo *) palloc(*num_partitions *
3142  sizeof(ResultRelInfo));
3143  *tup_conv_maps = (TupleConversionMap **) palloc0(*num_partitions *
3144  sizeof(TupleConversionMap *));
3145 
3146  /*
3147  * Initialize an empty slot that will be used to manipulate tuples of any
3148  * given partition's rowtype. It is attached to the caller-specified node
3149  * (such as ModifyTableState) and released when the node finishes
3150  * processing.
3151  */
3152  *partition_tuple_slot = MakeTupleTableSlot();
3153 
3154  leaf_part_rri = *partitions;
3155  i = 0;
3156  foreach(cell, leaf_parts)
3157  {
3158  Relation partrel;
3159  TupleDesc part_tupdesc;
3160 
3161  /*
3162  * We locked all the partitions above including the leaf partitions.
3163  * Note that each of the relations in *partitions are eventually
3164  * closed by the caller.
3165  */
3166  partrel = heap_open(lfirst_oid(cell), NoLock);
3167  part_tupdesc = RelationGetDescr(partrel);
3168 
3169  /*
3170  * Verify result relation is a valid target for the current operation.
3171  */
3172  CheckValidResultRel(partrel, CMD_INSERT);
3173 
3174  /*
3175  * Save a tuple conversion map to convert a tuple routed to this
3176  * partition from the parent's type to the partition's.
3177  */
3178  (*tup_conv_maps)[i] = convert_tuples_by_name(tupDesc, part_tupdesc,
3179  gettext_noop("could not convert row type"));
3180 
3181  InitResultRelInfo(leaf_part_rri,
3182  partrel,
3183  1, /* dummy */
3184  rel,
3185  0);
3186 
3187  /*
3188  * Open partition indices (remember we do not support ON CONFLICT in
3189  * case of partitioned tables, so we do not need support information
3190  * for speculative insertion)
3191  */
3192  if (leaf_part_rri->ri_RelationDesc->rd_rel->relhasindex &&
3193  leaf_part_rri->ri_IndexRelationDescs == NULL)
3194  ExecOpenIndices(leaf_part_rri, false);
3195 
3196  leaf_part_rri++;
3197  i++;
3198  }
3199 }
void InitResultRelInfo(ResultRelInfo *resultRelInfo, Relation resultRelationDesc, Index resultRelationIndex, Relation partition_root, int instrument_options)
Definition: execMain.c:1246
Relation ri_RelationDesc
Definition: execnodes.h:337
#define RelationGetDescr(relation)
Definition: rel.h:425
TupleTableSlot * MakeTupleTableSlot(void)
Definition: execTuples.c:111
#define gettext_noop(x)
Definition: c.h:139
Form_pg_class rd_rel
Definition: rel.h:113
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:1046
TupleConversionMap * convert_tuples_by_name(TupleDesc indesc, TupleDesc outdesc, const char *msg)
Definition: tupconvert.c:204
void * palloc0(Size size)
Definition: mcxt.c:878
Relation heap_open(Oid relationId, LOCKMODE lockmode)
Definition: heapam.c:1287
#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:991
void * palloc(Size size)
Definition: mcxt.c:849
int i
Definition: pg_list.h:45
RelationPtr ri_IndexRelationDescs
Definition: execnodes.h:339
#define lfirst_oid(lc)
Definition: pg_list.h:108
LockTupleMode ExecUpdateLockMode ( EState estate,
ResultRelInfo relinfo 
)

Definition at line 2207 of file execMain.c.

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

Referenced by ExecBRUpdateTriggers(), and ExecOnConflictUpdate().

2208 {
2209  Bitmapset *keyCols;
2210  Bitmapset *updatedCols;
2211 
2212  /*
2213  * Compute lock mode to use. If columns that are part of the key have not
2214  * been modified, then we can use a weaker lock, allowing for better
2215  * concurrency.
2216  */
2217  updatedCols = GetUpdatedColumns(relinfo, estate);
2218  keyCols = RelationGetIndexAttrBitmap(relinfo->ri_RelationDesc,
2220 
2221  if (bms_overlap(keyCols, updatedCols))
2222  return LockTupleExclusive;
2223 
2224  return LockTupleNoKeyExclusive;
2225 }
#define GetUpdatedColumns(relinfo, estate)
Definition: execMain.c:114
Relation ri_RelationDesc
Definition: execnodes.h:337
bool bms_overlap(const Bitmapset *a, const Bitmapset *b)
Definition: bitmapset.c:442
Bitmapset * RelationGetIndexAttrBitmap(Relation relation, IndexAttrBitmapKind attrKind)
Definition: relcache.c:4759
static void ExecutePlan ( EState estate,
PlanState planstate,
bool  use_parallel_mode,
CmdType  operation,
bool  sendTuples,
uint64  numberTuples,
ScanDirection  direction,
DestReceiver dest 
)
static

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

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

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

445 {
446  if (ExecutorEnd_hook)
447  (*ExecutorEnd_hook) (queryDesc);
448  else
449  standard_ExecutorEnd(queryDesc);
450 }
void standard_ExecutorEnd(QueryDesc *queryDesc)
Definition: execMain.c:453
ExecutorEnd_hook_type ExecutorEnd_hook
Definition: execMain.c:72
void ExecutorFinish ( QueryDesc queryDesc)

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

385 {
387  (*ExecutorFinish_hook) (queryDesc);
388  else
389  standard_ExecutorFinish(queryDesc);
390 }
void standard_ExecutorFinish(QueryDesc *queryDesc)
Definition: execMain.c:393
ExecutorFinish_hook_type ExecutorFinish_hook
Definition: execMain.c:71
void ExecutorRewind ( QueryDesc queryDesc)

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

511 {
512  EState *estate;
513  MemoryContext oldcontext;
514 
515  /* sanity checks */
516  Assert(queryDesc != NULL);
517 
518  estate = queryDesc->estate;
519 
520  Assert(estate != NULL);
521 
522  /* It's probably not sensible to rescan updating queries */
523  Assert(queryDesc->operation == CMD_SELECT);
524 
525  /*
526  * Switch into per-query memory context
527  */
528  oldcontext = MemoryContextSwitchTo(estate->es_query_cxt);
529 
530  /*
531  * rescan plan
532  */
533  ExecReScan(queryDesc->planstate);
534 
535  MemoryContextSwitchTo(oldcontext);
536 }
EState * estate
Definition: execdesc.h:47
void ExecReScan(PlanState *node)
Definition: execAmi.c:74
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:109
MemoryContext es_query_cxt
Definition: execnodes.h:399
PlanState * planstate
Definition: execdesc.h:48
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 
)

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

292 {
293  if (ExecutorRun_hook)
294  (*ExecutorRun_hook) (queryDesc, direction, count);
295  else
296  standard_ExecutorRun(queryDesc, direction, count);
297 }
ExecutorRun_hook_type ExecutorRun_hook
Definition: execMain.c:70
void standard_ExecutorRun(QueryDesc *queryDesc, ScanDirection direction, uint64 count)
Definition: execMain.c:300
void ExecutorStart ( QueryDesc queryDesc,
int  eflags 
)

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

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

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

1944 {
1945  Relation rel = resultRelInfo->ri_RelationDesc;
1946  TupleDesc tupdesc = RelationGetDescr(rel);
1947  ExprContext *econtext;
1948  ListCell *l1,
1949  *l2;
1950 
1951  /*
1952  * We will use the EState's per-tuple context for evaluating constraint
1953  * expressions (creating it if it's not already there).
1954  */
1955  econtext = GetPerTupleExprContext(estate);
1956 
1957  /* Arrange for econtext's scan tuple to be the tuple under test */
1958  econtext->ecxt_scantuple = slot;
1959 
1960  /* Check each of the constraints */
1961  forboth(l1, resultRelInfo->ri_WithCheckOptions,
1962  l2, resultRelInfo->ri_WithCheckOptionExprs)
1963  {
1964  WithCheckOption *wco = (WithCheckOption *) lfirst(l1);
1965  ExprState *wcoExpr = (ExprState *) lfirst(l2);
1966 
1967  /*
1968  * Skip any WCOs which are not the kind we are looking for at this
1969  * time.
1970  */
1971  if (wco->kind != kind)
1972  continue;
1973 
1974  /*
1975  * WITH CHECK OPTION checks are intended to ensure that the new tuple
1976  * is visible (in the case of a view) or that it passes the
1977  * 'with-check' policy (in the case of row security). If the qual
1978  * evaluates to NULL or FALSE, then the new tuple won't be included in
1979  * the view or doesn't pass the 'with-check' policy for the table. We
1980  * need ExecQual to return FALSE for NULL to handle the view case (the
1981  * opposite of what we do above for CHECK constraints).
1982  */
1983  if (!ExecQual((List *) wcoExpr, econtext, false))
1984  {
1985  char *val_desc;
1986  Bitmapset *modifiedCols;
1987  Bitmapset *insertedCols;
1988  Bitmapset *updatedCols;
1989 
1990  switch (wco->kind)
1991  {
1992  /*
1993  * For WITH CHECK OPTIONs coming from views, we might be
1994  * able to provide the details on the row, depending on
1995  * the permissions on the relation (that is, if the user
1996  * could view it directly anyway). For RLS violations, we
1997  * don't include the data since we don't know if the user
1998  * should be able to view the tuple as as that depends on
1999  * the USING policy.
2000  */
2001  case WCO_VIEW_CHECK:
2002  insertedCols = GetInsertedColumns(resultRelInfo, estate);
2003  updatedCols = GetUpdatedColumns(resultRelInfo, estate);
2004  modifiedCols = bms_union(insertedCols, updatedCols);
2006  slot,
2007  tupdesc,
2008  modifiedCols,
2009  64);
2010 
2011  ereport(ERROR,
2012  (errcode(ERRCODE_WITH_CHECK_OPTION_VIOLATION),
2013  errmsg("new row violates check option for view \"%s\"",
2014  wco->relname),
2015  val_desc ? errdetail("Failing row contains %s.",
2016  val_desc) : 0));
2017  break;
2018  case WCO_RLS_INSERT_CHECK:
2019  case WCO_RLS_UPDATE_CHECK:
2020  if (wco->polname != NULL)
2021  ereport(ERROR,
2022  (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
2023  errmsg("new row violates row-level security policy \"%s\" for table \"%s\"",
2024  wco->polname, wco->relname)));
2025  else
2026  ereport(ERROR,
2027  (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
2028  errmsg("new row violates row-level security policy for table \"%s\"",
2029  wco->relname)));
2030  break;
2032  if (wco->polname != NULL)
2033  ereport(ERROR,
2034  (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
2035  errmsg("new row violates row-level security policy \"%s\" (USING expression) for table \"%s\"",
2036  wco->polname, wco->relname)));
2037  else
2038  ereport(ERROR,
2039  (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
2040  errmsg("new row violates row-level security policy (USING expression) for table \"%s\"",
2041  wco->relname)));
2042  break;
2043  default:
2044  elog(ERROR, "unrecognized WCO kind: %u", wco->kind);
2045  break;
2046  }
2047  }
2048  }
2049 }
#define GetUpdatedColumns(relinfo, estate)
Definition: execMain.c:114
Relation ri_RelationDesc
Definition: execnodes.h:337
#define forboth(cell1, list1, cell2, list2)
Definition: pg_list.h:174
#define RelationGetDescr(relation)
Definition: rel.h:425
int errcode(int sqlerrcode)
Definition: elog.c:575
List * ri_WithCheckOptionExprs
Definition: execnodes.h:349
#define GetPerTupleExprContext(estate)
Definition: executor.h:338
#define ERROR
Definition: elog.h:43
static char * ExecBuildSlotValueDescription(Oid reloid, TupleTableSlot *slot, TupleDesc tupdesc, Bitmapset *modifiedCols, int maxfieldlen)
Definition: execMain.c:2071
int errdetail(const char *fmt,...)
Definition: elog.c:873
bool ExecQual(List *qual, ExprContext *econtext, bool resultForNull)
Definition: execQual.c:5056
#define ereport(elevel, rest)
Definition: elog.h:122
List * ri_WithCheckOptions
Definition: execnodes.h:348
#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:217
TupleTableSlot * ecxt_scantuple
Definition: execnodes.h:130
int errmsg(const char *fmt,...)
Definition: elog.c:797
#define elog
Definition: elog.h:219
Definition: pg_list.h:45
#define RelationGetRelid(relation)
Definition: rel.h:413
#define GetInsertedColumns(relinfo, estate)
Definition: execMain.c:112
static void InitPlan ( QueryDesc queryDesc,
int  eflags 
)
static

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

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

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

1251 {
1252  List *partition_check = NIL;
1253 
1254  MemSet(resultRelInfo, 0, sizeof(ResultRelInfo));
1255  resultRelInfo->type = T_ResultRelInfo;
1256  resultRelInfo->ri_RangeTableIndex = resultRelationIndex;
1257  resultRelInfo->ri_RelationDesc = resultRelationDesc;
1258  resultRelInfo->ri_NumIndices = 0;
1259  resultRelInfo->ri_IndexRelationDescs = NULL;
1260  resultRelInfo->ri_IndexRelationInfo = NULL;
1261  /* make a copy so as not to depend on relcache info not changing... */
1262  resultRelInfo->ri_TrigDesc = CopyTriggerDesc(resultRelationDesc->trigdesc);
1263  if (resultRelInfo->ri_TrigDesc)
1264  {
1265  int n = resultRelInfo->ri_TrigDesc->numtriggers;
1266 
1267  resultRelInfo->ri_TrigFunctions = (FmgrInfo *)
1268  palloc0(n * sizeof(FmgrInfo));
1269  resultRelInfo->ri_TrigWhenExprs = (List **)
1270  palloc0(n * sizeof(List *));
1271  if (instrument_options)
1272  resultRelInfo->ri_TrigInstrument = InstrAlloc(n, instrument_options);
1273  }
1274  else
1275  {
1276  resultRelInfo->ri_TrigFunctions = NULL;
1277  resultRelInfo->ri_TrigWhenExprs = NULL;
1278  resultRelInfo->ri_TrigInstrument = NULL;
1279  }
1280  if (resultRelationDesc->rd_rel->relkind == RELKIND_FOREIGN_TABLE)
1281  resultRelInfo->ri_FdwRoutine = GetFdwRoutineForRelation(resultRelationDesc, true);
1282  else
1283  resultRelInfo->ri_FdwRoutine = NULL;
1284  resultRelInfo->ri_FdwState = NULL;
1285  resultRelInfo->ri_usesFdwDirectModify = false;
1286  resultRelInfo->ri_ConstraintExprs = NULL;
1287  resultRelInfo->ri_junkFilter = NULL;
1288  resultRelInfo->ri_projectReturning = NULL;
1289 
1290  /*
1291  * If partition_root has been specified, that means we are building the
1292  * ResultRelationInfo for one of its leaf partitions. In that case, we
1293  * need *not* initialize the leaf partition's constraint, but rather the
1294  * the partition_root's (if any). We must do that explicitly like this,
1295  * because implicit partition constraints are not inherited like user-
1296  * defined constraints and would fail to be enforced by ExecConstraints()
1297  * after a tuple is routed to a leaf partition.
1298  */
1299  if (partition_root)
1300  {
1301  /*
1302  * Root table itself may or may not be a partition; partition_check
1303  * would be NIL in the latter case.
1304  */
1305  partition_check = RelationGetPartitionQual(partition_root);
1306 
1307  /*
1308  * This is not our own partition constraint, but rather an ancestor's.
1309  * So any Vars in it bear the ancestor's attribute numbers. We must
1310  * switch them to our own. (dummy varno = 1)
1311  */
1312  if (partition_check != NIL)
1313  partition_check = map_partition_varattnos(partition_check, 1,
1314  resultRelationDesc,
1315  partition_root);
1316  }
1317  else
1318  partition_check = RelationGetPartitionQual(resultRelationDesc);
1319 
1320  resultRelInfo->ri_PartitionCheck = partition_check;
1321  resultRelInfo->ri_PartitionRoot = partition_root;
1322 }
int ri_NumIndices
Definition: execnodes.h:338
#define NIL
Definition: pg_list.h:69
JunkFilter * ri_junkFilter
Definition: execnodes.h:351
Definition: fmgr.h:53
Relation ri_RelationDesc
Definition: execnodes.h:337
Relation ri_PartitionRoot
Definition: execnodes.h:357
Instrumentation * ri_TrigInstrument
Definition: execnodes.h:344
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:113
Index ri_RangeTableIndex
Definition: execnodes.h:336
NodeTag type
Definition: execnodes.h:335
List ** ri_ConstraintExprs
Definition: execnodes.h:350
TriggerDesc * trigdesc
Definition: rel.h:119
bool ri_usesFdwDirectModify
Definition: execnodes.h:347
ProjectionInfo * ri_projectReturning
Definition: execnodes.h:352
struct FdwRoutine * ri_FdwRoutine
Definition: execnodes.h:345
#define RELKIND_FOREIGN_TABLE
Definition: pg_class.h:167
TriggerDesc * ri_TrigDesc
Definition: execnodes.h:341
List ** ri_TrigWhenExprs
Definition: execnodes.h:343
int numtriggers
Definition: reltrigger.h:49
List * RelationGetPartitionQual(Relation rel)
Definition: partition.c:958
void * palloc0(Size size)
Definition: mcxt.c:878
List * ri_PartitionCheck
Definition: execnodes.h:355
void * ri_FdwState
Definition: execnodes.h:346
#define NULL
Definition: c.h:229
TriggerDesc * CopyTriggerDesc(TriggerDesc *trigdesc)
Definition: trigger.c:1826
FdwRoutine * GetFdwRoutineForRelation(Relation relation, bool makecopy)
Definition: foreign.c:395
IndexInfo ** ri_IndexRelationInfo
Definition: execnodes.h:340
Definition: pg_list.h:45
RelationPtr ri_IndexRelationDescs
Definition: execnodes.h:339
FmgrInfo * ri_TrigFunctions
Definition: execnodes.h:342
List * map_partition_varattnos(List *expr, int target_varno, Relation partrel, Relation parent)
Definition: partition.c:928
void standard_ExecutorEnd ( QueryDesc queryDesc)

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

454 {
455  EState *estate;
456  MemoryContext oldcontext;
457 
458  /* sanity checks */
459  Assert(queryDesc != NULL);
460 
461  estate = queryDesc->estate;
462 
463  Assert(estate != NULL);
464 
465  /*
466  * Check that ExecutorFinish was called, unless in EXPLAIN-only mode. This
467  * Assert is needed because ExecutorFinish is new as of 9.1, and callers
468  * might forget to call it.
469  */
470  Assert(estate->es_finished ||
472 
473  /*
474  * Switch into per-query memory context to run ExecEndPlan
475  */
476  oldcontext = MemoryContextSwitchTo(estate->es_query_cxt);
477 
478  ExecEndPlan(queryDesc->planstate, estate);
479 
480  /* do away with our snapshots */
483 
484  /*
485  * Must switch out of context before destroying it
486  */
487  MemoryContextSwitchTo(oldcontext);
488 
489  /*
490  * Release EState and per-query memory context. This should release
491  * everything the executor has allocated.
492  */
493  FreeExecutorState(estate);
494 
495  /* Reset queryDesc fields that no longer point to anything */
496  queryDesc->tupDesc = NULL;
497  queryDesc->estate = NULL;
498  queryDesc->planstate = NULL;
499  queryDesc->totaltime = NULL;
500 }
EState * estate
Definition: execdesc.h:47
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:109
Snapshot es_crosscheck_snapshot
Definition: execnodes.h:373
Snapshot es_snapshot
Definition: execnodes.h:372
void FreeExecutorState(EState *estate)
Definition: execUtils.c:169
MemoryContext es_query_cxt
Definition: execnodes.h:399
PlanState * planstate
Definition: execdesc.h:48
void UnregisterSnapshot(Snapshot snapshot)
Definition: snapmgr.c:900
TupleDesc tupDesc
Definition: execdesc.h:46
bool es_finished
Definition: execnodes.h:410
struct Instrumentation * totaltime
Definition: execdesc.h:51
#define NULL
Definition: c.h:229
#define Assert(condition)
Definition: c.h:675
static void ExecEndPlan(PlanState *planstate, EState *estate)
Definition: execMain.c:1513
int es_top_eflags
Definition: execnodes.h:408
#define EXEC_FLAG_EXPLAIN_ONLY
Definition: executor.h:58
void standard_ExecutorFinish ( QueryDesc queryDesc)

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

394 {
395  EState *estate;
396  MemoryContext oldcontext;
397 
398  /* sanity checks */
399  Assert(queryDesc != NULL);
400 
401  estate = queryDesc->estate;
402 
403  Assert(estate != NULL);
405 
406  /* This should be run once and only once per Executor instance */
407  Assert(!estate->es_finished);
408 
409  /* Switch into per-query memory context */
410  oldcontext = MemoryContextSwitchTo(estate->es_query_cxt);
411 
412  /* Allow instrumentation of Executor overall runtime */
413  if (queryDesc->totaltime)
414  InstrStartNode(queryDesc->totaltime);
415 
416  /* Run ModifyTable nodes to completion */
417  ExecPostprocessPlan(estate);
418 
419  /* Execute queued AFTER triggers, unless told not to */
420  if (!(estate->es_top_eflags & EXEC_FLAG_SKIP_TRIGGERS))
421  AfterTriggerEndQuery(estate);
422 
423  if (queryDesc->totaltime)
424  InstrStopNode(queryDesc->totaltime, 0);
425 
426  MemoryContextSwitchTo(oldcontext);
427 
428  estate->es_finished = true;
429 }
void InstrStopNode(Instrumentation *instr, double nTuples)
Definition: instrument.c:80
static void ExecPostprocessPlan(EState *estate)
Definition: execMain.c:1467
EState * estate
Definition: execdesc.h:47
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:109
MemoryContext es_query_cxt
Definition: execnodes.h:399
void InstrStartNode(Instrumentation *instr)
Definition: instrument.c:63
bool es_finished
Definition: execnodes.h:410
struct Instrumentation * totaltime
Definition: execdesc.h:51
#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:4170
int es_top_eflags
Definition: execnodes.h:408
#define EXEC_FLAG_EXPLAIN_ONLY
Definition: executor.h:58
void standard_ExecutorRun ( QueryDesc queryDesc,
ScanDirection  direction,
uint64  count 
)

Definition at line 300 of file execMain.c.

References Assert, CMD_SELECT, QueryDesc::dest, 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().

302 {
303  EState *estate;
304  CmdType operation;
305  DestReceiver *dest;
306  bool sendTuples;
307  MemoryContext oldcontext;
308 
309  /* sanity checks */
310  Assert(queryDesc != NULL);
311 
312  estate = queryDesc->estate;
313 
314  Assert(estate != NULL);
316 
317  /*
318  * Switch into per-query memory context
319  */
320  oldcontext = MemoryContextSwitchTo(estate->es_query_cxt);
321 
322  /* Allow instrumentation of Executor overall runtime */
323  if (queryDesc->totaltime)
324  InstrStartNode(queryDesc->totaltime);
325 
326  /*
327  * extract information from the query descriptor and the query feature.
328  */
329  operation = queryDesc->operation;
330  dest = queryDesc->dest;
331 
332  /*
333  * startup tuple receiver, if we will be emitting tuples
334  */
335  estate->es_processed = 0;
336  estate->es_lastoid = InvalidOid;
337 
338  sendTuples = (operation == CMD_SELECT ||
339  queryDesc->plannedstmt->hasReturning);
340 
341  if (sendTuples)
342  (*dest->rStartup) (dest, operation, queryDesc->tupDesc);
343 
344  /*
345  * run plan
346  */
347  if (!ScanDirectionIsNoMovement(direction))
348  ExecutePlan(estate,
349  queryDesc->planstate,
350  queryDesc->plannedstmt->parallelModeNeeded,
351  operation,
352  sendTuples,
353  count,
354  direction,
355  dest);
356 
357  /*
358  * shutdown tuple receiver, if we started it
359  */
360  if (sendTuples)
361  (*dest->rShutdown) (dest);
362 
363  if (queryDesc->totaltime)
364  InstrStopNode(queryDesc->totaltime, estate->es_processed);
365 
366  MemoryContextSwitchTo(oldcontext);
367 }
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:47
Oid es_lastoid
Definition: execnodes.h:406
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:109
#define ScanDirectionIsNoMovement(direction)
Definition: sdir.h:48
static void ExecutePlan(EState *estate, PlanState *planstate, bool use_parallel_mode, CmdType operation, bool sendTuples, uint64 numberTuples, ScanDirection direction, DestReceiver *dest)
Definition: execMain.c:1591
MemoryContext es_query_cxt
Definition: execnodes.h:399
PlanState * planstate
Definition: execdesc.h:48
void InstrStartNode(Instrumentation *instr)
Definition: instrument.c:63
bool hasReturning
Definition: plannodes.h:49
TupleDesc tupDesc
Definition: execdesc.h:46
CmdType operation
Definition: execdesc.h:36
#define InvalidOid
Definition: postgres_ext.h:36
struct Instrumentation * totaltime
Definition: execdesc.h:51
#define NULL
Definition: c.h:229
#define Assert(condition)
Definition: c.h:675
uint64 es_processed
Definition: execnodes.h:405
DestReceiver * dest
Definition: execdesc.h:41
int es_top_eflags
Definition: execnodes.h:408
bool parallelModeNeeded
Definition: plannodes.h:59
PlannedStmt * plannedstmt
Definition: execdesc.h:37
#define EXEC_FLAG_EXPLAIN_ONLY
Definition: executor.h:58
CmdType
Definition: nodes.h:651
void standard_ExecutorStart ( QueryDesc queryDesc,
int  eflags 
)

Definition at line 152 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_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, RegisterSnapshot(), PlannedStmt::rowMarks, QueryDesc::snapshot, QueryDesc::sourceText, and XactReadOnly.

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

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

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