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, bool *tupleDeleted, TupleTableSlot **epqreturnslot)
 
static bool ExecCrossPartitionUpdate (ModifyTableContext *context, ResultRelInfo *resultRelInfo, ItemPointer tupleid, HeapTuple oldtuple, TupleTableSlot *slot, bool canSetTag, UpdateContext *updateCxt, 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:1313
#define NIL
Definition: pg_list.h:68
#define RelationGetRelid(relation)
Definition: rel.h:504
uint64 es_processed
Definition: execnodes.h:663
ExecForeignBatchInsert_function ExecForeignBatchInsert
Definition: fdwapi.h:233
struct TransitionCaptureState * mt_transition_capture
Definition: execnodes.h:1314
Relation ri_RelationDesc
Definition: execnodes.h:450
List * ri_WithCheckOptions
Definition: execnodes.h:513
struct FdwRoutine * ri_FdwRoutine
Definition: execnodes.h:497
Oid tts_tableOid
Definition: tuptable.h:130
void ExecARInsertTriggers(EState *estate, ResultRelInfo *relinfo, TupleTableSlot *slot, List *recheckIndexes, TransitionCaptureState *transition_capture)
Definition: trigger.c:2540
static TupleTableSlot * ExecClearTuple(TupleTableSlot *slot)
Definition: tuptable.h:432

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:1202
int errcode(int sqlerrcode)
Definition: elog.c:858
int errmsg(const char *fmt,...)
Definition: elog.c:1069
#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:179
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:1895
#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:616
#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:409
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:1553
#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:1226
void ExecInitStoredGenerated(ResultRelInfo *resultRelInfo, EState *estate, CmdType cmdtype)
@ CMD_UPDATE
Definition: nodes.h:277
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:138
TupleTableSlot * ecxt_scantuple
Definition: execnodes.h:249
ExprState ** ri_GeneratedExprsI
Definition: execnodes.h:522
int ri_NumGeneratedNeededU
Definition: execnodes.h:527
ExprState ** ri_GeneratedExprsU
Definition: execnodes.h:523
int ri_NumGeneratedNeededI
Definition: execnodes.h:526
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:361
static void ExecMaterializeSlot(TupleTableSlot *slot)
Definition: tuptable.h:450

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,
TupleTableSlot **  retry_slot,
TupleTableSlot **  inserted_tuple,
ResultRelInfo **  insert_destrel 
)
static

Definition at line 1731 of file nodeModifyTable.c.

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

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, 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 2168 of file nodeModifyTable.c.

2174 {
2175  ListCell *lc;
2176  ResultRelInfo *rootRelInfo;
2177  List *ancestorRels;
2178 
2179  rootRelInfo = sourcePartInfo->ri_RootResultRelInfo;
2180  ancestorRels = ExecGetAncestorResultRels(context->estate, sourcePartInfo);
2181 
2182  /*
2183  * For any foreign keys that point directly into a non-root ancestors of
2184  * the source partition, we can in theory fire an update event to enforce
2185  * those constraints using their triggers, if we could tell that both the
2186  * source and the destination partitions are under the same ancestor. But
2187  * for now, we simply report an error that those cannot be enforced.
2188  */
2189  foreach(lc, ancestorRels)
2190  {
2191  ResultRelInfo *rInfo = lfirst(lc);
2192  TriggerDesc *trigdesc = rInfo->ri_TrigDesc;
2193  bool has_noncloned_fkey = false;
2194 
2195  /* Root ancestor's triggers will be processed. */
2196  if (rInfo == rootRelInfo)
2197  continue;
2198 
2199  if (trigdesc && trigdesc->trig_update_after_row)
2200  {
2201  for (int i = 0; i < trigdesc->numtriggers; i++)
2202  {
2203  Trigger *trig = &trigdesc->triggers[i];
2204 
2205  if (!trig->tgisclone &&
2207  {
2208  has_noncloned_fkey = true;
2209  break;
2210  }
2211  }
2212  }
2213 
2214  if (has_noncloned_fkey)
2215  ereport(ERROR,
2216  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2217  errmsg("cannot move tuple across partitions when a non-root ancestor of the source partition is directly referenced in a foreign key"),
2218  errdetail("A foreign key points to ancestor \"%s\" but not the root ancestor \"%s\".",
2221  errhint("Consider defining the foreign key on table \"%s\".",
2222  RelationGetRelationName(rootRelInfo->ri_RelationDesc))));
2223  }
2224 
2225  /* Perform the root table's triggers. */
2226  ExecARUpdateTriggers(context->estate,
2227  rootRelInfo, sourcePartInfo, destPartInfo,
2228  tupleid, NULL, newslot, NIL, NULL, true);
2229 }
int errhint(const char *fmt,...)
Definition: elog.c:1316
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:574
TriggerDesc * ri_TrigDesc
Definition: execnodes.h:480
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:3085
#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,
bool tupleDeleted,
TupleTableSlot **  epqreturnslot 
)
static

