PostgreSQL Source Code  git master
nodeModifyTable.c File Reference
#include "postgres.h"
#include "access/heapam.h"
#include "access/htup_details.h"
#include "access/tableam.h"
#include "access/xact.h"
#include "catalog/catalog.h"
#include "commands/trigger.h"
#include "executor/execPartition.h"
#include "executor/executor.h"
#include "executor/nodeModifyTable.h"
#include "foreign/fdwapi.h"
#include "miscadmin.h"
#include "nodes/nodeFuncs.h"
#include "optimizer/optimizer.h"
#include "rewrite/rewriteHandler.h"
#include "storage/bufmgr.h"
#include "storage/lmgr.h"
#include "utils/builtins.h"
#include "utils/datum.h"
#include "utils/memutils.h"
#include "utils/rel.h"
Include dependency graph for nodeModifyTable.c:

Go to the source code of this file.

Data Structures

struct  MTTargetRelLookup
 
struct  ModifyTableContext
 
struct  UpdateContext
 

Macros

#define MT_NRELS_HASH   64
 

Typedefs

typedef struct MTTargetRelLookup MTTargetRelLookup
 
typedef struct ModifyTableContext ModifyTableContext
 
typedef struct UpdateContext UpdateContext
 

Functions

static void ExecBatchInsert (ModifyTableState *mtstate, ResultRelInfo *resultRelInfo, TupleTableSlot **slots, TupleTableSlot **planSlots, int numSlots, EState *estate, bool canSetTag)
 
static void ExecPendingInserts (EState *estate)
 
static void ExecCrossPartitionUpdateForeignKey (ModifyTableContext *context, ResultRelInfo *sourcePartInfo, ResultRelInfo *destPartInfo, ItemPointer tupleid, TupleTableSlot *oldslot, TupleTableSlot *newslot)
 
static bool ExecOnConflictUpdate (ModifyTableContext *context, ResultRelInfo *resultRelInfo, ItemPointer conflictTid, TupleTableSlot *excludedSlot, bool canSetTag, TupleTableSlot **returning)
 
static TupleTableSlotExecPrepareTupleRouting (ModifyTableState *mtstate, EState *estate, PartitionTupleRouting *proute, ResultRelInfo *targetRelInfo, TupleTableSlot *slot, ResultRelInfo **partRelInfo)
 
static TupleTableSlotExecMerge (ModifyTableContext *context, ResultRelInfo *resultRelInfo, ItemPointer tupleid, bool canSetTag)
 
static void ExecInitMerge (ModifyTableState *mtstate, EState *estate)
 
static bool ExecMergeMatched (ModifyTableContext *context, ResultRelInfo *resultRelInfo, ItemPointer tupleid, bool canSetTag)
 
static void ExecMergeNotMatched (ModifyTableContext *context, ResultRelInfo *resultRelInfo, bool canSetTag)
 
static void ExecCheckPlanOutput (Relation resultRel, List *targetList)
 
static TupleTableSlotExecProcessReturning (ResultRelInfo *resultRelInfo, TupleTableSlot *tupleSlot, TupleTableSlot *planSlot)
 
static void ExecCheckTupleVisible (EState *estate, Relation rel, TupleTableSlot *slot)
 
static void ExecCheckTIDVisible (EState *estate, ResultRelInfo *relinfo, ItemPointer tid, TupleTableSlot *tempSlot)
 
void ExecInitStoredGenerated (ResultRelInfo *resultRelInfo, EState *estate, CmdType cmdtype)
 
void ExecComputeStoredGenerated (ResultRelInfo *resultRelInfo, EState *estate, TupleTableSlot *slot, CmdType cmdtype)
 
static void ExecInitInsertProjection (ModifyTableState *mtstate, ResultRelInfo *resultRelInfo)
 
static void ExecInitUpdateProjection (ModifyTableState *mtstate, ResultRelInfo *resultRelInfo)
 
static TupleTableSlotExecGetInsertNewTuple (ResultRelInfo *relinfo, TupleTableSlot *planSlot)
 
TupleTableSlotExecGetUpdateNewTuple (ResultRelInfo *relinfo, TupleTableSlot *planSlot, TupleTableSlot *oldSlot)
 
static TupleTableSlotExecInsert (ModifyTableContext *context, ResultRelInfo *resultRelInfo, TupleTableSlot *slot, bool canSetTag, TupleTableSlot **inserted_tuple, ResultRelInfo **insert_destrel)
 
static bool ExecDeletePrologue (ModifyTableContext *context, ResultRelInfo *resultRelInfo, ItemPointer tupleid, HeapTuple oldtuple, TupleTableSlot **epqreturnslot, TM_Result *result)
 
static TM_Result ExecDeleteAct (ModifyTableContext *context, ResultRelInfo *resultRelInfo, ItemPointer tupleid, bool changingPart)
 
static void ExecDeleteEpilogue (ModifyTableContext *context, ResultRelInfo *resultRelInfo, ItemPointer tupleid, HeapTuple oldtuple, bool changingPart)
 
static TupleTableSlotExecDelete (ModifyTableContext *context, ResultRelInfo *resultRelInfo, ItemPointer tupleid, HeapTuple oldtuple, bool processReturning, bool changingPart, bool canSetTag, TM_Result *tmresult, bool *tupleDeleted, TupleTableSlot **epqreturnslot)
 
static bool ExecCrossPartitionUpdate (ModifyTableContext *context, ResultRelInfo *resultRelInfo, ItemPointer tupleid, HeapTuple oldtuple, TupleTableSlot *slot, bool canSetTag, UpdateContext *updateCxt, TM_Result *tmresult, TupleTableSlot **retry_slot, TupleTableSlot **inserted_tuple, ResultRelInfo **insert_destrel)
 
static bool ExecUpdatePrologue (ModifyTableContext *context, ResultRelInfo *resultRelInfo, ItemPointer tupleid, HeapTuple oldtuple, TupleTableSlot *slot, TM_Result *result)
 
static void ExecUpdatePrepareSlot (ResultRelInfo *resultRelInfo, TupleTableSlot *slot, EState *estate)
 
static TM_Result ExecUpdateAct (ModifyTableContext *context, ResultRelInfo *resultRelInfo, ItemPointer tupleid, HeapTuple oldtuple, TupleTableSlot *slot, bool canSetTag, UpdateContext *updateCxt)
 
static void ExecUpdateEpilogue (ModifyTableContext *context, UpdateContext *updateCxt, ResultRelInfo *resultRelInfo, ItemPointer tupleid, HeapTuple oldtuple, TupleTableSlot *slot)
 
static TupleTableSlotExecUpdate (ModifyTableContext *context, ResultRelInfo *resultRelInfo, ItemPointer tupleid, HeapTuple oldtuple, TupleTableSlot *slot, bool canSetTag)
 
void ExecInitMergeTupleSlots (ModifyTableState *mtstate, ResultRelInfo *resultRelInfo)
 
static void fireBSTriggers (ModifyTableState *node)
 
static void fireASTriggers (ModifyTableState *node)
 
static void ExecSetupTransitionCaptureState (ModifyTableState *mtstate, EState *estate)
 
static TupleTableSlotExecModifyTable (PlanState *pstate)
 
ResultRelInfoExecLookupResultRelByOid (ModifyTableState *node, Oid resultoid, bool missing_ok, bool update_cache)
 
ModifyTableStateExecInitModifyTable (ModifyTable *node, EState *estate, int eflags)
 
void ExecEndModifyTable (ModifyTableState *node)
 
void ExecReScanModifyTable (ModifyTableState *node)
 

Macro Definition Documentation

◆ MT_NRELS_HASH

#define MT_NRELS_HASH   64

Typedef Documentation

◆ ModifyTableContext

◆ MTTargetRelLookup

◆ UpdateContext

typedef struct UpdateContext UpdateContext

Function Documentation

◆ ExecBatchInsert()

static void ExecBatchInsert ( ModifyTableState mtstate,
ResultRelInfo resultRelInfo,
TupleTableSlot **  slots,
TupleTableSlot **  planSlots,
int  numSlots,
EState estate,
bool  canSetTag 
)
static

Definition at line 1217 of file nodeModifyTable.c.

1224 {
1225  int i;
1226  int numInserted = numSlots;
1227  TupleTableSlot *slot = NULL;
1228  TupleTableSlot **rslots;
1229 
1230  /*
1231  * insert into foreign table: let the FDW do it
1232  */
1233  rslots = resultRelInfo->ri_FdwRoutine->ExecForeignBatchInsert(estate,
1234  resultRelInfo,
1235  slots,
1236  planSlots,
1237  &numInserted);
1238 
1239  for (i = 0; i < numInserted; i++)
1240  {
1241  slot = rslots[i];
1242 
1243  /*
1244  * AFTER ROW Triggers might reference the tableoid column, so
1245  * (re-)initialize tts_tableOid before evaluating them.
1246  */
1247  slot->tts_tableOid = RelationGetRelid(resultRelInfo->ri_RelationDesc);
1248 
1249  /* AFTER ROW INSERT Triggers */
1250  ExecARInsertTriggers(estate, resultRelInfo, slot, NIL,
1251  mtstate->mt_transition_capture);
1252 
1253  /*
1254  * Check any WITH CHECK OPTION constraints from parent views. See the
1255  * comment in ExecInsert.
1256  */
1257  if (resultRelInfo->ri_WithCheckOptions != NIL)
1258  ExecWithCheckOptions(WCO_VIEW_CHECK, resultRelInfo, slot, estate);
1259  }
1260 
1261  if (canSetTag && numInserted > 0)
1262  estate->es_processed += numInserted;
1263 
1264  /* Clean up all the slots, ready for the next batch */
1265  for (i = 0; i < numSlots; i++)
1266  {
1267  ExecClearTuple(slots[i]);
1268  ExecClearTuple(planSlots[i]);
1269  }
1270  resultRelInfo->ri_NumSlots = 0;
1271 }
void ExecWithCheckOptions(WCOKind kind, ResultRelInfo *resultRelInfo, TupleTableSlot *slot, EState *estate)
Definition: execMain.c:2075
int i
Definition: isn.c:73
@ WCO_VIEW_CHECK
Definition: parsenodes.h:1306
#define NIL
Definition: pg_list.h:68
#define RelationGetRelid(relation)
Definition: rel.h:504
uint64 es_processed
Definition: execnodes.h:669
ExecForeignBatchInsert_function ExecForeignBatchInsert
Definition: fdwapi.h:233
struct TransitionCaptureState * mt_transition_capture
Definition: execnodes.h:1320
Relation ri_RelationDesc
Definition: execnodes.h:456
List * ri_WithCheckOptions
Definition: execnodes.h:519
struct FdwRoutine * ri_FdwRoutine
Definition: execnodes.h:503
Oid tts_tableOid
Definition: tuptable.h:130
void ExecARInsertTriggers(EState *estate, ResultRelInfo *relinfo, TupleTableSlot *slot, List *recheckIndexes, TransitionCaptureState *transition_capture)
Definition: trigger.c:2541
static TupleTableSlot * ExecClearTuple(TupleTableSlot *slot)
Definition: tuptable.h:433

References EState::es_processed, ExecARInsertTriggers(), ExecClearTuple(), FdwRoutine::ExecForeignBatchInsert, ExecWithCheckOptions(), i, ModifyTableState::mt_transition_capture, NIL, RelationGetRelid, ResultRelInfo::ri_FdwRoutine, ResultRelInfo::ri_NumSlots, ResultRelInfo::ri_RelationDesc, ResultRelInfo::ri_WithCheckOptions, TupleTableSlot::tts_tableOid, and WCO_VIEW_CHECK.

Referenced by ExecInsert(), and ExecPendingInserts().

◆ ExecCheckPlanOutput()

static void ExecCheckPlanOutput ( Relation  resultRel,
List targetList 
)
static

Definition at line 181 of file nodeModifyTable.c.

182 {
183  TupleDesc resultDesc = RelationGetDescr(resultRel);
184  int attno = 0;
185  ListCell *lc;
186 
187  foreach(lc, targetList)
188  {
189  TargetEntry *tle = (TargetEntry *) lfirst(lc);
190  Form_pg_attribute attr;
191 
192  Assert(!tle->resjunk); /* caller removed junk items already */
193 
194  if (attno >= resultDesc->natts)
195  ereport(ERROR,
196  (errcode(ERRCODE_DATATYPE_MISMATCH),
197  errmsg("table row type and query-specified row type do not match"),
198  errdetail("Query has too many columns.")));
199  attr = TupleDescAttr(resultDesc, attno);
200  attno++;
201 
202  if (!attr->attisdropped)
203  {
204  /* Normal case: demand type match */
205  if (exprType((Node *) tle->expr) != attr->atttypid)
206  ereport(ERROR,
207  (errcode(ERRCODE_DATATYPE_MISMATCH),
208  errmsg("table row type and query-specified row type do not match"),
209  errdetail("Table has type %s at ordinal position %d, but query expects %s.",
210  format_type_be(attr->atttypid),
211  attno,
212  format_type_be(exprType((Node *) tle->expr)))));
213  }
214  else
215  {
216  /*
217  * For a dropped column, we can't check atttypid (it's likely 0).
218  * In any case the planner has most likely inserted an INT4 null.
219  * What we insist on is just *some* NULL constant.
220  */
221  if (!IsA(tle->expr, Const) ||
222  !((Const *) tle->expr)->constisnull)
223  ereport(ERROR,
224  (errcode(ERRCODE_DATATYPE_MISMATCH),
225  errmsg("table row type and query-specified row type do not match"),
226  errdetail("Query provides a value for a dropped column at ordinal position %d.",
227  attno)));
228  }
229  }
230  if (attno != resultDesc->natts)
231  ereport(ERROR,
232  (errcode(ERRCODE_DATATYPE_MISMATCH),
233  errmsg("table row type and query-specified row type do not match"),
234  errdetail("Query has too few columns.")));
235 }
int errdetail(const char *fmt,...)
Definition: elog.c:1208
int errcode(int sqlerrcode)
Definition: elog.c:860
int errmsg(const char *fmt,...)
Definition: elog.c:1075
#define ERROR
Definition: elog.h:39
#define ereport(elevel,...)
Definition: elog.h:149
char * format_type_be(Oid type_oid)
Definition: format_type.c:343
Assert(fmt[strlen(fmt) - 1] !='\n')
Oid exprType(const Node *expr)
Definition: nodeFuncs.c:43
#define IsA(nodeptr, _type_)
Definition: nodes.h:158
FormData_pg_attribute * Form_pg_attribute
Definition: pg_attribute.h:209
#define lfirst(lc)
Definition: pg_list.h:172
#define RelationGetDescr(relation)
Definition: rel.h:530
Definition: nodes.h:129
Expr * expr
Definition: primnodes.h:1922
#define TupleDescAttr(tupdesc, i)
Definition: tupdesc.h:92

References Assert(), ereport, errcode(), errdetail(), errmsg(), ERROR, TargetEntry::expr, exprType(), format_type_be(), IsA, lfirst, TupleDescData::natts, RelationGetDescr, and TupleDescAttr.

Referenced by ExecInitInsertProjection(), and ExecInitMerge().

◆ ExecCheckTIDVisible()

static void ExecCheckTIDVisible ( EState estate,
ResultRelInfo relinfo,
ItemPointer  tid,
TupleTableSlot tempSlot 
)
static

Definition at line 316 of file nodeModifyTable.c.

320 {
321  Relation rel = relinfo->ri_RelationDesc;
322 
323  /* Redundantly check isolation level */
325  return;
326 
327  if (!table_tuple_fetch_row_version(rel, tid, SnapshotAny, tempSlot))
328  elog(ERROR, "failed to fetch conflicting tuple for ON CONFLICT");
329  ExecCheckTupleVisible(estate, rel, tempSlot);
330  ExecClearTuple(tempSlot);
331 }
static void ExecCheckTupleVisible(EState *estate, Relation rel, TupleTableSlot *slot)
#define SnapshotAny
Definition: snapmgr.h:33
static bool table_tuple_fetch_row_version(Relation rel, ItemPointer tid, Snapshot snapshot, TupleTableSlot *slot)
Definition: tableam.h:1283
#define IsolationUsesXactSnapshot()
Definition: xact.h:51

References elog(), ERROR, ExecCheckTupleVisible(), ExecClearTuple(), IsolationUsesXactSnapshot, ResultRelInfo::ri_RelationDesc, SnapshotAny, and table_tuple_fetch_row_version().

Referenced by ExecInsert().

◆ ExecCheckTupleVisible()

static void ExecCheckTupleVisible ( EState estate,
Relation  rel,
TupleTableSlot slot 
)
static

Definition at line 282 of file nodeModifyTable.c.

285 {
287  return;
288 
289  if (!table_tuple_satisfies_snapshot(rel, slot, estate->es_snapshot))
290  {
291  Datum xminDatum;
292  TransactionId xmin;
293  bool isnull;
294 
295  xminDatum = slot_getsysattr(slot, MinTransactionIdAttributeNumber, &isnull);
296  Assert(!isnull);
297  xmin = DatumGetTransactionId(xminDatum);
298 
299  /*
300  * We should not raise a serialization failure if the conflict is
301  * against a tuple inserted by our own transaction, even if it's not
302  * visible to our snapshot. (This would happen, for example, if
303  * conflicting keys are proposed for insertion in a single command.)
304  */
306  ereport(ERROR,
308  errmsg("could not serialize access due to concurrent update")));
309  }
310 }
uint32 TransactionId
Definition: c.h:641
#define ERRCODE_T_R_SERIALIZATION_FAILURE
Definition: pgbench.c:76
uintptr_t Datum
Definition: postgres.h:64
static TransactionId DatumGetTransactionId(Datum X)
Definition: postgres.h:262
Snapshot es_snapshot
Definition: execnodes.h:622
#define MinTransactionIdAttributeNumber
Definition: sysattr.h:22
static bool table_tuple_satisfies_snapshot(Relation rel, TupleTableSlot *slot, Snapshot snapshot)
Definition: tableam.h:1330
static Datum slot_getsysattr(TupleTableSlot *slot, int attnum, bool *isnull)
Definition: tuptable.h:410
bool TransactionIdIsCurrentTransactionId(TransactionId xid)
Definition: xact.c:926

References Assert(), DatumGetTransactionId(), ereport, errcode(), ERRCODE_T_R_SERIALIZATION_FAILURE, errmsg(), ERROR, EState::es_snapshot, IsolationUsesXactSnapshot, MinTransactionIdAttributeNumber, slot_getsysattr(), table_tuple_satisfies_snapshot(), and TransactionIdIsCurrentTransactionId().

Referenced by ExecCheckTIDVisible(), and ExecOnConflictUpdate().

◆ ExecComputeStoredGenerated()

void ExecComputeStoredGenerated ( ResultRelInfo resultRelInfo,
EState estate,
TupleTableSlot slot,
CmdType  cmdtype 
)

Definition at line 446 of file nodeModifyTable.c.

449 {
450  Relation rel = resultRelInfo->ri_RelationDesc;
451  TupleDesc tupdesc = RelationGetDescr(rel);
452  int natts = tupdesc->natts;
453  ExprContext *econtext = GetPerTupleExprContext(estate);
454  ExprState **ri_GeneratedExprs;
455  MemoryContext oldContext;
456  Datum *values;
457  bool *nulls;
458 
459  /* We should not be called unless this is true */
460  Assert(tupdesc->constr && tupdesc->constr->has_generated_stored);
461 
462  /*
463  * Initialize the expressions if we didn't already, and check whether we
464  * can exit early because nothing needs to be computed.
465  */
466  if (cmdtype == CMD_UPDATE)
467  {
468  if (resultRelInfo->ri_GeneratedExprsU == NULL)
469  ExecInitStoredGenerated(resultRelInfo, estate, cmdtype);
470  if (resultRelInfo->ri_NumGeneratedNeededU == 0)
471  return;
472  ri_GeneratedExprs = resultRelInfo->ri_GeneratedExprsU;
473  }
474  else
475  {
476  if (resultRelInfo->ri_GeneratedExprsI == NULL)
477  ExecInitStoredGenerated(resultRelInfo, estate, cmdtype);
478  /* Early exit is impossible given the prior Assert */
479  Assert(resultRelInfo->ri_NumGeneratedNeededI > 0);
480  ri_GeneratedExprs = resultRelInfo->ri_GeneratedExprsI;
481  }
482 
483  oldContext = MemoryContextSwitchTo(GetPerTupleMemoryContext(estate));
484 
485  values = palloc(sizeof(*values) * natts);
486  nulls = palloc(sizeof(*nulls) * natts);
487 
488  slot_getallattrs(slot);
489  memcpy(nulls, slot->tts_isnull, sizeof(*nulls) * natts);
490 
491  for (int i = 0; i < natts; i++)
492  {
493  Form_pg_attribute attr = TupleDescAttr(tupdesc, i);
494 
495  if (ri_GeneratedExprs[i])
496  {
497  Datum val;
498  bool isnull;
499 
500  Assert(attr->attgenerated == ATTRIBUTE_GENERATED_STORED);
501 
502  econtext->ecxt_scantuple = slot;
503 
504  val = ExecEvalExpr(ri_GeneratedExprs[i], econtext, &isnull);
505 
506  /*
507  * We must make a copy of val as we have no guarantees about where
508  * memory for a pass-by-reference Datum is located.
509  */
510  if (!isnull)
511  val = datumCopy(val, attr->attbyval, attr->attlen);
512 
513  values[i] = val;
514  nulls[i] = isnull;
515  }
516  else
517  {
518  if (!nulls[i])
519  values[i] = datumCopy(slot->tts_values[i], attr->attbyval, attr->attlen);
520  }
521  }
522 
523  ExecClearTuple(slot);
524  memcpy(slot->tts_values, values, sizeof(*values) * natts);
525  memcpy(slot->tts_isnull, nulls, sizeof(*nulls) * natts);
526  ExecStoreVirtualTuple(slot);
527  ExecMaterializeSlot(slot);
528 
529  MemoryContextSwitchTo(oldContext);
530 }
static Datum values[MAXATTR]
Definition: bootstrap.c:156
Datum datumCopy(Datum value, bool typByVal, int typLen)
Definition: datum.c:132
TupleTableSlot * ExecStoreVirtualTuple(TupleTableSlot *slot)
Definition: execTuples.c:1551
#define GetPerTupleExprContext(estate)
Definition: executor.h:549
#define GetPerTupleMemoryContext(estate)
Definition: executor.h:554
static Datum ExecEvalExpr(ExprState *state, ExprContext *econtext, bool *isNull)
Definition: executor.h:332
long val
Definition: informix.c:664
void * palloc(Size size)
Definition: mcxt.c:1201
void ExecInitStoredGenerated(ResultRelInfo *resultRelInfo, EState *estate, CmdType cmdtype)
@ CMD_UPDATE
Definition: nodes.h:256
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:124
TupleTableSlot * ecxt_scantuple
Definition: execnodes.h:255
ExprState ** ri_GeneratedExprsI
Definition: execnodes.h:528
int ri_NumGeneratedNeededU
Definition: execnodes.h:533
ExprState ** ri_GeneratedExprsU
Definition: execnodes.h:529
int ri_NumGeneratedNeededI
Definition: execnodes.h:532
bool has_generated_stored
Definition: tupdesc.h:45
TupleConstr * constr
Definition: tupdesc.h:85
bool * tts_isnull
Definition: tuptable.h:127
Datum * tts_values
Definition: tuptable.h:125
static void slot_getallattrs(TupleTableSlot *slot)
Definition: tuptable.h:362
static void ExecMaterializeSlot(TupleTableSlot *slot)
Definition: tuptable.h:451

References Assert(), CMD_UPDATE, TupleDescData::constr, datumCopy(), ExprContext::ecxt_scantuple, ExecClearTuple(), ExecEvalExpr(), ExecInitStoredGenerated(), ExecMaterializeSlot(), ExecStoreVirtualTuple(), GetPerTupleExprContext, GetPerTupleMemoryContext, TupleConstr::has_generated_stored, i, MemoryContextSwitchTo(), TupleDescData::natts, palloc(), RelationGetDescr, ResultRelInfo::ri_GeneratedExprsI, ResultRelInfo::ri_GeneratedExprsU, ResultRelInfo::ri_NumGeneratedNeededI, ResultRelInfo::ri_NumGeneratedNeededU, ResultRelInfo::ri_RelationDesc, slot_getallattrs(), TupleTableSlot::tts_isnull, TupleTableSlot::tts_values, TupleDescAttr, val, and values.

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

◆ ExecCrossPartitionUpdate()

static bool ExecCrossPartitionUpdate ( ModifyTableContext context,
ResultRelInfo resultRelInfo,
ItemPointer  tupleid,
HeapTuple  oldtuple,
TupleTableSlot slot,
bool  canSetTag,
UpdateContext updateCxt,
TM_Result tmresult,
TupleTableSlot **  retry_slot,
TupleTableSlot **  inserted_tuple,
ResultRelInfo **  insert_destrel 
)
static

Definition at line 1735 of file nodeModifyTable.c.

