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/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 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 107 of file execMain.c.

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

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

Function Documentation

void CheckValidResultRel ( Relation  resultRel,
CmdType  operation 
)

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

1022 {
1023  TriggerDesc *trigDesc = resultRel->trigdesc;
1024  FdwRoutine *fdwroutine;
1025 
1026  switch (resultRel->rd_rel->relkind)
1027  {
1028  case RELKIND_RELATION:
1030  CheckCmdReplicaIdentity(resultRel, operation);
1031  break;
1032  case RELKIND_SEQUENCE:
1033  ereport(ERROR,
1034  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1035  errmsg("cannot change sequence \"%s\"",
1036  RelationGetRelationName(resultRel))));
1037  break;
1038  case RELKIND_TOASTVALUE:
1039  ereport(ERROR,
1040  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1041  errmsg("cannot change TOAST relation \"%s\"",
1042  RelationGetRelationName(resultRel))));
1043  break;
1044  case RELKIND_VIEW:
1045 
1046  /*
1047  * Okay only if there's a suitable INSTEAD OF trigger. Messages
1048  * here should match rewriteHandler.c's rewriteTargetView, except
1049  * that we omit errdetail because we haven't got the information
1050  * handy (and given that we really shouldn't get here anyway, it's
1051  * not worth great exertion to get).
1052  */
1053  switch (operation)
1054  {
1055  case CMD_INSERT:
1056  if (!trigDesc || !trigDesc->trig_insert_instead_row)
1057  ereport(ERROR,
1058  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
1059  errmsg("cannot insert into view \"%s\"",
1060  RelationGetRelationName(resultRel)),
1061  errhint("To enable inserting into the view, provide an INSTEAD OF INSERT trigger or an unconditional ON INSERT DO INSTEAD rule.")));
1062  break;
1063  case CMD_UPDATE:
1064  if (!trigDesc || !trigDesc->trig_update_instead_row)
1065  ereport(ERROR,
1066  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
1067  errmsg("cannot update view \"%s\"",
1068  RelationGetRelationName(resultRel)),
1069  errhint("To enable updating the view, provide an INSTEAD OF UPDATE trigger or an unconditional ON UPDATE DO INSTEAD rule.")));
1070  break;
1071  case CMD_DELETE:
1072  if (!trigDesc || !trigDesc->trig_delete_instead_row)
1073  ereport(ERROR,
1074  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
1075  errmsg("cannot delete from view \"%s\"",
1076  RelationGetRelationName(resultRel)),
1077  errhint("To enable deleting from the view, provide an INSTEAD OF DELETE trigger or an unconditional ON DELETE DO INSTEAD rule.")));
1078  break;
1079  default:
1080  elog(ERROR, "unrecognized CmdType: %d", (int) operation);
1081  break;
1082  }
1083  break;
1084  case RELKIND_MATVIEW:
1086  ereport(ERROR,
1087  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1088  errmsg("cannot change materialized view \"%s\"",
1089  RelationGetRelationName(resultRel))));
1090  break;
1091  case RELKIND_FOREIGN_TABLE:
1092  /* Okay only if the FDW supports it */
1093  fdwroutine = GetFdwRoutineForRelation(resultRel, false);
1094  switch (operation)
1095  {
1096  case CMD_INSERT:
1097  if (fdwroutine->ExecForeignInsert == NULL)
1098  ereport(ERROR,
1099  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1100  errmsg("cannot insert into foreign table \"%s\"",
1101  RelationGetRelationName(resultRel))));
1102  if (fdwroutine->IsForeignRelUpdatable != NULL &&
1103  (fdwroutine->IsForeignRelUpdatable(resultRel) & (1 << CMD_INSERT)) == 0)
1104  ereport(ERROR,
1105  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
1106  errmsg("foreign table \"%s\" does not allow inserts",
1107  RelationGetRelationName(resultRel))));
1108  break;
1109  case CMD_UPDATE:
1110  if (fdwroutine->ExecForeignUpdate == NULL)
1111  ereport(ERROR,
1112  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1113  errmsg("cannot update foreign table \"%s\"",
1114  RelationGetRelationName(resultRel))));
1115  if (fdwroutine->IsForeignRelUpdatable != NULL &&
1116  (fdwroutine->IsForeignRelUpdatable(resultRel) & (1 << CMD_UPDATE)) == 0)
1117  ereport(ERROR,
1118  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
1119  errmsg("foreign table \"%s\" does not allow updates",
1120  RelationGetRelationName(resultRel))));
1121  break;
1122  case CMD_DELETE:
1123  if (fdwroutine->ExecForeignDelete == NULL)
1124  ereport(ERROR,
1125  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1126  errmsg("cannot delete from foreign table \"%s\"",
1127  RelationGetRelationName(resultRel))));
1128  if (fdwroutine->IsForeignRelUpdatable != NULL &&
1129  (fdwroutine->IsForeignRelUpdatable(resultRel) & (1 << CMD_DELETE)) == 0)
1130  ereport(ERROR,
1131  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
1132  errmsg("foreign table \"%s\" does not allow deletes",
1133  RelationGetRelationName(resultRel))));
1134  break;
1135  default:
1136  elog(ERROR, "unrecognized CmdType: %d", (int) operation);
1137  break;
1138  }
1139  break;
1140  default:
1141  ereport(ERROR,
1142  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1143  errmsg("cannot change relation \"%s\"",
1144  RelationGetRelationName(resultRel))));
1145  break;
1146  }
1147 }
ExecForeignDelete_function ExecForeignDelete
Definition: fdwapi.h:198
int errhint(const char *fmt,...)
Definition: elog.c:987
bool MatViewIncrementalMaintenanceIsEnabled(void)
Definition: matview.c:836
ExecForeignInsert_function ExecForeignInsert
Definition: fdwapi.h:196
#define RELKIND_MATVIEW
Definition: pg_class.h:167
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:166
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:197
#define NULL
Definition: c.h:226
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:200
#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 1156 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().

1157 {
1158  FdwRoutine *fdwroutine;
1159 
1160  switch (rel->rd_rel->relkind)
1161  {
1162  case RELKIND_RELATION:
1164  /* OK */
1165  break;
1166  case RELKIND_SEQUENCE:
1167  /* Must disallow this because we don't vacuum sequences */
1168  ereport(ERROR,
1169  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1170  errmsg("cannot lock rows in sequence \"%s\"",
1171  RelationGetRelationName(rel))));
1172  break;
1173  case RELKIND_TOASTVALUE:
1174  /* We could allow this, but there seems no good reason to */
1175  ereport(ERROR,
1176  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1177  errmsg("cannot lock rows in TOAST relation \"%s\"",
1178  RelationGetRelationName(rel))));
1179  break;
1180  case RELKIND_VIEW:
1181  /* Should not get here; planner should have expanded the view */
1182  ereport(ERROR,
1183  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1184  errmsg("cannot lock rows in view \"%s\"",
1185  RelationGetRelationName(rel))));
1186  break;
1187  case RELKIND_MATVIEW:
1188  /* Allow referencing a matview, but not actual locking clauses */
1189  if (markType != ROW_MARK_REFERENCE)
1190  ereport(ERROR,
1191  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1192  errmsg("cannot lock rows in materialized view \"%s\"",
1193  RelationGetRelationName(rel))));
1194  break;
1195  case RELKIND_FOREIGN_TABLE:
1196  /* Okay only if the FDW supports it */
1197  fdwroutine = GetFdwRoutineForRelation(rel, false);
1198  if (fdwroutine->RefetchForeignRow == NULL)
1199  ereport(ERROR,
1200  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1201  errmsg("cannot lock rows in foreign table \"%s\"",
1202  RelationGetRelationName(rel))));
1203  break;
1204  default:
1205  ereport(ERROR,
1206  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1207  errmsg("cannot lock rows in relation \"%s\"",
1208  RelationGetRelationName(rel))));
1209  break;
1210  }
1211 }
#define RELKIND_MATVIEW
Definition: pg_class.h:167
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:166
#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:226
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:208
TupleTableSlot* EvalPlanQual ( EState estate,
EPQState epqstate,
Relation  relation,
Index  rti,
int  lockmode,
ItemPointer  tid,
TransactionId  priorXmax 
)

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

2306 {
2307  TupleTableSlot *slot;
2308  HeapTuple copyTuple;
2309 
2310  Assert(rti > 0);
2311 
2312  /*
2313  * Get and lock the updated version of the row; if fail, return NULL.
2314  */
2315  copyTuple = EvalPlanQualFetch(estate, relation, lockmode, LockWaitBlock,
2316  tid, priorXmax);
2317 
2318  if (copyTuple == NULL)
2319  return NULL;
2320 
2321  /*
2322  * For UPDATE/DELETE we have to return tid of actual row we're executing
2323  * PQ for.
2324  */
2325  *tid = copyTuple->t_self;
2326 
2327  /*
2328  * Need to run a recheck subquery. Initialize or reinitialize EPQ state.
2329  */
2330  EvalPlanQualBegin(epqstate, estate);
2331 
2332  /*
2333  * Free old test tuple, if any, and store new tuple where relation's scan
2334  * node will see it
2335  */
2336  EvalPlanQualSetTuple(epqstate, rti, copyTuple);
2337 
2338  /*
2339  * Fetch any non-locked source rows
2340  */
2341  EvalPlanQualFetchRowMarks(epqstate);
2342 
2343  /*
2344  * Run the EPQ query. We assume it will return at most one tuple.
2345  */
2346  slot = EvalPlanQualNext(epqstate);
2347 
2348  /*
2349  * If we got a tuple, force the slot to materialize the tuple so that it
2350  * is not dependent on any local state in the EPQ query (in particular,
2351  * it's highly likely that the slot contains references to any pass-by-ref
2352  * datums that may be present in copyTuple). As with the next step, this
2353  * is to guard against early re-use of the EPQ query.
2354  */
2355  if (!TupIsNull(slot))
2356  (void) ExecMaterializeSlot(slot);
2357 
2358  /*
2359  * Clear out the test tuple. This is needed in case the EPQ query is
2360  * re-used to test a tuple for a different relation. (Not clear that can
2361  * really happen, but let's be safe.)
2362  */
2363  EvalPlanQualSetTuple(epqstate, rti, NULL);
2364 
2365  return slot;
2366 }
void EvalPlanQualSetTuple(EPQState *epqstate, Index rti, HeapTuple tuple)
Definition: execMain.c:2654
HeapTuple EvalPlanQualFetch(EState *estate, Relation relation, int lockmode, LockWaitPolicy wait_policy, ItemPointer tid, TransactionId priorXmax)
Definition: execMain.c:2390
void EvalPlanQualFetchRowMarks(EPQState *epqstate)
Definition: execMain.c:2689
void EvalPlanQualBegin(EPQState *epqstate, EState *parentestate)
Definition: execMain.c:2840
TupleTableSlot * EvalPlanQualNext(EPQState *epqstate)
Definition: execMain.c:2824
ItemPointerData t_self
Definition: htup.h:65
#define TupIsNull(slot)
Definition: tuptable.h:138
#define NULL
Definition: c.h:226
#define Assert(condition)
Definition: c.h:671
HeapTuple ExecMaterializeSlot(TupleTableSlot *slot)
Definition: execTuples.c:725
void EvalPlanQualBegin ( EPQState epqstate,
EState parentestate 
)

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

2841 {
2842  EState *estate = epqstate->estate;
2843 
2844  if (estate == NULL)
2845  {
2846  /* First time through, so create a child EState */
2847  EvalPlanQualStart(epqstate, parentestate, epqstate->plan);
2848  }
2849  else
2850  {
2851  /*
2852  * We already have a suitable child EPQ tree, so just reset it.
2853  */
2854  int rtsize = list_length(parentestate->es_range_table);
2855  PlanState *planstate = epqstate->planstate;
2856 
2857  MemSet(estate->es_epqScanDone, 0, rtsize * sizeof(bool));
2858 
2859  /* Recopy current values of parent parameters */
2860  if (parentestate->es_plannedstmt->nParamExec > 0)
2861  {
2862  int i = parentestate->es_plannedstmt->nParamExec;
2863 
2864  while (--i >= 0)
2865  {
2866  /* copy value if any, but not execPlan link */
2867  estate->es_param_exec_vals[i].value =
2868  parentestate->es_param_exec_vals[i].value;
2869  estate->es_param_exec_vals[i].isnull =
2870  parentestate->es_param_exec_vals[i].isnull;
2871  }
2872  }
2873 
2874  /*
2875  * Mark child plan tree as needing rescan at all scan nodes. The
2876  * first ExecProcNode will take care of actually doing the rescan.
2877  */
2878  planstate->chgParam = bms_add_member(planstate->chgParam,
2879  epqstate->epqParam);
2880  }
2881 }
PlannedStmt * es_plannedstmt
Definition: execnodes.h:373
#define MemSet(start, val, len)
Definition: c.h:853
List * es_range_table
Definition: execnodes.h:372
PlanState * planstate
Definition: execnodes.h:1112
int nParamExec
Definition: plannodes.h:78
ParamExecData * es_param_exec_vals
Definition: execnodes.h:394
bool isnull
Definition: params.h:101
static void EvalPlanQualStart(EPQState *epqstate, EState *parentestate, Plan *planTree)
Definition: execMain.c:2890
Bitmapset * chgParam
Definition: execnodes.h:1072
Plan * plan
Definition: execnodes.h:1114
#define NULL
Definition: c.h:226
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:434
Datum value
Definition: params.h:100
int epqParam
Definition: execnodes.h:1116
EState * estate
Definition: execnodes.h:1111
void EvalPlanQualEnd ( EPQState epqstate)

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