Definition at line 1421 of file nodeModifyTable.c.

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

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:715
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:2689

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 4407 of file nodeModifyTable.c.

4408 {
4409  int i;
4410 
4411  /*
4412  * Allow any FDWs to shut down
4413  */
4414  for (i = 0; i < node->mt_nrels; i++)
4415  {
4416  int j;
4417  ResultRelInfo *resultRelInfo = node->resultRelInfo + i;
4418 
4419  if (!resultRelInfo->ri_usesFdwDirectModify &&
4420  resultRelInfo->ri_FdwRoutine != NULL &&
4421  resultRelInfo->ri_FdwRoutine->EndForeignModify != NULL)
4422  resultRelInfo->ri_FdwRoutine->EndForeignModify(node->ps.state,
4423  resultRelInfo);
4424 
4425  /*
4426  * Cleanup the initialized batch slots. This only matters for FDWs
4427  * with batching, but the other cases will have ri_NumSlotsInitialized
4428  * == 0.
4429  */
4430  for (j = 0; j < resultRelInfo->ri_NumSlotsInitialized; j++)
4431  {
4432  ExecDropSingleTupleTableSlot(resultRelInfo->ri_Slots[j]);
4433  ExecDropSingleTupleTableSlot(resultRelInfo->ri_PlanSlots[j]);
4434  }
4435  }
4436 
4437  /*
4438  * Close all the partitioned tables, leaf partitions, and their indices
4439  * and release the slot used for tuple routing, if set.
4440  */
4441  if (node->mt_partition_tuple_routing)
4442  {
4444 
4445  if (node->mt_root_tuple_slot)
4447  }
4448 
4449  /*
4450  * Free the exprcontext
4451  */
4452  ExecFreeExprContext(&node->ps);
4453 
4454  /*
4455  * clean out the tuple table
4456  */
4457  if (node->ps.ps_ResultTupleSlot)
4459 
4460  /*
4461  * Terminate EPQ execution if active
4462  */
4463  EvalPlanQualEnd(&node->mt_epqstate);
4464 
4465  /*
4466  * shut down subplan
4467  */
4468  ExecEndNode(outerPlanState(node));
4469 }
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:1255
void ExecFreeExprContext(PlanState *planstate)
Definition: execUtils.c:658
#define outerPlanState(node)
Definition: execnodes.h:1133
int j
Definition: isn.c:74
EndForeignModify_function EndForeignModify
Definition: fdwapi.h:237
ResultRelInfo * resultRelInfo
Definition: execnodes.h:1280
EPQState mt_epqstate
Definition: execnodes.h:1290
TupleTableSlot * ps_ResultTupleSlot
Definition: execnodes.h:1075
TupleTableSlot ** ri_Slots
Definition: execnodes.h:509
int ri_NumSlotsInitialized
Definition: execnodes.h:507
TupleTableSlot ** ri_PlanSlots
Definition: execnodes.h:510
bool ri_usesFdwDirectModify
Definition: execnodes.h:503

References FdwRoutine::EndForeignModify, EvalPlanQualEnd(), ExecCleanupTupleRouting(), ExecClearTuple(), ExecDropSingleTupleTableSlot(), ExecEndNode(), ExecFreeExprContext(), i, j, ModifyTableState::mt_epqstate, ModifyTableState::mt_nrels, ModifyTableState::mt_partition_tuple_routing, ModifyTableState::mt_root_tuple_slot, outerPlanState, ModifyTableState::ps, PlanState::ps_ResultTupleSlot, 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:253
ExprContext * pi_exprContext
Definition: execnodes.h:358
TupleTableSlot * ri_newTupleSlot
Definition: execnodes.h:473
ProjectionInfo * ri_projectNew
Definition: execnodes.h:471
const TupleTableSlotOps *const tts_ops
Definition: tuptable.h:121
static TupleTableSlot * ExecCopySlot(TupleTableSlot *dstslot, TupleTableSlot *srcslot)
Definition: tuptable.h:482

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:358
void ExecAssignExprContext(EState *estate, PlanState *planstate)
Definition: execUtils.c:488
List * lappend(List *list, void *datum)
Definition: list.c:338
static void ExecCheckPlanOutput(Relation resultRel, List *targetList)
#define outerPlan(node)
Definition: plannodes.h:183
List * es_tupleTable
Definition: execnodes.h:661
ExprContext * ps_ExprContext
Definition: execnodes.h:1076

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 3194 of file nodeModifyTable.c.

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