1745 {
1746  ModifyTableState *mtstate = context->mtstate;
1747  EState *estate = mtstate->ps.state;
1748  TupleConversionMap *tupconv_map;
1749  bool tuple_deleted;
1750  TupleTableSlot *epqslot = NULL;
1751 
1752  context->cpUpdateReturningSlot = NULL;
1753  *retry_slot = NULL;
1754 
1755  /*
1756  * Disallow an INSERT ON CONFLICT DO UPDATE that causes the original row
1757  * to migrate to a different partition. Maybe this can be implemented
1758  * some day, but it seems a fringe feature with little redeeming value.
1759  */
1760  if (((ModifyTable *) mtstate->ps.plan)->onConflictAction == ONCONFLICT_UPDATE)
1761  ereport(ERROR,
1762  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1763  errmsg("invalid ON UPDATE specification"),
1764  errdetail("The result tuple would appear in a different partition than the original tuple.")));
1765 
1766  /*
1767  * When an UPDATE is run directly on a leaf partition, simply fail with a
1768  * partition constraint violation error.
1769  */
1770  if (resultRelInfo == mtstate->rootResultRelInfo)
1771  ExecPartitionCheckEmitError(resultRelInfo, slot, estate);
1772 
1773  /* Initialize tuple routing info if not already done. */
1774  if (mtstate->mt_partition_tuple_routing == NULL)
1775  {
1776  Relation rootRel = mtstate->rootResultRelInfo->ri_RelationDesc;
1777  MemoryContext oldcxt;
1778 
1779  /* Things built here have to last for the query duration. */
1780  oldcxt = MemoryContextSwitchTo(estate->es_query_cxt);
1781 
1782  mtstate->mt_partition_tuple_routing =
1783  ExecSetupPartitionTupleRouting(estate, rootRel);
1784 
1785  /*
1786  * Before a partition's tuple can be re-routed, it must first be
1787  * converted to the root's format, so we'll need a slot for storing
1788  * such tuples.
1789  */
1790  Assert(mtstate->mt_root_tuple_slot == NULL);
1791  mtstate->mt_root_tuple_slot = table_slot_create(rootRel, NULL);
1792 
1793  MemoryContextSwitchTo(oldcxt);
1794  }
1795 
1796  /*
1797  * Row movement, part 1. Delete the tuple, but skip RETURNING processing.
1798  * We want to return rows from INSERT.
1799  */
1800  ExecDelete(context, resultRelInfo,
1801  tupleid, oldtuple,
1802  false, /* processReturning */
1803  true, /* changingPart */
1804  false, /* canSetTag */
1805  tmresult, &tuple_deleted, &epqslot);
1806 
1807  /*
1808  * For some reason if DELETE didn't happen (e.g. trigger prevented it, or
1809  * it was already deleted by self, or it was concurrently deleted by
1810  * another transaction), then we should skip the insert as well;
1811  * otherwise, an UPDATE could cause an increase in the total number of
1812  * rows across all partitions, which is clearly wrong.
1813  *
1814  * For a normal UPDATE, the case where the tuple has been the subject of a
1815  * concurrent UPDATE or DELETE would be handled by the EvalPlanQual
1816  * machinery, but for an UPDATE that we've translated into a DELETE from
1817  * this partition and an INSERT into some other partition, that's not
1818  * available, because CTID chains can't span relation boundaries. We
1819  * mimic the semantics to a limited extent by skipping the INSERT if the
1820  * DELETE fails to find a tuple. This ensures that two concurrent
1821  * attempts to UPDATE the same tuple at the same time can't turn one tuple
1822  * into two, and that an UPDATE of a just-deleted tuple can't resurrect
1823  * it.
1824  */
1825  if (!tuple_deleted)
1826  {
1827  /*
1828  * epqslot will be typically NULL. But when ExecDelete() finds that
1829  * another transaction has concurrently updated the same row, it
1830  * re-fetches the row, skips the delete, and epqslot is set to the
1831  * re-fetched tuple slot. In that case, we need to do all the checks
1832  * again. For MERGE, we leave everything to the caller (it must do
1833  * additional rechecking, and might end up executing a different
1834  * action entirely).
1835  */
1836  if (context->relaction != NULL)
1837  return *tmresult == TM_Ok;
1838  else if (TupIsNull(epqslot))
1839  return true;
1840  else
1841  {
1842  /* Fetch the most recent version of old tuple. */
1843  TupleTableSlot *oldSlot;
1844 
1845  /* ... but first, make sure ri_oldTupleSlot is initialized. */
1846  if (unlikely(!resultRelInfo->ri_projectNewInfoValid))
1847  ExecInitUpdateProjection(mtstate, resultRelInfo);
1848  oldSlot = resultRelInfo->ri_oldTupleSlot;
1849  if (!table_tuple_fetch_row_version(resultRelInfo->ri_RelationDesc,
1850  tupleid,
1851  SnapshotAny,
1852  oldSlot))
1853  elog(ERROR, "failed to fetch tuple being updated");
1854  /* and project the new tuple to retry the UPDATE with */
1855  *retry_slot = ExecGetUpdateNewTuple(resultRelInfo, epqslot,
1856  oldSlot);
1857  return false;
1858  }
1859  }
1860 
1861  /*
1862  * resultRelInfo is one of the per-relation resultRelInfos. So we should
1863  * convert the tuple into root's tuple descriptor if needed, since
1864  * ExecInsert() starts the search from root.
1865  */
1866  tupconv_map = ExecGetChildToRootMap(resultRelInfo);
1867  if (tupconv_map != NULL)
1868  slot = execute_attr_map_slot(tupconv_map->attrMap,
1869  slot,
1870  mtstate->mt_root_tuple_slot);
1871 
1872  /* Tuple routing starts from the root table. */
1873  context->cpUpdateReturningSlot =
1874  ExecInsert(context, mtstate->rootResultRelInfo, slot, canSetTag,
1875  inserted_tuple, insert_destrel);
1876 
1877  /*
1878  * Reset the transition state that may possibly have been written by
1879  * INSERT.
1880  */
1881  if (mtstate->mt_transition_capture)
1883 
1884  /* We're done moving. */
1885  return true;
1886 }
#define unlikely(x)
Definition: c.h:300
void ExecPartitionCheckEmitError(ResultRelInfo *resultRelInfo, TupleTableSlot *slot, EState *estate)
Definition: execMain.c:1869
PartitionTupleRouting * ExecSetupPartitionTupleRouting(EState *estate, Relation rel)
TupleConversionMap * ExecGetChildToRootMap(ResultRelInfo *resultRelInfo)
Definition: execUtils.c:1211
static TupleTableSlot * ExecInsert(ModifyTableContext *context, ResultRelInfo *resultRelInfo, TupleTableSlot *slot, bool canSetTag, TupleTableSlot **inserted_tuple, ResultRelInfo **insert_destrel)
TupleTableSlot * ExecGetUpdateNewTuple(ResultRelInfo *relinfo, TupleTableSlot *planSlot, TupleTableSlot *oldSlot)
static void ExecInitUpdateProjection(ModifyTableState *mtstate, ResultRelInfo *resultRelInfo)
static TupleTableSlot * ExecDelete(ModifyTableContext *context, ResultRelInfo *resultRelInfo, ItemPointer tupleid, HeapTuple oldtuple, bool processReturning, bool changingPart, bool canSetTag, TM_Result *tmresult, bool *tupleDeleted, TupleTableSlot **epqreturnslot)
@ ONCONFLICT_UPDATE
Definition: nodes.h:409
MemoryContext es_query_cxt
Definition: execnodes.h:665
MergeActionState * relaction
TupleTableSlot * cpUpdateReturningSlot
ModifyTableState * mtstate
struct PartitionTupleRouting * mt_partition_tuple_routing
Definition: execnodes.h:1317
TupleTableSlot * mt_root_tuple_slot
Definition: execnodes.h:1314
PlanState ps
Definition: execnodes.h:1281
ResultRelInfo * rootResultRelInfo
Definition: execnodes.h:1294
Plan * plan
Definition: execnodes.h:1043
EState * state
Definition: execnodes.h:1045
bool ri_projectNewInfoValid
Definition: execnodes.h:483
TupleTableSlot * ri_oldTupleSlot
Definition: execnodes.h:481
TupleTableSlot * tcs_original_insert_tuple
Definition: trigger.h:76
AttrMap * attrMap
Definition: tupconvert.h:28
TupleTableSlot * table_slot_create(Relation relation, List **reglist)
Definition: tableam.c:91
@ TM_Ok
Definition: tableam.h:77
TupleTableSlot * execute_attr_map_slot(AttrMap *attrMap, TupleTableSlot *in_slot, TupleTableSlot *out_slot)
Definition: tupconvert.c:192
#define TupIsNull(slot)
Definition: tuptable.h:300

References Assert(), TupleConversionMap::attrMap, ModifyTableContext::cpUpdateReturningSlot, elog(), ereport, errcode(), errdetail(), errmsg(), ERROR, EState::es_query_cxt, ExecDelete(), ExecGetChildToRootMap(), ExecGetUpdateNewTuple(), ExecInitUpdateProjection(), ExecInsert(), ExecPartitionCheckEmitError(), ExecSetupPartitionTupleRouting(), execute_attr_map_slot(), MemoryContextSwitchTo(), ModifyTableState::mt_partition_tuple_routing, ModifyTableState::mt_root_tuple_slot, ModifyTableState::mt_transition_capture, ModifyTableContext::mtstate, ONCONFLICT_UPDATE, PlanState::plan, ModifyTableState::ps, ModifyTableContext::relaction, ResultRelInfo::ri_oldTupleSlot, ResultRelInfo::ri_projectNewInfoValid, ResultRelInfo::ri_RelationDesc, ModifyTableState::rootResultRelInfo, SnapshotAny, PlanState::state, table_slot_create(), table_tuple_fetch_row_version(), TransitionCaptureState::tcs_original_insert_tuple, TM_Ok, TupIsNull, and unlikely.

Referenced by ExecUpdateAct().

◆ ExecCrossPartitionUpdateForeignKey()

static void ExecCrossPartitionUpdateForeignKey ( ModifyTableContext context,
ResultRelInfo sourcePartInfo,
ResultRelInfo destPartInfo,
ItemPointer  tupleid,
TupleTableSlot oldslot,
TupleTableSlot newslot 
)
static

Definition at line 2174 of file nodeModifyTable.c.

2180 {
2181  ListCell *lc;
2182  ResultRelInfo *rootRelInfo;
2183  List *ancestorRels;
2184 
2185  rootRelInfo = sourcePartInfo->ri_RootResultRelInfo;
2186  ancestorRels = ExecGetAncestorResultRels(context->estate, sourcePartInfo);
2187 
2188  /*
2189  * For any foreign keys that point directly into a non-root ancestors of
2190  * the source partition, we can in theory fire an update event to enforce
2191  * those constraints using their triggers, if we could tell that both the
2192  * source and the destination partitions are under the same ancestor. But
2193  * for now, we simply report an error that those cannot be enforced.
2194  */
2195  foreach(lc, ancestorRels)
2196  {
2197  ResultRelInfo *rInfo = lfirst(lc);
2198  TriggerDesc *trigdesc = rInfo->ri_TrigDesc;
2199  bool has_noncloned_fkey = false;
2200 
2201  /* Root ancestor's triggers will be processed. */
2202  if (rInfo == rootRelInfo)
2203  continue;
2204 
2205  if (trigdesc && trigdesc->trig_update_after_row)
2206  {
2207  for (int i = 0; i < trigdesc->numtriggers; i++)
2208  {
2209  Trigger *trig = &trigdesc->triggers[i];
2210 
2211  if (!trig->tgisclone &&
2213  {
2214  has_noncloned_fkey = true;
2215  break;
2216  }
2217  }
2218  }
2219 
2220  if (has_noncloned_fkey)
2221  ereport(ERROR,
2222  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2223  errmsg("cannot move tuple across partitions when a non-root ancestor of the source partition is directly referenced in a foreign key"),
2224  errdetail("A foreign key points to ancestor \"%s\" but not the root ancestor \"%s\".",
2227  errhint("Consider defining the foreign key on table \"%s\".",
2228  RelationGetRelationName(rootRelInfo->ri_RelationDesc))));
2229  }
2230 
2231  /* Perform the root table's triggers. */
2232  ExecARUpdateTriggers(context->estate,
2233  rootRelInfo, sourcePartInfo, destPartInfo,
2234  tupleid, NULL, newslot, NIL, NULL, true);
2235 }
int errhint(const char *fmt,...)
Definition: elog.c:1322
List * ExecGetAncestorResultRels(EState *estate, ResultRelInfo *resultRelInfo)
Definition: execMain.c:1396
#define RelationGetRelationName(relation)
Definition: rel.h:538
int RI_FKey_trigger_type(Oid tgfoid)
Definition: ri_triggers.c:3010
Definition: pg_list.h:54
struct ResultRelInfo * ri_RootResultRelInfo
Definition: execnodes.h:580
TriggerDesc * ri_TrigDesc
Definition: execnodes.h:486
int numtriggers
Definition: reltrigger.h:50
Trigger * triggers
Definition: reltrigger.h:49
bool trig_update_after_row
Definition: reltrigger.h:62
Oid tgfoid
Definition: reltrigger.h:28
bool tgisclone
Definition: reltrigger.h:32
void ExecARUpdateTriggers(EState *estate, ResultRelInfo *relinfo, ResultRelInfo *src_partinfo, ResultRelInfo *dst_partinfo, ItemPointer tupleid, HeapTuple fdw_trigtuple, TupleTableSlot *newslot, List *recheckIndexes, TransitionCaptureState *transition_capture, bool is_crosspart_update)
Definition: trigger.c:3104
#define RI_TRIGGER_PK
Definition: trigger.h:282

References ereport, errcode(), errdetail(), errhint(), errmsg(), ERROR, ModifyTableContext::estate, ExecARUpdateTriggers(), ExecGetAncestorResultRels(), i, lfirst, NIL, TriggerDesc::numtriggers, RelationGetRelationName, RI_FKey_trigger_type(), ResultRelInfo::ri_RelationDesc, ResultRelInfo::ri_RootResultRelInfo, ResultRelInfo::ri_TrigDesc, RI_TRIGGER_PK, Trigger::tgfoid, Trigger::tgisclone, TriggerDesc::trig_update_after_row, and TriggerDesc::triggers.

Referenced by ExecUpdateAct().

◆ ExecDelete()

static TupleTableSlot* ExecDelete ( ModifyTableContext context,
ResultRelInfo resultRelInfo,
ItemPointer  tupleid,
HeapTuple  oldtuple,
bool  processReturning,
bool  changingPart,
bool  canSetTag,
TM_Result tmresult,
bool tupleDeleted,
TupleTableSlot **  epqreturnslot 
)
static

Definition at line 1421 of file nodeModifyTable.c.

1431 {
1432  EState *estate = context->estate;
1433  Relation resultRelationDesc = resultRelInfo->ri_RelationDesc;
1434  TupleTableSlot *slot = NULL;
1435  TM_Result result;
1436 
1437  if (tupleDeleted)
1438  *tupleDeleted = false;
1439 
1440  /*
1441  * Prepare for the delete. This includes BEFORE ROW triggers, so we're
1442  * done if it says we are.
1443  */
1444  if (!ExecDeletePrologue(context, resultRelInfo, tupleid, oldtuple,
1445  epqreturnslot, tmresult))
1446  return NULL;
1447 
1448  /* INSTEAD OF ROW DELETE Triggers */
1449  if (resultRelInfo->ri_TrigDesc &&
1450  resultRelInfo->ri_TrigDesc->trig_delete_instead_row)
1451  {
1452  bool dodelete;
1453 
1454  Assert(oldtuple != NULL);
1455  dodelete = ExecIRDeleteTriggers(estate, resultRelInfo, oldtuple);
1456 
1457  if (!dodelete) /* "do nothing" */
1458  return NULL;
1459  }
1460  else if (resultRelInfo->ri_FdwRoutine)
1461  {
1462  /*
1463  * delete from foreign table: let the FDW do it
1464  *
1465  * We offer the returning slot as a place to store RETURNING data,
1466  * although the FDW can return some other slot if it wants.
1467  */
1468  slot = ExecGetReturningSlot(estate, resultRelInfo);
1469  slot = resultRelInfo->ri_FdwRoutine->ExecForeignDelete(estate,
1470  resultRelInfo,
1471  slot,
1472  context->planSlot);
1473 
1474  if (slot == NULL) /* "do nothing" */
1475  return NULL;
1476 
1477  /*
1478  * RETURNING expressions might reference the tableoid column, so
1479  * (re)initialize tts_tableOid before evaluating them.
1480  */
1481  if (TTS_EMPTY(slot))
1482  ExecStoreAllNullTuple(slot);
1483 
1484  slot->tts_tableOid = RelationGetRelid(resultRelationDesc);
1485  }
1486  else
1487  {
1488  /*
1489  * delete the tuple
1490  *
1491  * Note: if context->estate->es_crosscheck_snapshot isn't
1492  * InvalidSnapshot, we check that the row to be deleted is visible to
1493  * that snapshot, and throw a can't-serialize error if not. This is a
1494  * special-case behavior needed for referential integrity updates in
1495  * transaction-snapshot mode transactions.
1496  */
1497 ldelete:
1498  result = ExecDeleteAct(context, resultRelInfo, tupleid, changingPart);
1499 
1500  if (tmresult)
1501  *tmresult = result;
1502 
1503  switch (result)
1504  {
1505  case TM_SelfModified:
1506 
1507  /*
1508  * The target tuple was already updated or deleted by the
1509  * current command, or by a later command in the current
1510  * transaction. The former case is possible in a join DELETE
1511  * where multiple tuples join to the same target tuple. This
1512  * is somewhat questionable, but Postgres has always allowed
1513  * it: we just ignore additional deletion attempts.
1514  *
1515  * The latter case arises if the tuple is modified by a
1516  * command in a BEFORE trigger, or perhaps by a command in a
1517  * volatile function used in the query. In such situations we
1518  * should not ignore the deletion, but it is equally unsafe to
1519  * proceed. We don't want to discard the original DELETE
1520  * while keeping the triggered actions based on its deletion;
1521  * and it would be no better to allow the original DELETE
1522  * while discarding updates that it triggered. The row update
1523  * carries some information that might be important according
1524  * to business rules; so throwing an error is the only safe
1525  * course.
1526  *
1527  * If a trigger actually intends this type of interaction, it
1528  * can re-execute the DELETE and then return NULL to cancel
1529  * the outer delete.
1530  */
1531  if (context->tmfd.cmax != estate->es_output_cid)
1532  ereport(ERROR,
1533  (errcode(ERRCODE_TRIGGERED_DATA_CHANGE_VIOLATION),
1534  errmsg("tuple to be deleted was already modified by an operation triggered by the current command"),
1535  errhint("Consider using an AFTER trigger instead of a BEFORE trigger to propagate changes to other rows.")));
1536 
1537  /* Else, already deleted by self; nothing to do */
1538  return NULL;
1539 
1540  case TM_Ok:
1541  break;
1542 
1543  case TM_Updated:
1544  {
1545  TupleTableSlot *inputslot;
1546  TupleTableSlot *epqslot;
1547 
1549  ereport(ERROR,
1551  errmsg("could not serialize access due to concurrent update")));
1552 
1553  /*
1554  * Already know that we're going to need to do EPQ, so
1555  * fetch tuple directly into the right slot.
1556  */
1557  EvalPlanQualBegin(context->epqstate);
1558  inputslot = EvalPlanQualSlot(context->epqstate, resultRelationDesc,
1559  resultRelInfo->ri_RangeTableIndex);
1560 
1561  result = table_tuple_lock(resultRelationDesc, tupleid,
1562  estate->es_snapshot,
1563  inputslot, estate->es_output_cid,
1566  &context->tmfd);
1567 
1568  switch (result)
1569  {
1570  case TM_Ok:
1571  Assert(context->tmfd.traversed);
1572  epqslot = EvalPlanQual(context->epqstate,
1573  resultRelationDesc,
1574  resultRelInfo->ri_RangeTableIndex,
1575  inputslot);
1576  if (TupIsNull(epqslot))
1577  /* Tuple not passing quals anymore, exiting... */
1578  return NULL;
1579 
1580  /*
1581  * If requested, skip delete and pass back the
1582  * updated row.
1583  */
1584  if (epqreturnslot)
1585  {
1586  *epqreturnslot = epqslot;
1587  return NULL;
1588  }
1589  else
1590  goto ldelete;
1591 
1592  case TM_SelfModified:
1593 
1594  /*
1595  * This can be reached when following an update
1596  * chain from a tuple updated by another session,
1597  * reaching a tuple that was already updated in
1598  * this transaction. If previously updated by this
1599  * command, ignore the delete, otherwise error
1600  * out.
1601  *
1602  * See also TM_SelfModified response to
1603  * table_tuple_delete() above.
1604  */
1605  if (context->tmfd.cmax != estate->es_output_cid)
1606  ereport(ERROR,
1607  (errcode(ERRCODE_TRIGGERED_DATA_CHANGE_VIOLATION),
1608  errmsg("tuple to be deleted was already modified by an operation triggered by the current command"),
1609  errhint("Consider using an AFTER trigger instead of a BEFORE trigger to propagate changes to other rows.")));
1610  return NULL;
1611 
1612  case TM_Deleted:
1613  /* tuple already deleted; nothing to do */
1614  return NULL;
1615 
1616  default:
1617 
1618  /*
1619  * TM_Invisible should be impossible because we're
1620  * waiting for updated row versions, and would
1621  * already have errored out if the first version
1622  * is invisible.
1623  *
1624  * TM_Updated should be impossible, because we're
1625  * locking the latest version via
1626  * TUPLE_LOCK_FLAG_FIND_LAST_VERSION.
1627  */
1628  elog(ERROR, "unexpected table_tuple_lock status: %u",
1629  result);
1630  return NULL;
1631  }
1632 
1633  Assert(false);
1634  break;
1635  }
1636 
1637  case TM_Deleted:
1639  ereport(ERROR,
1641  errmsg("could not serialize access due to concurrent delete")));
1642  /* tuple already deleted; nothing to do */
1643  return NULL;
1644 
1645  default:
1646  elog(ERROR, "unrecognized table_tuple_delete status: %u",
1647  result);
1648  return NULL;
1649  }
1650 
1651  /*
1652  * Note: Normally one would think that we have to delete index tuples
1653  * associated with the heap tuple now...
1654  *
1655  * ... but in POSTGRES, we have no need to do this because VACUUM will
1656  * take care of it later. We can't delete index tuples immediately
1657  * anyway, since the tuple is still visible to other transactions.
1658  */
1659  }
1660 
1661  if (canSetTag)
1662  (estate->es_processed)++;
1663 
1664  /* Tell caller that the delete actually happened. */
1665  if (tupleDeleted)
1666  *tupleDeleted = true;
1667 
1668  ExecDeleteEpilogue(context, resultRelInfo, tupleid, oldtuple, changingPart);
1669 
1670  /* Process RETURNING if present and if requested */
1671  if (processReturning && resultRelInfo->ri_projectReturning)
1672  {
1673  /*
1674  * We have to put the target tuple into a slot, which means first we
1675  * gotta fetch it. We can use the trigger tuple slot.
1676  */
1677  TupleTableSlot *rslot;
1678 
1679  if (resultRelInfo->ri_FdwRoutine)
1680  {
1681  /* FDW must have provided a slot containing the deleted row */
1682  Assert(!TupIsNull(slot));
1683  }
1684  else
1685  {
1686  slot = ExecGetReturningSlot(estate, resultRelInfo);
1687  if (oldtuple != NULL)
1688  {
1689  ExecForceStoreHeapTuple(oldtuple, slot, false);
1690  }
1691  else
1692  {
1693  if (!table_tuple_fetch_row_version(resultRelationDesc, tupleid,
1694  SnapshotAny, slot))
1695  elog(ERROR, "failed to fetch deleted tuple for DELETE RETURNING");
1696  }
1697  }
1698 
1699  rslot = ExecProcessReturning(resultRelInfo, slot, context->planSlot);
1700 
1701  /*
1702  * Before releasing the target tuple again, make sure rslot has a
1703  * local copy of any pass-by-reference values.
1704  */
1705  ExecMaterializeSlot(rslot);
1706 
1707  ExecClearTuple(slot);
1708 
1709  return rslot;
1710  }
1711 
1712  return NULL;
1713 }
void EvalPlanQualBegin(EPQState *epqstate)
Definition: execMain.c:2775
TupleTableSlot * EvalPlanQual(EPQState *epqstate, Relation relation, Index rti, TupleTableSlot *inputslot)
Definition: execMain.c:2494
TupleTableSlot * EvalPlanQualSlot(EPQState *epqstate, Relation relation, Index rti)
Definition: execMain.c:2622
TupleTableSlot * ExecStoreAllNullTuple(TupleTableSlot *slot)
Definition: execTuples.c:1575
void ExecForceStoreHeapTuple(HeapTuple tuple, TupleTableSlot *slot, bool shouldFree)
Definition: execTuples.c:1468
TupleTableSlot * ExecGetReturningSlot(EState *estate, ResultRelInfo *relInfo)
Definition: execUtils.c:1187
@ LockWaitBlock
Definition: lockoptions.h:39
@ LockTupleExclusive
Definition: lockoptions.h:58
static bool ExecDeletePrologue(ModifyTableContext *context, ResultRelInfo *resultRelInfo, ItemPointer tupleid, HeapTuple oldtuple, TupleTableSlot **epqreturnslot, TM_Result *result)
static TM_Result ExecDeleteAct(ModifyTableContext *context, ResultRelInfo *resultRelInfo, ItemPointer tupleid, bool changingPart)
static TupleTableSlot * ExecProcessReturning(ResultRelInfo *resultRelInfo, TupleTableSlot *tupleSlot, TupleTableSlot *planSlot)
static void ExecDeleteEpilogue(ModifyTableContext *context, ResultRelInfo *resultRelInfo, ItemPointer tupleid, HeapTuple oldtuple, bool changingPart)
CommandId es_output_cid
Definition: execnodes.h:637
ExecForeignDelete_function ExecForeignDelete
Definition: fdwapi.h:236
TM_FailureData tmfd
TupleTableSlot * planSlot
Index ri_RangeTableIndex
Definition: execnodes.h:453
ProjectionInfo * ri_projectReturning
Definition: execnodes.h:539
bool traversed
Definition: tableam.h:145
CommandId cmax
Definition: tableam.h:144
bool trig_delete_instead_row
Definition: reltrigger.h:68
TM_Result
Definition: tableam.h:72
@ TM_Deleted
Definition: tableam.h:92
@ TM_Updated
Definition: tableam.h:89
@ TM_SelfModified
Definition: tableam.h:83
static TM_Result table_tuple_lock(Relation rel, ItemPointer tid, Snapshot snapshot, TupleTableSlot *slot, CommandId cid, LockTupleMode mode, LockWaitPolicy wait_policy, uint8 flags, TM_FailureData *tmfd)
Definition: tableam.h:1575
#define TUPLE_LOCK_FLAG_FIND_LAST_VERSION
Definition: tableam.h:260
bool ExecIRDeleteTriggers(EState *estate, ResultRelInfo *relinfo, HeapTuple trigtuple)
Definition: trigger.c:2818
#define TTS_EMPTY(slot)
Definition: tuptable.h:96

References Assert(), TM_FailureData::cmax, elog(), ModifyTableContext::epqstate, ereport, errcode(), ERRCODE_T_R_SERIALIZATION_FAILURE, errhint(), errmsg(), ERROR, EState::es_output_cid, EState::es_processed, EState::es_snapshot, ModifyTableContext::estate, EvalPlanQual(), EvalPlanQualBegin(), EvalPlanQualSlot(), ExecClearTuple(), ExecDeleteAct(), ExecDeleteEpilogue(), ExecDeletePrologue(), ExecForceStoreHeapTuple(), FdwRoutine::ExecForeignDelete, ExecGetReturningSlot(), ExecIRDeleteTriggers(), ExecMaterializeSlot(), ExecProcessReturning(), ExecStoreAllNullTuple(), IsolationUsesXactSnapshot, LockTupleExclusive, LockWaitBlock, ModifyTableContext::planSlot, RelationGetRelid, ResultRelInfo::ri_FdwRoutine, ResultRelInfo::ri_projectReturning, ResultRelInfo::ri_RangeTableIndex, ResultRelInfo::ri_RelationDesc, ResultRelInfo::ri_TrigDesc, SnapshotAny, table_tuple_fetch_row_version(), table_tuple_lock(), TM_Deleted, TM_Ok, TM_SelfModified, TM_Updated, ModifyTableContext::tmfd, TM_FailureData::traversed, TriggerDesc::trig_delete_instead_row, TTS_EMPTY, TupleTableSlot::tts_tableOid, TupIsNull, and TUPLE_LOCK_FLAG_FIND_LAST_VERSION.

Referenced by ExecCrossPartitionUpdate(), and ExecModifyTable().

◆ ExecDeleteAct()

static TM_Result ExecDeleteAct ( ModifyTableContext context,
ResultRelInfo resultRelInfo,
ItemPointer  tupleid,
bool  changingPart 
)
static

Definition at line 1341 of file nodeModifyTable.c.

1343 {
1344  EState *estate = context->estate;
1345 
1346  return table_tuple_delete(resultRelInfo->ri_RelationDesc, tupleid,
1347  estate->es_output_cid,
1348  estate->es_snapshot,
1349  estate->es_crosscheck_snapshot,
1350  true /* wait for commit */ ,
1351  &context->tmfd,
1352  changingPart);
1353 }
Snapshot es_crosscheck_snapshot
Definition: execnodes.h:623
static TM_Result table_tuple_delete(Relation rel, ItemPointer tid, CommandId cid, Snapshot snapshot, Snapshot crosscheck, bool wait, TM_FailureData *tmfd, bool changingPart)
Definition: tableam.h:1486

References EState::es_crosscheck_snapshot, EState::es_output_cid, EState::es_snapshot, ModifyTableContext::estate, ResultRelInfo::ri_RelationDesc, table_tuple_delete(), and ModifyTableContext::tmfd.

Referenced by ExecDelete(), and ExecMergeMatched().

◆ ExecDeleteEpilogue()

static void ExecDeleteEpilogue ( ModifyTableContext context,
ResultRelInfo resultRelInfo,
ItemPointer  tupleid,
HeapTuple  oldtuple,
bool  changingPart 
)
static

Definition at line 1363 of file nodeModifyTable.c.