3031 {
3032  EState *estate = epqstate->estate;
3033  MemoryContext oldcontext;
3034  ListCell *l;
3035 
3036  if (estate == NULL)
3037  return; /* idle, so nothing to do */
3038 
3039  oldcontext = MemoryContextSwitchTo(estate->es_query_cxt);
3040 
3041  ExecEndNode(epqstate->planstate);
3042 
3043  foreach(l, estate->es_subplanstates)
3044  {
3045  PlanState *subplanstate = (PlanState *) lfirst(l);
3046 
3047  ExecEndNode(subplanstate);
3048  }
3049 
3050  /* throw away the per-estate tuple table */
3051  ExecResetTupleTable(estate->es_tupleTable, false);
3052 
3053  /* close any trigger target relations attached to this EState */
3054  foreach(l, estate->es_trig_target_relations)
3055  {
3056  ResultRelInfo *resultRelInfo = (ResultRelInfo *) lfirst(l);
3057 
3058  /* Close indices and then the relation itself */
3059  ExecCloseIndices(resultRelInfo);
3060  heap_close(resultRelInfo->ri_RelationDesc, NoLock);
3061  }
3062 
3063  MemoryContextSwitchTo(oldcontext);
3064 
3065  FreeExecutorState(estate);
3066 
3067  /* Mark EPQState idle */
3068  epqstate->estate = NULL;
3069  epqstate->planstate = NULL;
3070  epqstate->origslot = NULL;
3071 }
Relation ri_RelationDesc
Definition: execnodes.h:335
void ExecEndNode(PlanState *node)
Definition: execProcnode.c:624
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:109
#define heap_close(r, l)
Definition: heapam.h:97
PlanState * planstate
Definition: execnodes.h:1112
void FreeExecutorState(EState *estate)
Definition: execUtils.c:168
MemoryContext es_query_cxt
Definition: execnodes.h:397
#define NoLock
Definition: lockdefs.h:34
TupleTableSlot * origslot
Definition: execnodes.h:1113
List * es_trig_target_relations
Definition: execnodes.h:387
List * es_tupleTable
Definition: execnodes.h:399
void ExecResetTupleTable(List *tupleTable, bool shouldFree)
Definition: execTuples.c:156
#define NULL
Definition: c.h:226
#define lfirst(lc)
Definition: pg_list.h:106
List * es_subplanstates
Definition: execnodes.h:412
EState * estate
Definition: execnodes.h:1111
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 2390 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().

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