3350 {
3351  EState *estate = mtstate->ps.state;
3352 
3353  Assert(!resultRelInfo->ri_projectNewInfoValid);
3354 
3355  resultRelInfo->ri_oldTupleSlot =
3356  table_slot_create(resultRelInfo->ri_RelationDesc,
3357  &estate->es_tupleTable);
3358  resultRelInfo->ri_newTupleSlot =
3359  table_slot_create(resultRelInfo->ri_RelationDesc,
3360  &estate->es_tupleTable);
3361  resultRelInfo->ri_projectNewInfoValid = true;
3362 }

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 3926 of file nodeModifyTable.c.

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

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:753
bool bms_overlap(const Bitmapset *a, const Bitmapset *b)
Definition: bitmapset.c:527
ExprState * ExecPrepareExpr(Expr *node, EState *estate)
Definition: execExpr.c:736
Bitmapset * ExecGetUpdatedCols(ResultRelInfo *relinfo, EState *estate)
Definition: execUtils.c:1319
void * palloc0(Size size)
Definition: mcxt.c:1257
Node * build_column_default(Relation rel, int attrno)
TriggerDesc * trigdesc
Definition: rel.h:117
Bitmapset * ri_extraUpdatedCols
Definition: execnodes.h:468
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:522
List * ExecInsertIndexTuples(ResultRelInfo *resultRelInfo, TupleTableSlot *slot, EState *estate, bool update, bool noDupErr, bool *specConflict, List *arbiterIndexes, bool onlySummarizing)
Definition: execIndexing.c:293
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:1239
#define InstrCountTuples2(node, delta)
Definition: execnodes.h:1136
bool list_member_ptr(const List *list, const void *datum)
Definition: list.c:681
void list_free(List *list)
Definition: list.c:1545
uint32 SpeculativeInsertionLockAcquire(TransactionId xid)
Definition: lmgr.c:783
void SpeculativeInsertionLockRelease(TransactionId xid)
Definition: lmgr.c:809
#define CHECK_FOR_INTERRUPTS()
Definition: miscadmin.h:121
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:427
@ ONCONFLICT_NOTHING
Definition: nodes.h:429
WCOKind
Definition: parsenodes.h:1312
@ WCO_RLS_INSERT_CHECK
Definition: parsenodes.h:1314
@ WCO_RLS_UPDATE_CHECK
Definition: parsenodes.h:1315
List * es_insert_pending_modifytables
Definition: execnodes.h:716
ExecForeignInsert_function ExecForeignInsert
Definition: fdwapi.h:232
CmdType commandType
Definition: parsenodes.h:1692
int ri_NumIndices
Definition: execnodes.h:453
RelationPtr ri_IndexRelationDescs
Definition: execnodes.h:456
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:2464
bool ExecIRInsertTriggers(EState *estate, ResultRelInfo *relinfo, TupleTableSlot *slot)
Definition: trigger.c:2557
TupleDesc CreateTupleDescCopy(TupleDesc tupdesc)
Definition: tupdesc.c:111
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 3877 of file nodeModifyTable.c.

3879 {
3880  if (node->mt_resultOidHash)
3881  {
3882  /* Use the pre-built hash table to locate the rel */
3883  MTTargetRelLookup *mtlookup;
3884 
3885  mtlookup = (MTTargetRelLookup *)
3886  hash_search(node->mt_resultOidHash, &resultoid, HASH_FIND, NULL);
3887  if (mtlookup)
3888  {
3889  if (update_cache)
3890  {
3891  node->mt_lastResultOid = resultoid;
3892  node->mt_lastResultIndex = mtlookup->relationIndex;
3893  }
3894  return node->resultRelInfo + mtlookup->relationIndex;
3895  }
3896  }
3897  else
3898  {
3899  /* With few target rels, just search the ResultRelInfo array */
3900  for (int ndx = 0; ndx < node->mt_nrels; ndx++)
3901  {
3902  ResultRelInfo *rInfo = node->resultRelInfo + ndx;
3903 
3904  if (RelationGetRelid(rInfo->ri_RelationDesc) == resultoid)
3905  {
3906  if (update_cache)
3907  {
3908  node->mt_lastResultOid = resultoid;
3909  node->mt_lastResultIndex = ndx;
3910  }
3911  return rInfo;
3912  }
3913  }
3914  }
3915 
3916  if (!missing_ok)
3917  elog(ERROR, "incorrect result relation OID %u", resultoid);
3918  return NULL;
3919 }
@ 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 2712 of file nodeModifyTable.c.

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

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

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

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 3539 of file nodeModifyTable.c.

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

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

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 3479 of file nodeModifyTable.c.