1365 {
1366  ModifyTableState *mtstate = context->mtstate;
1367  EState *estate = context->estate;
1368  TransitionCaptureState *ar_delete_trig_tcs;
1369 
1370  /*
1371  * If this delete is the result of a partition key update that moved the
1372  * tuple to a new partition, put this row into the transition OLD TABLE,
1373  * if there is one. We need to do this separately for DELETE and INSERT
1374  * because they happen on different tables.
1375  */
1376  ar_delete_trig_tcs = mtstate->mt_transition_capture;
1377  if (mtstate->operation == CMD_UPDATE && mtstate->mt_transition_capture &&
1379  {
1380  ExecARUpdateTriggers(estate, resultRelInfo,
1381  NULL, NULL,
1382  tupleid, oldtuple,
1383  NULL, NULL, mtstate->mt_transition_capture,
1384  false);
1385 
1386  /*
1387  * We've already captured the OLD TABLE row, so make sure any AR
1388  * DELETE trigger fired below doesn't capture it again.
1389  */
1390  ar_delete_trig_tcs = NULL;
1391  }
1392 
1393  /* AFTER ROW DELETE Triggers */
1394  ExecARDeleteTriggers(estate, resultRelInfo, tupleid, oldtuple,
1395  ar_delete_trig_tcs, changingPart);
1396 }
CmdType operation
Definition: execnodes.h:1282
void ExecARDeleteTriggers(EState *estate, ResultRelInfo *relinfo, ItemPointer tupleid, HeapTuple fdw_trigtuple, TransitionCaptureState *transition_capture, bool is_crosspart_update)
Definition: trigger.c:2781

References CMD_UPDATE, ModifyTableContext::estate, ExecARDeleteTriggers(), ExecARUpdateTriggers(), ModifyTableState::mt_transition_capture, ModifyTableContext::mtstate, ModifyTableState::operation, and TransitionCaptureState::tcs_update_old_table.

Referenced by ExecDelete(), and ExecMergeMatched().

◆ ExecDeletePrologue()

static bool ExecDeletePrologue ( ModifyTableContext context,
ResultRelInfo resultRelInfo,
ItemPointer  tupleid,
HeapTuple  oldtuple,
TupleTableSlot **  epqreturnslot,
TM_Result result 
)
static

Definition at line 1310 of file nodeModifyTable.c.

1313 {
1314  if (result)
1315  *result = TM_Ok;
1316 
1317  /* BEFORE ROW DELETE triggers */
1318  if (resultRelInfo->ri_TrigDesc &&
1319  resultRelInfo->ri_TrigDesc->trig_delete_before_row)
1320  {
1321  /* Flush any pending inserts, so rows are visible to the triggers */
1323  ExecPendingInserts(context->estate);
1324 
1325  return ExecBRDeleteTriggers(context->estate, context->epqstate,
1326  resultRelInfo, tupleid, oldtuple,
1327  epqreturnslot, result, &context->tmfd);
1328  }
1329 
1330  return true;
1331 }
static void ExecPendingInserts(EState *estate)
List * es_insert_pending_result_relations
Definition: execnodes.h:721
bool trig_delete_before_row
Definition: reltrigger.h:66
bool ExecBRDeleteTriggers(EState *estate, EPQState *epqstate, ResultRelInfo *relinfo, ItemPointer tupleid, HeapTuple fdw_trigtuple, TupleTableSlot **epqslot, TM_Result *tmresult, TM_FailureData *tmfd)
Definition: trigger.c:2690

References ModifyTableContext::epqstate, EState::es_insert_pending_result_relations, ModifyTableContext::estate, ExecBRDeleteTriggers(), ExecPendingInserts(), NIL, ResultRelInfo::ri_TrigDesc, TM_Ok, ModifyTableContext::tmfd, and TriggerDesc::trig_delete_before_row.

Referenced by ExecDelete(), and ExecMergeMatched().

◆ ExecEndModifyTable()

void ExecEndModifyTable ( ModifyTableState node)

Definition at line 4428 of file nodeModifyTable.c.

4429 {
4430  int i;
4431 
4432  /*
4433  * Allow any FDWs to shut down
4434  */
4435  for (i = 0; i < node->mt_nrels; i++)
4436  {
4437  int j;
4438  ResultRelInfo *resultRelInfo = node->resultRelInfo + i;
4439 
4440  if (!resultRelInfo->ri_usesFdwDirectModify &&
4441  resultRelInfo->ri_FdwRoutine != NULL &&
4442  resultRelInfo->ri_FdwRoutine->EndForeignModify != NULL)
4443  resultRelInfo->ri_FdwRoutine->EndForeignModify(node->ps.state,
4444  resultRelInfo);
4445 
4446  /*
4447  * Cleanup the initialized batch slots. This only matters for FDWs
4448  * with batching, but the other cases will have ri_NumSlotsInitialized
4449  * == 0.
4450  */
4451  for (j = 0; j < resultRelInfo->ri_NumSlotsInitialized; j++)
4452  {
4453  ExecDropSingleTupleTableSlot(resultRelInfo->ri_Slots[j]);
4454  ExecDropSingleTupleTableSlot(resultRelInfo->ri_PlanSlots[j]);
4455  }
4456  }
4457 
4458  /*
4459  * Close all the partitioned tables, leaf partitions, and their indices
4460  * and release the slot used for tuple routing, if set.
4461  */
4462  if (node->mt_partition_tuple_routing)
4463  {
4465 
4466  if (node->mt_root_tuple_slot)
4468  }
4469 
4470  /*
4471  * Terminate EPQ execution if active
4472  */
4473  EvalPlanQualEnd(&node->mt_epqstate);
4474 
4475  /*
4476  * shut down subplan
4477  */
4478  ExecEndNode(outerPlanState(node));
4479 }
void EvalPlanQualEnd(EPQState *epqstate)
Definition: execMain.c:3006
void ExecCleanupTupleRouting(ModifyTableState *mtstate, PartitionTupleRouting *proute)
void ExecEndNode(PlanState *node)
Definition: execProcnode.c:557
void ExecDropSingleTupleTableSlot(TupleTableSlot *slot)
Definition: execTuples.c:1253
#define outerPlanState(node)
Definition: execnodes.h:1139
int j
Definition: isn.c:74
EndForeignModify_function EndForeignModify
Definition: fdwapi.h:237
ResultRelInfo * resultRelInfo
Definition: execnodes.h:1286
EPQState mt_epqstate
Definition: execnodes.h:1296
TupleTableSlot ** ri_Slots
Definition: execnodes.h:515
int ri_NumSlotsInitialized
Definition: execnodes.h:513
TupleTableSlot ** ri_PlanSlots
Definition: execnodes.h:516
bool ri_usesFdwDirectModify
Definition: execnodes.h:509

References FdwRoutine::EndForeignModify, EvalPlanQualEnd(), ExecCleanupTupleRouting(), ExecDropSingleTupleTableSlot(), ExecEndNode(), i, j, ModifyTableState::mt_epqstate, ModifyTableState::mt_nrels, ModifyTableState::mt_partition_tuple_routing, ModifyTableState::mt_root_tuple_slot, outerPlanState, ModifyTableState::ps, ModifyTableState::resultRelInfo, ResultRelInfo::ri_FdwRoutine, ResultRelInfo::ri_NumSlotsInitialized, ResultRelInfo::ri_PlanSlots, ResultRelInfo::ri_Slots, ResultRelInfo::ri_usesFdwDirectModify, and PlanState::state.

Referenced by ExecEndNode().

◆ ExecGetInsertNewTuple()

static TupleTableSlot* ExecGetInsertNewTuple ( ResultRelInfo relinfo,
TupleTableSlot planSlot 
)
static

Definition at line 670 of file nodeModifyTable.c.

672 {
673  ProjectionInfo *newProj = relinfo->ri_projectNew;
674  ExprContext *econtext;
675 
676  /*
677  * If there's no projection to be done, just make sure the slot is of the
678  * right type for the target rel. If the planSlot is the right type we
679  * can use it as-is, else copy the data into ri_newTupleSlot.
680  */
681  if (newProj == NULL)
682  {
683  if (relinfo->ri_newTupleSlot->tts_ops != planSlot->tts_ops)
684  {
685  ExecCopySlot(relinfo->ri_newTupleSlot, planSlot);
686  return relinfo->ri_newTupleSlot;
687  }
688  else
689  return planSlot;
690  }
691 
692  /*
693  * Else project; since the projection output slot is ri_newTupleSlot, this
694  * will also fix any slot-type problem.
695  *
696  * Note: currently, this is dead code, because INSERT cases don't receive
697  * any junk columns so there's never a projection to be done.
698  */
699  econtext = newProj->pi_exprContext;
700  econtext->ecxt_outertuple = planSlot;
701  return ExecProject(newProj);
702 }
static TupleTableSlot * ExecProject(ProjectionInfo *projInfo)
Definition: executor.h:375
TupleTableSlot * ecxt_outertuple
Definition: execnodes.h:259
ExprContext * pi_exprContext
Definition: execnodes.h:364
TupleTableSlot * ri_newTupleSlot
Definition: execnodes.h:479
ProjectionInfo * ri_projectNew
Definition: execnodes.h:477
const TupleTableSlotOps *const tts_ops
Definition: tuptable.h:121
static TupleTableSlot * ExecCopySlot(TupleTableSlot *dstslot, TupleTableSlot *srcslot)
Definition: tuptable.h:488

References ExprContext::ecxt_outertuple, ExecCopySlot(), ExecProject(), ProjectionInfo::pi_exprContext, ResultRelInfo::ri_newTupleSlot, ResultRelInfo::ri_projectNew, and TupleTableSlot::tts_ops.

Referenced by ExecModifyTable().

◆ ExecGetUpdateNewTuple()

TupleTableSlot* ExecGetUpdateNewTuple ( ResultRelInfo relinfo,
TupleTableSlot planSlot,
TupleTableSlot oldSlot 
)

Definition at line 714 of file nodeModifyTable.c.

717 {
718  ProjectionInfo *newProj = relinfo->ri_projectNew;
719  ExprContext *econtext;
720 
721  /* Use a few extra Asserts to protect against outside callers */
722  Assert(relinfo->ri_projectNewInfoValid);
723  Assert(planSlot != NULL && !TTS_EMPTY(planSlot));
724  Assert(oldSlot != NULL && !TTS_EMPTY(oldSlot));
725 
726  econtext = newProj->pi_exprContext;
727  econtext->ecxt_outertuple = planSlot;
728  econtext->ecxt_scantuple = oldSlot;
729  return ExecProject(newProj);
730 }

References Assert(), ExprContext::ecxt_outertuple, ExprContext::ecxt_scantuple, ExecProject(), ProjectionInfo::pi_exprContext, ResultRelInfo::ri_projectNew, ResultRelInfo::ri_projectNewInfoValid, and TTS_EMPTY.

Referenced by ExecBRUpdateTriggers(), ExecCrossPartitionUpdate(), ExecModifyTable(), and ExecUpdate().

◆ ExecInitInsertProjection()

static void ExecInitInsertProjection ( ModifyTableState mtstate,
ResultRelInfo resultRelInfo 
)
static

Definition at line 542 of file nodeModifyTable.c.

544 {
545  ModifyTable *node = (ModifyTable *) mtstate->ps.plan;
546  Plan *subplan = outerPlan(node);
547  EState *estate = mtstate->ps.state;
548  List *insertTargetList = NIL;
549  bool need_projection = false;
550  ListCell *l;
551 
552  /* Extract non-junk columns of the subplan's result tlist. */
553  foreach(l, subplan->targetlist)
554  {
555  TargetEntry *tle = (TargetEntry *) lfirst(l);
556 
557  if (!tle->resjunk)
558  insertTargetList = lappend(insertTargetList, tle);
559  else
560  need_projection = true;
561  }
562 
563  /*
564  * The junk-free list must produce a tuple suitable for the result
565  * relation.
566  */
567  ExecCheckPlanOutput(resultRelInfo->ri_RelationDesc, insertTargetList);
568 
569  /* We'll need a slot matching the table's format. */
570  resultRelInfo->ri_newTupleSlot =
571  table_slot_create(resultRelInfo->ri_RelationDesc,
572  &estate->es_tupleTable);
573 
574  /* Build ProjectionInfo if needed (it probably isn't). */
575  if (need_projection)
576  {
577  TupleDesc relDesc = RelationGetDescr(resultRelInfo->ri_RelationDesc);
578 
579  /* need an expression context to do the projection */
580  if (mtstate->ps.ps_ExprContext == NULL)
581  ExecAssignExprContext(estate, &mtstate->ps);
582 
583  resultRelInfo->ri_projectNew =
584  ExecBuildProjectionInfo(insertTargetList,
585  mtstate->ps.ps_ExprContext,
586  resultRelInfo->ri_newTupleSlot,
587  &mtstate->ps,
588  relDesc);
589  }
590 
591  resultRelInfo->ri_projectNewInfoValid = true;
592 }
ProjectionInfo * ExecBuildProjectionInfo(List *targetList, ExprContext *econtext, TupleTableSlot *slot, PlanState *parent, TupleDesc inputDesc)
Definition: execExpr.c:355
void ExecAssignExprContext(EState *estate, PlanState *planstate)
Definition: execUtils.c:488
List * lappend(List *list, void *datum)
Definition: list.c:339
static void ExecCheckPlanOutput(Relation resultRel, List *targetList)
#define outerPlan(node)
Definition: plannodes.h:182
List * es_tupleTable
Definition: execnodes.h:667
ExprContext * ps_ExprContext
Definition: execnodes.h:1082

References EState::es_tupleTable, ExecAssignExprContext(), ExecBuildProjectionInfo(), ExecCheckPlanOutput(), lappend(), lfirst, NIL, outerPlan, PlanState::plan, ModifyTableState::ps, PlanState::ps_ExprContext, RelationGetDescr, ResultRelInfo::ri_newTupleSlot, ResultRelInfo::ri_projectNew, ResultRelInfo::ri_projectNewInfoValid, ResultRelInfo::ri_RelationDesc, PlanState::state, and table_slot_create().

Referenced by ExecModifyTable().

◆ ExecInitMerge()

void ExecInitMerge ( ModifyTableState mtstate,
EState estate 
)
static

Definition at line 3214 of file nodeModifyTable.c.

3215 {
3216  ModifyTable *node = (ModifyTable *) mtstate->ps.plan;
3217  ResultRelInfo *rootRelInfo = mtstate->rootResultRelInfo;
3218  ResultRelInfo *resultRelInfo;
3219  ExprContext *econtext;
3220  ListCell *lc;
3221  int i;
3222 
3223  if (node->mergeActionLists == NIL)
3224  return;
3225 
3226  mtstate->mt_merge_subcommands = 0;
3227 
3228  if (mtstate->ps.ps_ExprContext == NULL)
3229  ExecAssignExprContext(estate, &mtstate->ps);
3230  econtext = mtstate->ps.ps_ExprContext;
3231 
3232  /*
3233  * Create a MergeActionState for each action on the mergeActionList and
3234  * add it to either a list of matched actions or not-matched actions.
3235  *
3236  * Similar logic appears in ExecInitPartitionInfo(), so if changing
3237  * anything here, do so there too.
3238  */
3239  i = 0;
3240  foreach(lc, node->mergeActionLists)
3241  {
3242  List *mergeActionList = lfirst(lc);
3243  TupleDesc relationDesc;
3244  ListCell *l;
3245 
3246  resultRelInfo = mtstate->resultRelInfo + i;
3247  i++;
3248  relationDesc = RelationGetDescr(resultRelInfo->ri_RelationDesc);
3249 
3250  /* initialize slots for MERGE fetches from this rel */
3251  if (unlikely(!resultRelInfo->ri_projectNewInfoValid))
3252  ExecInitMergeTupleSlots(mtstate, resultRelInfo);
3253 
3254  foreach(l, mergeActionList)
3255  {
3257  MergeActionState *action_state;
3258  TupleTableSlot *tgtslot;
3259  TupleDesc tgtdesc;
3260  List **list;
3261 
3262  /*
3263  * Build action merge state for this rel. (For partitions,
3264  * equivalent code exists in ExecInitPartitionInfo.)
3265  */
3266  action_state = makeNode(MergeActionState);
3267  action_state->mas_action = action;
3268  action_state->mas_whenqual = ExecInitQual((List *) action->qual,
3269  &mtstate->ps);
3270 
3271  /*
3272  * We create two lists - one for WHEN MATCHED actions and one for
3273  * WHEN NOT MATCHED actions - and stick the MergeActionState into
3274  * the appropriate list.
3275  */
3276  if (action_state->mas_action->matched)
3277  list = &resultRelInfo->ri_matchedMergeAction;
3278  else
3279  list = &resultRelInfo->ri_notMatchedMergeAction;
3280  *list = lappend(*list, action_state);
3281 
3282  switch (action->commandType)
3283  {
3284  case CMD_INSERT:
3285  ExecCheckPlanOutput(rootRelInfo->ri_RelationDesc,
3286  action->targetList);
3287 
3288  /*
3289  * If the MERGE targets a partitioned table, any INSERT
3290  * actions must be routed through it, not the child
3291  * relations. Initialize the routing struct and the root
3292  * table's "new" tuple slot for that, if not already done.
3293  * The projection we prepare, for all relations, uses the
3294  * root relation descriptor, and targets the plan's root
3295  * slot. (This is consistent with the fact that we
3296  * checked the plan output to match the root relation,
3297  * above.)
3298  */
3299  if (rootRelInfo->ri_RelationDesc->rd_rel->relkind ==
3300  RELKIND_PARTITIONED_TABLE)
3301  {
3302  if (mtstate->mt_partition_tuple_routing == NULL)
3303  {
3304  /*
3305  * Initialize planstate for routing if not already
3306  * done.
3307  *
3308  * Note that the slot is managed as a standalone
3309  * slot belonging to ModifyTableState, so we pass
3310  * NULL for the 2nd argument.
3311  */
3312  mtstate->mt_root_tuple_slot =
3313  table_slot_create(rootRelInfo->ri_RelationDesc,
3314  NULL);
3315  mtstate->mt_partition_tuple_routing =
3317  rootRelInfo->ri_RelationDesc);
3318  }
3319  tgtslot = mtstate->mt_root_tuple_slot;
3320  tgtdesc = RelationGetDescr(rootRelInfo->ri_RelationDesc);
3321  }
3322  else
3323  {
3324  /* not partitioned? use the stock relation and slot */
3325  tgtslot = resultRelInfo->ri_newTupleSlot;
3326  tgtdesc = RelationGetDescr(resultRelInfo->ri_RelationDesc);
3327  }
3328 
3329  action_state->mas_proj =
3330  ExecBuildProjectionInfo(action->targetList, econtext,
3331  tgtslot,
3332  &mtstate->ps,
3333  tgtdesc);
3334 
3335  mtstate->mt_merge_subcommands |= MERGE_INSERT;
3336  break;
3337  case CMD_UPDATE:
3338  action_state->mas_proj =
3339  ExecBuildUpdateProjection(action->targetList,
3340  true,
3341  action->updateColnos,
3342  relationDesc,
3343  econtext,
3344  resultRelInfo->ri_newTupleSlot,
3345  &mtstate->ps);
3346  mtstate->mt_merge_subcommands |= MERGE_UPDATE;
3347  break;
3348  case CMD_DELETE:
3349  mtstate->mt_merge_subcommands |= MERGE_DELETE;
3350  break;
3351  case CMD_NOTHING:
3352  break;
3353  default:
3354  elog(ERROR, "unknown operation");
3355  break;
3356  }
3357  }
3358  }
3359 }
ProjectionInfo * ExecBuildUpdateProjection(List *targetList, bool evalTargetList, List *targetColnos, TupleDesc relDesc, ExprContext *econtext, TupleTableSlot *slot, PlanState *parent)
Definition: execExpr.c:515
ExprState * ExecInitQual(List *qual, PlanState *parent)
Definition: execExpr.c:214
#define MERGE_UPDATE
Definition: execnodes.h:1272
#define MERGE_INSERT
Definition: execnodes.h:1271
#define MERGE_DELETE
Definition: execnodes.h:1273
if(TABLE==NULL||TABLE_index==NULL)
Definition: isn.c:77
void ExecInitMergeTupleSlots(ModifyTableState *mtstate, ResultRelInfo *resultRelInfo)
@ CMD_INSERT
Definition: nodes.h:257
@ CMD_DELETE
Definition: nodes.h:258
@ CMD_NOTHING
Definition: nodes.h:262
#define makeNode(_type_)
Definition: nodes.h:155
MergeAction * mas_action
Definition: execnodes.h:425
ProjectionInfo * mas_proj
Definition: execnodes.h:426
ExprState * mas_whenqual
Definition: execnodes.h:428
bool matched
Definition: primnodes.h:1738
int mt_merge_subcommands
Definition: execnodes.h:1326
List * mergeActionLists
Definition: plannodes.h:252

References generate_unaccent_rules::action, CMD_DELETE, CMD_INSERT, CMD_NOTHING, CMD_UPDATE, elog(), ERROR, ExecAssignExprContext(), ExecBuildProjectionInfo(), ExecBuildUpdateProjection(), ExecCheckPlanOutput(), ExecInitMergeTupleSlots(), ExecInitQual(), ExecSetupPartitionTupleRouting(), i, if(), lappend(), lfirst, sort-test::list, makeNode, MergeActionState::mas_action, MergeActionState::mas_proj, MergeActionState::mas_whenqual, MergeAction::matched, MERGE_DELETE, MERGE_INSERT, MERGE_UPDATE, ModifyTable::mergeActionLists, ModifyTableState::mt_merge_subcommands, ModifyTableState::mt_partition_tuple_routing, ModifyTableState::mt_root_tuple_slot, NIL, PlanState::plan, ModifyTableState::ps, PlanState::ps_ExprContext, RelationGetDescr, ModifyTableState::resultRelInfo, ModifyTableState::rootResultRelInfo, table_slot_create(), and unlikely.

Referenced by ExecInitModifyTable().

◆ ExecInitMergeTupleSlots()

void ExecInitMergeTupleSlots ( ModifyTableState mtstate,
ResultRelInfo resultRelInfo 
)

Definition at line 3368 of file nodeModifyTable.c.

3370 {
3371  EState *estate = mtstate->ps.state;
3372 
3373  Assert(!resultRelInfo->ri_projectNewInfoValid);
3374 
3375  resultRelInfo->ri_oldTupleSlot =
3376  table_slot_create(resultRelInfo->ri_RelationDesc,
3377  &estate->es_tupleTable);
3378  resultRelInfo->ri_newTupleSlot =
3379  table_slot_create(resultRelInfo->ri_RelationDesc,
3380  &estate->es_tupleTable);
3381  resultRelInfo->ri_projectNewInfoValid = true;
3382 }

References Assert(), EState::es_tupleTable, ModifyTableState::ps, ResultRelInfo::ri_newTupleSlot, ResultRelInfo::ri_oldTupleSlot, ResultRelInfo::ri_projectNewInfoValid, ResultRelInfo::ri_RelationDesc, PlanState::state, and table_slot_create().

Referenced by ExecInitMerge(), and ExecInitPartitionInfo().

◆ ExecInitModifyTable()

ModifyTableState* ExecInitModifyTable ( ModifyTable node,
EState estate,
int  eflags 
)

Definition at line 3946 of file nodeModifyTable.c.