2690 {
2691  ListCell *l;
2692 
2693  Assert(epqstate->origslot != NULL);
2694 
2695  foreach(l, epqstate->arowMarks)
2696  {
2697  ExecAuxRowMark *aerm = (ExecAuxRowMark *) lfirst(l);
2698  ExecRowMark *erm = aerm->rowmark;
2699  Datum datum;
2700  bool isNull;
2701  HeapTupleData tuple;
2702 
2704  elog(ERROR, "EvalPlanQual doesn't support locking rowmarks");
2705 
2706  /* clear any leftover test tuple for this rel */
2707  EvalPlanQualSetTuple(epqstate, erm->rti, NULL);
2708 
2709  /* if child rel, must check whether it produced this row */
2710  if (erm->rti != erm->prti)
2711  {
2712  Oid tableoid;
2713 
2714  datum = ExecGetJunkAttribute(epqstate->origslot,
2715  aerm->toidAttNo,
2716  &isNull);
2717  /* non-locked rels could be on the inside of outer joins */
2718  if (isNull)
2719  continue;
2720  tableoid = DatumGetObjectId(datum);
2721 
2722  Assert(OidIsValid(erm->relid));
2723  if (tableoid != erm->relid)
2724  {
2725  /* this child is inactive right now */
2726  continue;
2727  }
2728  }
2729 
2730  if (erm->markType == ROW_MARK_REFERENCE)
2731  {
2732  HeapTuple copyTuple;
2733 
2734  Assert(erm->relation != NULL);
2735 
2736  /* fetch the tuple's ctid */
2737  datum = ExecGetJunkAttribute(epqstate->origslot,
2738  aerm->ctidAttNo,
2739  &isNull);
2740  /* non-locked rels could be on the inside of outer joins */
2741  if (isNull)
2742  continue;
2743 
2744  /* fetch requests on foreign tables must be passed to their FDW */
2745  if (erm->relation->rd_rel->relkind == RELKIND_FOREIGN_TABLE)
2746  {
2747  FdwRoutine *fdwroutine;
2748  bool updated = false;
2749 
2750  fdwroutine = GetFdwRoutineForRelation(erm->relation, false);
2751  /* this should have been checked already, but let's be safe */
2752  if (fdwroutine->RefetchForeignRow == NULL)
2753  ereport(ERROR,
2754  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2755  errmsg("cannot lock rows in foreign table \"%s\"",
2757  copyTuple = fdwroutine->RefetchForeignRow(epqstate->estate,
2758  erm,
2759  datum,
2760  &updated);
2761  if (copyTuple == NULL)
2762  elog(ERROR, "failed to fetch tuple for EvalPlanQual recheck");
2763 
2764  /*
2765  * Ideally we'd insist on updated == false here, but that
2766  * assumes that FDWs can track that exactly, which they might
2767  * not be able to. So just ignore the flag.
2768  */
2769  }
2770  else
2771  {
2772  /* ordinary table, fetch the tuple */
2773  Buffer buffer;
2774 
2775  tuple.t_self = *((ItemPointer) DatumGetPointer(datum));
2776  if (!heap_fetch(erm->relation, SnapshotAny, &tuple, &buffer,
2777  false, NULL))
2778  elog(ERROR, "failed to fetch tuple for EvalPlanQual recheck");
2779 
2780  /* successful, copy tuple */
2781  copyTuple = heap_copytuple(&tuple);
2782  ReleaseBuffer(buffer);
2783  }
2784 
2785  /* store tuple */
2786  EvalPlanQualSetTuple(epqstate, erm->rti, copyTuple);
2787  }
2788  else
2789  {
2790  HeapTupleHeader td;
2791 
2792  Assert(erm->markType == ROW_MARK_COPY);
2793 
2794  /* fetch the whole-row Var for the relation */
2795  datum = ExecGetJunkAttribute(epqstate->origslot,
2796  aerm->wholeAttNo,
2797  &isNull);
2798  /* non-locked rels could be on the inside of outer joins */
2799  if (isNull)
2800  continue;
2801  td = DatumGetHeapTupleHeader(datum);
2802 
2803  /* build a temporary HeapTuple control structure */
2805  tuple.t_data = td;
2806  /* relation might be a foreign table, if so provide tableoid */
2807  tuple.t_tableOid = erm->relid;
2808  /* also copy t_ctid in case there's valid data there */
2809  tuple.t_self = td->t_ctid;
2810 
2811  /* copy and store tuple */
2812  EvalPlanQualSetTuple(epqstate, erm->rti,
2813  heap_copytuple(&tuple));
2814  }
2815  }
2816 }
HeapTuple heap_copytuple(HeapTuple tuple)
Definition: heaptuple.c:608
void EvalPlanQualSetTuple(EPQState *epqstate, Index rti, HeapTuple tuple)
Definition: execMain.c:2654
Relation relation
Definition: execnodes.h:460
bool heap_fetch(Relation relation, Snapshot snapshot, HeapTuple tuple, Buffer *userbuf, bool keep_buf, Relation stats_relation)
Definition: heapam.c:1849
#define DatumGetObjectId(X)
Definition: postgres.h:508
int errcode(int sqlerrcode)
Definition: elog.c:575
void ReleaseBuffer(Buffer buffer)
Definition: bufmgr.c:3292
Form_pg_class rd_rel
Definition: rel.h:113
unsigned int Oid
Definition: postgres_ext.h:31
#define OidIsValid(objectId)
Definition: c.h:534
#define DatumGetHeapTupleHeader(X)
Definition: fmgr.h:254
#define RowMarkRequiresRowShareLock(marktype)
Definition: plannodes.h:897
ItemPointerData * ItemPointer
Definition: itemptr.h:48
ExecRowMark * rowmark
Definition: execnodes.h:487
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:1115
uint32 t_len
Definition: htup.h:64
Index rti
Definition: execnodes.h:462
AttrNumber wholeAttNo
Definition: execnodes.h:490
Index prti
Definition: execnodes.h:463
#define RelationGetRelationName(relation)
Definition: rel.h:433
Oid t_tableOid
Definition: htup.h:66
#define RELKIND_FOREIGN_TABLE
Definition: pg_class.h:166
TupleTableSlot * origslot
Definition: execnodes.h:1113
#define ereport(elevel, rest)
Definition: elog.h:122
uintptr_t Datum
Definition: postgres.h:374
#define SnapshotAny
Definition: tqual.h:28
#define NULL
Definition: c.h:226
#define Assert(condition)
Definition: c.h:671
#define lfirst(lc)
Definition: pg_list.h:106
RowMarkType markType
Definition: execnodes.h:465
AttrNumber toidAttNo
Definition: execnodes.h:489
#define DatumGetPointer(X)
Definition: postgres.h:557
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:1111
int Buffer
Definition: buf.h:23
AttrNumber ctidAttNo
Definition: execnodes.h:488
RefetchForeignRow_function RefetchForeignRow
Definition: fdwapi.h:208
#define HeapTupleHeaderGetDatumLength(tup)
Definition: htup_details.h:439
HeapTuple EvalPlanQualGetTuple ( EPQState epqstate,
Index  rti 
)

Definition at line 2674 of file execMain.c.

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

2675 {
2676  EState *estate = epqstate->estate;
2677 
2678  Assert(rti > 0);
2679 
2680  return estate->es_epqTuple[rti - 1];
2681 }
HeapTuple * es_epqTuple
Definition: execnodes.h:432
#define Assert(condition)
Definition: c.h:671
EState * estate
Definition: execnodes.h:1111
void EvalPlanQualInit ( EPQState epqstate,
EState estate,
Plan subplan,
List auxrowmarks,
int  epqParam 
)

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

2621 {
2622  /* Mark the EPQ state inactive */
2623  epqstate->estate = NULL;
2624  epqstate->planstate = NULL;
2625  epqstate->origslot = NULL;
2626  /* ... and remember data that EvalPlanQualBegin will need */
2627  epqstate->plan = subplan;
2628  epqstate->arowMarks = auxrowmarks;
2629  epqstate->epqParam = epqParam;
2630 }
PlanState * planstate
Definition: execnodes.h:1112
List * arowMarks
Definition: execnodes.h:1115
TupleTableSlot * origslot
Definition: execnodes.h:1113
Plan * plan
Definition: execnodes.h:1114
#define NULL
Definition: c.h:226
int epqParam
Definition: execnodes.h:1116
EState * estate
Definition: execnodes.h:1111
TupleTableSlot* EvalPlanQualNext ( EPQState epqstate)

Definition at line 2824 of file execMain.c.

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

Referenced by EvalPlanQual(), and ExecLockRows().

2825 {
2826  MemoryContext oldcontext;
2827  TupleTableSlot *slot;
2828 
2829  oldcontext = MemoryContextSwitchTo(epqstate->estate->es_query_cxt);
2830  slot = ExecProcNode(epqstate->planstate);
2831  MemoryContextSwitchTo(oldcontext);
2832 
2833  return slot;
2834 }
TupleTableSlot * ExecProcNode(PlanState *node)
Definition: execProcnode.c:380
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:109
PlanState * planstate
Definition: execnodes.h:1112
MemoryContext es_query_cxt
Definition: execnodes.h:397
EState * estate
Definition: execnodes.h:1111
void EvalPlanQualSetPlan ( EPQState epqstate,
Plan subplan,
List auxrowmarks 
)

Definition at line 2638 of file execMain.c.

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

Referenced by ExecInitModifyTable(), and ExecModifyTable().

2639 {
2640  /* If we have a live EPQ query, shut it down */
2641  EvalPlanQualEnd(epqstate);
2642  /* And set/change the plan pointer */
2643  epqstate->plan = subplan;
2644  /* The rowmarks depend on the plan, too */
2645  epqstate->arowMarks = auxrowmarks;
2646 }
void EvalPlanQualEnd(EPQState *epqstate)
Definition: execMain.c:3030
List * arowMarks
Definition: execnodes.h:1115
Plan * plan
Definition: execnodes.h:1114
void EvalPlanQualSetTuple ( EPQState epqstate,
Index  rti,
HeapTuple  tuple 
)

Definition at line 2654 of file execMain.c.

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

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

2655 {
2656  EState *estate = epqstate->estate;
2657 
2658  Assert(rti > 0);
2659 
2660  /*
2661  * free old test tuple, if any, and store new tuple where relation's scan
2662  * node will see it
2663  */
2664  if (estate->es_epqTuple[rti - 1] != NULL)
2665  heap_freetuple(estate->es_epqTuple[rti - 1]);
2666  estate->es_epqTuple[rti - 1] = tuple;
2667  estate->es_epqTupleSet[rti - 1] = true;
2668 }
HeapTuple * es_epqTuple
Definition: execnodes.h:432
void heap_freetuple(HeapTuple htup)
Definition: heaptuple.c:1374
#define NULL
Definition: c.h:226
#define Assert(condition)
Definition: c.h:671
bool * es_epqTupleSet
Definition: execnodes.h:433
EState * estate
Definition: execnodes.h:1111
static void EvalPlanQualStart ( EPQState epqstate,
EState parentestate,
Plan planTree 
)
static

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

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

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

2233 {
2234  ExecAuxRowMark *aerm = (ExecAuxRowMark *) palloc0(sizeof(ExecAuxRowMark));
2235  char resname[32];
2236 
2237  aerm->rowmark = erm;
2238 
2239  /* Look up the resjunk columns associated with this rowmark */
2240  if (erm->markType != ROW_MARK_COPY)
2241  {
2242  /* need ctid for all methods other than COPY */
2243  snprintf(resname, sizeof(resname), "ctid%u", erm->rowmarkId);
2244  aerm->ctidAttNo = ExecFindJunkAttributeInTlist(targetlist,
2245  resname);
2246  if (!AttributeNumberIsValid(aerm->ctidAttNo))
2247  elog(ERROR, "could not find junk %s column", resname);
2248  }
2249  else
2250  {
2251  /* need wholerow if COPY */
2252  snprintf(resname, sizeof(resname), "wholerow%u", erm->rowmarkId);
2253  aerm->wholeAttNo = ExecFindJunkAttributeInTlist(targetlist,
2254  resname);
2255  if (!AttributeNumberIsValid(aerm->wholeAttNo))
2256  elog(ERROR, "could not find junk %s column", resname);
2257  }
2258 
2259  /* if child rel, need tableoid */
2260  if (erm->rti != erm->prti)
2261  {
2262  snprintf(resname, sizeof(resname), "tableoid%u", erm->rowmarkId);
2263  aerm->toidAttNo = ExecFindJunkAttributeInTlist(targetlist,
2264  resname);
2265  if (!AttributeNumberIsValid(aerm->toidAttNo))
2266  elog(ERROR, "could not find junk %s column", resname);
2267  }
2268 
2269  return aerm;
2270 }
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:487
#define ERROR
Definition: elog.h:43
Index rti
Definition: execnodes.h:462
AttrNumber wholeAttNo
Definition: execnodes.h:490
Index prti
Definition: execnodes.h:463
Index rowmarkId
Definition: execnodes.h:464
#define AttributeNumberIsValid(attributeNumber)
Definition: attnum.h:34
void * palloc0(Size size)
Definition: mcxt.c:920
RowMarkType markType
Definition: execnodes.h:465
AttrNumber toidAttNo
Definition: execnodes.h:489
#define elog
Definition: elog.h:219
AttrNumber ctidAttNo
Definition: execnodes.h:488
static char * ExecBuildSlotValueDescription ( Oid  reloid,
TupleTableSlot slot,
TupleDesc  tupdesc,
Bitmapset modifiedCols,
int  maxfieldlen 
)
static

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

2051 {
2053  StringInfoData collist;
2054  bool write_comma = false;
2055  bool write_comma_collist = false;
2056  int i;
2057  AclResult aclresult;
2058  bool table_perm = false;
2059  bool any_perm = false;
2060 
2061  /*
2062  * Check if RLS is enabled and should be active for the relation; if so,
2063  * then don't return anything. Otherwise, go through normal permission
2064  * checks.
2065  */
2066  if (check_enable_rls(reloid, InvalidOid, true) == RLS_ENABLED)
2067  return NULL;
2068 
2069  initStringInfo(&buf);
2070 
2071  appendStringInfoChar(&buf, '(');
2072 
2073  /*
2074  * Check if the user has permissions to see the row. Table-level SELECT
2075  * allows access to all columns. If the user does not have table-level
2076  * SELECT then we check each column and include those the user has SELECT
2077  * rights on. Additionally, we always include columns the user provided
2078  * data for.
2079  */
2080  aclresult = pg_class_aclcheck(reloid, GetUserId(), ACL_SELECT);
2081  if (aclresult != ACLCHECK_OK)
2082  {
2083  /* Set up the buffer for the column list */
2084  initStringInfo(&collist);
2085  appendStringInfoChar(&collist, '(');
2086  }
2087  else
2088  table_perm = any_perm = true;
2089 
2090  /* Make sure the tuple is fully deconstructed */
2091  slot_getallattrs(slot);
2092 
2093  for (i = 0; i < tupdesc->natts; i++)
2094  {
2095  bool column_perm = false;
2096  char *val;
2097  int vallen;
2098 
2099  /* ignore dropped columns */
2100  if (tupdesc->attrs[i]->attisdropped)
2101  continue;
2102 
2103  if (!table_perm)
2104  {
2105  /*
2106  * No table-level SELECT, so need to make sure they either have
2107  * SELECT rights on the column or that they have provided the data
2108  * for the column. If not, omit this column from the error
2109  * message.
2110  */
2111  aclresult = pg_attribute_aclcheck(reloid, tupdesc->attrs[i]->attnum,
2112  GetUserId(), ACL_SELECT);
2113  if (bms_is_member(tupdesc->attrs[i]->attnum - FirstLowInvalidHeapAttributeNumber,
2114  modifiedCols) || aclresult == ACLCHECK_OK)
2115  {
2116  column_perm = any_perm = true;
2117 
2118  if (write_comma_collist)
2119  appendStringInfoString(&collist, ", ");
2120  else
2121  write_comma_collist = true;
2122 
2123  appendStringInfoString(&collist, NameStr(tupdesc->attrs[i]->attname));
2124  }
2125  }
2126 
2127  if (table_perm || column_perm)
2128  {
2129  if (slot->tts_isnull[i])
2130  val = "null";
2131  else
2132  {
2133  Oid foutoid;
2134  bool typisvarlena;
2135 
2136  getTypeOutputInfo(tupdesc->attrs[i]->atttypid,
2137  &foutoid, &typisvarlena);
2138  val = OidOutputFunctionCall(foutoid, slot->tts_values[i]);
2139  }
2140 
2141  if (write_comma)
2142  appendStringInfoString(&buf, ", ");
2143  else
2144  write_comma = true;
2145 
2146  /* truncate if needed */
2147  vallen = strlen(val);
2148  if (vallen <= maxfieldlen)
2149  appendStringInfoString(&buf, val);
2150  else
2151  {
2152  vallen = pg_mbcliplen(val, vallen, maxfieldlen);
2153  appendBinaryStringInfo(&buf, val, vallen);
2154  appendStringInfoString(&buf, "...");
2155  }
2156  }
2157  }
2158 
2159  /* If we end up with zero columns being returned, then return NULL. */
2160  if (!any_perm)
2161  return NULL;
2162 
2163  appendStringInfoChar(&buf, ')');
2164 
2165  if (!table_perm)
2166  {
2167  appendStringInfoString(&collist, ") = ");
2168  appendStringInfoString(&collist, buf.data);
2169 
2170  return collist.data;
2171  }
2172 
2173  return buf.data;
2174 }
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:4283
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:226
AclResult pg_class_aclcheck(Oid table_oid, Oid roleid, AclMode mode)
Definition: aclchk.c:4397
char * OidOutputFunctionCall(Oid functionId, Datum val)
Definition: fmgr.c:2006
int i
#define NameStr(name)
Definition: c.h:495
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 579 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().

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

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

701 {
702  int col = -1;
703 
704  /*
705  * When the query doesn't explicitly update any columns, allow the query
706  * if we have permission on any column of the rel. This is to handle
707  * SELECT FOR UPDATE as well as possible corner cases in UPDATE.
708  */
709  if (bms_is_empty(modifiedCols))
710  {
711  if (pg_attribute_aclcheck_all(relOid, userid, requiredPerms,
713  return false;
714  }
715 
716  while ((col = bms_next_member(modifiedCols, col)) >= 0)
717  {
718  /* bit #s are offset by FirstLowInvalidHeapAttributeNumber */
720 
721  if (attno == InvalidAttrNumber)
722  {
723  /* whole-row reference can't happen here */
724  elog(ERROR, "whole-row update is not implemented");
725  }
726  else
727  {
728  if (pg_attribute_aclcheck(relOid, attno, userid,
729  requiredPerms) != ACLCHECK_OK)
730  return false;
731  }
732  }
733  return true;
734 }
AclResult pg_attribute_aclcheck(Oid table_oid, AttrNumber attnum, Oid roleid, AclMode mode)
Definition: aclchk.c:4283
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:4312
#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 548 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().

549 {
550  ListCell *l;
551  bool result = true;
552 
553  foreach(l, rangeTable)
554  {
555  RangeTblEntry *rte = (RangeTblEntry *) lfirst(l);
556 
557  result = ExecCheckRTEPerms(rte);
558  if (!result)
559  {
560  Assert(rte->rtekind == RTE_RELATION);
561  if (ereport_on_violation)
563  get_rel_name(rte->relid));
564  return false;
565  }
566  }
567 
569  result = (*ExecutorCheckPerms_hook) (rangeTable,
570  ereport_on_violation);
571  return result;
572 }
void aclcheck_error(AclResult aclerr, AclObjectKind objectkind, const char *objectname)
Definition: aclchk.c:3378
static bool ExecCheckRTEPerms(RangeTblEntry *rte)
Definition: execMain.c:579
ExecutorCheckPerms_hook_type ExecutorCheckPerms_hook
Definition: execMain.c:74
#define Assert(condition)
Definition: c.h:671
#define lfirst(lc)
Definition: pg_list.h:106
RTEKind rtekind
Definition: parsenodes.h:882
char * get_rel_name(Oid relid)
Definition: lsyscache.c:1694
static void ExecCheckXactReadOnly ( PlannedStmt plannedstmt)
static

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

747 {
748  ListCell *l;
749 
750  /*
751  * Fail if write permissions are requested in parallel mode for table
752  * (temp or non-temp), otherwise fail for any non-temp table.
753  */
754  foreach(l, plannedstmt->rtable)
755  {
756  RangeTblEntry *rte = (RangeTblEntry *) lfirst(l);
757 
758  if (rte->rtekind != RTE_RELATION)
759  continue;
760 
761  if ((rte->requiredPerms & (~ACL_SELECT)) == 0)
762  continue;
763 
765  continue;
766 
768  }
769 
770  if (plannedstmt->commandType != CMD_SELECT || plannedstmt->hasModifyingCTE)
772 }
void PreventCommandIfParallelMode(const char *cmdname)
Definition: utility.c:253
Oid get_rel_namespace(Oid relid)
Definition: lsyscache.c:1718
Definition: nodes.h:508
AclMode requiredPerms
Definition: parsenodes.h:965
bool isTempNamespace(Oid namespaceId)
Definition: namespace.c:2952
const char * CreateCommandTag(Node *parsetree)
Definition: utility.c:2012
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:882
void ExecConstraints ( ResultRelInfo resultRelInfo,
TupleTableSlot slot,
TupleTableSlot orig_slot,
EState estate 
)

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

1792 {
1793  Relation rel = resultRelInfo->ri_RelationDesc;
1794  TupleDesc tupdesc = RelationGetDescr(rel);
1795  TupleConstr *constr = tupdesc->constr;
1796  Bitmapset *modifiedCols;
1797  Bitmapset *insertedCols;
1798  Bitmapset *updatedCols;
1799 
1800  Assert(constr || resultRelInfo->ri_PartitionCheck);
1801 
1802  if (constr && constr->has_not_null)
1803  {
1804  int natts = tupdesc->natts;
1805  int attrChk;
1806 
1807  for (attrChk = 1; attrChk <= natts; attrChk++)
1808  {
1809  if (tupdesc->attrs[attrChk - 1]->attnotnull &&
1810  slot_attisnull(slot, attrChk))
1811  {
1812  char *val_desc;
1813  Relation orig_rel = rel;
1814  TupleDesc orig_tupdesc = tupdesc;
1815 
1816  /*
1817  * choose the correct relation to build val_desc from the
1818  * tuple contained in orig_slot
1819  */
1820  if (resultRelInfo->ri_PartitionRoot)
1821  {
1822  rel = resultRelInfo->ri_PartitionRoot;
1823  tupdesc = RelationGetDescr(rel);
1824  }
1825 
1826  insertedCols = GetInsertedColumns(resultRelInfo, estate);
1827  updatedCols = GetUpdatedColumns(resultRelInfo, estate);
1828  modifiedCols = bms_union(insertedCols, updatedCols);
1830  orig_slot,
1831  tupdesc,
1832  modifiedCols,
1833  64);
1834 
1835  ereport(ERROR,
1836  (errcode(ERRCODE_NOT_NULL_VIOLATION),
1837  errmsg("null value in column \"%s\" violates not-null constraint",
1838  NameStr(orig_tupdesc->attrs[attrChk - 1]->attname)),
1839  val_desc ? errdetail("Failing row contains %s.", val_desc) : 0,
1840  errtablecol(orig_rel, attrChk)));
1841  }
1842  }
1843  }
1844 
1845  if (constr && constr->num_check > 0)
1846  {
1847  const char *failed;
1848 
1849  if ((failed = ExecRelCheck(resultRelInfo, slot, estate)) != NULL)
1850  {
1851  char *val_desc;
1852  Relation orig_rel = rel;
1853 
1854  /* See the comment above. */
1855  if (resultRelInfo->ri_PartitionRoot)
1856  {
1857  rel = resultRelInfo->ri_PartitionRoot;
1858  tupdesc = RelationGetDescr(rel);
1859  }
1860 
1861  insertedCols = GetInsertedColumns(resultRelInfo, estate);
1862  updatedCols = GetUpdatedColumns(resultRelInfo, estate);
1863  modifiedCols = bms_union(insertedCols, updatedCols);
1865  orig_slot,
1866  tupdesc,
1867  modifiedCols,
1868  64);
1869  ereport(ERROR,
1870  (errcode(ERRCODE_CHECK_VIOLATION),
1871  errmsg("new row for relation \"%s\" violates check constraint \"%s\"",
1872  RelationGetRelationName(orig_rel), failed),
1873  val_desc ? errdetail("Failing row contains %s.", val_desc) : 0,
1874  errtableconstraint(orig_rel, failed)));
1875  }
1876  }
1877 
1878  if (resultRelInfo->ri_PartitionCheck &&
1879  !ExecPartitionCheck(resultRelInfo, slot, estate))
1880  {
1881  char *val_desc;
1882  Relation orig_rel = rel;
1883 
1884  /* See the comment above. */
1885  if (resultRelInfo->ri_PartitionRoot)
1886  {
1887  rel = resultRelInfo->ri_PartitionRoot;
1888  tupdesc = RelationGetDescr(rel);
1889  }
1890 
1891  insertedCols = GetInsertedColumns(resultRelInfo, estate);
1892  updatedCols = GetUpdatedColumns(resultRelInfo, estate);
1893  modifiedCols = bms_union(insertedCols, updatedCols);
1895  orig_slot,
1896  tupdesc,
1897  modifiedCols,
1898  64);
1899  ereport(ERROR,
1900  (errcode(ERRCODE_CHECK_VIOLATION),
1901  errmsg("new row for relation \"%s\" violates partition constraint",
1902  RelationGetRelationName(orig_rel)),
1903  val_desc ? errdetail("Failing row contains %s.", val_desc) : 0));
1904  }
1905 }
#define GetUpdatedColumns(relinfo, estate)
Definition: execMain.c:109
Relation ri_RelationDesc
Definition: execnodes.h:335
#define RelationGetDescr(relation)
Definition: rel.h:425
Relation ri_PartitionRoot
Definition: execnodes.h:355
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:1743
#define ERROR
Definition: elog.h:43
static char * ExecBuildSlotValueDescription(Oid reloid, TupleTableSlot *slot, TupleDesc tupdesc, Bitmapset *modifiedCols, int maxfieldlen)
Definition: execMain.c:2046
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:353
static const char * ExecRelCheck(ResultRelInfo *resultRelInfo, TupleTableSlot *slot, EState *estate)
Definition: execMain.c:1679
bool slot_attisnull(TupleTableSlot *slot, int attnum)
Definition: heaptuple.c:1330
#define NULL
Definition: c.h:226
#define Assert(condition)
Definition: c.h:671
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:495
uint16 num_check
Definition: tupdesc.h:42
#define RelationGetRelid(relation)
Definition: rel.h:413
#define GetInsertedColumns(relinfo, estate)
Definition: execMain.c:107
bool ExecContextForcesOids ( PlanState planstate,
bool hasoids 
)