3485 {
3486  ResultRelInfo *partrel;
3487  TupleConversionMap *map;
3488 
3489  /*
3490  * Lookup the target partition's ResultRelInfo. If ExecFindPartition does
3491  * not find a valid partition for the tuple in 'slot' then an error is
3492  * raised. An error may also be raised if the found partition is not a
3493  * valid target for INSERTs. This is required since a partitioned table
3494  * UPDATE to another partition becomes a DELETE+INSERT.
3495  */
3496  partrel = ExecFindPartition(mtstate, targetRelInfo, proute, slot, estate);
3497 
3498  /*
3499  * If we're capturing transition tuples, we might need to convert from the
3500  * partition rowtype to root partitioned table's rowtype. But if there
3501  * are no BEFORE triggers on the partition that could change the tuple, we
3502  * can just remember the original unconverted tuple to avoid a needless
3503  * round trip conversion.
3504  */
3505  if (mtstate->mt_transition_capture != NULL)
3506  {
3507  bool has_before_insert_row_trig;
3508 
3509  has_before_insert_row_trig = (partrel->ri_TrigDesc &&
3511 
3513  !has_before_insert_row_trig ? slot : NULL;
3514  }
3515 
3516  /*
3517  * Convert the tuple, if necessary.
3518  */
3519  map = ExecGetRootToChildMap(partrel, estate);
3520  if (map != NULL)
3521  {
3522  TupleTableSlot *new_slot = partrel->ri_PartitionTupleSlot;
3523 
3524  slot = execute_attr_map_slot(map->attrMap, slot, new_slot);
3525  }
3526 
3527  *partRelInfo = partrel;
3528  return slot;
3529 }
ResultRelInfo * ExecFindPartition(ModifyTableState *mtstate, ResultRelInfo *rootResultRelInfo, PartitionTupleRouting *proute, TupleTableSlot *slot, EState *estate)
TupleConversionMap * ExecGetRootToChildMap(ResultRelInfo *resultRelInfo, EState *estate)
Definition: execUtils.c:1263
TupleTableSlot * ri_PartitionTupleSlot
Definition: execnodes.h:575

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 4472 of file nodeModifyTable.c.

4473 {
4474  /*
4475  * Currently, we don't need to support rescan on ModifyTable nodes. The
4476  * semantics of that would be a bit debatable anyway.
4477  */
4478  elog(ERROR, "ExecReScanModifyTable is not implemented");
4479 }

References elog(), and ERROR.

Referenced by ExecReScan().

◆ ExecSetupTransitionCaptureState()

static void ExecSetupTransitionCaptureState ( ModifyTableState mtstate,
EState estate 
)
static

Definition at line 3450 of file nodeModifyTable.c.

3451 {
3452  ModifyTable *plan = (ModifyTable *) mtstate->ps.plan;
3453  ResultRelInfo *targetRelInfo = mtstate->rootResultRelInfo;
3454 
3455  /* Check for transition tables on the directly targeted relation. */
3456  mtstate->mt_transition_capture =
3457  MakeTransitionCaptureState(targetRelInfo->ri_TrigDesc,
3458  RelationGetRelid(targetRelInfo->ri_RelationDesc),
3459  mtstate->operation);
3460  if (plan->operation == CMD_INSERT &&
3461  plan->onConflictAction == ONCONFLICT_UPDATE)
3462  mtstate->mt_oc_transition_capture =
3463  MakeTransitionCaptureState(targetRelInfo->ri_TrigDesc,
3464  RelationGetRelid(targetRelInfo->ri_RelationDesc),
3465  CMD_UPDATE);
3466 }
#define plan(x)
Definition: pg_regress.c:154
struct TransitionCaptureState * mt_oc_transition_capture
Definition: execnodes.h:1317
TransitionCaptureState * MakeTransitionCaptureState(TriggerDesc *trigdesc, Oid relid, CmdType cmdType)
Definition: trigger.c:4870

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 2259 of file nodeModifyTable.c.

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

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 1968 of file nodeModifyTable.c.

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

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

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

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 1891 of file nodeModifyTable.c.

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

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 ExecMergeMatched(), and ExecUpdate().

◆ fireASTriggers()

static void fireASTriggers ( ModifyTableState node)
static

Definition at line 3405 of file nodeModifyTable.c.

3406 {
3407  ModifyTable *plan = (