3947 {
3948  ModifyTableState *mtstate;
3949  Plan *subplan = outerPlan(node);
3950  CmdType operation = node->operation;
3951  int nrels = list_length(node->resultRelations);
3952  ResultRelInfo *resultRelInfo;
3953  List *arowmarks;
3954  ListCell *l;
3955  int i;
3956  Relation rel;
3957 
3958  /* check for unsupported flags */
3959  Assert(!(eflags & (EXEC_FLAG_BACKWARD | EXEC_FLAG_MARK)));
3960 
3961  /*
3962  * create state structure
3963  */
3964  mtstate = makeNode(ModifyTableState);
3965  mtstate->ps.plan = (Plan *) node;
3966  mtstate->ps.state = estate;
3967  mtstate->ps.ExecProcNode = ExecModifyTable;
3968 
3969  mtstate->operation = operation;
3970  mtstate->canSetTag = node->canSetTag;
3971  mtstate->mt_done = false;
3972 
3973  mtstate->mt_nrels = nrels;
3974  mtstate->resultRelInfo = (ResultRelInfo *)
3975  palloc(nrels * sizeof(ResultRelInfo));
3976 
3977  mtstate->mt_merge_inserted = 0;
3978  mtstate->mt_merge_updated = 0;
3979  mtstate->mt_merge_deleted = 0;
3980 
3981  /*----------
3982  * Resolve the target relation. This is the same as:
3983  *
3984  * - the relation for which we will fire FOR STATEMENT triggers,
3985  * - the relation into whose tuple format all captured transition tuples
3986  * must be converted, and
3987  * - the root partitioned table used for tuple routing.
3988  *
3989  * If it's a partitioned or inherited table, the root partition or
3990  * appendrel RTE doesn't appear elsewhere in the plan and its RT index is
3991  * given explicitly in node->rootRelation. Otherwise, the target relation
3992  * is the sole relation in the node->resultRelations list.
3993  *----------
3994  */
3995  if (node->rootRelation > 0)
3996  {
3998  ExecInitResultRelation(estate, mtstate->rootResultRelInfo,
3999  node->rootRelation);
4000  }
4001  else
4002  {
4003  Assert(list_length(node->resultRelations) == 1);
4004  mtstate->rootResultRelInfo = mtstate->resultRelInfo;
4005  ExecInitResultRelation(estate, mtstate->resultRelInfo,
4006  linitial_int(node->resultRelations));
4007  }
4008 
4009  /* set up epqstate with dummy subplan data for the moment */
4010  EvalPlanQualInit(&mtstate->mt_epqstate, estate, NULL, NIL,
4011  node->epqParam, node->resultRelations);
4012  mtstate->fireBSTriggers = true;
4013 
4014  /*
4015  * Build state for collecting transition tuples. This requires having a
4016  * valid trigger query context, so skip it in explain-only mode.
4017  */
4018  if (!(eflags & EXEC_FLAG_EXPLAIN_ONLY))
4019  ExecSetupTransitionCaptureState(mtstate, estate);
4020 
4021  /*
4022  * Open all the result relations and initialize the ResultRelInfo structs.
4023  * (But root relation was initialized above, if it's part of the array.)
4024  * We must do this before initializing the subplan, because direct-modify
4025  * FDWs expect their ResultRelInfos to be available.
4026  */
4027  resultRelInfo = mtstate->resultRelInfo;
4028  i = 0;
4029  foreach(l, node->resultRelations)
4030  {
4031  Index resultRelation = lfirst_int(l);
4032 
4033  if (resultRelInfo != mtstate->rootResultRelInfo)
4034  {
4035  ExecInitResultRelation(estate, resultRelInfo, resultRelation);
4036 
4037  /*
4038  * For child result relations, store the root result relation
4039  * pointer. We do so for the convenience of places that want to
4040  * look at the query's original target relation but don't have the
4041  * mtstate handy.
4042  */
4043  resultRelInfo->ri_RootResultRelInfo = mtstate->rootResultRelInfo;
4044  }
4045 
4046  /* Initialize the usesFdwDirectModify flag */
4047  resultRelInfo->ri_usesFdwDirectModify =
4049 
4050  /*
4051  * Verify result relation is a valid target for the current operation
4052  */
4053  CheckValidResultRel(resultRelInfo, operation);
4054 
4055  resultRelInfo++;
4056  i++;
4057  }
4058 
4059  /*
4060  * Now we may initialize the subplan.
4061  */
4062  outerPlanState(mtstate) = ExecInitNode(subplan, estate, eflags);
4063 
4064  /*
4065  * Do additional per-result-relation initialization.
4066  */
4067  for (i = 0; i < nrels; i++)
4068  {
4069  resultRelInfo = &mtstate->resultRelInfo[i];
4070 
4071  /* Let FDWs init themselves for foreign-table result rels */
4072  if (!resultRelInfo->ri_usesFdwDirectModify &&
4073  resultRelInfo->ri_FdwRoutine != NULL &&
4074  resultRelInfo->ri_FdwRoutine->BeginForeignModify != NULL)
4075  {
4076  List *fdw_private = (List *) list_nth(node->fdwPrivLists, i);
4077 
4078  resultRelInfo->ri_FdwRoutine->BeginForeignModify(mtstate,
4079  resultRelInfo,
4080  fdw_private,
4081  i,
4082  eflags);
4083  }
4084 
4085  /*
4086  * For UPDATE/DELETE/MERGE, find the appropriate junk attr now, either
4087  * a 'ctid' or 'wholerow' attribute depending on relkind. For foreign
4088  * tables, the FDW might have created additional junk attr(s), but
4089  * those are no concern of ours.
4090  */
4091  if (operation == CMD_UPDATE || operation == CMD_DELETE ||
4092  operation == CMD_MERGE)
4093  {
4094  char relkind;
4095 
4096  relkind = resultRelInfo->ri_RelationDesc->rd_rel->relkind;
4097  if (relkind == RELKIND_RELATION ||
4098  relkind == RELKIND_MATVIEW ||
4099  relkind == RELKIND_PARTITIONED_TABLE)
4100  {
4101  resultRelInfo->ri_RowIdAttNo =
4102  ExecFindJunkAttributeInTlist(subplan->targetlist, "ctid");
4103  if (!AttributeNumberIsValid(resultRelInfo->ri_RowIdAttNo))
4104  elog(ERROR, "could not find junk ctid column");
4105  }
4106  else if (relkind == RELKIND_FOREIGN_TABLE)
4107  {
4108  /*
4109  * We don't support MERGE with foreign tables for now. (It's
4110  * problematic because the implementation uses CTID.)
4111  */
4112  Assert(operation != CMD_MERGE);
4113 
4114  /*
4115  * When there is a row-level trigger, there should be a
4116  * wholerow attribute. We also require it to be present in
4117  * UPDATE and MERGE, so we can get the values of unchanged
4118  * columns.
4119  */
4120  resultRelInfo->ri_RowIdAttNo =
4122  "wholerow");
4123  if ((mtstate->operation == CMD_UPDATE || mtstate->operation == CMD_MERGE) &&
4124  !AttributeNumberIsValid(resultRelInfo->ri_RowIdAttNo))
4125  elog(ERROR, "could not find junk wholerow column");
4126  }
4127  else
4128  {
4129  /* No support for MERGE */
4130  Assert(operation != CMD_MERGE);
4131  /* Other valid target relkinds must provide wholerow */
4132  resultRelInfo->ri_RowIdAttNo =
4134  "wholerow");
4135  if (!AttributeNumberIsValid(resultRelInfo->ri_RowIdAttNo))
4136  elog(ERROR, "could not find junk wholerow column");
4137  }
4138  }
4139  }
4140 
4141  /*
4142  * If this is an inherited update/delete/merge, there will be a junk
4143  * attribute named "tableoid" present in the subplan's targetlist. It
4144  * will be used to identify the result relation for a given tuple to be
4145  * updated/deleted/merged.
4146  */
4147  mtstate->mt_resultOidAttno =
4148  ExecFindJunkAttributeInTlist(subplan->targetlist, "tableoid");
4149  Assert(AttributeNumberIsValid(mtstate->mt_resultOidAttno) || nrels == 1);
4150  mtstate->mt_lastResultOid = InvalidOid; /* force lookup at first tuple */
4151  mtstate->mt_lastResultIndex = 0; /* must be zero if no such attr */
4152 
4153  /* Get the root target relation */
4154  rel = mtstate->rootResultRelInfo->ri_RelationDesc;
4155 
4156  /*
4157  * Build state for tuple routing if it's a partitioned INSERT. An UPDATE
4158  * or MERGE might need this too, but only if it actually moves tuples
4159  * between partitions; in that case setup is done by
4160  * ExecCrossPartitionUpdate.
4161  */
4162  if (rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE &&
4163  operation == CMD_INSERT)
4164  mtstate->mt_partition_tuple_routing =
4165  ExecSetupPartitionTupleRouting(estate, rel);
4166 
4167  /*
4168  * Initialize any WITH CHECK OPTION constraints if needed.
4169  */
4170  resultRelInfo = mtstate->resultRelInfo;
4171  foreach(l, node->withCheckOptionLists)
4172  {
4173  List *wcoList = (List *) lfirst(l);
4174  List *wcoExprs = NIL;
4175  ListCell *ll;
4176 
4177  foreach(ll, wcoList)
4178  {
4179  WithCheckOption *wco = (WithCheckOption *) lfirst(ll);
4180  ExprState *wcoExpr = ExecInitQual((List *) wco->qual,
4181  &mtstate->ps);
4182 
4183  wcoExprs = lappend(wcoExprs, wcoExpr);
4184  }
4185 
4186  resultRelInfo->ri_WithCheckOptions = wcoList;
4187  resultRelInfo->ri_WithCheckOptionExprs = wcoExprs;
4188  resultRelInfo++;
4189  }
4190 
4191  /*
4192  * Initialize RETURNING projections if needed.
4193  */
4194  if (node->returningLists)
4195  {
4196  TupleTableSlot *slot;
4197  ExprContext *econtext;
4198 
4199  /*
4200  * Initialize result tuple slot and assign its rowtype using the first
4201  * RETURNING list. We assume the rest will look the same.
4202  */
4203  mtstate->ps.plan->targetlist = (List *) linitial(node->returningLists);
4204 
4205  /* Set up a slot for the output of the RETURNING projection(s) */
4207  slot = mtstate->ps.ps_ResultTupleSlot;
4208 
4209  /* Need an econtext too */
4210  if (mtstate->ps.ps_ExprContext == NULL)
4211  ExecAssignExprContext(estate, &mtstate->ps);
4212  econtext = mtstate->ps.ps_ExprContext;
4213 
4214  /*
4215  * Build a projection for each result rel.
4216  */
4217  resultRelInfo = mtstate->resultRelInfo;
4218  foreach(l, node->returningLists)
4219  {
4220  List *rlist = (List *) lfirst(l);
4221 
4222  resultRelInfo->ri_returningList = rlist;
4223  resultRelInfo->ri_projectReturning =
4224  ExecBuildProjectionInfo(rlist, econtext, slot, &mtstate->ps,
4225  resultRelInfo->ri_RelationDesc->rd_att);
4226  resultRelInfo++;
4227  }
4228  }
4229  else
4230  {
4231  /*
4232  * We still must construct a dummy result tuple type, because InitPlan
4233  * expects one (maybe should change that?).
4234  */
4235  mtstate->ps.plan->targetlist = NIL;
4236  ExecInitResultTypeTL(&mtstate->ps);
4237 
4238  mtstate->ps.ps_ExprContext = NULL;
4239  }
4240 
4241  /* Set the list of arbiter indexes if needed for ON CONFLICT */
4242  resultRelInfo = mtstate->resultRelInfo;
4243  if (node->onConflictAction != ONCONFLICT_NONE)
4244  {
4245  /* insert may only have one relation, inheritance is not expanded */
4246  Assert(nrels == 1);
4247  resultRelInfo->ri_onConflictArbiterIndexes = node->arbiterIndexes;
4248  }
4249 
4250  /*
4251  * If needed, Initialize target list, projection and qual for ON CONFLICT
4252  * DO UPDATE.
4253  */
4254  if (node->onConflictAction == ONCONFLICT_UPDATE)
4255  {
4257  ExprContext *econtext;
4258  TupleDesc relationDesc;
4259 
4260  /* already exists if created by RETURNING processing above */
4261  if (mtstate->ps.ps_ExprContext == NULL)
4262  ExecAssignExprContext(estate, &mtstate->ps);
4263 
4264  econtext = mtstate->ps.ps_ExprContext;
4265  relationDesc = resultRelInfo->ri_RelationDesc->rd_att;
4266 
4267  /* create state for DO UPDATE SET operation */
4268  resultRelInfo->ri_onConflict = onconfl;
4269 
4270  /* initialize slot for the existing tuple */
4271  onconfl->oc_Existing =
4272  table_slot_create(resultRelInfo->ri_RelationDesc,
4273  &mtstate->ps.state->es_tupleTable);
4274 
4275  /*
4276  * Create the tuple slot for the UPDATE SET projection. We want a slot
4277  * of the table's type here, because the slot will be used to insert
4278  * into the table, and for RETURNING processing - which may access
4279  * system attributes.
4280  */
4281  onconfl->oc_ProjSlot =
4282  table_slot_create(resultRelInfo->ri_RelationDesc,
4283  &mtstate->ps.state->es_tupleTable);
4284 
4285  /* build UPDATE SET projection state */
4286  onconfl->oc_ProjInfo =
4288  true,
4289  node->onConflictCols,
4290  relationDesc,
4291  econtext,
4292  onconfl->oc_ProjSlot,
4293  &mtstate->ps);
4294 
4295  /* initialize state to evaluate the WHERE clause, if any */
4296  if (node->onConflictWhere)
4297  {
4298  ExprState *qualexpr;
4299 
4300  qualexpr = ExecInitQual((List *) node->onConflictWhere,
4301  &mtstate->ps);
4302  onconfl->oc_WhereClause = qualexpr;
4303  }
4304  }
4305 
4306  /*
4307  * If we have any secondary relations in an UPDATE or DELETE, they need to
4308  * be treated like non-locked relations in SELECT FOR UPDATE, i.e., the
4309  * EvalPlanQual mechanism needs to be told about them. This also goes for
4310  * the source relations in a MERGE. Locate the relevant ExecRowMarks.
4311  */
4312  arowmarks = NIL;
4313  foreach(l, node->rowMarks)
4314  {
4316  ExecRowMark *erm;
4317  ExecAuxRowMark *aerm;
4318 
4319  /* ignore "parent" rowmarks; they are irrelevant at runtime */
4320  if (rc->isParent)
4321  continue;
4322 
4323  /* Find ExecRowMark and build ExecAuxRowMark */
4324  erm = ExecFindRowMark(estate, rc->rti, false);
4325  aerm = ExecBuildAuxRowMark(erm, subplan->targetlist);
4326  arowmarks = lappend(arowmarks, aerm);
4327  }
4328 
4329  /* For a MERGE command, initialize its state */
4330  if (mtstate->operation == CMD_MERGE)
4331  ExecInitMerge(mtstate, estate);
4332 
4333  EvalPlanQualSetPlan(&mtstate->mt_epqstate, subplan, arowmarks);
4334 
4335  /*
4336  * If there are a lot of result relations, use a hash table to speed the
4337  * lookups. If there are not a lot, a simple linear search is faster.
4338  *
4339  * It's not clear where the threshold is, but try 64 for starters. In a
4340  * debugging build, use a small threshold so that we get some test
4341  * coverage of both code paths.
4342  */
4343 #ifdef USE_ASSERT_CHECKING
4344 #define MT_NRELS_HASH 4
4345 #else
4346 #define MT_NRELS_HASH 64
4347 #endif
4348  if (nrels >= MT_NRELS_HASH)
4349  {
4350  HASHCTL hash_ctl;
4351 
4352  hash_ctl.keysize = sizeof(Oid);
4353  hash_ctl.entrysize = sizeof(MTTargetRelLookup);
4354  hash_ctl.hcxt = CurrentMemoryContext;
4355  mtstate->mt_resultOidHash =
4356  hash_create("ModifyTable target hash",
4357  nrels, &hash_ctl,
4359  for (i = 0; i < nrels; i++)
4360  {
4361  Oid hashkey;
4362  MTTargetRelLookup *mtlookup;
4363  bool found;
4364 
4365  resultRelInfo = &mtstate->resultRelInfo[i];
4366  hashkey = RelationGetRelid(resultRelInfo->ri_RelationDesc);
4367  mtlookup = (MTTargetRelLookup *)
4368  hash_search(mtstate->mt_resultOidHash, &hashkey,
4369  HASH_ENTER, &found);
4370  Assert(!found);
4371  mtlookup->relationIndex = i;
4372  }
4373  }
4374  else
4375  mtstate->mt_resultOidHash = NULL;
4376 
4377  /*
4378  * Determine if the FDW supports batch insert and determine the batch size
4379  * (a FDW may support batching, but it may be disabled for the
4380  * server/table).
4381  *
4382  * We only do this for INSERT, so that for UPDATE/DELETE the batch size
4383  * remains set to 0.
4384  */
4385  if (operation == CMD_INSERT)
4386  {
4387  /* insert may only have one relation, inheritance is not expanded */
4388  Assert(nrels == 1);
4389  resultRelInfo = mtstate->resultRelInfo;
4390  if (!resultRelInfo->ri_usesFdwDirectModify &&
4391  resultRelInfo->ri_FdwRoutine != NULL &&
4392  resultRelInfo->ri_FdwRoutine->GetForeignModifyBatchSize &&
4393  resultRelInfo->ri_FdwRoutine->ExecForeignBatchInsert)
4394  {
4395  resultRelInfo->ri_BatchSize =
4396  resultRelInfo->ri_FdwRoutine->GetForeignModifyBatchSize(resultRelInfo);
4397  Assert(resultRelInfo->ri_BatchSize >= 1);
4398  }
4399  else
4400  resultRelInfo->ri_BatchSize = 1;
4401  }
4402 
4403  /*
4404  * Lastly, if this is not the primary (canSetTag) ModifyTable node, add it
4405  * to estate->es_auxmodifytables so that it will be run to completion by
4406  * ExecPostprocessPlan. (It'd actually work fine to add the primary
4407  * ModifyTable node too, but there's no need.) Note the use of lcons not
4408  * lappend: we need later-initialized ModifyTable nodes to be shut down
4409  * before earlier ones. This ensures that we don't throw away RETURNING
4410  * rows that need to be seen by a later CTE subplan.
4411  */
4412  if (!mtstate->canSetTag)
4413  estate->es_auxmodifytables = lcons(mtstate,
4414  estate->es_auxmodifytables);
4415 
4416  return mtstate;
4417 }
#define AttributeNumberIsValid(attributeNumber)
Definition: attnum.h:34
bool bms_is_member(int x, const Bitmapset *a)
Definition: bitmapset.c:523
unsigned int Index
Definition: c.h:603
void * hash_search(HTAB *hashp, const void *keyPtr, HASHACTION action, bool *foundPtr)
Definition: dynahash.c:953
HTAB * hash_create(const char *tabname, long nelem, const HASHCTL *info, int flags)
Definition: dynahash.c:350
AttrNumber ExecFindJunkAttributeInTlist(List *targetlist, const char *attrName)
Definition: execJunk.c:222
void EvalPlanQualInit(EPQState *epqstate, EState *parentestate, Plan *subplan, List *auxrowmarks, int epqParam, List *resultRelations)
Definition: execMain.c:2563
ExecAuxRowMark * ExecBuildAuxRowMark(ExecRowMark *erm, List *targetlist)
Definition: execMain.c:2424
void EvalPlanQualSetPlan(EPQState *epqstate, Plan *subplan, List *auxrowmarks)
Definition: execMain.c:2605
ExecRowMark * ExecFindRowMark(EState *estate, Index rti, bool missing_ok)
Definition: execMain.c:2401
void CheckValidResultRel(ResultRelInfo *resultRelInfo, CmdType operation)
Definition: execMain.c:1024
PlanState * ExecInitNode(Plan *node, EState *estate, int eflags)
Definition: execProcnode.c:142
const TupleTableSlotOps TTSOpsVirtual
Definition: execTuples.c:83
void ExecInitResultTypeTL(PlanState *planstate)
Definition: execTuples.c:1754
void ExecInitResultTupleSlotTL(PlanState *planstate, const TupleTableSlotOps *tts_ops)
Definition: execTuples.c:1798
void ExecInitResultRelation(EState *estate, ResultRelInfo *resultRelInfo, Index rti)
Definition: execUtils.c:819
#define EXEC_FLAG_BACKWARD
Definition: executor.h:68
#define EXEC_FLAG_EXPLAIN_ONLY
Definition: executor.h:65
#define EXEC_FLAG_MARK
Definition: executor.h:69
@ HASH_ENTER
Definition: hsearch.h:114
#define HASH_CONTEXT
Definition: hsearch.h:102
#define HASH_ELEM
Definition: hsearch.h:95
#define HASH_BLOBS
Definition: hsearch.h:97
List * lcons(void *datum, List *list)
Definition: list.c:495
MemoryContext CurrentMemoryContext
Definition: mcxt.c:135
static void ExecSetupTransitionCaptureState(ModifyTableState *mtstate, EState *estate)
static TupleTableSlot * ExecModifyTable(PlanState *pstate)
struct MTTargetRelLookup MTTargetRelLookup
#define MT_NRELS_HASH
static void ExecInitMerge(ModifyTableState *mtstate, EState *estate)
@ ONCONFLICT_NONE
Definition: nodes.h:407
CmdType
Definition: nodes.h:253
@ CMD_MERGE
Definition: nodes.h:259
#define lfirst_node(type, lc)
Definition: pg_list.h:176
static int list_length(const List *l)
Definition: pg_list.h:152
#define lfirst_int(lc)
Definition: pg_list.h:173
#define linitial_int(l)
Definition: pg_list.h:179
#define linitial(l)
Definition: pg_list.h:178
static void * list_nth(const List *list, int n)
Definition: pg_list.h:299
#define InvalidOid
Definition: postgres_ext.h:36
unsigned int Oid
Definition: postgres_ext.h:31
List * es_auxmodifytables
Definition: execnodes.h:682
BeginForeignModify_function BeginForeignModify
Definition: fdwapi.h:231
GetForeignModifyBatchSize_function GetForeignModifyBatchSize
Definition: fdwapi.h:234
Size keysize
Definition: hsearch.h:75
Size entrysize
Definition: hsearch.h:76
MemoryContext hcxt
Definition: hsearch.h:86
double mt_merge_deleted
Definition: execnodes.h:1331
double mt_merge_inserted
Definition: execnodes.h:1329
double mt_merge_updated
Definition: execnodes.h:1330
HTAB * mt_resultOidHash
Definition: execnodes.h:1308
List * arbiterIndexes
Definition: plannodes.h:246
List * onConflictCols
Definition: plannodes.h:248
CmdType operation
Definition: plannodes.h:232
int epqParam
Definition: plannodes.h:244
List * resultRelations
Definition: plannodes.h:237
Bitmapset * fdwDirectModifyPlans
Definition: plannodes.h:242
List * onConflictSet
Definition: plannodes.h:247
bool canSetTag
Definition: plannodes.h:233
List * fdwPrivLists
Definition: plannodes.h:241
List * returningLists
Definition: plannodes.h:240
List * withCheckOptionLists
Definition: plannodes.h:239
Index rootRelation
Definition: plannodes.h:235
Node * onConflictWhere
Definition: plannodes.h:249
List * rowMarks
Definition: plannodes.h:243
OnConflictAction onConflictAction
Definition: plannodes.h:245
TupleTableSlot * oc_ProjSlot
Definition: execnodes.h:410
TupleTableSlot * oc_Existing
Definition: execnodes.h:409
ExprState * oc_WhereClause
Definition: execnodes.h:412
ProjectionInfo * oc_ProjInfo
Definition: execnodes.h:411
bool isParent
Definition: plannodes.h:1387
TupleTableSlot * ps_ResultTupleSlot
Definition: execnodes.h:1081
ExecProcNodeMtd ExecProcNode
Definition: execnodes.h:1049
List * targetlist
Definition: plannodes.h:152
TupleDesc rd_att
Definition: rel.h:112
Form_pg_class rd_rel
Definition: rel.h:111
OnConflictSetState * ri_onConflict
Definition: execnodes.h:545
List * ri_onConflictArbiterIndexes
Definition: execnodes.h:542
List * ri_WithCheckOptionExprs
Definition: execnodes.h:522
List * ri_returningList
Definition: execnodes.h:536
AttrNumber ri_RowIdAttNo
Definition: execnodes.h:471
int ri_BatchSize
Definition: execnodes.h:514

References ModifyTable::arbiterIndexes, Assert(), AttributeNumberIsValid, FdwRoutine::BeginForeignModify, bms_is_member(), ModifyTableState::canSetTag, ModifyTable::canSetTag, CheckValidResultRel(), CMD_DELETE, CMD_INSERT, CMD_MERGE, CMD_UPDATE, CurrentMemoryContext, elog(), HASHCTL::entrysize, ModifyTable::epqParam, ERROR, EState::es_auxmodifytables, EState::es_tupleTable, EvalPlanQualInit(), EvalPlanQualSetPlan(), EXEC_FLAG_BACKWARD, EXEC_FLAG_EXPLAIN_ONLY, EXEC_FLAG_MARK, ExecAssignExprContext(), ExecBuildAuxRowMark(), ExecBuildProjectionInfo(), ExecBuildUpdateProjection(), ExecFindJunkAttributeInTlist(), ExecFindRowMark(), FdwRoutine::ExecForeignBatchInsert, ExecInitMerge(), ExecInitNode(), ExecInitQual(), ExecInitResultRelation(), ExecInitResultTupleSlotTL(), ExecInitResultTypeTL(), ExecModifyTable(), PlanState::ExecProcNode, ExecSetupPartitionTupleRouting(), ExecSetupTransitionCaptureState(), ModifyTable::fdwDirectModifyPlans, ModifyTable::fdwPrivLists, ModifyTableState::fireBSTriggers, FdwRoutine::GetForeignModifyBatchSize, HASH_BLOBS, HASH_CONTEXT, hash_create(), HASH_ELEM, HASH_ENTER, hash_search(), HASHCTL::hcxt, i, InvalidOid, PlanRowMark::isParent, HASHCTL::keysize, lappend(), lcons(), lfirst, lfirst_int, lfirst_node, linitial, linitial_int, list_length(), list_nth(), makeNode, ModifyTableState::mt_done, ModifyTableState::mt_epqstate, ModifyTableState::mt_lastResultIndex, ModifyTableState::mt_lastResultOid, ModifyTableState::mt_merge_deleted, ModifyTableState::mt_merge_inserted, ModifyTableState::mt_merge_updated, ModifyTableState::mt_nrels, MT_NRELS_HASH, ModifyTableState::mt_partition_tuple_routing, ModifyTableState::mt_resultOidAttno, ModifyTableState::mt_resultOidHash, NIL, OnConflictSetState::oc_Existing, OnConflictSetState::oc_ProjInfo, OnConflictSetState::oc_ProjSlot, OnConflictSetState::oc_WhereClause, ONCONFLICT_NONE, ONCONFLICT_UPDATE, ModifyTable::onConflictAction, ModifyTable::onConflictCols, ModifyTable::onConflictSet, ModifyTable::onConflictWhere, ModifyTableState::operation, ModifyTable::operation, outerPlan, outerPlanState, palloc(), PlanState::plan, ModifyTableState::ps, PlanState::ps_ExprContext, PlanState::ps_ResultTupleSlot, WithCheckOption::qual, RelationData::rd_att, RelationData::rd_rel, RelationGetRelid, MTTargetRelLookup::relationIndex, ModifyTable::resultRelations, ModifyTableState::resultRelInfo, ModifyTable::returningLists, ResultRelInfo::ri_BatchSize, ResultRelInfo::ri_FdwRoutine, ResultRelInfo::ri_onConflict, ResultRelInfo::ri_onConflictArbiterIndexes, ResultRelInfo::ri_projectReturning, ResultRelInfo::ri_RelationDesc, ResultRelInfo::ri_returningList, ResultRelInfo::ri_RootResultRelInfo, ResultRelInfo::ri_RowIdAttNo, ResultRelInfo::ri_usesFdwDirectModify, ResultRelInfo::ri_WithCheckOptionExprs, ResultRelInfo::ri_WithCheckOptions, ModifyTable::rootRelation, ModifyTableState::rootResultRelInfo, ModifyTable::rowMarks, PlanRowMark::rti, PlanState::state, table_slot_create(), Plan::targetlist, TTSOpsVirtual, and ModifyTable::withCheckOptionLists.

Referenced by ExecInitNode().

◆ ExecInitStoredGenerated()

void ExecInitStoredGenerated ( ResultRelInfo resultRelInfo,
EState estate,
CmdType  cmdtype 
)

Definition at line 346 of file nodeModifyTable.c.