Definition at line 1406 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(), and tlist_matches_tupdesc().

1407 {
1408  ResultRelInfo *ri = planstate->state->es_result_relation_info;
1409 
1410  if (ri != NULL)
1411  {
1412  Relation rel = ri->ri_RelationDesc;
1413 
1414  if (rel != NULL)
1415  {
1416  *hasoids = rel->rd_rel->relhasoids;
1417  return true;
1418  }
1419  }
1420 
1421  if (planstate->state->es_top_eflags & EXEC_FLAG_WITH_OIDS)
1422  {
1423  *hasoids = true;
1424  return true;
1425  }
1426  if (planstate->state->es_top_eflags & EXEC_FLAG_WITHOUT_OIDS)
1427  {
1428  *hasoids = false;
1429  return true;
1430  }
1431 
1432  return false;
1433 }
Relation ri_RelationDesc
Definition: execnodes.h:335
EState * state
Definition: execnodes.h:1049
Form_pg_class rd_rel
Definition: rel.h:113
#define EXEC_FLAG_WITHOUT_OIDS
Definition: executor.h:64
#define NULL
Definition: c.h:226
#define EXEC_FLAG_WITH_OIDS
Definition: executor.h:63
int es_top_eflags
Definition: execnodes.h:406
ResultRelInfo * es_result_relation_info
Definition: execnodes.h:384
static void ExecEndPlan ( PlanState planstate,
EState estate 
)
static

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

1489 {
1490  ResultRelInfo *resultRelInfo;
1491  int i;
1492  ListCell *l;
1493 
1494  /*
1495  * shut down the node-type-specific query processing
1496  */
1497  ExecEndNode(planstate);
1498 
1499  /*
1500  * for subplans too
1501  */
1502  foreach(l, estate->es_subplanstates)
1503  {
1504  PlanState *subplanstate = (PlanState *) lfirst(l);
1505 
1506  ExecEndNode(subplanstate);
1507  }
1508 
1509  /*
1510  * destroy the executor's tuple table. Actually we only care about
1511  * releasing buffer pins and tupdesc refcounts; there's no need to pfree
1512  * the TupleTableSlots, since the containing memory context is about to go
1513  * away anyway.
1514  */
1515  ExecResetTupleTable(estate->es_tupleTable, false);
1516 
1517  /*
1518  * close the result relation(s) if any, but hold locks until xact commit.
1519  */
1520  resultRelInfo = estate->es_result_relations;
1521  for (i = estate->es_num_result_relations; i > 0; i--)
1522  {
1523  /* Close indices and then the relation itself */
1524  ExecCloseIndices(resultRelInfo);
1525  heap_close(resultRelInfo->ri_RelationDesc, NoLock);
1526  resultRelInfo++;
1527  }
1528 
1529  /*
1530  * likewise close any trigger target relations
1531  */
1532  foreach(l, estate->es_trig_target_relations)
1533  {
1534  resultRelInfo = (ResultRelInfo *) lfirst(l);
1535  /* Close indices and then the relation itself */
1536  ExecCloseIndices(resultRelInfo);
1537  heap_close(resultRelInfo->ri_RelationDesc, NoLock);
1538  }
1539 
1540  /*
1541  * close any relations selected FOR [KEY] UPDATE/SHARE, again keeping
1542  * locks
1543  */
1544  foreach(l, estate->es_rowMarks)
1545  {
1546  ExecRowMark *erm = (ExecRowMark *) lfirst(l);
1547 
1548  if (erm->relation)
1549  heap_close(erm->relation, NoLock);
1550  }
1551 }
Relation ri_RelationDesc
Definition: execnodes.h:335
void ExecEndNode(PlanState *node)
Definition: execProcnode.c:624
Relation relation
Definition: execnodes.h:460
#define heap_close(r, l)
Definition: heapam.h:97
#define NoLock
Definition: lockdefs.h:34
ResultRelInfo * es_result_relations
Definition: execnodes.h:382
List * es_trig_target_relations
Definition: execnodes.h:387
List * es_tupleTable
Definition: execnodes.h:399
void ExecResetTupleTable(List *tupleTable, bool shouldFree)
Definition: execTuples.c:156
int es_num_result_relations
Definition: execnodes.h:383
#define lfirst(lc)
Definition: pg_list.h:106
List * es_subplanstates
Definition: execnodes.h:412
List * es_rowMarks
Definition: execnodes.h:401
int i
void ExecCloseIndices(ResultRelInfo *resultRelInfo)
Definition: execIndexing.c:224
int ExecFindPartition ( ResultRelInfo resultRelInfo,
PartitionDispatch pd,
TupleTableSlot slot,
EState estate 
)

Definition at line 3188 of file execMain.c.

References Assert, bms_union(), ereport, errcode(), errdetail(), errmsg(), ERROR, ExecBuildSlotValueDescription(), get_partition_for_tuple(), get_rel_name(), GetInsertedColumns, GetUpdatedColumns, OidIsValid, RelationGetDescr, RelationGetRelid, and ResultRelInfo::ri_RelationDesc.

Referenced by CopyFrom(), and ExecInsert().

3190 {
3191  int result;
3192  Oid failed_at;
3193 
3194  result = get_partition_for_tuple(pd, slot, estate, &failed_at);
3195  if (result < 0)
3196  {
3197  Relation rel = resultRelInfo->ri_RelationDesc;
3198  char *val_desc;
3199  Bitmapset *insertedCols,
3200  *updatedCols,
3201  *modifiedCols;
3202  TupleDesc tupDesc = RelationGetDescr(rel);
3203 
3204  insertedCols = GetInsertedColumns(resultRelInfo, estate);
3205  updatedCols = GetUpdatedColumns(resultRelInfo, estate);
3206  modifiedCols = bms_union(insertedCols, updatedCols);
3208  slot,
3209  tupDesc,
3210  modifiedCols,
3211  64);
3212  Assert(OidIsValid(failed_at));
3213  ereport(ERROR,
3214  (errcode(ERRCODE_CHECK_VIOLATION),
3215  errmsg("no partition of relation \"%s\" found for row",
3216  get_rel_name(failed_at)),
3217  val_desc ? errdetail("Failing row contains %s.", val_desc) : 0));
3218  }
3219 
3220  return result;
3221 }
#define GetUpdatedColumns(relinfo, estate)
Definition: execMain.c:109
Relation ri_RelationDesc
Definition: execnodes.h:335
#define RelationGetDescr(relation)
Definition: rel.h:425
int errcode(int sqlerrcode)
Definition: elog.c:575
unsigned int Oid
Definition: postgres_ext.h:31
#define OidIsValid(objectId)
Definition: c.h:534
#define ERROR
Definition: elog.h:43
int get_partition_for_tuple(PartitionDispatch *pd, TupleTableSlot *slot, EState *estate, Oid *failed_at)
Definition: partition.c:1672
static char * ExecBuildSlotValueDescription(Oid reloid, TupleTableSlot *slot, TupleDesc tupdesc, Bitmapset *modifiedCols, int maxfieldlen)
Definition: execMain.c:2046
int errdetail(const char *fmt,...)
Definition: elog.c:873
#define ereport(elevel, rest)
Definition: elog.h:122
#define Assert(condition)
Definition: c.h:671
Bitmapset * bms_union(const Bitmapset *a, const Bitmapset *b)
Definition: bitmapset.c:217
int errmsg(const char *fmt,...)
Definition: elog.c:797
char * get_rel_name(Oid relid)
Definition: lsyscache.c:1694
#define RelationGetRelid(relation)
Definition: rel.h:413
#define GetInsertedColumns(relinfo, estate)
Definition: execMain.c:107
ExecRowMark* ExecFindRowMark ( EState estate,
Index  rti,
bool  missing_ok 
)