349 {
350  Relation rel = resultRelInfo->ri_RelationDesc;
351  TupleDesc tupdesc = RelationGetDescr(rel);
352  int natts = tupdesc->natts;
353  ExprState **ri_GeneratedExprs;
354  int ri_NumGeneratedNeeded;
355  Bitmapset *updatedCols;
356  MemoryContext oldContext;
357 
358  /* Nothing to do if no generated columns */
359  if (!(tupdesc->constr && tupdesc->constr->has_generated_stored))
360  return;
361 
362  /*
363  * In an UPDATE, we can skip computing any generated columns that do not
364  * depend on any UPDATE target column. But if there is a BEFORE ROW
365  * UPDATE trigger, we cannot skip because the trigger might change more
366  * columns.
367  */
368  if (cmdtype == CMD_UPDATE &&
369  !(rel->trigdesc && rel->trigdesc->trig_update_before_row))
370  updatedCols = ExecGetUpdatedCols(resultRelInfo, estate);
371  else
372  updatedCols = NULL;
373 
374  /*
375  * Make sure these data structures are built in the per-query memory
376  * context so they'll survive throughout the query.
377  */
378  oldContext = MemoryContextSwitchTo(estate->es_query_cxt);
379 
380  ri_GeneratedExprs = (ExprState **) palloc0(natts * sizeof(ExprState *));
381  ri_NumGeneratedNeeded = 0;
382 
383  for (int i = 0; i < natts; i++)
384  {
385  if (TupleDescAttr(tupdesc, i)->attgenerated == ATTRIBUTE_GENERATED_STORED)
386  {
387  Expr *expr;
388 
389  /* Fetch the GENERATED AS expression tree */
390  expr = (Expr *) build_column_default(rel, i + 1);
391  if (expr == NULL)
392  elog(ERROR, "no generation expression found for column number %d of table \"%s\"",
393  i + 1, RelationGetRelationName(rel));
394 
395  /*
396  * If it's an update with a known set of update target columns,
397  * see if we can skip the computation.
398  */
399  if (updatedCols)
400  {
401  Bitmapset *attrs_used = NULL;
402 
403  pull_varattnos((Node *) expr, 1, &attrs_used);
404 
405  if (!bms_overlap(updatedCols, attrs_used))
406  continue; /* need not update this column */
407  }
408 
409  /* No luck, so prepare the expression for execution */
410  ri_GeneratedExprs[i] = ExecPrepareExpr(expr, estate);
411  ri_NumGeneratedNeeded++;
412 
413  /* If UPDATE, mark column in resultRelInfo->ri_extraUpdatedCols */
414  if (cmdtype == CMD_UPDATE)
415  resultRelInfo->ri_extraUpdatedCols =
416  bms_add_member(resultRelInfo->ri_extraUpdatedCols,
418  }
419  }
420 
421  /* Save in appropriate set of fields */
422  if (cmdtype == CMD_UPDATE)
423  {
424  /* Don't call twice */
425  Assert(resultRelInfo->ri_GeneratedExprsU == NULL);
426 
427  resultRelInfo->ri_GeneratedExprsU = ri_GeneratedExprs;
428  resultRelInfo->ri_NumGeneratedNeededU = ri_NumGeneratedNeeded;
429  }
430  else
431  {
432  /* Don't call twice */
433  Assert(resultRelInfo->ri_GeneratedExprsI == NULL);
434 
435  resultRelInfo->ri_GeneratedExprsI = ri_GeneratedExprs;
436  resultRelInfo->ri_NumGeneratedNeededI = ri_NumGeneratedNeeded;
437  }
438 
439  MemoryContextSwitchTo(oldContext);
440 }
Bitmapset * bms_add_member(Bitmapset *a, int x)
Definition: bitmapset.c:828
bool bms_overlap(const Bitmapset *a, const Bitmapset *b)
Definition: bitmapset.c:595
ExprState * ExecPrepareExpr(Expr *node, EState *estate)
Definition: execExpr.c:733
Bitmapset * ExecGetUpdatedCols(ResultRelInfo *relinfo, EState *estate)
Definition: execUtils.c:1293
void * palloc0(Size size)
Definition: mcxt.c:1232
Node * build_column_default(Relation rel, int attrno)
TriggerDesc * trigdesc
Definition: rel.h:117
Bitmapset * ri_extraUpdatedCols
Definition: execnodes.h:474
bool trig_update_before_row
Definition: reltrigger.h:61
#define FirstLowInvalidHeapAttributeNumber
Definition: sysattr.h:27
void pull_varattnos(Node *node, Index varno, Bitmapset **varattnos)
Definition: var.c:291

References Assert(), bms_add_member(), bms_overlap(), build_column_default(), CMD_UPDATE, TupleDescData::constr, elog(), ERROR, EState::es_query_cxt, ExecGetUpdatedCols(), ExecPrepareExpr(), FirstLowInvalidHeapAttributeNumber, TupleConstr::has_generated_stored, i, MemoryContextSwitchTo(), TupleDescData::natts, palloc0(), pull_varattnos(), RelationGetDescr, RelationGetRelationName, ResultRelInfo::ri_extraUpdatedCols, ResultRelInfo::ri_GeneratedExprsI, ResultRelInfo::ri_GeneratedExprsU, ResultRelInfo::ri_NumGeneratedNeededI, ResultRelInfo::ri_NumGeneratedNeededU, ResultRelInfo::ri_RelationDesc, TriggerDesc::trig_update_before_row, RelationData::trigdesc, and TupleDescAttr.

Referenced by ExecComputeStoredGenerated(), and ExecGetExtraUpdatedCols().

◆ ExecInitUpdateProjection()

static void ExecInitUpdateProjection ( ModifyTableState mtstate,
ResultRelInfo resultRelInfo 
)
static

Definition at line 612 of file nodeModifyTable.c.

614 {
615  ModifyTable *node = (ModifyTable *) mtstate->ps.plan;
616  Plan *subplan = outerPlan(node);
617  EState *estate = mtstate->ps.state;
618  TupleDesc relDesc = RelationGetDescr(resultRelInfo->ri_RelationDesc);
619  int whichrel;
620  List *updateColnos;
621 
622  /*
623  * Usually, mt_lastResultIndex matches the target rel. If it happens not
624  * to, we can get the index the hard way with an integer division.
625  */
626  whichrel = mtstate->mt_lastResultIndex;
627  if (resultRelInfo != mtstate->resultRelInfo + whichrel)
628  {
629  whichrel = resultRelInfo - mtstate->resultRelInfo;
630  Assert(whichrel >= 0 && whichrel < mtstate->mt_nrels);
631  }
632 
633  updateColnos = (List *) list_nth(node->updateColnosLists, whichrel);
634 
635  /*
636  * For UPDATE, we use the old tuple to fill up missing values in the tuple
637  * produced by the subplan to get the new tuple. We need two slots, both
638  * matching the table's desired format.
639  */
640  resultRelInfo->ri_oldTupleSlot =
641  table_slot_create(resultRelInfo->ri_RelationDesc,
642  &estate->es_tupleTable);
643  resultRelInfo->ri_newTupleSlot =
644  table_slot_create(resultRelInfo->ri_RelationDesc,
645  &estate->es_tupleTable);
646 
647  /* need an expression context to do the projection */
648  if (mtstate->ps.ps_ExprContext == NULL)
649  ExecAssignExprContext(estate, &mtstate->ps);
650 
651  resultRelInfo->ri_projectNew =
652  ExecBuildUpdateProjection(subplan->targetlist,
653  false, /* subplan did the evaluation */
654  updateColnos,
655  relDesc,
656  mtstate->ps.ps_ExprContext,
657  resultRelInfo->ri_newTupleSlot,
658  &mtstate->ps);
659 
660  resultRelInfo->ri_projectNewInfoValid = true;
661 }
List * updateColnosLists
Definition: plannodes.h:238

References Assert(), EState::es_tupleTable, ExecAssignExprContext(), ExecBuildUpdateProjection(), list_nth(), ModifyTableState::mt_lastResultIndex, outerPlan, PlanState::plan, ModifyTableState::ps, PlanState::ps_ExprContext, RelationGetDescr, ModifyTableState::resultRelInfo, ResultRelInfo::ri_newTupleSlot, ResultRelInfo::ri_oldTupleSlot, ResultRelInfo::ri_projectNew, ResultRelInfo::ri_projectNewInfoValid, ResultRelInfo::ri_RelationDesc, PlanState::state, table_slot_create(), and ModifyTable::updateColnosLists.

Referenced by ExecCrossPartitionUpdate(), ExecModifyTable(), and ExecUpdate().

◆ ExecInsert()

static TupleTableSlot* ExecInsert ( ModifyTableContext context,
ResultRelInfo resultRelInfo,
TupleTableSlot slot,
bool  canSetTag,
TupleTableSlot **  inserted_tuple,
ResultRelInfo **  insert_destrel 
)
static

Definition at line 752 of file nodeModifyTable.c.

758 {
759  ModifyTableState *mtstate = context->mtstate;
760  EState *estate = context->estate;
761  Relation resultRelationDesc;
762  List *recheckIndexes = NIL;
763  TupleTableSlot *planSlot = context->planSlot;
764  TupleTableSlot *result = NULL;
765  TransitionCaptureState *ar_insert_trig_tcs;
766  ModifyTable *node = (ModifyTable *) mtstate->ps.plan;
767  OnConflictAction onconflict = node->onConflictAction;
769  MemoryContext oldContext;
770 
771  /*
772  * If the input result relation is a partitioned table, find the leaf
773  * partition to insert the tuple into.
774  */
775  if (proute)
776  {
777  ResultRelInfo *partRelInfo;
778 
779  slot = ExecPrepareTupleRouting(mtstate, estate, proute,
780  resultRelInfo, slot,
781  &partRelInfo);
782  resultRelInfo = partRelInfo;
783  }
784 
785  ExecMaterializeSlot(slot);
786 
787  resultRelationDesc = resultRelInfo->ri_RelationDesc;
788 
789  /*
790  * Open the table's indexes, if we have not done so already, so that we
791  * can add new index entries for the inserted tuple.
792  */
793  if (resultRelationDesc->rd_rel->relhasindex &&
794  resultRelInfo->ri_IndexRelationDescs == NULL)
795  ExecOpenIndices(resultRelInfo, onconflict != ONCONFLICT_NONE);
796 
797  /*
798  * BEFORE ROW INSERT Triggers.
799  *
800  * Note: We fire BEFORE ROW TRIGGERS for every attempted insertion in an
801  * INSERT ... ON CONFLICT statement. We cannot check for constraint
802  * violations before firing these triggers, because they can change the
803  * values to insert. Also, they can run arbitrary user-defined code with
804  * side-effects that we can't cancel by just not inserting the tuple.
805  */
806  if (resultRelInfo->ri_TrigDesc &&
807  resultRelInfo->ri_TrigDesc->trig_insert_before_row)
808  {
809  /* Flush any pending inserts, so rows are visible to the triggers */
811  ExecPendingInserts(estate);
812 
813  if (!ExecBRInsertTriggers(estate, resultRelInfo, slot))
814  return NULL; /* "do nothing" */
815  }
816 
817  /* INSTEAD OF ROW INSERT Triggers */
818  if (resultRelInfo->ri_TrigDesc &&
819  resultRelInfo->ri_TrigDesc->trig_insert_instead_row)
820  {
821  if (!ExecIRInsertTriggers(estate, resultRelInfo, slot))
822  return NULL; /* "do nothing" */
823  }
824  else if (resultRelInfo->ri_FdwRoutine)
825  {
826  /*
827  * GENERATED expressions might reference the tableoid column, so
828  * (re-)initialize tts_tableOid before evaluating them.
829  */
830  slot->tts_tableOid = RelationGetRelid(resultRelInfo->ri_RelationDesc);
831 
832  /*
833  * Compute stored generated columns
834  */
835  if (resultRelationDesc->rd_att->constr &&
836  resultRelationDesc->rd_att->constr->has_generated_stored)
837  ExecComputeStoredGenerated(resultRelInfo, estate, slot,
838  CMD_INSERT);
839 
840  /*
841  * If the FDW supports batching, and batching is requested, accumulate
842  * rows and insert them in batches. Otherwise use the per-row inserts.
843  */
844  if (resultRelInfo->ri_BatchSize > 1)
845  {
846  bool flushed = false;
847 
848  /*
849  * When we've reached the desired batch size, perform the
850  * insertion.
851  */
852  if (resultRelInfo->ri_NumSlots == resultRelInfo->ri_BatchSize)
853  {
854  ExecBatchInsert(mtstate, resultRelInfo,
855  resultRelInfo->ri_Slots,
856  resultRelInfo->ri_PlanSlots,
857  resultRelInfo->ri_NumSlots,
858  estate, canSetTag);
859  flushed = true;
860  }
861 
862  oldContext = MemoryContextSwitchTo(estate->es_query_cxt);
863 
864  if (resultRelInfo->ri_Slots == NULL)
865  {
866  resultRelInfo->ri_Slots = palloc(sizeof(TupleTableSlot *) *
867  resultRelInfo->ri_BatchSize);
868  resultRelInfo->ri_PlanSlots = palloc(sizeof(TupleTableSlot *) *
869  resultRelInfo->ri_BatchSize);
870  }
871 
872  /*
873  * Initialize the batch slots. We don't know how many slots will
874  * be needed, so we initialize them as the batch grows, and we
875  * keep them across batches. To mitigate an inefficiency in how
876  * resource owner handles objects with many references (as with
877  * many slots all referencing the same tuple descriptor) we copy
878  * the appropriate tuple descriptor for each slot.
879  */
880  if (resultRelInfo->ri_NumSlots >= resultRelInfo->ri_NumSlotsInitialized)
881  {
883  TupleDesc plan_tdesc =
885 
886  resultRelInfo->ri_Slots[resultRelInfo->ri_NumSlots] =
887  MakeSingleTupleTableSlot(tdesc, slot->tts_ops);
888 
889  resultRelInfo->ri_PlanSlots[resultRelInfo->ri_NumSlots] =
890  MakeSingleTupleTableSlot(plan_tdesc, planSlot->tts_ops);
891 
892  /* remember how many batch slots we initialized */
893  resultRelInfo->ri_NumSlotsInitialized++;
894  }
895 
896  ExecCopySlot(resultRelInfo->ri_Slots[resultRelInfo->ri_NumSlots],
897  slot);
898 
899  ExecCopySlot(resultRelInfo->ri_PlanSlots[resultRelInfo->ri_NumSlots],
900  planSlot);
901 
902  /*
903  * If these are the first tuples stored in the buffers, add the
904  * target rel and the mtstate to the
905  * es_insert_pending_result_relations and
906  * es_insert_pending_modifytables lists respectively, except in
907  * the case where flushing was done above, in which case they
908  * would already have been added to the lists, so no need to do
909  * this.
910  */
911  if (resultRelInfo->ri_NumSlots == 0 && !flushed)
912  {
914  resultRelInfo));
917  resultRelInfo);
919  lappend(estate->es_insert_pending_modifytables, mtstate);
920  }
922  resultRelInfo));
923 
924  resultRelInfo->ri_NumSlots++;
925 
926  MemoryContextSwitchTo(oldContext);
927 
928  return NULL;
929  }
930 
931  /*
932  * insert into foreign table: let the FDW do it
933  */
934  slot = resultRelInfo->ri_FdwRoutine->ExecForeignInsert(estate,
935  resultRelInfo,
936  slot,
937  planSlot);
938 
939  if (slot == NULL) /* "do nothing" */
940  return NULL;
941 
942  /*
943  * AFTER ROW Triggers or RETURNING expressions might reference the
944  * tableoid column, so (re-)initialize tts_tableOid before evaluating
945  * them. (This covers the case where the FDW replaced the slot.)
946  */
947  slot->tts_tableOid = RelationGetRelid(resultRelInfo->ri_RelationDesc);
948  }
949  else
950  {
951  WCOKind wco_kind;
952 
953  /*
954  * Constraints and GENERATED expressions might reference the tableoid
955  * column, so (re-)initialize tts_tableOid before evaluating them.
956  */
957  slot->tts_tableOid = RelationGetRelid(resultRelationDesc);
958 
959  /*
960  * Compute stored generated columns
961  */
962  if (resultRelationDesc->rd_att->constr &&
963  resultRelationDesc->rd_att->constr->has_generated_stored)
964  ExecComputeStoredGenerated(resultRelInfo, estate, slot,
965  CMD_INSERT);
966 
967  /*
968  * Check any RLS WITH CHECK policies.
969  *
970  * Normally we should check INSERT policies. But if the insert is the
971  * result of a partition key update that moved the tuple to a new
972  * partition, we should instead check UPDATE policies, because we are
973  * executing policies defined on the target table, and not those
974  * defined on the child partitions.
975  *
976  * If we're running MERGE, we refer to the action that we're executing
977  * to know if we're doing an INSERT or UPDATE to a partition table.
978  */
979  if (mtstate->operation == CMD_UPDATE)
980  wco_kind = WCO_RLS_UPDATE_CHECK;
981  else if (mtstate->operation == CMD_MERGE)
982  wco_kind = (context->relaction->mas_action->commandType == CMD_UPDATE) ?
984  else
985  wco_kind = WCO_RLS_INSERT_CHECK;
986 
987  /*
988  * ExecWithCheckOptions() will skip any WCOs which are not of the kind
989  * we are looking for at this point.
990  */
991  if (resultRelInfo->ri_WithCheckOptions != NIL)
992  ExecWithCheckOptions(wco_kind, resultRelInfo, slot, estate);
993 
994  /*
995  * Check the constraints of the tuple.
996  */
997  if (resultRelationDesc->rd_att->constr)
998  ExecConstraints(resultRelInfo, slot, estate);
999 
1000  /*
1001  * Also check the tuple against the partition constraint, if there is
1002  * one; except that if we got here via tuple-routing, we don't need to
1003  * if there's no BR trigger defined on the partition.
1004  */
1005  if (resultRelationDesc->rd_rel->relispartition &&
1006  (resultRelInfo->ri_RootResultRelInfo == NULL ||
1007  (resultRelInfo->ri_TrigDesc &&
1008  resultRelInfo->ri_TrigDesc->trig_insert_before_row)))
1009  ExecPartitionCheck(resultRelInfo, slot, estate, true);
1010 
1011  if (onconflict != ONCONFLICT_NONE && resultRelInfo->ri_NumIndices > 0)
1012  {
1013  /* Perform a speculative insertion. */
1014  uint32 specToken;
1015  ItemPointerData conflictTid;
1016  bool specConflict;
1017  List *arbiterIndexes;
1018 
1019  arbiterIndexes = resultRelInfo->ri_onConflictArbiterIndexes;
1020 
1021  /*
1022  * Do a non-conclusive check for conflicts first.
1023  *
1024  * We're not holding any locks yet, so this doesn't guarantee that
1025  * the later insert won't conflict. But it avoids leaving behind
1026  * a lot of canceled speculative insertions, if you run a lot of
1027  * INSERT ON CONFLICT statements that do conflict.
1028  *
1029  * We loop back here if we find a conflict below, either during
1030  * the pre-check, or when we re-check after inserting the tuple
1031  * speculatively. Better allow interrupts in case some bug makes
1032  * this an infinite loop.
1033  */
1034  vlock:
1036  specConflict = false;
1037  if (!ExecCheckIndexConstraints(resultRelInfo, slot, estate,
1038  &conflictTid, arbiterIndexes))
1039  {
1040  /* committed conflict tuple found */
1041  if (onconflict == ONCONFLICT_UPDATE)
1042  {
1043  /*
1044  * In case of ON CONFLICT DO UPDATE, execute the UPDATE
1045  * part. Be prepared to retry if the UPDATE fails because
1046  * of another concurrent UPDATE/DELETE to the conflict
1047  * tuple.
1048  */
1049  TupleTableSlot *returning = NULL;
1050 
1051  if (ExecOnConflictUpdate(context, resultRelInfo,
1052  &conflictTid, slot, canSetTag,
1053  &returning))
1054  {
1055  InstrCountTuples2(&mtstate->ps, 1);
1056  return returning;
1057  }
1058  else
1059  goto vlock;
1060  }
1061  else
1062  {
1063  /*
1064  * In case of ON CONFLICT DO NOTHING, do nothing. However,
1065  * verify that the tuple is visible to the executor's MVCC
1066  * snapshot at higher isolation levels.
1067  *
1068  * Using ExecGetReturningSlot() to store the tuple for the
1069  * recheck isn't that pretty, but we can't trivially use
1070  * the input slot, because it might not be of a compatible
1071  * type. As there's no conflicting usage of
1072  * ExecGetReturningSlot() in the DO NOTHING case...
1073  */
1074  Assert(onconflict == ONCONFLICT_NOTHING);
1075  ExecCheckTIDVisible(estate, resultRelInfo, &conflictTid,
1076  ExecGetReturningSlot(estate, resultRelInfo));
1077  InstrCountTuples2(&mtstate->ps, 1);
1078  return NULL;
1079  }
1080  }
1081 
1082  /*
1083  * Before we start insertion proper, acquire our "speculative
1084  * insertion lock". Others can use that to wait for us to decide
1085  * if we're going to go ahead with the insertion, instead of
1086  * waiting for the whole transaction to complete.
1087  */
1089 
1090  /* insert the tuple, with the speculative token */
1091  table_tuple_insert_speculative(resultRelationDesc, slot,
1092  estate->es_output_cid,
1093  0,
1094  NULL,
1095  specToken);
1096 
1097  /* insert index entries for tuple */
1098  recheckIndexes = ExecInsertIndexTuples(resultRelInfo,
1099  slot, estate, false, true,
1100  &specConflict,
1101  arbiterIndexes,
1102  false);
1103 
1104  /* adjust the tuple's state accordingly */
1105  table_tuple_complete_speculative(resultRelationDesc, slot,
1106  specToken, !specConflict);
1107 
1108  /*
1109  * Wake up anyone waiting for our decision. They will re-check
1110  * the tuple, see that it's no longer speculative, and wait on our
1111  * XID as if this was a regularly inserted tuple all along. Or if
1112  * we killed the tuple, they will see it's dead, and proceed as if
1113  * the tuple never existed.
1114  */
1116 
1117  /*
1118  * If there was a conflict, start from the beginning. We'll do
1119  * the pre-check again, which will now find the conflicting tuple
1120  * (unless it aborts before we get there).
1121  */
1122  if (specConflict)
1123  {
1124  list_free(recheckIndexes);
1125  goto vlock;
1126  }
1127 
1128  /* Since there was no insertion conflict, we're done */
1129  }
1130  else
1131  {
1132  /* insert the tuple normally */
1133  table_tuple_insert(resultRelationDesc, slot,
1134  estate->es_output_cid,
1135  0, NULL);
1136 
1137  /* insert index entries for tuple */
1138  if (resultRelInfo->ri_NumIndices > 0)
1139  recheckIndexes = ExecInsertIndexTuples(resultRelInfo,
1140  slot, estate, false,
1141  false, NULL, NIL,
1142  false);
1143  }
1144  }
1145 
1146  if (canSetTag)
1147  (estate->es_processed)++;
1148 
1149  /*
1150  * If this insert is the result of a partition key update that moved the
1151  * tuple to a new partition, put this row into the transition NEW TABLE,
1152  * if there is one. We need to do this separately for DELETE and INSERT
1153  * because they happen on different tables.
1154  */
1155  ar_insert_trig_tcs = mtstate->mt_transition_capture;
1156  if (mtstate->operation == CMD_UPDATE && mtstate->mt_transition_capture
1158  {
1159  ExecARUpdateTriggers(estate, resultRelInfo,
1160  NULL, NULL,
1161  NULL,
1162  NULL,
1163  slot,
1164  NULL,
1165  mtstate->mt_transition_capture,
1166  false);
1167 
1168  /*
1169  * We've already captured the NEW TABLE row, so make sure any AR
1170  * INSERT trigger fired below doesn't capture it again.
1171  */
1172  ar_insert_trig_tcs = NULL;
1173  }
1174 
1175  /* AFTER ROW INSERT Triggers */
1176  ExecARInsertTriggers(estate, resultRelInfo, slot, recheckIndexes,
1177  ar_insert_trig_tcs);
1178 
1179  list_free(recheckIndexes);
1180 
1181  /*
1182  * Check any WITH CHECK OPTION constraints from parent views. We are
1183  * required to do this after testing all constraints and uniqueness
1184  * violations per the SQL spec, so we do it after actually inserting the
1185  * record into the heap and all indexes.
1186  *
1187  * ExecWithCheckOptions will elog(ERROR) if a violation is found, so the
1188  * tuple will never be seen, if it violates the WITH CHECK OPTION.
1189  *
1190  * ExecWithCheckOptions() will skip any WCOs which are not of the kind we
1191  * are looking for at this point.
1192  */
1193  if (resultRelInfo->ri_WithCheckOptions != NIL)
1194  ExecWithCheckOptions(WCO_VIEW_CHECK, resultRelInfo, slot, estate);
1195 
1196  /* Process RETURNING if present */
1197  if (resultRelInfo->ri_projectReturning)
1198  result = ExecProcessReturning(resultRelInfo, slot, planSlot);
1199 
1200  if (inserted_tuple)
1201  *inserted_tuple = slot;
1202  if (insert_destrel)
1203  *insert_destrel = resultRelInfo;
1204 
1205  return result;
1206 }
unsigned int uint32
Definition: c.h:495
bool ExecCheckIndexConstraints(ResultRelInfo *resultRelInfo, TupleTableSlot *slot, EState *estate, ItemPointer conflictTid, List *arbiterIndexes)
Definition: execIndexing.c:527
List * ExecInsertIndexTuples(ResultRelInfo *resultRelInfo, TupleTableSlot *slot, EState *estate, bool update, bool noDupErr, bool *specConflict, List *arbiterIndexes, bool onlySummarizing)
Definition: execIndexing.c:298
void ExecOpenIndices(ResultRelInfo *resultRelInfo, bool speculative)
Definition: execIndexing.c:156
bool ExecPartitionCheck(ResultRelInfo *resultRelInfo, TupleTableSlot *slot, EState *estate, bool emitError)
Definition: execMain.c:1816
void ExecConstraints(ResultRelInfo *resultRelInfo, TupleTableSlot *slot, EState *estate)
Definition: execMain.c:1940
TupleTableSlot * MakeSingleTupleTableSlot(TupleDesc tupdesc, const TupleTableSlotOps *tts_ops)
Definition: execTuples.c:1237
#define InstrCountTuples2(node, delta)
Definition: execnodes.h:1142
bool list_member_ptr(const List *list, const void *datum)
Definition: list.c:682
void list_free(List *list)
Definition: list.c:1546
uint32 SpeculativeInsertionLockAcquire(TransactionId xid)
Definition: lmgr.c:783
void SpeculativeInsertionLockRelease(TransactionId xid)
Definition: lmgr.c:809
#define CHECK_FOR_INTERRUPTS()
Definition: miscadmin.h:122
static void ExecCheckTIDVisible(EState *estate, ResultRelInfo *relinfo, ItemPointer tid, TupleTableSlot *tempSlot)
void ExecComputeStoredGenerated(ResultRelInfo *resultRelInfo, EState *estate, TupleTableSlot *slot, CmdType cmdtype)
static TupleTableSlot * ExecPrepareTupleRouting(ModifyTableState *mtstate, EState *estate, PartitionTupleRouting *proute, ResultRelInfo *targetRelInfo, TupleTableSlot *slot, ResultRelInfo **partRelInfo)
static bool ExecOnConflictUpdate(ModifyTableContext *context, ResultRelInfo *resultRelInfo, ItemPointer conflictTid, TupleTableSlot *excludedSlot, bool canSetTag, TupleTableSlot **returning)
static void ExecBatchInsert(ModifyTableState *mtstate, ResultRelInfo *resultRelInfo, TupleTableSlot **slots, TupleTableSlot **planSlots, int numSlots, EState *estate, bool canSetTag)
OnConflictAction
Definition: nodes.h:406
@ ONCONFLICT_NOTHING
Definition: nodes.h:408
WCOKind
Definition: parsenodes.h:1305
@ WCO_RLS_INSERT_CHECK
Definition: parsenodes.h:1307
@ WCO_RLS_UPDATE_CHECK
Definition: parsenodes.h:1308
List * es_insert_pending_modifytables
Definition: execnodes.h:722
ExecForeignInsert_function ExecForeignInsert
Definition: fdwapi.h:232
CmdType commandType
Definition: primnodes.h:1739
int ri_NumIndices
Definition: execnodes.h:459
RelationPtr ri_IndexRelationDescs
Definition: execnodes.h:462
bool trig_insert_instead_row
Definition: reltrigger.h:58
bool trig_insert_before_row
Definition: reltrigger.h:56
TupleDesc tts_tupleDescriptor
Definition: tuptable.h:123
static void table_tuple_complete_speculative(Relation rel, TupleTableSlot *slot, uint32 specToken, bool succeeded)
Definition: tableam.h:1430
static void table_tuple_insert(Relation rel, TupleTableSlot *slot, CommandId cid, int options, struct BulkInsertStateData *bistate)
Definition: tableam.h:1397
static void table_tuple_insert_speculative(Relation rel, TupleTableSlot *slot, CommandId cid, int options, struct BulkInsertStateData *bistate, uint32 specToken)
Definition: tableam.h:1416
bool ExecBRInsertTriggers(EState *estate, ResultRelInfo *relinfo, TupleTableSlot *slot)
Definition: trigger.c:2465
bool ExecIRInsertTriggers(EState *estate, ResultRelInfo *relinfo, TupleTableSlot *slot)
Definition: trigger.c:2558
TupleDesc CreateTupleDescCopy(TupleDesc tupdesc)
Definition: tupdesc.c:133
TransactionId GetCurrentTransactionId(void)
Definition: xact.c:445

References Assert(), CHECK_FOR_INTERRUPTS, CMD_INSERT, CMD_MERGE, CMD_UPDATE, MergeAction::commandType, TupleDescData::constr, CreateTupleDescCopy(), EState::es_insert_pending_modifytables, EState::es_insert_pending_result_relations, EState::es_output_cid, EState::es_processed, EState::es_query_cxt, ModifyTableContext::estate, ExecARInsertTriggers(), ExecARUpdateTriggers(), ExecBatchInsert(), ExecBRInsertTriggers(), ExecCheckIndexConstraints(), ExecCheckTIDVisible(), ExecComputeStoredGenerated(), ExecConstraints(), ExecCopySlot(), FdwRoutine::ExecForeignInsert, ExecGetReturningSlot(), ExecInsertIndexTuples(), ExecIRInsertTriggers(), ExecMaterializeSlot(), ExecOnConflictUpdate(), ExecOpenIndices(), ExecPartitionCheck(), ExecPendingInserts(), ExecPrepareTupleRouting(), ExecProcessReturning(), ExecWithCheckOptions(), GetCurrentTransactionId(), TupleConstr::has_generated_stored, if(), InstrCountTuples2, lappend(), list_free(), list_member_ptr(), MakeSingleTupleTableSlot(), MergeActionState::mas_action, MemoryContextSwitchTo(), ModifyTableState::mt_partition_tuple_routing, ModifyTableState::mt_transition_capture, ModifyTableContext::mtstate, NIL, ONCONFLICT_NONE, ONCONFLICT_NOTHING, ONCONFLICT_UPDATE, ModifyTable::onConflictAction, ModifyTableState::operation, palloc(), PlanState::plan, ModifyTableContext::planSlot, ModifyTableState::ps, RelationData::rd_att, RelationData::rd_rel, ModifyTableContext::relaction, RelationGetRelid, ResultRelInfo::ri_BatchSize, ResultRelInfo::ri_FdwRoutine, ResultRelInfo::ri_IndexRelationDescs, ResultRelInfo::ri_NumIndices, ResultRelInfo::ri_NumSlots, ResultRelInfo::ri_NumSlotsInitialized, ResultRelInfo::ri_onConflictArbiterIndexes, ResultRelInfo::ri_PlanSlots, ResultRelInfo::ri_projectReturning, ResultRelInfo::ri_RelationDesc, ResultRelInfo::ri_RootResultRelInfo, ResultRelInfo::ri_Slots, ResultRelInfo::ri_TrigDesc, ResultRelInfo::ri_WithCheckOptions, SpeculativeInsertionLockAcquire(), SpeculativeInsertionLockRelease(), table_tuple_complete_speculative(), table_tuple_insert(), table_tuple_insert_speculative(), TransitionCaptureState::tcs_update_new_table, TriggerDesc::trig_insert_before_row, TriggerDesc::trig_insert_instead_row, TupleTableSlot::tts_ops, TupleTableSlot::tts_tableOid, TupleTableSlot::tts_tupleDescriptor, WCO_RLS_INSERT_CHECK, WCO_RLS_UPDATE_CHECK, and WCO_VIEW_CHECK.

Referenced by ExecCrossPartitionUpdate(), ExecMergeNotMatched(), and ExecModifyTable().

◆ ExecLookupResultRelByOid()

ResultRelInfo* ExecLookupResultRelByOid ( ModifyTableState node,
Oid  resultoid,
bool  missing_ok,
bool  update_cache 
)

Definition at line 3897 of file nodeModifyTable.c.

3899 {
3900  if (node->mt_resultOidHash)
3901  {
3902  /* Use the pre-built hash table to locate the rel */
3903  MTTargetRelLookup *mtlookup;
3904 
3905  mtlookup = (MTTargetRelLookup *)
3906  hash_search(node->mt_resultOidHash, &resultoid, HASH_FIND, NULL);
3907  if (mtlookup)
3908  {
3909  if (update_cache)
3910  {
3911  node->mt_lastResultOid = resultoid;
3912  node->mt_lastResultIndex = mtlookup->relationIndex;
3913  }
3914  return node->resultRelInfo + mtlookup->relationIndex;
3915  }
3916  }
3917  else
3918  {
3919  /* With few target rels, just search the ResultRelInfo array */
3920  for (int ndx = 0; ndx < node->mt_nrels; ndx++)
3921  {
3922  ResultRelInfo *rInfo = node->resultRelInfo + ndx;
3923 
3924  if (RelationGetRelid(rInfo->ri_RelationDesc) == resultoid)
3925  {
3926  if (update_cache)
3927  {
3928  node->mt_lastResultOid = resultoid;
3929  node->mt_lastResultIndex = ndx;
3930  }
3931  return rInfo;
3932  }
3933  }
3934  }
3935 
3936  if (!missing_ok)
3937  elog(ERROR, "incorrect result relation OID %u", resultoid);
3938  return NULL;
3939 }
@ HASH_FIND
Definition: hsearch.h:113

References elog(), ERROR, HASH_FIND, hash_search(), ModifyTableState::mt_lastResultIndex, ModifyTableState::mt_lastResultOid, ModifyTableState::mt_nrels, ModifyTableState::mt_resultOidHash, RelationGetRelid, MTTargetRelLookup::relationIndex, ModifyTableState::resultRelInfo, and ResultRelInfo::ri_RelationDesc.

Referenced by ExecFindPartition(), and ExecModifyTable().

◆ ExecMerge()

static TupleTableSlot * ExecMerge ( ModifyTableContext context,
ResultRelInfo resultRelInfo,
ItemPointer  tupleid,
bool  canSetTag 
)
static

Definition at line 2718 of file nodeModifyTable.c.

2720 {
2721  bool matched;
2722 
2723  /*-----
2724  * If we are dealing with a WHEN MATCHED case (tupleid is valid), we
2725  * execute the first action for which the additional WHEN MATCHED AND
2726  * quals pass. If an action without quals is found, that action is
2727  * executed.
2728  *
2729  * Similarly, if we are dealing with WHEN NOT MATCHED case, we look at
2730  * the given WHEN NOT MATCHED actions in sequence until one passes.
2731  *
2732  * Things get interesting in case of concurrent update/delete of the
2733  * target tuple. Such concurrent update/delete is detected while we are
2734  * executing a WHEN MATCHED action.
2735  *
2736  * A concurrent update can:
2737  *
2738  * 1. modify the target tuple so that it no longer satisfies the
2739  * additional quals attached to the current WHEN MATCHED action
2740  *
2741  * In this case, we are still dealing with a WHEN MATCHED case.
2742  * We recheck the list of WHEN MATCHED actions from the start and
2743  * choose the first one that satisfies the new target tuple.
2744  *
2745  * 2. modify the target tuple so that the join quals no longer pass and
2746  * hence the source tuple no longer has a match.
2747  *
2748  * In this case, the source tuple no longer matches the target tuple,
2749  * so we now instead find a qualifying WHEN NOT MATCHED action to
2750  * execute.
2751  *
2752  * XXX Hmmm, what if the updated tuple would now match one that was
2753  * considered NOT MATCHED so far?
2754  *
2755  * A concurrent delete changes a WHEN MATCHED case to WHEN NOT MATCHED.
2756  *
2757  * ExecMergeMatched takes care of following the update chain and
2758  * re-finding the qualifying WHEN MATCHED action, as long as the updated
2759  * target tuple still satisfies the join quals, i.e., it remains a WHEN
2760  * MATCHED case. If the tuple gets deleted or the join quals fail, it
2761  * returns and we try ExecMergeNotMatched. Given that ExecMergeMatched
2762  * always make progress by following the update chain and we never switch
2763  * from ExecMergeNotMatched to ExecMergeMatched, there is no risk of a
2764  * livelock.
2765  */
2766  matched = tupleid != NULL;
2767  if (matched)
2768  matched = ExecMergeMatched(context, resultRelInfo, tupleid, canSetTag);
2769 
2770  /*
2771  * Either we were dealing with a NOT MATCHED tuple or ExecMergeMatched()
2772  * returned "false", indicating the previously MATCHED tuple no longer
2773  * matches.
2774  */
2775  if (!matched)
2776  ExecMergeNotMatched(context, resultRelInfo, canSetTag);
2777 
2778  /* No RETURNING support yet */
2779  return NULL;
2780 }
static void ExecMergeNotMatched(ModifyTableContext *context, ResultRelInfo *resultRelInfo, bool canSetTag)
static bool ExecMergeMatched(ModifyTableContext *context, ResultRelInfo *resultRelInfo, ItemPointer tupleid, bool canSetTag)

References ExecMergeMatched(), and ExecMergeNotMatched().

Referenced by ExecModifyTable().

◆ ExecMergeMatched()

static bool ExecMergeMatched ( ModifyTableContext context,
ResultRelInfo resultRelInfo,
ItemPointer  tupleid,
bool  canSetTag 
)
static

Definition at line 2804 of file nodeModifyTable.c.

2806 {
2807  ModifyTableState *mtstate = context->mtstate;
2808  TupleTableSlot *newslot;
2809  EState *estate = context->estate;
2810  ExprContext *econtext = mtstate->ps.ps_ExprContext;
2811  bool isNull;
2812  EPQState *epqstate = &mtstate->mt_epqstate;
2813  ListCell *l;
2814 
2815  /*
2816  * If there are no WHEN MATCHED actions, we are done.
2817  */
2818  if (resultRelInfo->ri_matchedMergeAction == NIL)
2819  return true;
2820 
2821  /*
2822  * Make tuple and any needed join variables available to ExecQual and
2823  * ExecProject. The target's existing tuple is installed in the scantuple.
2824  * Again, this target relation's slot is required only in the case of a
2825  * MATCHED tuple and UPDATE/DELETE actions.
2826  */
2827  econtext->ecxt_scantuple = resultRelInfo->ri_oldTupleSlot;
2828  econtext->ecxt_innertuple = context->planSlot;
2829  econtext->ecxt_outertuple = NULL;
2830 
2831 lmerge_matched:
2832 
2833  /*
2834  * This routine is only invoked for matched rows, and we must have found
2835  * the tupleid of the target row in that case; fetch that tuple.
2836  *
2837  * We use SnapshotAny for this because we might get called again after
2838  * EvalPlanQual returns us a new tuple, which may not be visible to our
2839  * MVCC snapshot.
2840  */
2841 
2842  if (!table_tuple_fetch_row_version(resultRelInfo->ri_RelationDesc,
2843  tupleid,
2844  SnapshotAny,
2845  resultRelInfo->ri_oldTupleSlot))
2846  elog(ERROR, "failed to fetch the target tuple");
2847 
2848  foreach(l, resultRelInfo->ri_matchedMergeAction)
2849  {
2850  MergeActionState *relaction = (MergeActionState *) lfirst(l);
2851  CmdType commandType = relaction->mas_action->commandType;
2852  TM_Result result;
2853  UpdateContext updateCxt = {0};
2854 
2855  /*
2856  * Test condition, if any.
2857  *
2858  * In the absence of any condition, we perform the action
2859  * unconditionally (no need to check separately since ExecQual() will
2860  * return true if there are no conditions to evaluate).
2861  */
2862  if (!ExecQual(relaction->mas_whenqual, econtext))
2863  continue;
2864 
2865  /*
2866  * Check if the existing target tuple meets the USING checks of
2867  * UPDATE/DELETE RLS policies. If those checks fail, we throw an
2868  * error.
2869  *
2870  * The WITH CHECK quals for UPDATE RLS policies are applied in
2871  * ExecUpdateAct() and hence we need not do anything special to handle
2872  * them.
2873  *
2874  * NOTE: We must do this after WHEN quals are evaluated, so that we
2875  * check policies only when they matter.
2876  */
2877  if (resultRelInfo->ri_WithCheckOptions && commandType != CMD_NOTHING)
2878  {
2879  ExecWithCheckOptions(commandType == CMD_UPDATE ?
2881  resultRelInfo,
2882  resultRelInfo->ri_oldTupleSlot,
2883  context->mtstate->ps.state);
2884  }
2885 
2886  /* Perform stated action */
2887  switch (commandType)
2888  {
2889  case CMD_UPDATE:
2890 
2891  /*
2892  * Project the output tuple, and use that to update the table.
2893  * We don't need to filter out junk attributes, because the
2894  * UPDATE action's targetlist doesn't have any.
2895  */
2896  newslot = ExecProject(relaction->mas_proj);
2897 
2898  context->relaction = relaction;
2899  if (!ExecUpdatePrologue(context, resultRelInfo,
2900  tupleid, NULL, newslot, &result))
2901  {
2902  if (result == TM_Ok)
2903  return true; /* "do nothing" */
2904  break; /* concurrent update/delete */
2905  }
2906  result = ExecUpdateAct(context, resultRelInfo, tupleid, NULL,
2907  newslot, canSetTag, &updateCxt);
2908 
2909  /*
2910  * As in ExecUpdate(), if ExecUpdateAct() reports that a
2911  * cross-partition update was done, then there's nothing else
2912  * for us to do --- the UPDATE has been turned into a DELETE
2913  * and an INSERT, and we must not perform any of the usual
2914  * post-update tasks.
2915  */
2916  if (updateCxt.crossPartUpdate)
2917  {
2918  mtstate->mt_merge_updated += 1;
2919  return true;
2920  }
2921 
2922  if (result == TM_Ok && updateCxt.updated)
2923  {
2924  ExecUpdateEpilogue(context, &updateCxt, resultRelInfo,
2925  tupleid, NULL, newslot);
2926  mtstate->mt_merge_updated += 1;
2927  }
2928  break;
2929 
2930  case CMD_DELETE:
2931  context->relaction = relaction;
2932  if (!ExecDeletePrologue(context, resultRelInfo, tupleid,
2933  NULL, NULL, &result))
2934  {
2935  if (result == TM_Ok)
2936  return true; /* "do nothing" */
2937  break; /* concurrent update/delete */
2938  }
2939  result = ExecDeleteAct(context, resultRelInfo, tupleid, false);
2940  if (result == TM_Ok)
2941  {
2942  ExecDeleteEpilogue(context, resultRelInfo, tupleid, NULL,
2943  false);
2944  mtstate->mt_merge_deleted += 1;
2945  }
2946  break;
2947 
2948  case CMD_NOTHING:
2949  /* Doing nothing is always OK */
2950  result = TM_Ok;
2951  break;
2952 
2953  default:
2954  elog(ERROR, "unknown action in MERGE WHEN MATCHED clause");
2955  }
2956 
2957  switch (result)
2958  {
2959  case TM_Ok:
2960  /* all good; perform final actions */
2961  if (canSetTag && commandType != CMD_NOTHING)
2962  (estate->es_processed)++;
2963 
2964  break;
2965 
2966  case TM_SelfModified:
2967 
2968  /*
2969  * The SQL standard disallows this for MERGE.
2970  */
2972  ereport(ERROR,
2973  (errcode(ERRCODE_CARDINALITY_VIOLATION),
2974  /* translator: %s is a SQL command name */
2975  errmsg("%s command cannot affect row a second time",
2976  "MERGE"),
2977  errhint("Ensure that not more than one source row matches any one target row.")));
2978  /* This shouldn't happen */
2979  elog(ERROR, "attempted to update or delete invisible tuple");
2980  break;
2981 
2982  case TM_Deleted:
2984  ereport(ERROR,
2986  errmsg("could not serialize access due to concurrent delete")));
2987 
2988  /*
2989  * If the tuple was already deleted, return to let caller
2990  * handle it under NOT MATCHED clauses.
2991  */
2992  return false;
2993 
2994  case TM_Updated:
2995  {
2996  Relation resultRelationDesc;
2997  TupleTableSlot *epqslot,
2998  *inputslot;
2999  LockTupleMode lockmode;
3000 
3001  /*
3002  * The target tuple was concurrently updated by some other
3003  * transaction. Run EvalPlanQual() with the new version of
3004  * the tuple. If it does not return a tuple, then we
3005  * switch to the NOT MATCHED list of actions. If it does
3006  * return a tuple and the join qual is still satisfied,
3007  * then we just need to recheck the MATCHED actions,
3008  * starting from the top, and execute the first qualifying
3009  * action.
3010  */
3011  resultRelationDesc = resultRelInfo->ri_RelationDesc;
3012  lockmode = ExecUpdateLockMode(estate, resultRelInfo);
3013 
3014  inputslot = EvalPlanQualSlot(epqstate, resultRelationDesc,
3015  resultRelInfo->ri_RangeTableIndex);
3016 
3017  result = table_tuple_lock(resultRelationDesc, tupleid,
3018  estate->es_snapshot,
3019  inputslot, estate->es_output_cid,
3020  lockmode, LockWaitBlock,
3022  &context->tmfd);
3023  switch (result)
3024  {
3025  case TM_Ok:
3026  epqslot = EvalPlanQual(epqstate,
3027  resultRelationDesc,
3028  resultRelInfo->ri_RangeTableIndex,
3029  inputslot);
3030 
3031  /*
3032  * If we got no tuple, or the tuple we get has a
3033  * NULL ctid, go back to caller: this one is not a
3034  * MATCHED tuple anymore, so they can retry with
3035  * NOT MATCHED actions.
3036  */
3037  if (TupIsNull(epqslot))
3038  return false;
3039 
3040  (void) ExecGetJunkAttribute(epqslot,
3041  resultRelInfo->ri_RowIdAttNo,
3042  &isNull);
3043  if (isNull)
3044  return false;
3045 
3046  /*
3047  * When a tuple was updated and migrated to
3048  * another partition concurrently, the current
3049  * MERGE implementation can't follow. There's
3050  * probably a better way to handle this case, but
3051  * it'd require recognizing the relation to which
3052  * the tuple moved, and setting our current
3053  * resultRelInfo to that.
3054  */
3056  ereport(ERROR,
3058  errmsg("tuple to be deleted was already moved to another partition due to concurrent update")));
3059 
3060  /*
3061  * A non-NULL ctid means that we are still dealing
3062  * with MATCHED case. Restart the loop so that we
3063  * apply all the MATCHED rules again, to ensure
3064  * that the first qualifying WHEN MATCHED action
3065  * is executed.
3066  *
3067  * Update tupleid to that of the new tuple, for
3068  * the refetch we do at the top.
3069  */
3070  ItemPointerCopy(&context->tmfd.ctid, tupleid);
3071  goto lmerge_matched;
3072 
3073  case TM_Deleted:
3074 
3075  /*
3076  * tuple already deleted; tell caller to run NOT
3077  * MATCHED actions
3078  */
3079  return false;
3080 
3081  case TM_SelfModified:
3082 
3083  /*
3084  * This can be reached when following an update
3085  * chain from a tuple updated by another session,
3086  * reaching a tuple that was already updated in
3087  * this transaction. If previously modified by
3088  * this command, ignore the redundant update,
3089  * otherwise error out.
3090  *
3091  * See also response to TM_SelfModified in
3092  * ExecUpdate().
3093  */
3094  if (context->tmfd.cmax != estate->es_output_cid)
3095  ereport(ERROR,
3096  (errcode(ERRCODE_TRIGGERED_DATA_CHANGE_VIOLATION),
3097  errmsg("tuple to be updated or deleted was already modified by an operation triggered by the current command"),
3098  errhint("Consider using an AFTER trigger instead of a BEFORE trigger to propagate changes to other rows.")));
3099  return false;
3100 
3101  default:
3102  /* see table_tuple_lock call in ExecDelete() */
3103  elog(ERROR, "unexpected table_tuple_lock status: %u",
3104  result);
3105  return false;
3106  }
3107  }
3108 
3109  case TM_Invisible:
3110  case TM_WouldBlock:
3111  case TM_BeingModified:
3112  /* these should not occur */
3113  elog(ERROR, "unexpected tuple operation result: %d", result);
3114  break;
3115  }
3116 
3117  /*
3118  * We've activated one of the WHEN clauses, so we don't search
3119  * further. This is required behaviour, not an optimization.
3120  */
3121  break;
3122  }
3123 
3124  /*
3125  * Successfully executed an action or no qualifying action was found.
3126  */
3127  return true;
3128 }
LockTupleMode ExecUpdateLockMode(EState *estate, ResultRelInfo *relinfo)
Definition: execMain.c:2375
static bool ExecQual(ExprState *state, ExprContext *econtext)
Definition: executor.h:412
static Datum ExecGetJunkAttribute(TupleTableSlot *slot, AttrNumber attno, bool *isNull)
Definition: executor.h:190
static bool ItemPointerIndicatesMovedPartitions(const ItemPointerData *pointer)
Definition: itemptr.h:197
static void ItemPointerCopy(const ItemPointerData *fromPointer, ItemPointerData *toPointer)
Definition: itemptr.h:172
LockTupleMode
Definition: lockoptions.h:50
static TM_Result ExecUpdateAct(ModifyTableContext *context, ResultRelInfo *resultRelInfo, ItemPointer tupleid, HeapTuple oldtuple, TupleTableSlot *slot, bool canSetTag, UpdateContext *updateCxt)
static void ExecUpdateEpilogue(ModifyTableContext *context, UpdateContext *updateCxt, ResultRelInfo *resultRelInfo, ItemPointer tupleid, HeapTuple oldtuple, TupleTableSlot *slot)
static bool ExecUpdatePrologue(ModifyTableContext *context, ResultRelInfo *resultRelInfo, ItemPointer tupleid, HeapTuple oldtuple, TupleTableSlot *slot, TM_Result *result)
@ WCO_RLS_MERGE_UPDATE_CHECK
Definition: parsenodes.h:1310
@ WCO_RLS_MERGE_DELETE_CHECK
Definition: parsenodes.h:1311
TupleTableSlot * ecxt_innertuple
Definition: execnodes.h:257
List * ri_matchedMergeAction
Definition: execnodes.h:548
TransactionId xmax
Definition: tableam.h:143
ItemPointerData ctid
Definition: tableam.h:142
@ TM_BeingModified
Definition: tableam.h:99
@ TM_WouldBlock
Definition: tableam.h:102
@ TM_Invisible
Definition: tableam.h:80

References TM_FailureData::cmax, CMD_DELETE, CMD_NOTHING, CMD_UPDATE, MergeAction::commandType, UpdateContext::crossPartUpdate, TM_FailureData::ctid, ExprContext::ecxt_innertuple, ExprContext::ecxt_outertuple, ExprContext::ecxt_scantuple, elog(), ereport, errcode(), ERRCODE_T_R_SERIALIZATION_FAILURE, errhint(), errmsg(), ERROR, EState::es_output_cid, EState::es_processed, EState::es_snapshot, ModifyTableContext::estate, EvalPlanQual(), EvalPlanQualSlot(), ExecDeleteAct(), ExecDeleteEpilogue(), ExecDeletePrologue(), ExecGetJunkAttribute(), ExecProject(), ExecQual(), ExecUpdateAct(), ExecUpdateEpilogue(), ExecUpdateLockMode(), ExecUpdatePrologue(), ExecWithCheckOptions(), IsolationUsesXactSnapshot, ItemPointerCopy(), ItemPointerIndicatesMovedPartitions(), lfirst, LockWaitBlock, MergeActionState::mas_action, MergeActionState::mas_proj, MergeActionState::mas_whenqual, ModifyTableState::mt_epqstate, ModifyTableState::mt_merge_deleted, ModifyTableState::mt_merge_updated, ModifyTableContext::mtstate, NIL, ModifyTableContext::planSlot, ModifyTableState::ps, PlanState::ps_ExprContext, ModifyTableContext::relaction, ResultRelInfo::ri_matchedMergeAction, ResultRelInfo::ri_oldTupleSlot, ResultRelInfo::ri_RangeTableIndex, ResultRelInfo::ri_RelationDesc, ResultRelInfo::ri_RowIdAttNo, ResultRelInfo::ri_WithCheckOptions, SnapshotAny, PlanState::state, table_tuple_fetch_row_version(), table_tuple_lock(), TM_BeingModified, TM_Deleted, TM_Invisible, TM_Ok, TM_SelfModified, TM_Updated, TM_WouldBlock, ModifyTableContext::tmfd, TransactionIdIsCurrentTransactionId(), TupIsNull, TUPLE_LOCK_FLAG_FIND_LAST_VERSION, UpdateContext::updated, WCO_RLS_MERGE_DELETE_CHECK, WCO_RLS_MERGE_UPDATE_CHECK, and TM_FailureData::xmax.

Referenced by ExecMerge().

◆ ExecMergeNotMatched()

static void ExecMergeNotMatched ( ModifyTableContext context,
ResultRelInfo resultRelInfo,
bool  canSetTag 
)
static

Definition at line 3134 of file nodeModifyTable.c.

3136 {
3137  ModifyTableState *mtstate = context->mtstate;
3138  ExprContext *econtext = mtstate->ps.ps_ExprContext;
3139  List *actionStates = NIL;
3140  ListCell *l;
3141 
3142  /*
3143  * For INSERT actions, the root relation's merge action is OK since the
3144  * INSERT's targetlist and the WHEN conditions can only refer to the
3145  * source relation and hence it does not matter which result relation we
3146  * work with.
3147  *
3148  * XXX does this mean that we can avoid creating copies of actionStates on
3149  * partitioned tables, for not-matched actions?
3150  */
3151  actionStates = resultRelInfo->ri_notMatchedMergeAction;
3152 
3153  /*
3154  * Make source tuple available to ExecQual and ExecProject. We don't need
3155  * the target tuple, since the WHEN quals and targetlist can't refer to
3156  * the target columns.
3157  */
3158  econtext->ecxt_scantuple = NULL;
3159  econtext->ecxt_innertuple = context->planSlot;
3160  econtext->ecxt_outertuple = NULL;
3161 
3162  foreach(l, actionStates)
3163  {
3165  CmdType commandType = action->mas_action->commandType;
3166  TupleTableSlot *newslot;
3167 
3168  /*
3169  * Test condition, if any.
3170  *
3171  * In the absence of any condition, we perform the action
3172  * unconditionally (no need to check separately since ExecQual() will
3173  * return true if there are no conditions to evaluate).
3174  */
3175  if (!ExecQual(action->mas_whenqual, econtext))
3176  continue;
3177 
3178  /* Perform stated action */
3179  switch (commandType)
3180  {
3181  case CMD_INSERT:
3182 
3183  /*
3184  * Project the tuple. In case of a partitioned table, the
3185  * projection was already built to use the root's descriptor,
3186  * so we don't need to map the tuple here.
3187  */
3188  newslot = ExecProject(action->mas_proj);
3189  context->relaction = action;
3190 
3191  (void) ExecInsert(context, mtstate->rootResultRelInfo, newslot,
3192  canSetTag, NULL, NULL);
3193  mtstate->mt_merge_inserted += 1;
3194  break;
3195  case CMD_NOTHING:
3196  /* Do nothing */
3197  break;
3198  default:
3199  elog(ERROR, "unknown action in MERGE WHEN NOT MATCHED clause");
3200  }
3201 
3202  /*
3203  * We've activated one of the WHEN clauses, so we don't search
3204  * further. This is required behaviour, not an optimization.
3205  */
3206  break;
3207  }
3208 }
List * ri_notMatchedMergeAction
Definition: execnodes.h:549

References generate_unaccent_rules::action, CMD_INSERT, CMD_NOTHING, ExprContext::ecxt_innertuple, ExprContext::ecxt_outertuple, ExprContext::ecxt_scantuple, elog(), ERROR, ExecInsert(), ExecProject(), ExecQual(), lfirst, ModifyTableState::mt_merge_inserted, ModifyTableContext::mtstate, NIL, ModifyTableContext::planSlot, ModifyTableState::ps, PlanState::ps_ExprContext, ModifyTableContext::relaction, ResultRelInfo::ri_notMatchedMergeAction, and ModifyTableState::rootResultRelInfo.

Referenced by ExecMerge().

◆ ExecModifyTable()

static TupleTableSlot* ExecModifyTable ( PlanState pstate)
static

Definition at line 3559 of file nodeModifyTable.c.