Definition at line 2208 of file execMain.c.

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

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

2209 {
2210  ListCell *lc;
2211 
2212  foreach(lc, estate->es_rowMarks)
2213  {
2214  ExecRowMark *erm = (ExecRowMark *) lfirst(lc);
2215 
2216  if (erm->rti == rti)
2217  return erm;
2218  }
2219  if (!missing_ok)
2220  elog(ERROR, "failed to find ExecRowMark for rangetable index %u", rti);
2221  return NULL;
2222 }
#define ERROR
Definition: elog.h:43
Index rti
Definition: execnodes.h:462
#define NULL
Definition: c.h:226
#define lfirst(lc)
Definition: pg_list.h:106
List * es_rowMarks
Definition: execnodes.h:401
#define elog
Definition: elog.h:219
ResultRelInfo* ExecGetTriggerResultRel ( EState estate,
Oid  relid 
)

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

1317 {
1318  ResultRelInfo *rInfo;
1319  int nr;
1320  ListCell *l;
1321  Relation rel;
1322  MemoryContext oldcontext;
1323 
1324  /* First, search through the query result relations */
1325  rInfo = estate->es_result_relations;
1326  nr = estate->es_num_result_relations;
1327  while (nr > 0)
1328  {
1329  if (RelationGetRelid(rInfo->ri_RelationDesc) == relid)
1330  return rInfo;
1331  rInfo++;
1332  nr--;
1333  }
1334  /* Nope, but maybe we already made an extra ResultRelInfo for it */
1335  foreach(l, estate->es_trig_target_relations)
1336  {
1337  rInfo = (ResultRelInfo *) lfirst(l);
1338  if (RelationGetRelid(rInfo->ri_RelationDesc) == relid)
1339  return rInfo;
1340  }
1341  /* Nope, so we need a new one */
1342 
1343  /*
1344  * Open the target relation's relcache entry. We assume that an
1345  * appropriate lock is still held by the backend from whenever the trigger
1346  * event got queued, so we need take no new lock here. Also, we need not
1347  * recheck the relkind, so no need for CheckValidResultRel.
1348  */
1349  rel = heap_open(relid, NoLock);
1350 
1351  /*
1352  * Make the new entry in the right context.
1353  */
1354  oldcontext = MemoryContextSwitchTo(estate->es_query_cxt);
1355  rInfo = makeNode(ResultRelInfo);
1356  InitResultRelInfo(rInfo,
1357  rel,
1358  0, /* dummy rangetable index */
1359  NULL,
1360  estate->es_instrument);
1361  estate->es_trig_target_relations =
1362  lappend(estate->es_trig_target_relations, rInfo);
1363  MemoryContextSwitchTo(oldcontext);
1364 
1365  /*
1366  * Currently, we don't need any index information in ResultRelInfos used
1367  * only for triggers, so no need to call ExecOpenIndices.
1368  */
1369 
1370  return rInfo;
1371 }
void InitResultRelInfo(ResultRelInfo *resultRelInfo, Relation resultRelationDesc, Index resultRelationIndex, Relation partition_root, int instrument_options)
Definition: execMain.c:1221
Relation ri_RelationDesc
Definition: execnodes.h:335
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:109
MemoryContext es_query_cxt
Definition: execnodes.h:397
#define NoLock
Definition: lockdefs.h:34
ResultRelInfo * es_result_relations
Definition: execnodes.h:382
int es_instrument
Definition: execnodes.h:407
List * lappend(List *list, void *datum)
Definition: list.c:128
List * es_trig_target_relations
Definition: execnodes.h:387
Relation heap_open(Oid relationId, LOCKMODE lockmode)
Definition: heapam.c:1287
int es_num_result_relations
Definition: execnodes.h:383
#define makeNode(_type_)
Definition: nodes.h:556
#define NULL
Definition: c.h:226
#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 1743 of file execMain.c.

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

Referenced by ExecConstraints().

1745 {
1746  ExprContext *econtext;
1747 
1748  /*
1749  * If first time through, build expression state tree for the partition
1750  * check expression. Keep it in the per-query memory context so they'll
1751  * survive throughout the query.
1752  */
1753  if (resultRelInfo->ri_PartitionCheckExpr == NULL)
1754  {
1755  List *qual = resultRelInfo->ri_PartitionCheck;
1756 
1757  resultRelInfo->ri_PartitionCheckExpr = (List *)
1758  ExecPrepareExpr((Expr *) qual, estate);
1759  }
1760 
1761  /*
1762  * We will use the EState's per-tuple context for evaluating constraint
1763  * expressions (creating it if it's not already there).
1764  */
1765  econtext = GetPerTupleExprContext(estate);
1766 
1767  /* Arrange for econtext's scan tuple to be the tuple under test */
1768  econtext->ecxt_scantuple = slot;
1769 
1770  /*
1771  * As in case of the catalogued constraints, we treat a NULL result as
1772  * success here, not a failure.
1773  */
1774  return ExecQual(resultRelInfo->ri_PartitionCheckExpr, econtext, true);
1775 }
ExprState * ExecPrepareExpr(Expr *node, EState *estate)
Definition: execQual.c:5004
List * ri_PartitionCheckExpr
Definition: execnodes.h:354
#define GetPerTupleExprContext(estate)
Definition: executor.h:338
bool ExecQual(List *qual, ExprContext *econtext, bool resultForNull)
Definition: execQual.c:5055
List * ri_PartitionCheck
Definition: execnodes.h:353
#define NULL
Definition: c.h:226
TupleTableSlot * ecxt_scantuple
Definition: execnodes.h:128
Definition: pg_list.h:45
static void ExecPostprocessPlan ( EState estate)
static

Definition at line 1442 of file execMain.c.

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

Referenced by standard_ExecutorFinish().

1443 {
1444  ListCell *lc;
1445 
1446  /*
1447  * Make sure nodes run forward.
1448  */
1450 
1451  /*
1452  * Run any secondary ModifyTable nodes to completion, in case the main
1453  * query did not fetch all rows from them. (We do this to ensure that
1454  * such nodes have predictable results.)
1455  */
1456  foreach(lc, estate->es_auxmodifytables)
1457  {
1458  PlanState *ps = (PlanState *) lfirst(lc);
1459 
1460  for (;;)
1461  {
1462  TupleTableSlot *slot;
1463 
1464  /* Reset the per-output-tuple exprcontext each time */
1465  ResetPerTupleExprContext(estate);
1466 
1467  slot = ExecProcNode(ps);
1468 
1469  if (TupIsNull(slot))
1470  break;
1471  }
1472  }
1473 }
TupleTableSlot * ExecProcNode(PlanState *node)
Definition: execProcnode.c:380
#define ResetPerTupleExprContext(estate)
Definition: executor.h:347
ScanDirection es_direction
Definition: execnodes.h:369
#define TupIsNull(slot)
Definition: tuptable.h:138
List * es_auxmodifytables
Definition: execnodes.h:414
#define lfirst(lc)
Definition: pg_list.h:106
static const char* ExecRelCheck ( ResultRelInfo resultRelInfo,
TupleTableSlot slot,
EState estate 
)
static

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

1681 {
1682  Relation rel = resultRelInfo->ri_RelationDesc;
1683  int ncheck = rel->rd_att->constr->num_check;
1684  ConstrCheck *check = rel->rd_att->constr->check;
1685  ExprContext *econtext;
1686  MemoryContext oldContext;
1687  List *qual;
1688  int i;
1689 
1690  /*
1691  * If first time through for this result relation, build expression
1692  * nodetrees for rel's constraint expressions. Keep them in the per-query
1693  * memory context so they'll survive throughout the query.
1694  */
1695  if (resultRelInfo->ri_ConstraintExprs == NULL)
1696  {
1697  oldContext = MemoryContextSwitchTo(estate->es_query_cxt);
1698  resultRelInfo->ri_ConstraintExprs =
1699  (List **) palloc(ncheck * sizeof(List *));
1700  for (i = 0; i < ncheck; i++)
1701  {
1702  /* ExecQual wants implicit-AND form */
1703  qual = make_ands_implicit(stringToNode(check[i].ccbin));
1704  resultRelInfo->ri_ConstraintExprs[i] = (List *)
1705  ExecPrepareExpr((Expr *) qual, estate);
1706  }
1707  MemoryContextSwitchTo(oldContext);
1708  }
1709 
1710  /*
1711  * We will use the EState's per-tuple context for evaluating constraint
1712  * expressions (creating it if it's not already there).
1713  */
1714  econtext = GetPerTupleExprContext(estate);
1715 
1716  /* Arrange for econtext's scan tuple to be the tuple under test */
1717  econtext->ecxt_scantuple = slot;
1718 
1719  /* And evaluate the constraints */
1720  for (i = 0; i < ncheck; i++)
1721  {
1722  qual = resultRelInfo->ri_ConstraintExprs[i];
1723 
1724  /*
1725  * NOTE: SQL specifies that a NULL result from a constraint expression
1726  * is not to be treated as a failure. Therefore, tell ExecQual to
1727  * return TRUE for NULL.
1728  */
1729  if (!ExecQual(qual, econtext, true))
1730  return check[i].ccname;
1731  }
1732 
1733  /* NULL result means no error */
1734  return NULL;
1735 }
void * stringToNode(char *str)
Definition: read.c:38
Relation ri_RelationDesc
Definition: execnodes.h:335
ExprState * ExecPrepareExpr(Expr *node, EState *estate)
Definition: execQual.c:5004
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:397
List * make_ands_implicit(Expr *clause)
Definition: clauses.c:377
List ** ri_ConstraintExprs
Definition: execnodes.h:348
bool ExecQual(List *qual, ExprContext *econtext, bool resultForNull)
Definition: execQual.c:5055
TupleDesc rd_att
Definition: rel.h:114
#define NULL
Definition: c.h:226
TupleConstr * constr
Definition: tupdesc.h:76
TupleTableSlot * ecxt_scantuple
Definition: execnodes.h:128
void * palloc(Size size)
Definition: mcxt.c:891
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 3099 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().