3560 {
3561  ModifyTableState *node = castNode(ModifyTableState, pstate);
3562  ModifyTableContext context;
3563  EState *estate = node->ps.state;
3564  CmdType operation = node->operation;
3565  ResultRelInfo *resultRelInfo;
3566  PlanState *subplanstate;
3567  TupleTableSlot *slot;
3568  TupleTableSlot *oldSlot;
3569  ItemPointerData tuple_ctid;
3570  HeapTupleData oldtupdata;
3571  HeapTuple oldtuple;
3572  ItemPointer tupleid;
3573 
3575 
3576  /*
3577  * This should NOT get called during EvalPlanQual; we should have passed a
3578  * subplan tree to EvalPlanQual, instead. Use a runtime test not just
3579  * Assert because this condition is easy to miss in testing. (Note:
3580  * although ModifyTable should not get executed within an EvalPlanQual
3581  * operation, we do have to allow it to be initialized and shut down in
3582  * case it is within a CTE subplan. Hence this test must be here, not in
3583  * ExecInitModifyTable.)
3584  */
3585  if (estate->es_epq_active != NULL)
3586  elog(ERROR, "ModifyTable should not be called during EvalPlanQual");
3587 
3588  /*
3589  * If we've already completed processing, don't try to do more. We need
3590  * this test because ExecPostprocessPlan might call us an extra time, and
3591  * our subplan's nodes aren't necessarily robust against being called
3592  * extra times.
3593  */
3594  if (node->mt_done)
3595  return NULL;
3596 
3597  /*
3598  * On first call, fire BEFORE STATEMENT triggers before proceeding.
3599  */
3600  if (node->fireBSTriggers)
3601  {
3602  fireBSTriggers(node);
3603  node->fireBSTriggers = false;
3604  }
3605 
3606  /* Preload local variables */
3607  resultRelInfo = node->resultRelInfo + node->mt_lastResultIndex;
3608  subplanstate = outerPlanState(node);
3609 
3610  /* Set global context */
3611  context.mtstate = node;
3612  context.epqstate = &node->mt_epqstate;
3613  context.estate = estate;
3614 
3615  /*
3616  * Fetch rows from subplan, and execute the required table modification
3617  * for each row.
3618  */
3619  for (;;)
3620  {
3621  /*
3622  * Reset the per-output-tuple exprcontext. This is needed because
3623  * triggers expect to use that context as workspace. It's a bit ugly
3624  * to do this below the top level of the plan, however. We might need
3625  * to rethink this later.
3626  */
3627  ResetPerTupleExprContext(estate);
3628 
3629  /*
3630  * Reset per-tuple memory context used for processing on conflict and
3631  * returning clauses, to free any expression evaluation storage
3632  * allocated in the previous cycle.
3633  */
3634  if (pstate->ps_ExprContext)
3636 
3637  context.planSlot = ExecProcNode(subplanstate);
3638 
3639  /* No more tuples to process? */
3640  if (TupIsNull(context.planSlot))
3641  break;
3642 
3643  /*
3644  * When there are multiple result relations, each tuple contains a
3645  * junk column that gives the OID of the rel from which it came.
3646  * Extract it and select the correct result relation.
3647  */
3649  {
3650  Datum datum;
3651  bool isNull;
3652  Oid resultoid;
3653 
3654  datum = ExecGetJunkAttribute(context.planSlot, node->mt_resultOidAttno,
3655  &isNull);
3656  if (isNull)
3657  {
3658  /*
3659  * For commands other than MERGE, any tuples having InvalidOid
3660  * for tableoid are errors. For MERGE, we may need to handle
3661  * them as WHEN NOT MATCHED clauses if any, so do that.
3662  *
3663  * Note that we use the node's toplevel resultRelInfo, not any
3664  * specific partition's.
3665  */
3666  if (operation == CMD_MERGE)
3667  {
3668  EvalPlanQualSetSlot(&node->mt_epqstate, context.planSlot);
3669 
3670  ExecMerge(&context, node->resultRelInfo, NULL, node->canSetTag);
3671  continue; /* no RETURNING support yet */
3672  }
3673 
3674  elog(ERROR, "tableoid is NULL");
3675  }
3676  resultoid = DatumGetObjectId(datum);
3677 
3678  /* If it's not the same as last time, we need to locate the rel */
3679  if (resultoid != node->mt_lastResultOid)
3680  resultRelInfo = ExecLookupResultRelByOid(node, resultoid,
3681  false, true);
3682  }
3683 
3684  /*
3685  * If resultRelInfo->ri_usesFdwDirectModify is true, all we need to do
3686  * here is compute the RETURNING expressions.
3687  */
3688  if (resultRelInfo->ri_usesFdwDirectModify)
3689  {
3690  Assert(resultRelInfo->ri_projectReturning);
3691 
3692  /*
3693  * A scan slot containing the data that was actually inserted,
3694  * updated or deleted has already been made available to
3695  * ExecProcessReturning by IterateDirectModify, so no need to
3696  * provide it here.
3697  */
3698  slot = ExecProcessReturning(resultRelInfo, NULL, context.planSlot);
3699 
3700  return slot;
3701  }
3702 
3703  EvalPlanQualSetSlot(&node->mt_epqstate, context.planSlot);
3704  slot = context.planSlot;
3705 
3706  tupleid = NULL;
3707  oldtuple = NULL;
3708 
3709  /*
3710  * For UPDATE/DELETE/MERGE, fetch the row identity info for the tuple
3711  * to be updated/deleted/merged. For a heap relation, that's a TID;
3712  * otherwise we may have a wholerow junk attr that carries the old
3713  * tuple in toto. Keep this in step with the part of
3714  * ExecInitModifyTable that sets up ri_RowIdAttNo.
3715  */
3716  if (operation == CMD_UPDATE || operation == CMD_DELETE ||
3717  operation == CMD_MERGE)
3718  {
3719  char relkind;
3720  Datum datum;
3721  bool isNull;
3722 
3723  relkind = resultRelInfo->ri_RelationDesc->rd_rel->relkind;
3724  if (relkind == RELKIND_RELATION ||
3725  relkind == RELKIND_MATVIEW ||
3726  relkind == RELKIND_PARTITIONED_TABLE)
3727  {
3728  /* ri_RowIdAttNo refers to a ctid attribute */
3729  Assert(AttributeNumberIsValid(resultRelInfo->ri_RowIdAttNo));
3730  datum = ExecGetJunkAttribute(slot,
3731  resultRelInfo->ri_RowIdAttNo,
3732  &isNull);
3733 
3734  /*
3735  * For commands other than MERGE, any tuples having a null row
3736  * identifier are errors. For MERGE, we may need to handle
3737  * them as WHEN NOT MATCHED clauses if any, so do that.
3738  *
3739  * Note that we use the node's toplevel resultRelInfo, not any
3740  * specific partition's.
3741  */
3742  if (isNull)
3743  {
3744  if (operation == CMD_MERGE)
3745  {
3746  EvalPlanQualSetSlot(&node->mt_epqstate, context.planSlot);
3747 
3748  ExecMerge(&context, node->resultRelInfo, NULL, node->canSetTag);
3749  continue; /* no RETURNING support yet */
3750  }
3751 
3752  elog(ERROR, "ctid is NULL");
3753  }
3754 
3755  tupleid = (ItemPointer) DatumGetPointer(datum);
3756  tuple_ctid = *tupleid; /* be sure we don't free ctid!! */
3757  tupleid = &tuple_ctid;
3758  }
3759 
3760  /*
3761  * Use the wholerow attribute, when available, to reconstruct the
3762  * old relation tuple. The old tuple serves one or both of two
3763  * purposes: 1) it serves as the OLD tuple for row triggers, 2) it
3764  * provides values for any unchanged columns for the NEW tuple of
3765  * an UPDATE, because the subplan does not produce all the columns
3766  * of the target table.
3767  *
3768  * Note that the wholerow attribute does not carry system columns,
3769  * so foreign table triggers miss seeing those, except that we
3770  * know enough here to set t_tableOid. Quite separately from
3771  * this, the FDW may fetch its own junk attrs to identify the row.
3772  *
3773  * Other relevant relkinds, currently limited to views, always
3774  * have a wholerow attribute.
3775  */
3776  else if (AttributeNumberIsValid(resultRelInfo->ri_RowIdAttNo))
3777  {
3778  datum = ExecGetJunkAttribute(slot,
3779  resultRelInfo->ri_RowIdAttNo,
3780  &isNull);
3781  /* shouldn't ever get a null result... */
3782  if (isNull)
3783  elog(ERROR, "wholerow is NULL");
3784 
3785  oldtupdata.t_data = DatumGetHeapTupleHeader(datum);
3786  oldtupdata.t_len =
3788  ItemPointerSetInvalid(&(oldtupdata.t_self));
3789  /* Historically, view triggers see invalid t_tableOid. */
3790  oldtupdata.t_tableOid =
3791  (relkind == RELKIND_VIEW) ? InvalidOid :
3792  RelationGetRelid(resultRelInfo->ri_RelationDesc);
3793 
3794  oldtuple = &oldtupdata;
3795  }
3796  else
3797  {
3798  /* Only foreign tables are allowed to omit a row-ID attr */
3799  Assert(relkind == RELKIND_FOREIGN_TABLE);
3800  }
3801  }
3802 
3803  switch (operation)
3804  {
3805  case CMD_INSERT:
3806  /* Initialize projection info if first time for this table */
3807  if (unlikely(!resultRelInfo->ri_projectNewInfoValid))
3808  ExecInitInsertProjection(node, resultRelInfo);
3809  slot = ExecGetInsertNewTuple(resultRelInfo, context.planSlot);
3810  slot = ExecInsert(&context, resultRelInfo, slot,
3811  node->canSetTag, NULL, NULL);
3812  break;
3813 
3814  case CMD_UPDATE:
3815  /* Initialize projection info if first time for this table */
3816  if (unlikely(!resultRelInfo->ri_projectNewInfoValid))
3817  ExecInitUpdateProjection(node, resultRelInfo);
3818 
3819  /*
3820  * Make the new tuple by combining plan's output tuple with
3821  * the old tuple being updated.
3822  */
3823  oldSlot = resultRelInfo->ri_oldTupleSlot;
3824  if (oldtuple != NULL)
3825  {
3826  /* Use the wholerow junk attr as the old tuple. */
3827  ExecForceStoreHeapTuple(oldtuple, oldSlot, false);
3828  }
3829  else
3830  {
3831  /* Fetch the most recent version of old tuple. */
3832  Relation relation = resultRelInfo->ri_RelationDesc;
3833 
3834  if (!table_tuple_fetch_row_version(relation, tupleid,
3835  SnapshotAny,
3836  oldSlot))
3837  elog(ERROR, "failed to fetch tuple being updated");
3838  }
3839  slot = ExecGetUpdateNewTuple(resultRelInfo, context.planSlot,
3840  oldSlot);
3841  context.relaction = NULL;
3842 
3843  /* Now apply the update. */
3844  slot = ExecUpdate(&context, resultRelInfo, tupleid, oldtuple,
3845  slot, node->canSetTag);
3846  break;
3847 
3848  case CMD_DELETE:
3849  slot = ExecDelete(&context, resultRelInfo, tupleid, oldtuple,
3850  true, false, node->canSetTag, NULL, NULL, NULL);
3851  break;
3852 
3853  case CMD_MERGE:
3854  slot = ExecMerge(&context, resultRelInfo, tupleid, node->canSetTag);
3855  break;
3856 
3857  default:
3858  elog(ERROR, "unknown operation");
3859  break;
3860  }
3861 
3862  /*
3863  * If we got a RETURNING result, return it to caller. We'll continue
3864  * the work on next call.
3865  */
3866  if (slot)
3867  return slot;
3868  }
3869 
3870  /*
3871  * Insert remaining tuples for batch insert.
3872  */
3873  if (estate->es_insert_pending_result_relations != NIL)
3874  ExecPendingInserts(estate);
3875 
3876  /*
3877  * We're done, but fire AFTER STATEMENT triggers before exiting.
3878  */
3879  fireASTriggers(node);
3880 
3881  node->mt_done = true;
3882 
3883  return NULL;
3884 }
#define ResetPerTupleExprContext(estate)
Definition: executor.h:558
#define ResetExprContext(econtext)
Definition: executor.h:543
#define EvalPlanQualSetSlot(epqstate, slot)
Definition: executor.h:243
static TupleTableSlot * ExecProcNode(PlanState *node)
Definition: executor.h:268
#define DatumGetHeapTupleHeader(X)
Definition: fmgr.h:295
#define HeapTupleHeaderGetDatumLength(tup)
Definition: htup_details.h:450
static void ItemPointerSetInvalid(ItemPointerData *pointer)
Definition: itemptr.h:184
ItemPointerData * ItemPointer
Definition: itemptr.h:49
static void ExecInitInsertProjection(ModifyTableState *mtstate, ResultRelInfo *resultRelInfo)
static TupleTableSlot * ExecMerge(ModifyTableContext *context, ResultRelInfo *resultRelInfo, ItemPointer tupleid, bool canSetTag)
static TupleTableSlot * ExecGetInsertNewTuple(ResultRelInfo *relinfo, TupleTableSlot *planSlot)
static TupleTableSlot * ExecUpdate(ModifyTableContext *context, ResultRelInfo *resultRelInfo, ItemPointer tupleid, HeapTuple oldtuple, TupleTableSlot *slot, bool canSetTag)
ResultRelInfo * ExecLookupResultRelByOid(ModifyTableState *node, Oid resultoid, bool missing_ok, bool update_cache)
static void fireBSTriggers(ModifyTableState *node)
static void fireASTriggers(ModifyTableState *node)
#define castNode(_type_, nodeptr)
Definition: nodes.h:176
static Oid DatumGetObjectId(Datum X)
Definition: postgres.h:242
static Pointer DatumGetPointer(Datum X)
Definition: postgres.h:312
struct EPQState * es_epq_active
Definition: execnodes.h:697
ItemPointerData t_self
Definition: htup.h:65
uint32 t_len
Definition: htup.h:64
HeapTupleHeader t_data
Definition: htup.h:68
Oid t_tableOid
Definition: htup.h:66

References Assert(), AttributeNumberIsValid, ModifyTableState::canSetTag, castNode, CHECK_FOR_INTERRUPTS, CMD_DELETE, CMD_INSERT, CMD_MERGE, CMD_UPDATE, DatumGetHeapTupleHeader, DatumGetObjectId(), DatumGetPointer(), elog(), ModifyTableContext::epqstate, ERROR, EState::es_epq_active, EState::es_insert_pending_result_relations, ModifyTableContext::estate, EvalPlanQualSetSlot, ExecDelete(), ExecForceStoreHeapTuple(), ExecGetInsertNewTuple(), ExecGetJunkAttribute(), ExecGetUpdateNewTuple(), ExecInitInsertProjection(), ExecInitUpdateProjection(), ExecInsert(), ExecLookupResultRelByOid(), ExecMerge(), ExecPendingInserts(), ExecProcessReturning(), ExecProcNode(), ExecUpdate(), fireASTriggers(), fireBSTriggers(), ModifyTableState::fireBSTriggers, HeapTupleHeaderGetDatumLength, InvalidOid, ItemPointerSetInvalid(), ModifyTableState::mt_done, ModifyTableState::mt_epqstate, ModifyTableState::mt_lastResultIndex, ModifyTableState::mt_lastResultOid, ModifyTableState::mt_resultOidAttno, ModifyTableContext::mtstate, NIL, ModifyTableState::operation, outerPlanState, ModifyTableContext::planSlot, ModifyTableState::ps, PlanState::ps_ExprContext, RelationData::rd_rel, ModifyTableContext::relaction, RelationGetRelid, ResetExprContext, ResetPerTupleExprContext, ModifyTableState::resultRelInfo, ResultRelInfo::ri_oldTupleSlot, ResultRelInfo::ri_projectNewInfoValid, ResultRelInfo::ri_projectReturning, ResultRelInfo::ri_RelationDesc, ResultRelInfo::ri_RowIdAttNo, ResultRelInfo::ri_usesFdwDirectModify, SnapshotAny, PlanState::state, HeapTupleData::t_data, HeapTupleData::t_len, HeapTupleData::t_self, HeapTupleData::t_tableOid, table_tuple_fetch_row_version(), TupIsNull, and unlikely.

Referenced by ExecInitModifyTable().

◆ ExecOnConflictUpdate()

static bool ExecOnConflictUpdate ( ModifyTableContext context,
ResultRelInfo resultRelInfo,
ItemPointer  conflictTid,
TupleTableSlot excludedSlot,
bool  canSetTag,
TupleTableSlot **  returning 
)
static

Definition at line 2506 of file nodeModifyTable.c.

2512 {
2513  ModifyTableState *mtstate = context->mtstate;
2514  ExprContext *econtext = mtstate->ps.ps_ExprContext;
2515  Relation relation = resultRelInfo->ri_RelationDesc;
2516  ExprState *onConflictSetWhere = resultRelInfo->ri_onConflict->oc_WhereClause;
2517  TupleTableSlot *existing = resultRelInfo->ri_onConflict->oc_Existing;
2518  TM_FailureData tmfd;
2519  LockTupleMode lockmode;
2520  TM_Result test;
2521  Datum xminDatum;
2522  TransactionId xmin;
2523  bool isnull;
2524 
2525  /* Determine lock mode to use */
2526  lockmode = ExecUpdateLockMode(context->estate, resultRelInfo);
2527 
2528  /*
2529  * Lock tuple for update. Don't follow updates when tuple cannot be
2530  * locked without doing so. A row locking conflict here means our
2531  * previous conclusion that the tuple is conclusively committed is not
2532  * true anymore.
2533  */
2534  test = table_tuple_lock(relation, conflictTid,
2535  context->estate->es_snapshot,
2536  existing, context->estate->es_output_cid,
2537  lockmode, LockWaitBlock, 0,
2538  &tmfd);
2539  switch (test)
2540  {
2541  case TM_Ok:
2542  /* success! */
2543  break;
2544 
2545  case TM_Invisible:
2546 
2547  /*
2548  * This can occur when a just inserted tuple is updated again in
2549  * the same command. E.g. because multiple rows with the same
2550  * conflicting key values are inserted.
2551  *
2552  * This is somewhat similar to the ExecUpdate() TM_SelfModified
2553  * case. We do not want to proceed because it would lead to the
2554  * same row being updated a second time in some unspecified order,
2555  * and in contrast to plain UPDATEs there's no historical behavior
2556  * to break.
2557  *
2558  * It is the user's responsibility to prevent this situation from
2559  * occurring. These problems are why the SQL standard similarly
2560  * specifies that for SQL MERGE, an exception must be raised in
2561  * the event of an attempt to update the same row twice.
2562  */
2563  xminDatum = slot_getsysattr(existing,
2565  &isnull);
2566  Assert(!isnull);
2567  xmin = DatumGetTransactionId(xminDatum);
2568 
2570  ereport(ERROR,
2571  (errcode(ERRCODE_CARDINALITY_VIOLATION),
2572  /* translator: %s is a SQL command name */
2573  errmsg("%s command cannot affect row a second time",
2574  "ON CONFLICT DO UPDATE"),
2575  errhint("Ensure that no rows proposed for insertion within the same command have duplicate constrained values.")));
2576 
2577  /* This shouldn't happen */
2578  elog(ERROR, "attempted to lock invisible tuple");
2579  break;
2580 
2581  case TM_SelfModified:
2582 
2583  /*
2584  * This state should never be reached. As a dirty snapshot is used
2585  * to find conflicting tuples, speculative insertion wouldn't have
2586  * seen this row to conflict with.
2587  */
2588  elog(ERROR, "unexpected self-updated tuple");
2589  break;
2590 
2591  case TM_Updated:
2593  ereport(ERROR,
2595  errmsg("could not serialize access due to concurrent update")));
2596 
2597  /*
2598  * As long as we don't support an UPDATE of INSERT ON CONFLICT for
2599  * a partitioned table we shouldn't reach to a case where tuple to
2600  * be lock is moved to another partition due to concurrent update
2601  * of the partition key.
2602  */
2604 
2605  /*
2606  * Tell caller to try again from the very start.
2607  *
2608  * It does not make sense to use the usual EvalPlanQual() style
2609  * loop here, as the new version of the row might not conflict
2610  * anymore, or the conflicting tuple has actually been deleted.
2611  */
2612  ExecClearTuple(existing);
2613  return false;
2614 
2615  case TM_Deleted:
2617  ereport(ERROR,
2619  errmsg("could not serialize access due to concurrent delete")));
2620 
2621  /* see TM_Updated case */
2623  ExecClearTuple(existing);
2624  return false;
2625 
2626  default:
2627  elog(ERROR, "unrecognized table_tuple_lock status: %u", test);
2628  }
2629 
2630  /* Success, the tuple is locked. */
2631 
2632  /*
2633  * Verify that the tuple is visible to our MVCC snapshot if the current
2634  * isolation level mandates that.
2635  *
2636  * It's not sufficient to rely on the check within ExecUpdate() as e.g.
2637  * CONFLICT ... WHERE clause may prevent us from reaching that.
2638  *
2639  * This means we only ever continue when a new command in the current
2640  * transaction could see the row, even though in READ COMMITTED mode the
2641  * tuple will not be visible according to the current statement's
2642  * snapshot. This is in line with the way UPDATE deals with newer tuple
2643  * versions.
2644  */
2645  ExecCheckTupleVisible(context->estate, relation, existing);
2646 
2647  /*
2648  * Make tuple and any needed join variables available to ExecQual and
2649  * ExecProject. The EXCLUDED tuple is installed in ecxt_innertuple, while
2650  * the target's existing tuple is installed in the scantuple. EXCLUDED
2651  * has been made to reference INNER_VAR in setrefs.c, but there is no
2652  * other redirection.
2653  */
2654  econtext->ecxt_scantuple = existing;
2655  econtext->ecxt_innertuple = excludedSlot;
2656  econtext->ecxt_outertuple = NULL;
2657 
2658  if (!ExecQual(onConflictSetWhere, econtext))
2659  {
2660  ExecClearTuple(existing); /* see return below */
2661  InstrCountFiltered1(&mtstate->ps, 1);
2662  return true; /* done with the tuple */
2663  }
2664 
2665  if (resultRelInfo->ri_WithCheckOptions != NIL)
2666  {
2667  /*
2668  * Check target's existing tuple against UPDATE-applicable USING
2669  * security barrier quals (if any), enforced here as RLS checks/WCOs.
2670  *
2671  * The rewriter creates UPDATE RLS checks/WCOs for UPDATE security
2672  * quals, and stores them as WCOs of "kind" WCO_RLS_CONFLICT_CHECK,
2673  * but that's almost the extent of its special handling for ON
2674  * CONFLICT DO UPDATE.
2675  *
2676  * The rewriter will also have associated UPDATE applicable straight
2677  * RLS checks/WCOs for the benefit of the ExecUpdate() call that
2678  * follows. INSERTs and UPDATEs naturally have mutually exclusive WCO
2679  * kinds, so there is no danger of spurious over-enforcement in the
2680  * INSERT or UPDATE path.
2681  */
2683  existing,
2684  mtstate->ps.state);
2685  }
2686 
2687  /* Project the new tuple version */
2688  ExecProject(resultRelInfo->ri_onConflict->oc_ProjInfo);
2689 
2690  /*
2691  * Note that it is possible that the target tuple has been modified in
2692  * this session, after the above table_tuple_lock. We choose to not error
2693  * out in that case, in line with ExecUpdate's treatment of similar cases.
2694  * This can happen if an UPDATE is triggered from within ExecQual(),
2695  * ExecWithCheckOptions() or ExecProject() above, e.g. by selecting from a
2696  * wCTE in the ON CONFLICT's SET.
2697  */
2698 
2699  /* Execute UPDATE with projection */
2700  *returning = ExecUpdate(context, resultRelInfo,
2701  conflictTid, NULL,
2702  resultRelInfo->ri_onConflict->oc_ProjSlot,
2703  canSetTag);
2704 
2705  /*
2706  * Clear out existing tuple, as there might not be another conflict among
2707  * the next input rows. Don't want to hold resources till the end of the
2708  * query.
2709  */
2710  ExecClearTuple(existing);
2711  return true;
2712 }
#define InstrCountFiltered1(node, delta)
Definition: execnodes.h:1147
@ WCO_RLS_CONFLICT_CHECK
Definition: parsenodes.h:1309
static void test(void)

References Assert(), TM_FailureData::ctid, DatumGetTransactionId(), ExprContext::ecxt_innertuple, ExprContext::ecxt_outertuple, ExprContext::ecxt_scantuple, elog(), ereport, errcode(), ERRCODE_T_R_SERIALIZATION_FAILURE, errhint(), errmsg(), ERROR, EState::es_output_cid, EState::es_snapshot, ModifyTableContext::estate, ExecCheckTupleVisible(), ExecClearTuple(), ExecProject(), ExecQual(), ExecUpdate(), ExecUpdateLockMode(), ExecWithCheckOptions(), InstrCountFiltered1, IsolationUsesXactSnapshot, ItemPointerIndicatesMovedPartitions(), LockWaitBlock, MinTransactionIdAttributeNumber, ModifyTableContext::mtstate, NIL, OnConflictSetState::oc_Existing, OnConflictSetState::oc_ProjInfo, OnConflictSetState::oc_ProjSlot, OnConflictSetState::oc_WhereClause, ModifyTableState::ps, PlanState::ps_ExprContext, ResultRelInfo::ri_onConflict, ResultRelInfo::ri_RelationDesc, ResultRelInfo::ri_WithCheckOptions, slot_getsysattr(), PlanState::state, table_tuple_lock(), test(), TM_Deleted, TM_Invisible, TM_Ok, TM_SelfModified, TM_Updated, TransactionIdIsCurrentTransactionId(), and WCO_RLS_CONFLICT_CHECK.

Referenced by ExecInsert().

◆ ExecPendingInserts()

static void ExecPendingInserts ( EState estate)
static

Definition at line 1277 of file nodeModifyTable.c.

1278 {
1279  ListCell *l1,
1280  *l2;
1281 
1283  l2, estate->es_insert_pending_modifytables)
1284  {
1285  ResultRelInfo *resultRelInfo = (ResultRelInfo *) lfirst(l1);
1286  ModifyTableState *mtstate = (ModifyTableState *) lfirst(l2);
1287 
1288  Assert(mtstate);
1289  ExecBatchInsert(mtstate, resultRelInfo,
1290  resultRelInfo->ri_Slots,
1291  resultRelInfo->ri_PlanSlots,
1292  resultRelInfo->ri_NumSlots,
1293  estate, mtstate->canSetTag);
1294  }
1295 
1300 }
#define forboth(cell1, list1, cell2, list2)
Definition: pg_list.h:518

References Assert(), ModifyTableState::canSetTag, EState::es_insert_pending_modifytables, EState::es_insert_pending_result_relations, ExecBatchInsert(), forboth, lfirst, list_free(), NIL, ResultRelInfo::ri_NumSlots, ResultRelInfo::ri_PlanSlots, and ResultRelInfo::ri_Slots.

Referenced by ExecDeletePrologue(), ExecInsert(), ExecModifyTable(), and ExecUpdatePrologue().

◆ ExecPrepareTupleRouting()

static TupleTableSlot * ExecPrepareTupleRouting ( ModifyTableState mtstate,
EState estate,
PartitionTupleRouting proute,
ResultRelInfo targetRelInfo,
TupleTableSlot slot,
ResultRelInfo **  partRelInfo 
)
static

Definition at line 3499 of file nodeModifyTable.c.