3105 {
3106  TupleDesc tupDesc = RelationGetDescr(rel);
3107  List *leaf_parts;
3108  ListCell *cell;
3109  int i;
3110  ResultRelInfo *leaf_part_rri;
3111 
3112  /* Get the tuple-routing information and lock partitions */
3113  *pd = RelationGetPartitionDispatchInfo(rel, RowExclusiveLock, num_parted,
3114  &leaf_parts);
3115  *num_partitions = list_length(leaf_parts);
3116  *partitions = (ResultRelInfo *) palloc(*num_partitions *
3117  sizeof(ResultRelInfo));
3118  *tup_conv_maps = (TupleConversionMap **) palloc0(*num_partitions *
3119  sizeof(TupleConversionMap *));
3120 
3121  /*
3122  * Initialize an empty slot that will be used to manipulate tuples of any
3123  * given partition's rowtype. It is attached to the caller-specified node
3124  * (such as ModifyTableState) and released when the node finishes
3125  * processing.
3126  */
3127  *partition_tuple_slot = MakeTupleTableSlot();
3128 
3129  leaf_part_rri = *partitions;
3130  i = 0;
3131  foreach(cell, leaf_parts)
3132  {
3133  Relation partrel;
3134  TupleDesc part_tupdesc;
3135 
3136  /*
3137  * We locked all the partitions above including the leaf partitions.
3138  * Note that each of the relations in *partitions are eventually
3139  * closed by the caller.
3140  */
3141  partrel = heap_open(lfirst_oid(cell), NoLock);
3142  part_tupdesc = RelationGetDescr(partrel);
3143 
3144  /*
3145  * Verify result relation is a valid target for the current operation.
3146  */
3147  CheckValidResultRel(partrel, CMD_INSERT);
3148 
3149  /*
3150  * Save a tuple conversion map to convert a tuple routed to this
3151  * partition from the parent's type to the partition's.
3152  */
3153  (*tup_conv_maps)[i] = convert_tuples_by_name(tupDesc, part_tupdesc,
3154  gettext_noop("could not convert row type"));
3155 
3156  InitResultRelInfo(leaf_part_rri,
3157  partrel,
3158  1, /* dummy */
3159  rel,
3160  0);
3161 
3162  /*
3163  * Open partition indices (remember we do not support ON CONFLICT in
3164  * case of partitioned tables, so we do not need support information
3165  * for speculative insertion)
3166  */
3167  if (leaf_part_rri->ri_RelationDesc->rd_rel->relhasindex &&
3168  leaf_part_rri->ri_IndexRelationDescs == NULL)
3169  ExecOpenIndices(leaf_part_rri, false);
3170 
3171  leaf_part_rri++;
3172  i++;
3173  }
3174 }
void InitResultRelInfo(ResultRelInfo *resultRelInfo, Relation resultRelationDesc, Index resultRelationIndex, Relation partition_root, int instrument_options)
Definition: execMain.c:1221
Relation ri_RelationDesc
Definition: execnodes.h:335
#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:1021
TupleConversionMap * convert_tuples_by_name(TupleDesc indesc, TupleDesc outdesc, const char *msg)
Definition: tupconvert.c:204
void * palloc0(Size size)
Definition: mcxt.c:920
Relation heap_open(Oid relationId, LOCKMODE lockmode)
Definition: heapam.c:1287
#define NULL
Definition: c.h:226
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:998
void * palloc(Size size)
Definition: mcxt.c:891
int i
Definition: pg_list.h:45
RelationPtr ri_IndexRelationDescs
Definition: execnodes.h:337
#define lfirst_oid(lc)
Definition: pg_list.h:108
LockTupleMode ExecUpdateLockMode ( EState estate,
ResultRelInfo relinfo 
)

Definition at line 2182 of file execMain.c.

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

Referenced by ExecBRUpdateTriggers(), and ExecOnConflictUpdate().

2183 {
2184  Bitmapset *keyCols;
2185  Bitmapset *updatedCols;
2186 
2187  /*
2188  * Compute lock mode to use. If columns that are part of the key have not
2189  * been modified, then we can use a weaker lock, allowing for better
2190  * concurrency.
2191  */
2192  updatedCols = GetUpdatedColumns(relinfo, estate);
2193  keyCols = RelationGetIndexAttrBitmap(relinfo->ri_RelationDesc,
2195 
2196  if (bms_overlap(keyCols, updatedCols))
2197  return LockTupleExclusive;
2198 
2199  return LockTupleNoKeyExclusive;
2200 }
#define GetUpdatedColumns(relinfo, estate)
Definition: execMain.c:109
Relation ri_RelationDesc
Definition: execnodes.h:335
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 1566 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().

1574 {
1575  TupleTableSlot *slot;
1576  uint64 current_tuple_count;
1577 
1578  /*
1579  * initialize local variables
1580  */
1581  current_tuple_count = 0;
1582 
1583  /*
1584  * Set the direction.
1585  */
1586  estate->es_direction = direction;
1587 
1588  /*
1589  * If a tuple count was supplied, we must force the plan to run without
1590  * parallelism, because we might exit early. Also disable parallelism
1591  * when writing into a relation, because no database changes are allowed
1592  * in parallel mode.
1593  */
1594  if (numberTuples || dest->mydest == DestIntoRel)
1595  use_parallel_mode = false;
1596 
1597  if (use_parallel_mode)
1599 
1600  /*
1601  * Loop until we've processed the proper number of tuples from the plan.
1602  */
1603  for (;;)
1604  {
1605  /* Reset the per-output-tuple exprcontext */
1606  ResetPerTupleExprContext(estate);
1607 
1608  /*
1609  * Execute the plan and obtain a tuple
1610  */
1611  slot = ExecProcNode(planstate);
1612 
1613  /*
1614  * if the tuple is null, then we assume there is nothing more to
1615  * process so we just end the loop...
1616  */
1617  if (TupIsNull(slot))
1618  {
1619  /* Allow nodes to release or shut down resources. */
1620  (void) ExecShutdownNode(planstate);
1621  break;
1622  }
1623 
1624  /*
1625  * If we have a junk filter, then project a new tuple with the junk
1626  * removed.
1627  *
1628  * Store this new "clean" tuple in the junkfilter's resultSlot.
1629  * (Formerly, we stored it back over the "dirty" tuple, which is WRONG
1630  * because that tuple slot has the wrong descriptor.)
1631  */
1632  if (estate->es_junkFilter != NULL)
1633  slot = ExecFilterJunk(estate->es_junkFilter, slot);
1634 
1635  /*
1636  * If we are supposed to send the tuple somewhere, do so. (In
1637  * practice, this is probably always the case at this point.)
1638  */
1639  if (sendTuples)
1640  {
1641  /*
1642  * If we are not able to send the tuple, we assume the destination
1643  * has closed and no more tuples can be sent. If that's the case,
1644  * end the loop.
1645  */
1646  if (!((*dest->receiveSlot) (slot, dest)))
1647  break;
1648  }
1649 
1650  /*
1651  * Count tuples processed, if this is a SELECT. (For other operation
1652  * types, the ModifyTable plan node must count the appropriate
1653  * events.)
1654  */
1655  if (operation == CMD_SELECT)
1656  (estate->es_processed)++;
1657 
1658  /*
1659  * check our tuple count.. if we've processed the proper number then
1660  * quit, else loop again and process more tuples. Zero numberTuples
1661  * means no limit.
1662  */
1663  current_tuple_count++;
1664  if (numberTuples && numberTuples == current_tuple_count)
1665  break;
1666  }
1667 
1668  if (use_parallel_mode)
1669  ExitParallelMode();
1670 }
JunkFilter * es_junkFilter
Definition: execnodes.h:376
TupleTableSlot * ExecProcNode(PlanState *node)
Definition: execProcnode.c:380
#define ResetPerTupleExprContext(estate)
Definition: executor.h:347
bool ExecShutdownNode(PlanState *node)
Definition: execProcnode.c:813
CommandDest mydest
Definition: dest.h:128
ScanDirection es_direction
Definition: execnodes.h:369
void ExitParallelMode(void)
Definition: xact.c:892
#define TupIsNull(slot)
Definition: tuptable.h:138
TupleTableSlot * ExecFilterJunk(JunkFilter *junkfilter, TupleTableSlot *slot)
Definition: execJunk.c:262
#define NULL
Definition: c.h:226
uint64 es_processed
Definition: execnodes.h:403
void EnterParallelMode(void)
Definition: xact.c:879
bool(* receiveSlot)(TupleTableSlot *slot, DestReceiver *self)
Definition: dest.h:118
void ExecutorEnd ( QueryDesc queryDesc)

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

440 {
441  if (ExecutorEnd_hook)
442  (*ExecutorEnd_hook) (queryDesc);
443  else
444  standard_ExecutorEnd(queryDesc);
445 }
void standard_ExecutorEnd(QueryDesc *queryDesc)
Definition: execMain.c:448
ExecutorEnd_hook_type ExecutorEnd_hook
Definition: execMain.c:71
void ExecutorFinish ( QueryDesc queryDesc)

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

380 {
382  (*ExecutorFinish_hook) (queryDesc);
383  else
384  standard_ExecutorFinish(queryDesc);
385 }
void standard_ExecutorFinish(QueryDesc *queryDesc)
Definition: execMain.c:388
ExecutorFinish_hook_type ExecutorFinish_hook
Definition: execMain.c:70
void ExecutorRewind ( QueryDesc queryDesc)

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

506 {
507  EState *estate;
508  MemoryContext oldcontext;
509 
510  /* sanity checks */
511  Assert(queryDesc != NULL);
512 
513  estate = queryDesc->estate;
514 
515  Assert(estate != NULL);
516 
517  /* It's probably not sensible to rescan updating queries */
518  Assert(queryDesc->operation == CMD_SELECT);
519 
520  /*
521  * Switch into per-query memory context
522  */
523  oldcontext = MemoryContextSwitchTo(estate->es_query_cxt);
524 
525  /*
526  * rescan plan
527  */
528  ExecReScan(queryDesc->planstate);
529 
530  MemoryContextSwitchTo(oldcontext);
531 }
EState * estate
Definition: execdesc.h:47
void ExecReScan(PlanState *node)
Definition: execAmi.c:73
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:109
MemoryContext es_query_cxt
Definition: execnodes.h:397
PlanState * planstate
Definition: execdesc.h:48
CmdType operation
Definition: execdesc.h:36
#define NULL
Definition: c.h:226
#define Assert(condition)
Definition: c.h:671
void ExecutorRun ( QueryDesc queryDesc,
ScanDirection  direction,
uint64  count 
)

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

287 {
288  if (ExecutorRun_hook)
289  (*ExecutorRun_hook) (queryDesc, direction, count);
290  else
291  standard_ExecutorRun(queryDesc, direction, count);
292 }
ExecutorRun_hook_type ExecutorRun_hook
Definition: execMain.c:69
void standard_ExecutorRun(QueryDesc *queryDesc, ScanDirection direction, uint64 count)
Definition: execMain.c:295
void ExecutorStart ( QueryDesc queryDesc,
int  eflags 
)

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

139 {
140  if (ExecutorStart_hook)
141  (*ExecutorStart_hook) (queryDesc, eflags);
142  else
143  standard_ExecutorStart(queryDesc, eflags);
144 }
void standard_ExecutorStart(QueryDesc *queryDesc, int eflags)
Definition: execMain.c:147
ExecutorStart_hook_type ExecutorStart_hook
Definition: execMain.c:68
void ExecWithCheckOptions ( WCOKind  kind,
ResultRelInfo resultRelInfo,
TupleTableSlot slot,
EState estate 
)

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

1919 {
1920  Relation rel = resultRelInfo->ri_RelationDesc;
1921  TupleDesc tupdesc = RelationGetDescr(rel);
1922  ExprContext *econtext;
1923  ListCell *l1,
1924  *l2;
1925 
1926  /*
1927  * We will use the EState's per-tuple context for evaluating constraint
1928  * expressions (creating it if it's not already there).
1929  */
1930  econtext = GetPerTupleExprContext(estate);
1931 
1932  /* Arrange for econtext's scan tuple to be the tuple under test */
1933  econtext->ecxt_scantuple = slot;
1934 
1935  /* Check each of the constraints */
1936  forboth(l1, resultRelInfo->ri_WithCheckOptions,
1937  l2, resultRelInfo->ri_WithCheckOptionExprs)
1938  {
1939  WithCheckOption *wco = (WithCheckOption *) lfirst(l1);
1940  ExprState *wcoExpr = (ExprState *) lfirst(l2);
1941 
1942  /*
1943  * Skip any WCOs which are not the kind we are looking for at this
1944  * time.
1945  */
1946  if (wco->kind != kind)
1947  continue;
1948 
1949  /*
1950  * WITH CHECK OPTION checks are intended to ensure that the new tuple
1951  * is visible (in the case of a view) or that it passes the
1952  * 'with-check' policy (in the case of row security). If the qual
1953  * evaluates to NULL or FALSE, then the new tuple won't be included in
1954  * the view or doesn't pass the 'with-check' policy for the table. We
1955  * need ExecQual to return FALSE for NULL to handle the view case (the
1956  * opposite of what we do above for CHECK constraints).
1957  */
1958  if (!ExecQual((List *) wcoExpr, econtext, false))
1959  {
1960  char *val_desc;
1961  Bitmapset *modifiedCols;
1962  Bitmapset *insertedCols;
1963  Bitmapset *updatedCols;
1964 
1965  switch (wco->kind)
1966  {
1967  /*
1968  * For WITH CHECK OPTIONs coming from views, we might be
1969  * able to provide the details on the row, depending on
1970  * the permissions on the relation (that is, if the user
1971  * could view it directly anyway). For RLS violations, we
1972  * don't include the data since we don't know if the user
1973  * should be able to view the tuple as as that depends on
1974  * the USING policy.
1975  */
1976  case WCO_VIEW_CHECK:
1977  insertedCols = GetInsertedColumns(resultRelInfo, estate);
1978  updatedCols = GetUpdatedColumns(resultRelInfo, estate);
1979  modifiedCols = bms_union(insertedCols, updatedCols);
1981  slot,
1982  tupdesc,
1983  modifiedCols,
1984  64);
1985 
1986  ereport(ERROR,
1987  (errcode(ERRCODE_WITH_CHECK_OPTION_VIOLATION),
1988  errmsg("new row violates check option for view \"%s\"",
1989  wco->relname),
1990  val_desc ? errdetail("Failing row contains %s.",
1991  val_desc) : 0));
1992  break;
1993  case WCO_RLS_INSERT_CHECK:
1994  case WCO_RLS_UPDATE_CHECK:
1995  if (wco->polname != NULL)
1996  ereport(ERROR,
1997  (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
1998  errmsg("new row violates row-level security policy \"%s\" for table \"%s\"",
1999  wco->polname, wco->relname)));
2000  else
2001  ereport(ERROR,
2002  (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
2003  errmsg("new row violates row-level security policy for table \"%s\"",
2004  wco->relname)));
2005  break;
2007  if (wco->polname != NULL)
2008  ereport(ERROR,
2009  (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
2010  errmsg("new row violates row-level security policy \"%s\" (USING expression) for table \"%s\"",
2011  wco->polname, wco->relname)));
2012  else
2013  ereport(ERROR,
2014  (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
2015  errmsg("new row violates row-level security policy (USING expression) for table \"%s\"",
2016  wco->relname)));
2017  break;
2018  default:
2019  elog(ERROR, "unrecognized WCO kind: %u", wco->kind);
2020  break;
2021  }
2022  }
2023  }
2024 }
#define GetUpdatedColumns(relinfo, estate)
Definition: execMain.c:109
Relation ri_RelationDesc
Definition: execnodes.h:335
#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:347
#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:2046
int errdetail(const char *fmt,...)
Definition: elog.c:873
bool ExecQual(List *qual, ExprContext *econtext, bool resultForNull)
Definition: execQual.c:5055
#define ereport(elevel, rest)
Definition: elog.h:122
List * ri_WithCheckOptions
Definition: execnodes.h:346
#define NULL
Definition: c.h:226
#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:128
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:107
static void InitPlan ( QueryDesc queryDesc,
int  eflags 
)
static