3505 {
3506  ResultRelInfo *partrel;
3507  TupleConversionMap *map;
3508 
3509  /*
3510  * Lookup the target partition's ResultRelInfo. If ExecFindPartition does
3511  * not find a valid partition for the tuple in 'slot' then an error is
3512  * raised. An error may also be raised if the found partition is not a
3513  * valid target for INSERTs. This is required since a partitioned table
3514  * UPDATE to another partition becomes a DELETE+INSERT.
3515  */
3516  partrel = ExecFindPartition(mtstate, targetRelInfo, proute, slot, estate);
3517 
3518  /*
3519  * If we're capturing transition tuples, we might need to convert from the
3520  * partition rowtype to root partitioned table's rowtype. But if there
3521  * are no BEFORE triggers on the partition that could change the tuple, we
3522  * can just remember the original unconverted tuple to avoid a needless
3523  * round trip conversion.
3524  */
3525  if (mtstate->mt_transition_capture != NULL)
3526  {
3527  bool has_before_insert_row_trig;
3528 
3529  has_before_insert_row_trig = (partrel->ri_TrigDesc &&
3531 
3533  !has_before_insert_row_trig ? slot : NULL;
3534  }
3535 
3536  /*
3537  * Convert the tuple, if necessary.
3538  */
3539  map = ExecGetRootToChildMap(partrel, estate);
3540  if (map != NULL)
3541  {
3542  TupleTableSlot *new_slot = partrel->ri_PartitionTupleSlot;
3543 
3544  slot = execute_attr_map_slot(map->attrMap, slot, new_slot);
3545  }
3546 
3547  *partRelInfo = partrel;
3548  return slot;
3549 }
ResultRelInfo * ExecFindPartition(ModifyTableState *mtstate, ResultRelInfo *rootResultRelInfo, PartitionTupleRouting *proute, TupleTableSlot *slot, EState *estate)
TupleConversionMap * ExecGetRootToChildMap(ResultRelInfo *resultRelInfo, EState *estate)
Definition: execUtils.c:1237
TupleTableSlot * ri_PartitionTupleSlot
Definition: execnodes.h:581

References TupleConversionMap::attrMap, ExecFindPartition(), ExecGetRootToChildMap(), execute_attr_map_slot(), ModifyTableState::mt_transition_capture, ResultRelInfo::ri_PartitionTupleSlot, ResultRelInfo::ri_TrigDesc, TransitionCaptureState::tcs_original_insert_tuple, and TriggerDesc::trig_insert_before_row.

Referenced by ExecInsert().

◆ ExecProcessReturning()

static TupleTableSlot* ExecProcessReturning ( ResultRelInfo resultRelInfo,
TupleTableSlot tupleSlot,
TupleTableSlot planSlot 
)
static

Definition at line 250 of file nodeModifyTable.c.

253 {
254  ProjectionInfo *projectReturning = resultRelInfo->ri_projectReturning;
255  ExprContext *econtext = projectReturning->pi_exprContext;
256 
257  /* Make tuple and any needed join variables available to ExecProject */
258  if (tupleSlot)
259  econtext->ecxt_scantuple = tupleSlot;
260  econtext->ecxt_outertuple = planSlot;
261 
262  /*
263  * RETURNING expressions might reference the tableoid column, so
264  * reinitialize tts_tableOid before evaluating them.
265  */
266  econtext->ecxt_scantuple->tts_tableOid =
267  RelationGetRelid(resultRelInfo->ri_RelationDesc);
268 
269  /* Compute the RETURNING expressions */
270  return ExecProject(projectReturning);
271 }

References ExprContext::ecxt_outertuple, ExprContext::ecxt_scantuple, ExecProject(), ProjectionInfo::pi_exprContext, RelationGetRelid, ResultRelInfo::ri_projectReturning, ResultRelInfo::ri_RelationDesc, and TupleTableSlot::tts_tableOid.

Referenced by ExecDelete(), ExecInsert(), ExecModifyTable(), and ExecUpdate().

◆ ExecReScanModifyTable()

void ExecReScanModifyTable ( ModifyTableState node)

Definition at line 4482 of file nodeModifyTable.c.

4483 {
4484  /*
4485  * Currently, we don't need to support rescan on ModifyTable nodes. The
4486  * semantics of that would be a bit debatable anyway.
4487  */
4488  elog(ERROR, "ExecReScanModifyTable is not implemented");
4489 }

References elog(), and ERROR.

Referenced by ExecReScan().

◆ ExecSetupTransitionCaptureState()

static void ExecSetupTransitionCaptureState ( ModifyTableState mtstate,
EState estate 
)
static

Definition at line 3470 of file nodeModifyTable.c.

3471 {
3472  ModifyTable *plan = (ModifyTable *) mtstate->ps.plan;
3473  ResultRelInfo *targetRelInfo = mtstate->rootResultRelInfo;
3474 
3475  /* Check for transition tables on the directly targeted relation. */
3476  mtstate->mt_transition_capture =
3477  MakeTransitionCaptureState(targetRelInfo->ri_TrigDesc,
3478  RelationGetRelid(targetRelInfo->ri_RelationDesc),
3479  mtstate->operation);
3480  if (plan->operation == CMD_INSERT &&
3481  plan->onConflictAction == ONCONFLICT_UPDATE)
3482  mtstate->mt_oc_transition_capture =
3483  MakeTransitionCaptureState(targetRelInfo->ri_TrigDesc,
3484  RelationGetRelid(targetRelInfo->ri_RelationDesc),
3485  CMD_UPDATE);
3486 }
#define plan(x)
Definition: pg_regress.c:162
struct TransitionCaptureState * mt_oc_transition_capture
Definition: execnodes.h:1323
TransitionCaptureState * MakeTransitionCaptureState(TriggerDesc *trigdesc, Oid relid, CmdType cmdType)
Definition: trigger.c:4889

References CMD_INSERT, CMD_UPDATE, MakeTransitionCaptureState(), ModifyTableState::mt_oc_transition_capture, ModifyTableState::mt_transition_capture, ONCONFLICT_UPDATE, ModifyTableState::operation, PlanState::plan, plan, ModifyTableState::ps, RelationGetRelid, and ModifyTableState::rootResultRelInfo.

Referenced by ExecInitModifyTable().

◆ ExecUpdate()

static TupleTableSlot* ExecUpdate ( ModifyTableContext context,
ResultRelInfo resultRelInfo,
ItemPointer  tupleid,
HeapTuple  oldtuple,
TupleTableSlot slot,
bool  canSetTag 
)
static

Definition at line 2265 of file nodeModifyTable.c.

2268 {
2269  EState *estate = context->estate;
2270  Relation resultRelationDesc = resultRelInfo->ri_RelationDesc;
2271  UpdateContext updateCxt = {0};
2272  TM_Result result;
2273 
2274  /*
2275  * abort the operation if not running transactions
2276  */
2278  elog(ERROR, "cannot UPDATE during bootstrap");
2279 
2280  /*
2281  * Prepare for the update. This includes BEFORE ROW triggers, so we're
2282  * done if it says we are.
2283  */
2284  if (!ExecUpdatePrologue(context, resultRelInfo, tupleid, oldtuple, slot, NULL))
2285  return NULL;
2286 
2287  /* INSTEAD OF ROW UPDATE Triggers */
2288  if (resultRelInfo->ri_TrigDesc &&
2289  resultRelInfo->ri_TrigDesc->trig_update_instead_row)
2290  {
2291  if (!ExecIRUpdateTriggers(estate, resultRelInfo,
2292  oldtuple, slot))
2293  return NULL; /* "do nothing" */
2294  }
2295  else if (resultRelInfo->ri_FdwRoutine)
2296  {
2297  /* Fill in GENERATEd columns */
2298  ExecUpdatePrepareSlot(resultRelInfo, slot, estate);
2299 
2300  /*
2301  * update in foreign table: let the FDW do it
2302  */
2303  slot = resultRelInfo->ri_FdwRoutine->ExecForeignUpdate(estate,
2304  resultRelInfo,
2305  slot,
2306  context->planSlot);
2307 
2308  if (slot == NULL) /* "do nothing" */
2309  return NULL;
2310 
2311  /*
2312  * AFTER ROW Triggers or RETURNING expressions might reference the
2313  * tableoid column, so (re-)initialize tts_tableOid before evaluating
2314  * them. (This covers the case where the FDW replaced the slot.)
2315  */
2316  slot->tts_tableOid = RelationGetRelid(resultRelationDesc);
2317  }
2318  else
2319  {
2320  /*
2321  * If we generate a new candidate tuple after EvalPlanQual testing, we
2322  * must loop back here to try again. (We don't need to redo triggers,
2323  * however. If there are any BEFORE triggers then trigger.c will have
2324  * done table_tuple_lock to lock the correct tuple, so there's no need
2325  * to do them again.)
2326  */
2327 redo_act:
2328  result = ExecUpdateAct(context, resultRelInfo, tupleid, oldtuple, slot,
2329  canSetTag, &updateCxt);
2330 
2331  /*
2332  * If ExecUpdateAct reports that a cross-partition update was done,
2333  * then the RETURNING tuple (if any) has been projected and there's
2334  * nothing else for us to do.
2335  */
2336  if (updateCxt.crossPartUpdate)
2337  return context->cpUpdateReturningSlot;
2338 
2339  switch (result)
2340  {
2341  case TM_SelfModified:
2342 
2343  /*
2344  * The target tuple was already updated or deleted by the
2345  * current command, or by a later command in the current
2346  * transaction. The former case is possible in a join UPDATE
2347  * where multiple tuples join to the same target tuple. This
2348  * is pretty questionable, but Postgres has always allowed it:
2349  * we just execute the first update action and ignore
2350  * additional update attempts.
2351  *
2352  * The latter case arises if the tuple is modified by a
2353  * command in a BEFORE trigger, or perhaps by a command in a
2354  * volatile function used in the query. In such situations we
2355  * should not ignore the update, but it is equally unsafe to
2356  * proceed. We don't want to discard the original UPDATE
2357  * while keeping the triggered actions based on it; and we
2358  * have no principled way to merge this update with the
2359  * previous ones. So throwing an error is the only safe
2360  * course.
2361  *
2362  * If a trigger actually intends this type of interaction, it
2363  * can re-execute the UPDATE (assuming it can figure out how)
2364  * and then return NULL to cancel the outer update.
2365  */
2366  if (context->tmfd.cmax != estate->es_output_cid)
2367  ereport(ERROR,
2368  (errcode(ERRCODE_TRIGGERED_DATA_CHANGE_VIOLATION),
2369  errmsg("tuple to be updated was already modified by an operation triggered by the current command"),
2370  errhint("Consider using an AFTER trigger instead of a BEFORE trigger to propagate changes to other rows.")));
2371 
2372  /* Else, already updated by self; nothing to do */
2373  return NULL;
2374 
2375  case TM_Ok:
2376  break;
2377 
2378  case TM_Updated:
2379  {
2380  TupleTableSlot *inputslot;
2381  TupleTableSlot *epqslot;
2382  TupleTableSlot *oldSlot;
2383 
2385  ereport(ERROR,
2387  errmsg("could not serialize access due to concurrent update")));
2388 
2389  /*
2390  * Already know that we're going to need to do EPQ, so
2391  * fetch tuple directly into the right slot.
2392  */
2393  inputslot = EvalPlanQualSlot(context->epqstate, resultRelationDesc,
2394  resultRelInfo->ri_RangeTableIndex);
2395 
2396  result = table_tuple_lock(resultRelationDesc, tupleid,
2397  estate->es_snapshot,
2398  inputslot, estate->es_output_cid,
2399  updateCxt.lockmode, LockWaitBlock,
2401  &context->tmfd);
2402 
2403  switch (result)
2404  {
2405  case TM_Ok:
2406  Assert(context->tmfd.traversed);
2407 
2408  epqslot = EvalPlanQual(context->epqstate,
2409  resultRelationDesc,
2410  resultRelInfo->ri_RangeTableIndex,
2411  inputslot);
2412  if (TupIsNull(epqslot))
2413  /* Tuple not passing quals anymore, exiting... */
2414  return NULL;
2415 
2416  /* Make sure ri_oldTupleSlot is initialized. */
2417  if (unlikely(!resultRelInfo->ri_projectNewInfoValid))
2419  resultRelInfo);
2420 
2421  /* Fetch the most recent version of old tuple. */
2422  oldSlot = resultRelInfo->ri_oldTupleSlot;
2423  if (!table_tuple_fetch_row_version(resultRelationDesc,
2424  tupleid,
2425  SnapshotAny,
2426  oldSlot))
2427  elog(ERROR, "failed to fetch tuple being updated");
2428  slot = ExecGetUpdateNewTuple(resultRelInfo,
2429  epqslot, oldSlot);
2430  goto redo_act;
2431 
2432  case TM_Deleted:
2433  /* tuple already deleted; nothing to do */
2434  return NULL;
2435 
2436  case TM_SelfModified:
2437 
2438  /*
2439  * This can be reached when following an update
2440  * chain from a tuple updated by another session,
2441  * reaching a tuple that was already updated in
2442  * this transaction. If previously modified by
2443  * this command, ignore the redundant update,
2444  * otherwise error out.
2445  *
2446  * See also TM_SelfModified response to
2447  * table_tuple_update() above.
2448  */
2449  if (context->tmfd.cmax != estate->es_output_cid)
2450  ereport(ERROR,
2451  (errcode(ERRCODE_TRIGGERED_DATA_CHANGE_VIOLATION),
2452  errmsg("tuple to be updated was already modified by an operation triggered by the current command"),
2453  errhint("Consider using an AFTER trigger instead of a BEFORE trigger to propagate changes to other rows.")));
2454  return NULL;
2455 
2456  default:
2457  /* see table_tuple_lock call in ExecDelete() */
2458  elog(ERROR, "unexpected table_tuple_lock status: %u",
2459  result);
2460  return NULL;
2461  }
2462  }
2463 
2464  break;
2465 
2466  case TM_Deleted:
2468  ereport(ERROR,
2470  errmsg("could not serialize access due to concurrent delete")));
2471  /* tuple already deleted; nothing to do */
2472  return NULL;
2473 
2474  default:
2475  elog(ERROR, "unrecognized table_tuple_update status: %u",
2476  result);
2477  return NULL;
2478  }
2479  }
2480 
2481  if (canSetTag)
2482  (estate->es_processed)++;
2483 
2484  ExecUpdateEpilogue(context, &updateCxt, resultRelInfo, tupleid, oldtuple,
2485  slot);
2486 
2487  /* Process RETURNING if present */
2488  if (resultRelInfo->ri_projectReturning)
2489  return ExecProcessReturning(resultRelInfo, slot, context->planSlot);
2490 
2491  return NULL;
2492 }
#define IsBootstrapProcessingMode()
Definition: miscadmin.h:415
static void ExecUpdatePrepareSlot(ResultRelInfo *resultRelInfo, TupleTableSlot *slot, EState *estate)
ExecForeignUpdate_function ExecForeignUpdate
Definition: fdwapi.h:235
bool trig_update_instead_row
Definition: reltrigger.h:63
LockTupleMode lockmode
bool ExecIRUpdateTriggers(EState *estate, ResultRelInfo *relinfo, HeapTuple trigtuple, TupleTableSlot *newslot)
Definition: trigger.c:3163

References Assert(), TM_FailureData::cmax, ModifyTableContext::cpUpdateReturningSlot, UpdateContext::crossPartUpdate, elog(), ModifyTableContext::epqstate, ereport, errcode(), ERRCODE_T_R_SERIALIZATION_FAILURE, errhint(), errmsg(), ERROR, EState::es_output_cid, EState::es_processed, EState::es_snapshot, ModifyTableContext::estate, EvalPlanQual(), EvalPlanQualSlot(), FdwRoutine::ExecForeignUpdate, ExecGetUpdateNewTuple(), ExecInitUpdateProjection(), ExecIRUpdateTriggers(), ExecProcessReturning(), ExecUpdateAct(), ExecUpdateEpilogue(), ExecUpdatePrepareSlot(), ExecUpdatePrologue(), IsBootstrapProcessingMode, IsolationUsesXactSnapshot, UpdateContext::lockmode, LockWaitBlock, ModifyTableContext::mtstate, ModifyTableContext::planSlot, RelationGetRelid, ResultRelInfo::ri_FdwRoutine, ResultRelInfo::ri_oldTupleSlot, ResultRelInfo::ri_projectNewInfoValid, ResultRelInfo::ri_projectReturning, ResultRelInfo::ri_RangeTableIndex, ResultRelInfo::ri_RelationDesc, ResultRelInfo::ri_TrigDesc, SnapshotAny, table_tuple_fetch_row_version(), table_tuple_lock(), TM_Deleted, TM_Ok, TM_SelfModified, TM_Updated, ModifyTableContext::tmfd, TM_FailureData::traversed, TriggerDesc::trig_update_instead_row, TupleTableSlot::tts_tableOid, TupIsNull, TUPLE_LOCK_FLAG_FIND_LAST_VERSION, and unlikely.

Referenced by ExecModifyTable(), and ExecOnConflictUpdate().

◆ ExecUpdateAct()

static TM_Result ExecUpdateAct ( ModifyTableContext context,
ResultRelInfo resultRelInfo,
ItemPointer  tupleid,
HeapTuple  oldtuple,
TupleTableSlot slot,
bool  canSetTag,
UpdateContext updateCxt 
)
static

Definition at line 1973 of file nodeModifyTable.c.

1976 {
1977  EState *estate = context->estate;
1978  Relation resultRelationDesc = resultRelInfo->ri_RelationDesc;
1979  bool partition_constraint_failed;
1980  TM_Result result;
1981 
1982  updateCxt->crossPartUpdate = false;
1983 
1984  /*
1985  * If we move the tuple to a new partition, we loop back here to recompute
1986  * GENERATED values (which are allowed to be different across partitions)
1987  * and recheck any RLS policies and constraints. We do not fire any
1988  * BEFORE triggers of the new partition, however.
1989  */
1990 lreplace:
1991  /* Fill in GENERATEd columns */
1992  ExecUpdatePrepareSlot(resultRelInfo, slot, estate);
1993 
1994  /* ensure slot is independent, consider e.g. EPQ */
1995  ExecMaterializeSlot(slot);
1996 
1997  /*
1998  * If partition constraint fails, this row might get moved to another
1999  * partition, in which case we should check the RLS CHECK policy just
2000  * before inserting into the new partition, rather than doing it here.
2001  * This is because a trigger on that partition might again change the row.
2002  * So skip the WCO checks if the partition constraint fails.
2003  */
2004  partition_constraint_failed =
2005  resultRelationDesc->rd_rel->relispartition &&
2006  !ExecPartitionCheck(resultRelInfo, slot, estate, false);
2007 
2008  /* Check any RLS UPDATE WITH CHECK policies */
2009  if (!partition_constraint_failed &&
2010  resultRelInfo->ri_WithCheckOptions != NIL)
2011  {
2012  /*
2013  * ExecWithCheckOptions() will skip any WCOs which are not of the kind
2014  * we are looking for at this point.
2015  */
2017  resultRelInfo, slot, estate);
2018  }
2019 
2020  /*
2021  * If a partition check failed, try to move the row into the right
2022  * partition.
2023  */
2024  if (partition_constraint_failed)
2025  {
2026  TupleTableSlot *inserted_tuple,
2027  *retry_slot;
2028  ResultRelInfo *insert_destrel = NULL;
2029 
2030  /*
2031  * ExecCrossPartitionUpdate will first DELETE the row from the
2032  * partition it's currently in and then insert it back into the root
2033  * table, which will re-route it to the correct partition. However,
2034  * if the tuple has been concurrently updated, a retry is needed.
2035  */
2036  if (ExecCrossPartitionUpdate(context, resultRelInfo,
2037  tupleid, oldtuple, slot,
2038  canSetTag, updateCxt,
2039  &result,
2040  &retry_slot,
2041  &inserted_tuple,
2042  &insert_destrel))
2043  {
2044  /* success! */
2045  updateCxt->updated = true;
2046  updateCxt->crossPartUpdate = true;
2047 
2048  /*
2049  * If the partitioned table being updated is referenced in foreign
2050  * keys, queue up trigger events to check that none of them were
2051  * violated. No special treatment is needed in
2052  * non-cross-partition update situations, because the leaf
2053  * partition's AR update triggers will take care of that. During
2054  * cross-partition updates implemented as delete on the source
2055  * partition followed by insert on the destination partition,
2056  * AR-UPDATE triggers of the root table (that is, the table
2057  * mentioned in the query) must be fired.
2058  *
2059  * NULL insert_destrel means that the move failed to occur, that
2060  * is, the update failed, so no need to anything in that case.
2061  */
2062  if (insert_destrel &&
2063  resultRelInfo->ri_TrigDesc &&
2064  resultRelInfo->ri_TrigDesc->trig_update_after_row)
2066  resultRelInfo,
2067  insert_destrel,
2068  tupleid, slot,
2069  inserted_tuple);
2070 
2071  return TM_Ok;
2072  }
2073 
2074  /*
2075  * No luck, a retry is needed. If running MERGE, we do not do so
2076  * here; instead let it handle that on its own rules.
2077  */
2078  if (context->relaction != NULL)
2079  return result;
2080 
2081  /*
2082  * ExecCrossPartitionUpdate installed an updated version of the new
2083  * tuple in the retry slot; start over.
2084  */
2085  slot = retry_slot;
2086  goto lreplace;
2087  }
2088 
2089  /*
2090  * Check the constraints of the tuple. We've already checked the
2091  * partition constraint above; however, we must still ensure the tuple
2092  * passes all other constraints, so we will call ExecConstraints() and
2093  * have it validate all remaining checks.
2094  */
2095  if (resultRelationDesc->rd_att->constr)
2096  ExecConstraints(resultRelInfo, slot, estate);
2097 
2098  /*
2099  * replace the heap tuple
2100  *
2101  * Note: if es_crosscheck_snapshot isn't InvalidSnapshot, we check that
2102  * the row to be updated is visible to that snapshot, and throw a
2103  * can't-serialize error if not. This is a special-case behavior needed
2104  * for referential integrity updates in transaction-snapshot mode
2105  * transactions.
2106  */
2107  result = table_tuple_update(resultRelationDesc, tupleid, slot,
2108  estate->es_output_cid,
2109  estate->es_snapshot,
2110  estate->es_crosscheck_snapshot,
2111  true /* wait for commit */ ,
2112  &context->tmfd, &updateCxt->lockmode,
2113  &updateCxt->updateIndexes);
2114  if (result == TM_Ok)
2115  updateCxt->updated = true;
2116 
2117  return result;
2118 }
static void ExecCrossPartitionUpdateForeignKey(ModifyTableContext *context, ResultRelInfo *sourcePartInfo, ResultRelInfo *destPartInfo, ItemPointer tupleid, TupleTableSlot *oldslot, TupleTableSlot *newslot)
static bool ExecCrossPartitionUpdate(ModifyTableContext *context, ResultRelInfo *resultRelInfo, ItemPointer tupleid, HeapTuple oldtuple, TupleTableSlot *slot, bool canSetTag, UpdateContext *updateCxt, TM_Result *tmresult, TupleTableSlot **retry_slot, TupleTableSlot **inserted_tuple, ResultRelInfo **insert_destrel)
TU_UpdateIndexes updateIndexes
static TM_Result table_tuple_update(Relation rel, ItemPointer otid, TupleTableSlot *slot, CommandId cid, Snapshot snapshot, Snapshot crosscheck, bool wait, TM_FailureData *tmfd, LockTupleMode *lockmode, TU_UpdateIndexes *update_indexes)
Definition: tableam.h:1530

References TupleDescData::constr, UpdateContext::crossPartUpdate, EState::es_crosscheck_snapshot, EState::es_output_cid, EState::es_snapshot, ModifyTableContext::estate, ExecConstraints(), ExecCrossPartitionUpdate(), ExecCrossPartitionUpdateForeignKey(), ExecMaterializeSlot(), ExecPartitionCheck(), ExecUpdatePrepareSlot(), ExecWithCheckOptions(), UpdateContext::lockmode, NIL, RelationData::rd_att, RelationData::rd_rel, ModifyTableContext::relaction, ResultRelInfo::ri_RelationDesc, ResultRelInfo::ri_TrigDesc, ResultRelInfo::ri_WithCheckOptions, table_tuple_update(), TM_Ok, ModifyTableContext::tmfd, TriggerDesc::trig_update_after_row, UpdateContext::updated, UpdateContext::updateIndexes, and WCO_RLS_UPDATE_CHECK.

Referenced by ExecMergeMatched(), and ExecUpdate().

◆ ExecUpdateEpilogue()

static void ExecUpdateEpilogue ( ModifyTableContext context,
UpdateContext updateCxt,
ResultRelInfo resultRelInfo,
ItemPointer  tupleid,
HeapTuple  oldtuple,
TupleTableSlot slot 
)
static

Definition at line 2127 of file nodeModifyTable.c.

2130 {
2131  ModifyTableState *mtstate = context->mtstate;
2132  List *recheckIndexes = NIL;
2133 
2134  /* insert index entries for tuple if necessary */
2135  if (resultRelInfo->ri_NumIndices > 0 && (updateCxt->updateIndexes != TU_None))
2136  recheckIndexes = ExecInsertIndexTuples(resultRelInfo,
2137  slot, context->estate,
2138  true, false,
2139  NULL, NIL,
2140  (updateCxt->updateIndexes == TU_Summarizing));
2141 
2142  /* AFTER ROW UPDATE Triggers */
2143  ExecARUpdateTriggers(context->estate, resultRelInfo,
2144  NULL, NULL,
2145  tupleid, oldtuple, slot,
2146  recheckIndexes,
2147  mtstate->operation == CMD_INSERT ?
2148  mtstate->mt_oc_transition_capture :
2149  mtstate->mt_transition_capture,
2150  false);
2151 
2152  list_free(recheckIndexes);
2153 
2154  /*
2155  * Check any WITH CHECK OPTION constraints from parent views. We are
2156  * required to do this after testing all constraints and uniqueness
2157  * violations per the SQL spec, so we do it after actually updating the
2158  * record in the heap and all indexes.
2159  *
2160  * ExecWithCheckOptions() will skip any WCOs which are not of the kind we
2161  * are looking for at this point.
2162  */
2163  if (resultRelInfo->ri_WithCheckOptions != NIL)
2164  ExecWithCheckOptions(WCO_VIEW_CHECK, resultRelInfo,
2165  slot, context->estate);
2166 }
@ TU_Summarizing
Definition: tableam.h:118
@ TU_None
Definition: tableam.h:112

References CMD_INSERT, ModifyTableContext::estate, ExecARUpdateTriggers(), ExecInsertIndexTuples(), ExecWithCheckOptions(), list_free(), ModifyTableState::mt_oc_transition_capture, ModifyTableState::mt_transition_capture, ModifyTableContext::mtstate, NIL, ModifyTableState::operation, ResultRelInfo::ri_NumIndices, ResultRelInfo::ri_WithCheckOptions, TU_None, TU_Summarizing, UpdateContext::updateIndexes, and WCO_VIEW_CHECK.

Referenced by ExecMergeMatched(), and ExecUpdate().

◆ ExecUpdatePrepareSlot()

static void ExecUpdatePrepareSlot ( ResultRelInfo resultRelInfo,
TupleTableSlot slot,
EState estate 
)
static

Definition at line 1938 of file nodeModifyTable.c.

1941 {
1942  Relation resultRelationDesc = resultRelInfo->ri_RelationDesc;
1943 
1944  /*
1945  * Constraints and GENERATED expressions might reference the tableoid
1946  * column, so (re-)initialize tts_tableOid before evaluating them.
1947  */
1948  slot->tts_tableOid = RelationGetRelid(resultRelationDesc);
1949 
1950  /*
1951  * Compute stored generated columns
1952  */
1953  if (resultRelationDesc->rd_att->constr &&
1954  resultRelationDesc->rd_att->constr->has_generated_stored)
1955  ExecComputeStoredGenerated(resultRelInfo, estate, slot,
1956  CMD_UPDATE);
1957 }

References CMD_UPDATE, TupleDescData::constr, ExecComputeStoredGenerated(), TupleConstr::has_generated_stored, RelationData::rd_att, RelationGetRelid, ResultRelInfo::ri_RelationDesc, and TupleTableSlot::tts_tableOid.

Referenced by ExecUpdate(), and ExecUpdateAct().

◆ ExecUpdatePrologue()

static bool ExecUpdatePrologue ( ModifyTableContext context,
ResultRelInfo resultRelInfo,
ItemPointer  tupleid,
HeapTuple  oldtuple,
TupleTableSlot slot,
TM_Result result 
)
static

Definition at line 1896 of file nodeModifyTable.c.

1899 {
1900  Relation resultRelationDesc = resultRelInfo->ri_RelationDesc;
1901 
1902  if (result)
1903  *result = TM_Ok;
1904 
1905  ExecMaterializeSlot(slot);
1906 
1907  /*
1908  * Open the table's indexes, if we have not done so already, so that we
1909  * can add new index entries for the updated tuple.
1910  */
1911  if (resultRelationDesc->rd_rel->relhasindex &&
1912  resultRelInfo->ri_IndexRelationDescs == NULL)
1913  ExecOpenIndices(resultRelInfo, false);
1914 
1915  /* BEFORE ROW UPDATE triggers */
1916  if (resultRelInfo->ri_TrigDesc &&
1917  resultRelInfo->ri_TrigDesc->trig_update_before_row)
1918  {
1919  /* Flush any pending inserts, so rows are visible to the triggers */
1921  ExecPendingInserts(context->estate);
1922 
1923  return ExecBRUpdateTriggers(context->estate, context->epqstate,
1924  resultRelInfo, tupleid, oldtuple, slot,
1925  result, &context->tmfd);
1926  }
1927 
1928  return true;
1929 }
bool ExecBRUpdateTriggers(EState *estate, EPQState *epqstate, ResultRelInfo *relinfo, ItemPointer tupleid, HeapTuple fdw_trigtuple, TupleTableSlot *newslot, TM_Result *tmresult, TM_FailureData *tmfd)
Definition: trigger.c:2941

References ModifyTableContext::epqstate, EState::es_insert_pending_result_relations, ModifyTableContext::estate, ExecBRUpdateTriggers(), ExecMaterializeSlot(), ExecOpenIndices(), ExecPendingInserts(), NIL, RelationData::rd_rel, ResultRelInfo::ri_IndexRelationDescs, ResultRelInfo::ri_RelationDesc, ResultRelInfo::ri_TrigDesc, TM_Ok, ModifyTableContext::tmfd, and TriggerDesc::trig_update_before_row.

Referenced by