Definition at line 783 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(), ExecRowMark::markType, PlanRowMark::markType, NIL, 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().

784 {
785  CmdType operation = queryDesc->operation;
786  PlannedStmt *plannedstmt = queryDesc->plannedstmt;
787  Plan *plan = plannedstmt->planTree;
788  List *rangeTable = plannedstmt->rtable;
789  EState *estate = queryDesc->estate;
790  PlanState *planstate;
791  TupleDesc tupType;
792  ListCell *l;
793  int i;
794 
795  /*
796  * Do permissions checks
797  */
798  ExecCheckRTPerms(rangeTable, true);
799 
800  /*
801  * initialize the node's execution state
802  */
803  estate->es_range_table = rangeTable;
804  estate->es_plannedstmt = plannedstmt;
805 
806  /*
807  * initialize result relation stuff, and open/lock the result rels.
808  *
809  * We must do this before initializing the plan tree, else we might try to
810  * do a lock upgrade if a result rel is also a source rel.
811  */
812  if (plannedstmt->resultRelations)
813  {
814  List *resultRelations = plannedstmt->resultRelations;
815  int numResultRelations = list_length(resultRelations);
816  ResultRelInfo *resultRelInfos;
817  ResultRelInfo *resultRelInfo;
818 
819  resultRelInfos = (ResultRelInfo *)
820  palloc(numResultRelations * sizeof(ResultRelInfo));
821  resultRelInfo = resultRelInfos;
822  foreach(l, resultRelations)
823  {
824  Index resultRelationIndex = lfirst_int(l);
825  Oid resultRelationOid;
826  Relation resultRelation;
827 
828  resultRelationOid = getrelid(resultRelationIndex, rangeTable);
829  resultRelation = heap_open(resultRelationOid, RowExclusiveLock);
830 
831  InitResultRelInfo(resultRelInfo,
832  resultRelation,
833  resultRelationIndex,
834  NULL,
835  estate->es_instrument);
836  resultRelInfo++;
837  }
838  estate->es_result_relations = resultRelInfos;
839  estate->es_num_result_relations = numResultRelations;
840  /* es_result_relation_info is NULL except when within ModifyTable */
841  estate->es_result_relation_info = NULL;
842  }
843  else
844  {
845  /*
846  * if no result relation, then set state appropriately
847  */
848  estate->es_result_relations = NULL;
849  estate->es_num_result_relations = 0;
850  estate->es_result_relation_info = NULL;
851  }
852 
853  /*
854  * Similarly, we have to lock relations selected FOR [KEY] UPDATE/SHARE
855  * before we initialize the plan tree, else we'd be risking lock upgrades.
856  * While we are at it, build the ExecRowMark list.
857  */
858  estate->es_rowMarks = NIL;
859  foreach(l, plannedstmt->rowMarks)
860  {
861  PlanRowMark *rc = (PlanRowMark *) lfirst(l);
862  Oid relid;
863  Relation relation;
864  ExecRowMark *erm;
865 
866  /* ignore "parent" rowmarks; they are irrelevant at runtime */
867  if (rc->isParent)
868  continue;
869 
870  /* get relation's OID (will produce InvalidOid if subquery) */
871  relid = getrelid(rc->rti, rangeTable);
872 
873  /*
874  * If you change the conditions under which rel locks are acquired
875  * here, be sure to adjust ExecOpenScanRelation to match.
876  */
877  switch (rc->markType)
878  {
879  case ROW_MARK_EXCLUSIVE:
881  case ROW_MARK_SHARE:
882  case ROW_MARK_KEYSHARE:
883  relation = heap_open(relid, RowShareLock);
884  break;
885  case ROW_MARK_REFERENCE:
886  relation = heap_open(relid, AccessShareLock);
887  break;
888  case ROW_MARK_COPY:
889  /* no physical table access is required */
890  relation = NULL;
891  break;
892  default:
893  elog(ERROR, "unrecognized markType: %d", rc->markType);
894  relation = NULL; /* keep compiler quiet */
895  break;
896  }
897 
898  /* Check that relation is a legal target for marking */
899  if (relation)
900  CheckValidRowMarkRel(relation, rc->markType);
901 
902  erm = (ExecRowMark *) palloc(sizeof(ExecRowMark));
903  erm->relation = relation;
904  erm->relid = relid;
905  erm->rti = rc->rti;
906  erm->prti = rc->prti;
907  erm->rowmarkId = rc->rowmarkId;
908  erm->markType = rc->markType;
909  erm->strength = rc->strength;
910  erm->waitPolicy = rc->waitPolicy;
911  erm->ermActive = false;
913  erm->ermExtra = NULL;
914  estate->es_rowMarks = lappend(estate->es_rowMarks, erm);
915  }
916 
917  /*
918  * Initialize the executor's tuple table to empty.
919  */
920  estate->es_tupleTable = NIL;
921  estate->es_trig_tuple_slot = NULL;
922  estate->es_trig_oldtup_slot = NULL;
923  estate->es_trig_newtup_slot = NULL;
924 
925  /* mark EvalPlanQual not active */
926  estate->es_epqTuple = NULL;
927  estate->es_epqTupleSet = NULL;
928  estate->es_epqScanDone = NULL;
929 
930  /*
931  * Initialize private state information for each SubPlan. We must do this
932  * before running ExecInitNode on the main query tree, since
933  * ExecInitSubPlan expects to be able to find these entries.
934  */
935  Assert(estate->es_subplanstates == NIL);
936  i = 1; /* subplan indices count from 1 */
937  foreach(l, plannedstmt->subplans)
938  {
939  Plan *subplan = (Plan *) lfirst(l);
940  PlanState *subplanstate;
941  int sp_eflags;
942 
943  /*
944  * A subplan will never need to do BACKWARD scan nor MARK/RESTORE. If
945  * it is a parameterless subplan (not initplan), we suggest that it be
946  * prepared to handle REWIND efficiently; otherwise there is no need.
947  */
948  sp_eflags = eflags
950  if (bms_is_member(i, plannedstmt->rewindPlanIDs))
951  sp_eflags |= EXEC_FLAG_REWIND;
952 
953  subplanstate = ExecInitNode(subplan, estate, sp_eflags);
954 
955  estate->es_subplanstates = lappend(estate->es_subplanstates,
956  subplanstate);
957 
958  i++;
959  }
960 
961  /*
962  * Initialize the private state information for all the nodes in the query
963  * tree. This opens files, allocates storage and leaves us ready to start
964  * processing tuples.
965  */
966  planstate = ExecInitNode(plan, estate, eflags);
967 
968  /*
969  * Get the tuple descriptor describing the type of tuples to return.
970  */
971  tupType = ExecGetResultType(planstate);
972 
973  /*
974  * Initialize the junk filter if needed. SELECT queries need a filter if
975  * there are any junk attrs in the top-level tlist.
976  */
977  if (operation == CMD_SELECT)
978  {
979  bool junk_filter_needed = false;
980  ListCell *tlist;
981 
982  foreach(tlist, plan->targetlist)
983  {
984  TargetEntry *tle = (TargetEntry *) lfirst(tlist);
985 
986  if (tle->resjunk)
987  {
988  junk_filter_needed = true;
989  break;
990  }
991  }
992 
993  if (junk_filter_needed)
994  {
995  JunkFilter *j;
996 
997  j = ExecInitJunkFilter(planstate->plan->targetlist,
998  tupType->tdhasoid,
999  ExecInitExtraTupleSlot(estate));
1000  estate->es_junkFilter = j;
1001 
1002  /* Want to return the cleaned tuple type */
1003  tupType = j->jf_cleanTupType;
1004  }
1005  }
1006 
1007  queryDesc->tupDesc = tupType;
1008  queryDesc->planstate = planstate;
1009 }
#define NIL
Definition: pg_list.h:69
HeapTuple * es_epqTuple
Definition: execnodes.h:432
JunkFilter * es_junkFilter
Definition: execnodes.h:376
void InitResultRelInfo(ResultRelInfo *resultRelInfo, Relation resultRelationDesc, Index resultRelationIndex, Relation partition_root, int instrument_options)
Definition: execMain.c:1221
TupleTableSlot * ExecInitExtraTupleSlot(EState *estate)
Definition: execTuples.c:852
RowMarkType markType
Definition: plannodes.h:943
EState * estate
Definition: execdesc.h:47
bool tdhasoid
Definition: tupdesc.h:79
TupleTableSlot * es_trig_newtup_slot
Definition: execnodes.h:390
Relation relation
Definition: execnodes.h:460
#define AccessShareLock
Definition: lockdefs.h:36
PlannedStmt * es_plannedstmt
Definition: execnodes.h:373
bool ermActive
Definition: execnodes.h:468
Index prti
Definition: plannodes.h:941
LockWaitPolicy waitPolicy
Definition: execnodes.h:467
#define EXEC_FLAG_WITH_NO_DATA
Definition: executor.h:65
LockClauseStrength strength
Definition: execnodes.h:466
List * es_range_table
Definition: execnodes.h:372
unsigned int Oid
Definition: postgres_ext.h:31
Index rowmarkId
Definition: plannodes.h:942
LockWaitPolicy waitPolicy
Definition: plannodes.h:946
static void CheckValidRowMarkRel(Relation rel, RowMarkType markType)
Definition: execMain.c:1156
struct Plan * planTree
Definition: plannodes.h:61
ItemPointerData curCtid
Definition: execnodes.h:469
bool resjunk
Definition: primnodes.h:1337
#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:462
void * ermExtra
Definition: execnodes.h:470
TupleDesc jf_cleanTupType
Definition: execnodes.h:294
ResultRelInfo * es_result_relations
Definition: execnodes.h:382
#define RowExclusiveLock
Definition: lockdefs.h:38
Index prti
Definition: execnodes.h:463
JunkFilter * ExecInitJunkFilter(List *targetList, bool hasoid, TupleTableSlot *slot)
Definition: execJunk.c:61
TupleTableSlot * es_trig_oldtup_slot
Definition: execnodes.h:389
int es_instrument
Definition: execnodes.h:407
TupleTableSlot * es_trig_tuple_slot
Definition: execnodes.h:388
#define EXEC_FLAG_REWIND
Definition: executor.h:59
Index rowmarkId
Definition: execnodes.h:464
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:399
#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:383
unsigned int Index
Definition: c.h:362
List * rowMarks
Definition: plannodes.h:72
Plan * plan
Definition: execnodes.h:1047
Index rti
Definition: plannodes.h:940
List * subplans
Definition: plannodes.h:68
#define NULL
Definition: c.h:226
#define Assert(condition)
Definition: c.h:671
#define lfirst(lc)
Definition: pg_list.h:106
Bitmapset * rewindPlanIDs
Definition: plannodes.h:70
RowMarkType markType
Definition: execnodes.h:465
LockClauseStrength strength
Definition: plannodes.h:945
static int list_length(const List *l)
Definition: pg_list.h:89
bool * es_epqTupleSet
Definition: execnodes.h:433
List * es_subplanstates
Definition: execnodes.h:412
List * es_rowMarks
Definition: execnodes.h:401
List * rtable
Definition: plannodes.h:63
TupleDesc ExecGetResultType(PlanState *planstate)
Definition: execUtils.c:459
List * targetlist
Definition: plannodes.h:129
#define ItemPointerSetInvalid(pointer)
Definition: itemptr.h:131
void * palloc(Size size)
Definition: mcxt.c:891
#define getrelid(rangeindex, rangetable)
Definition: parsetree.h:41
List * resultRelations
Definition: plannodes.h:66
int i
bool * es_epqScanDone
Definition: execnodes.h:434
bool ExecCheckRTPerms(List *rangeTable, bool ereport_on_violation)
Definition: execMain.c:548
bool isParent
Definition: plannodes.h:947
#define elog
Definition: elog.h:219
PlannedStmt * plannedstmt
Definition: execdesc.h:37
PlanState * ExecInitNode(Plan *node, EState *estate, int eflags)
Definition: execProcnode.c:137
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:641
ResultRelInfo * es_result_relation_info
Definition: execnodes.h:384
void InitResultRelInfo ( ResultRelInfo resultRelInfo,
Relation  resultRelationDesc,
Index  resultRelationIndex,
Relation  partition_root,
int  instrument_options 
)

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

1226 {
1227  List *partition_check = NIL;
1228 
1229  MemSet(resultRelInfo, 0, sizeof(ResultRelInfo));
1230  resultRelInfo->type = T_ResultRelInfo;
1231  resultRelInfo->ri_RangeTableIndex = resultRelationIndex;
1232  resultRelInfo->ri_RelationDesc = resultRelationDesc;
1233  resultRelInfo->ri_NumIndices = 0;
1234  resultRelInfo->ri_IndexRelationDescs = NULL;
1235  resultRelInfo->ri_IndexRelationInfo = NULL;
1236  /* make a copy so as not to depend on relcache info not changing... */
1237  resultRelInfo->ri_TrigDesc = CopyTriggerDesc(resultRelationDesc->trigdesc);
1238  if (resultRelInfo->ri_TrigDesc)
1239  {
1240  int n = resultRelInfo->ri_TrigDesc->numtriggers;
1241 
1242  resultRelInfo->ri_TrigFunctions = (FmgrInfo *)
1243  palloc0(n * sizeof(FmgrInfo));
1244  resultRelInfo->ri_TrigWhenExprs = (List **)
1245  palloc0(n * sizeof(List *));
1246  if (instrument_options)
1247  resultRelInfo->ri_TrigInstrument = InstrAlloc(n, instrument_options);
1248  }
1249  else
1250  {
1251  resultRelInfo->ri_TrigFunctions = NULL;
1252  resultRelInfo->ri_TrigWhenExprs = NULL;
1253  resultRelInfo->ri_TrigInstrument = NULL;
1254  }
1255  if (resultRelationDesc->rd_rel->relkind == RELKIND_FOREIGN_TABLE)
1256  resultRelInfo->ri_FdwRoutine = GetFdwRoutineForRelation(resultRelationDesc, true);
1257  else
1258  resultRelInfo->ri_FdwRoutine = NULL;
1259  resultRelInfo->ri_FdwState = NULL;
1260  resultRelInfo->ri_usesFdwDirectModify = false;
1261  resultRelInfo->ri_ConstraintExprs = NULL;
1262  resultRelInfo->ri_junkFilter = NULL;
1263  resultRelInfo->ri_projectReturning = NULL;
1264 
1265  /*
1266  * If partition_root has been specified, that means we are building the
1267  * ResultRelationInfo for one of its leaf partitions. In that case, we
1268  * need *not* initialize the leaf partition's constraint, but rather the
1269  * the partition_root's (if any). We must do that explicitly like this,
1270  * because implicit partition constraints are not inherited like user-
1271  * defined constraints and would fail to be enforced by ExecConstraints()
1272  * after a tuple is routed to a leaf partition.
1273  */
1274  if (partition_root)
1275  {
1276  /*
1277  * Root table itself may or may not be a partition; partition_check
1278  * would be NIL in the latter case.
1279  */
1280  partition_check = RelationGetPartitionQual(partition_root);
1281 
1282  /*
1283  * This is not our own partition constraint, but rather an ancestor's.
1284  * So any Vars in it bear the ancestor's attribute numbers. We must
1285  * switch them to our own. (dummy varno = 1)
1286  */
1287  if (partition_check != NIL)
1288  partition_check = map_partition_varattnos(partition_check, 1,
1289  resultRelationDesc,
1290  partition_root);
1291  }
1292  else
1293  partition_check = RelationGetPartitionQual(resultRelationDesc);
1294 
1295  resultRelInfo->ri_PartitionCheck = partition_check;
1296  resultRelInfo->ri_PartitionRoot = partition_root;
1297 }
int ri_NumIndices
Definition: execnodes.h:336
#define NIL
Definition: pg_list.h:69
JunkFilter * ri_junkFilter
Definition: execnodes.h:349
Definition: fmgr.h:53
Relation ri_RelationDesc
Definition: execnodes.h:335
Relation ri_PartitionRoot
Definition: execnodes.h:355
Instrumentation * ri_TrigInstrument
Definition: execnodes.h:342
Instrumentation * InstrAlloc(int n, int instrument_options)
Definition: instrument.c:30
#define MemSet(start, val, len)
Definition: c.h:853
Form_pg_class rd_rel
Definition: rel.h:113
Index ri_RangeTableIndex
Definition: execnodes.h:334
NodeTag type
Definition: execnodes.h:333
List ** ri_ConstraintExprs
Definition: execnodes.h:348
TriggerDesc * trigdesc
Definition: rel.h:119
bool ri_usesFdwDirectModify
Definition: execnodes.h:345
ProjectionInfo * ri_projectReturning
Definition: execnodes.h:350
struct FdwRoutine * ri_FdwRoutine
Definition: execnodes.h:343
#define RELKIND_FOREIGN_TABLE
Definition: pg_class.h:166
TriggerDesc * ri_TrigDesc
Definition: execnodes.h:339
List ** ri_TrigWhenExprs
Definition: execnodes.h:341
int numtriggers
Definition: reltrigger.h:49
List * RelationGetPartitionQual(Relation rel)
Definition: partition.c:965
void * palloc0(Size size)
Definition: mcxt.c:920
List * ri_PartitionCheck
Definition: execnodes.h:353
void * ri_FdwState
Definition: execnodes.h:344
#define NULL
Definition: c.h:226
TriggerDesc * CopyTriggerDesc(TriggerDesc *trigdesc)
Definition: trigger.c:1826
FdwRoutine * GetFdwRoutineForRelation(Relation relation, bool makecopy)
Definition: foreign.c:395
IndexInfo ** ri_IndexRelationInfo
Definition: execnodes.h:338
Definition: pg_list.h:45
RelationPtr ri_IndexRelationDescs
Definition: execnodes.h:337
FmgrInfo * ri_TrigFunctions
Definition: execnodes.h:340
List * map_partition_varattnos(List *expr, int target_varno, Relation partrel, Relation parent)
Definition: partition.c:935
void standard_ExecutorEnd ( QueryDesc queryDesc)

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

449 {
450  EState *estate;
451  MemoryContext oldcontext;
452 
453  /* sanity checks */
454  Assert(queryDesc != NULL);
455 
456  estate = queryDesc->estate;
457 
458  Assert(estate != NULL);
459 
460  /*
461  * Check that ExecutorFinish was called, unless in EXPLAIN-only mode. This
462  * Assert is needed because ExecutorFinish is new as of 9.1, and callers
463  * might forget to call it.
464  */
465  Assert(estate->es_finished ||
467 
468  /*
469  * Switch into per-query memory context to run ExecEndPlan
470  */
471  oldcontext = MemoryContextSwitchTo(estate->es_query_cxt);
472 
473  ExecEndPlan(queryDesc->planstate, estate);
474 
475  /* do away with our snapshots */
478 
479  /*
480  * Must switch out of context before destroying it
481  */
482  MemoryContextSwitchTo(oldcontext);
483 
484  /*
485  * Release EState and per-query memory context. This should release
486  * everything the executor has allocated.
487  */
488  FreeExecutorState(estate);
489 
490  /* Reset queryDesc fields that no longer point to anything */
491  queryDesc->tupDesc = NULL;
492  queryDesc->estate = NULL;
493  queryDesc->planstate = NULL;
494  queryDesc->totaltime = NULL;
495 }
EState * estate
Definition: execdesc.h:47
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:109
Snapshot es_crosscheck_snapshot
Definition: execnodes.h:371
Snapshot es_snapshot
Definition: execnodes.h:370
void FreeExecutorState(EState *estate)
Definition: execUtils.c:168
MemoryContext es_query_cxt
Definition: execnodes.h:397
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:408
struct Instrumentation * totaltime
Definition: execdesc.h:51
#define NULL
Definition: c.h:226
#define Assert(condition)
Definition: c.h:671
static void ExecEndPlan(PlanState *planstate, EState *estate)
Definition: execMain.c:1488
int es_top_eflags
Definition: execnodes.h:406
#define EXEC_FLAG_EXPLAIN_ONLY
Definition: executor.h:58
void standard_ExecutorFinish ( QueryDesc queryDesc)

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

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

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

297 {
298  EState *estate;
299  CmdType operation;
300  DestReceiver *dest;
301  bool sendTuples;
302  MemoryContext oldcontext;
303 
304  /* sanity checks */
305  Assert(queryDesc != NULL);
306 
307  estate = queryDesc->estate;
308 
309  Assert(estate != NULL);
311 
312  /*
313  * Switch into per-query memory context
314  */
315  oldcontext = MemoryContextSwitchTo(estate->es_query_cxt);
316 
317  /* Allow instrumentation of Executor overall runtime */
318  if (queryDesc->totaltime)
319  InstrStartNode(queryDesc->totaltime);
320 
321  /*
322  * extract information from the query descriptor and the query feature.
323  */
324  operation = queryDesc->operation;
325  dest = queryDesc->dest;
326 
327  /*
328  * startup tuple receiver, if we will be emitting tuples
329  */
330  estate->es_processed = 0;
331  estate->es_lastoid = InvalidOid;
332 
333  sendTuples = (operation == CMD_SELECT ||
334  queryDesc->plannedstmt->hasReturning);
335 
336  if (sendTuples)
337  (*dest->rStartup) (dest, operation, queryDesc->tupDesc);
338 
339  /*
340  * run plan
341  */
342  if (!ScanDirectionIsNoMovement(direction))
343  ExecutePlan(estate,
344  queryDesc->planstate,
345  queryDesc->plannedstmt->parallelModeNeeded,
346  operation,
347  sendTuples,
348  count,
349  direction,
350  dest);
351 
352  /*
353  * shutdown tuple receiver, if we started it
354  */
355  if (sendTuples)
356  (*dest->rShutdown) (dest);
357 
358  if (queryDesc->totaltime)
359  InstrStopNode(queryDesc->totaltime, estate->es_processed);
360 
361  MemoryContextSwitchTo(oldcontext);
362 }
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:404
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:1566
MemoryContext es_query_cxt
Definition: execnodes.h:397
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:226
#define Assert(condition)
Definition: c.h:671
uint64 es_processed
Definition: execnodes.h:403
DestReceiver * dest
Definition: execdesc.h:41
int es_top_eflags
Definition: execnodes.h:406
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:641
void standard_ExecutorStart ( QueryDesc queryDesc,
int  eflags 
)

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

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

Variable Documentation

ExecutorCheckPerms_hook_type ExecutorCheckPerms_hook = NULL

Definition at line 74 of file execMain.c.

Referenced by _PG_init(), and ExecCheckRTPerms().

ExecutorEnd_hook_type ExecutorEnd_hook = NULL

Definition at line 71 of file execMain.c.

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

ExecutorFinish_hook_type ExecutorFinish_hook = NULL

Definition at line 70 of file execMain.c.

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

ExecutorRun_hook_type ExecutorRun_hook = NULL

Definition at line 69 of file execMain.c.

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

ExecutorStart_hook_type ExecutorStart_hook = NULL

Definition at line 68 of file execMain.c.

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