PostgreSQL Source Code  git master
nodeModifyTable.c File Reference
#include "postgres.h"
#include "access/htup_details.h"
#include "access/tableam.h"
#include "access/xact.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/lmgr.h"
#include "utils/builtins.h"
#include "utils/datum.h"
#include "utils/rel.h"
#include "utils/snapmgr.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, HeapTuple oldtuple, bool canSetTag)
 
static void ExecInitMerge (ModifyTableState *mtstate, EState *estate)
 
static TupleTableSlotExecMergeMatched (ModifyTableContext *context, ResultRelInfo *resultRelInfo, ItemPointer tupleid, HeapTuple oldtuple, bool canSetTag, bool *matched)
 
static TupleTableSlotExecMergeNotMatched (ModifyTableContext *context, ResultRelInfo *resultRelInfo, bool canSetTag)
 
static void ExecCheckPlanOutput (Relation resultRel, List *targetList)
 
static TupleTableSlotExecProcessReturning (ResultRelInfo *resultRelInfo, TupleTableSlot *tupleSlot, TupleTableSlot *planSlot)
 
static void ExecCheckTupleVisible (EState *estate, Relation rel, TupleTableSlot *slot)
 
static void ExecCheckTIDVisible (EState *estate, ResultRelInfo *relinfo, ItemPointer tid, TupleTableSlot *tempSlot)
 
void ExecInitStoredGenerated (ResultRelInfo *resultRelInfo, EState *estate, CmdType cmdtype)
 
void ExecComputeStoredGenerated (ResultRelInfo *resultRelInfo, EState *estate, TupleTableSlot *slot, CmdType cmdtype)
 
static void ExecInitInsertProjection (ModifyTableState *mtstate, ResultRelInfo *resultRelInfo)
 
static void ExecInitUpdateProjection (ModifyTableState *mtstate, ResultRelInfo *resultRelInfo)
 
static TupleTableSlotExecGetInsertNewTuple (ResultRelInfo *relinfo, TupleTableSlot *planSlot)
 
TupleTableSlotExecGetUpdateNewTuple (ResultRelInfo *relinfo, TupleTableSlot *planSlot, TupleTableSlot *oldSlot)
 
static TupleTableSlotExecInsert (ModifyTableContext *context, ResultRelInfo *resultRelInfo, TupleTableSlot *slot, bool canSetTag, TupleTableSlot **inserted_tuple, ResultRelInfo **insert_destrel)
 
static bool ExecDeletePrologue (ModifyTableContext *context, ResultRelInfo *resultRelInfo, ItemPointer tupleid, HeapTuple oldtuple, TupleTableSlot **epqreturnslot, TM_Result *result)
 
static TM_Result ExecDeleteAct (ModifyTableContext *context, ResultRelInfo *resultRelInfo, ItemPointer tupleid, bool changingPart)
 
static void ExecDeleteEpilogue (ModifyTableContext *context, ResultRelInfo *resultRelInfo, ItemPointer tupleid, HeapTuple oldtuple, bool changingPart)
 
static TupleTableSlotExecDelete (ModifyTableContext *context, ResultRelInfo *resultRelInfo, ItemPointer tupleid, HeapTuple oldtuple, bool processReturning, bool changingPart, bool canSetTag, TM_Result *tmresult, bool *tupleDeleted, TupleTableSlot **epqreturnslot)
 
static bool ExecCrossPartitionUpdate (ModifyTableContext *context, ResultRelInfo *resultRelInfo, ItemPointer tupleid, HeapTuple oldtuple, TupleTableSlot *slot, bool canSetTag, UpdateContext *updateCxt, TM_Result *tmresult, TupleTableSlot **retry_slot, TupleTableSlot **inserted_tuple, ResultRelInfo **insert_destrel)
 
static bool ExecUpdatePrologue (ModifyTableContext *context, ResultRelInfo *resultRelInfo, ItemPointer tupleid, HeapTuple oldtuple, TupleTableSlot *slot, TM_Result *result)
 
static void ExecUpdatePrepareSlot (ResultRelInfo *resultRelInfo, TupleTableSlot *slot, EState *estate)
 
static TM_Result ExecUpdateAct (ModifyTableContext *context, ResultRelInfo *resultRelInfo, ItemPointer tupleid, HeapTuple oldtuple, TupleTableSlot *slot, bool canSetTag, UpdateContext *updateCxt)
 
static void ExecUpdateEpilogue (ModifyTableContext *context, UpdateContext *updateCxt, ResultRelInfo *resultRelInfo, ItemPointer tupleid, HeapTuple oldtuple, TupleTableSlot *slot)
 
static TupleTableSlotExecUpdate (ModifyTableContext *context, ResultRelInfo *resultRelInfo, ItemPointer tupleid, HeapTuple oldtuple, TupleTableSlot *slot, bool canSetTag)
 
void ExecInitMergeTupleSlots (ModifyTableState *mtstate, ResultRelInfo *resultRelInfo)
 
static void fireBSTriggers (ModifyTableState *node)
 
static void fireASTriggers (ModifyTableState *node)
 
static void ExecSetupTransitionCaptureState (ModifyTableState *mtstate, EState *estate)
 
static TupleTableSlotExecModifyTable (PlanState *pstate)
 
ResultRelInfoExecLookupResultRelByOid (ModifyTableState *node, Oid resultoid, bool missing_ok, bool update_cache)
 
ModifyTableStateExecInitModifyTable (ModifyTable *node, EState *estate, int eflags)
 
void ExecEndModifyTable (ModifyTableState *node)
 
void ExecReScanModifyTable (ModifyTableState *node)
 

Macro Definition Documentation

◆ MT_NRELS_HASH

#define MT_NRELS_HASH   64

Typedef Documentation

◆ ModifyTableContext

◆ MTTargetRelLookup

◆ UpdateContext

typedef struct UpdateContext UpdateContext

Function Documentation

◆ ExecBatchInsert()

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

Definition at line 1214 of file nodeModifyTable.c.

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

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

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

317 {
318  Relation rel = relinfo->ri_RelationDesc;
319 
320  /* Redundantly check isolation level */
322  return;
323 
324  if (!table_tuple_fetch_row_version(rel, tid, SnapshotAny, tempSlot))
325  elog(ERROR, "failed to fetch conflicting tuple for ON CONFLICT");
326  ExecCheckTupleVisible(estate, rel, tempSlot);
327  ExecClearTuple(tempSlot);
328 }
#define elog(elevel,...)
Definition: elog.h:224
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:1298
#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 279 of file nodeModifyTable.c.

282 {
284  return;
285 
286  if (!table_tuple_satisfies_snapshot(rel, slot, estate->es_snapshot))
287  {
288  Datum xminDatum;
289  TransactionId xmin;
290  bool isnull;
291 
292  xminDatum = slot_getsysattr(slot, MinTransactionIdAttributeNumber, &isnull);
293  Assert(!isnull);
294  xmin = DatumGetTransactionId(xminDatum);
295 
296  /*
297  * We should not raise a serialization failure if the conflict is
298  * against a tuple inserted by our own transaction, even if it's not
299  * visible to our snapshot. (This would happen, for example, if
300  * conflicting keys are proposed for insertion in a single command.)
301  */
303  ereport(ERROR,
305  errmsg("could not serialize access due to concurrent update")));
306  }
307 }
uint32 TransactionId
Definition: c.h:652
#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:624
#define MinTransactionIdAttributeNumber
Definition: sysattr.h:22
static bool table_tuple_satisfies_snapshot(Relation rel, TupleTableSlot *slot, Snapshot snapshot)
Definition: tableam.h:1345
static Datum slot_getsysattr(TupleTableSlot *slot, int attnum, bool *isnull)
Definition: tuptable.h:416
bool TransactionIdIsCurrentTransactionId(TransactionId xid)
Definition: xact.c:938

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

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

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

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

◆ ExecCrossPartitionUpdate()

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

Definition at line 1732 of file nodeModifyTable.c.

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

References Assert, TupleConversionMap::attrMap, CMD_MERGE, context, 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, ONCONFLICT_UPDATE, ModifyTableState::operation, PlanState::plan, ModifyTableState::ps, ResultRelInfo::ri_oldTupleSlot, ResultRelInfo::ri_projectNewInfoValid, ResultRelInfo::ri_RelationDesc, ModifyTableState::rootResultRelInfo, SnapshotAny, PlanState::state, table_slot_create(), table_tuple_fetch_row_version(), TransitionCaptureState::tcs_original_insert_tuple, TM_Ok, TupIsNull, and unlikely.

Referenced by ExecUpdateAct().

◆ ExecCrossPartitionUpdateForeignKey()

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

Definition at line 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:1319
List * ExecGetAncestorResultRels(EState *estate, ResultRelInfo *resultRelInfo)
Definition: execMain.c:1372
#define RelationGetRelationName(relation)
Definition: rel.h:539
int RI_FKey_trigger_type(Oid tgfoid)
Definition: ri_triggers.c:3123
Definition: pg_list.h:54
struct ResultRelInfo * ri_RootResultRelInfo
Definition: execnodes.h:582
TriggerDesc * ri_TrigDesc
Definition: execnodes.h:486
int numtriggers
Definition: reltrigger.h:50
Trigger * triggers
Definition: reltrigger.h:49
bool trig_update_after_row
Definition: reltrigger.h:62
Oid tgfoid
Definition: reltrigger.h:28
bool tgisclone
Definition: reltrigger.h:32
void ExecARUpdateTriggers(EState *estate, ResultRelInfo *relinfo, ResultRelInfo *src_partinfo, ResultRelInfo *dst_partinfo, ItemPointer tupleid, HeapTuple fdw_trigtuple, TupleTableSlot *newslot, List *recheckIndexes, TransitionCaptureState *transition_capture, bool is_crosspart_update)
Definition: trigger.c:3097
#define RI_TRIGGER_PK
Definition: trigger.h:282

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

Referenced by ExecUpdateAct().

◆ ExecDelete()

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

Definition at line 1418 of file nodeModifyTable.c.

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

References Assert, context, elog, ereport, errcode(), ERRCODE_T_R_SERIALIZATION_FAILURE, errhint(), errmsg(), ERROR, EState::es_output_cid, EState::es_processed, EState::es_snapshot, EvalPlanQual(), EvalPlanQualBegin(), EvalPlanQualSlot(), ExecClearTuple(), ExecDeleteAct(), ExecDeleteEpilogue(), ExecDeletePrologue(), ExecForceStoreHeapTuple(), FdwRoutine::ExecForeignDelete, ExecGetReturningSlot(), ExecIRDeleteTriggers(), ExecMaterializeSlot(), ExecProcessReturning(), ExecStoreAllNullTuple(), IsolationUsesXactSnapshot, LockTupleExclusive, LockWaitBlock, 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, 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 1338 of file nodeModifyTable.c.

1340 {
1341  EState *estate = context->estate;
1342 
1343  return table_tuple_delete(resultRelInfo->ri_RelationDesc, tupleid,
1344  estate->es_output_cid,
1345  estate->es_snapshot,
1346  estate->es_crosscheck_snapshot,
1347  true /* wait for commit */ ,
1348  &context->tmfd,
1349  changingPart);
1350 }
Snapshot es_crosscheck_snapshot
Definition: execnodes.h:625
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:1501

References context, EState::es_crosscheck_snapshot, EState::es_output_cid, EState::es_snapshot, ResultRelInfo::ri_RelationDesc, and table_tuple_delete().

Referenced by ExecDelete(), and ExecMergeMatched().

◆ ExecDeleteEpilogue()

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

Definition at line 1360 of file nodeModifyTable.c.

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

References CMD_UPDATE, context, ExecARDeleteTriggers(), ExecARUpdateTriggers(), ModifyTableState::mt_transition_capture, 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 1307 of file nodeModifyTable.c.

1310 {
1311  if (result)
1312  *result = TM_Ok;
1313 
1314  /* BEFORE ROW DELETE triggers */
1315  if (resultRelInfo->ri_TrigDesc &&
1316  resultRelInfo->ri_TrigDesc->trig_delete_before_row)
1317  {
1318  /* Flush any pending inserts, so rows are visible to the triggers */
1319  if (context->estate->es_insert_pending_result_relations != NIL)
1320  ExecPendingInserts(context->estate);
1321 
1322  return ExecBRDeleteTriggers(context->estate, context->epqstate,
1323  resultRelInfo, tupleid, oldtuple,
1324  epqreturnslot, result, &context->tmfd);
1325  }
1326 
1327  return true;
1328 }
static void ExecPendingInserts(EState *estate)
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:2683

References context, ExecBRDeleteTriggers(), ExecPendingInserts(), NIL, ResultRelInfo::ri_TrigDesc, TM_Ok, and TriggerDesc::trig_delete_before_row.

Referenced by ExecDelete(), and ExecMergeMatched().

◆ ExecEndModifyTable()

void ExecEndModifyTable ( ModifyTableState node)

Definition at line 4680 of file nodeModifyTable.c.

4681 {
4682  int i;
4683 
4684  /*
4685  * Allow any FDWs to shut down
4686  */
4687  for (i = 0; i < node->mt_nrels; i++)
4688  {
4689  int j;
4690  ResultRelInfo *resultRelInfo = node->resultRelInfo + i;
4691 
4692  if (!resultRelInfo->ri_usesFdwDirectModify &&
4693  resultRelInfo->ri_FdwRoutine != NULL &&
4694  resultRelInfo->ri_FdwRoutine->EndForeignModify != NULL)
4695  resultRelInfo->ri_FdwRoutine->EndForeignModify(node->ps.state,
4696  resultRelInfo);
4697 
4698  /*
4699  * Cleanup the initialized batch slots. This only matters for FDWs
4700  * with batching, but the other cases will have ri_NumSlotsInitialized
4701  * == 0.
4702  */
4703  for (j = 0; j < resultRelInfo->ri_NumSlotsInitialized; j++)
4704  {
4705  ExecDropSingleTupleTableSlot(resultRelInfo->ri_Slots[j]);
4706  ExecDropSingleTupleTableSlot(resultRelInfo->ri_PlanSlots[j]);
4707  }
4708  }
4709 
4710  /*
4711  * Close all the partitioned tables, leaf partitions, and their indices
4712  * and release the slot used for tuple routing, if set.
4713  */
4714  if (node->mt_partition_tuple_routing)
4715  {
4717 
4718  if (node->mt_root_tuple_slot)
4720  }
4721 
4722  /*
4723  * Terminate EPQ execution if active
4724  */
4725  EvalPlanQualEnd(&node->mt_epqstate);
4726 
4727  /*
4728  * shut down subplan
4729  */
4730  ExecEndNode(outerPlanState(node));
4731 }
void EvalPlanQualEnd(EPQState *epqstate)
Definition: execMain.c:2982
void ExecCleanupTupleRouting(ModifyTableState *mtstate, PartitionTupleRouting *proute)
void ExecEndNode(PlanState *node)
Definition: execProcnode.c:557
void ExecDropSingleTupleTableSlot(TupleTableSlot *slot)
Definition: execTuples.c:1341
#define outerPlanState(node)
Definition: execnodes.h:1214
int j
Definition: isn.c:74
EndForeignModify_function EndForeignModify
Definition: fdwapi.h:237
ResultRelInfo * resultRelInfo
Definition: execnodes.h:1361
EPQState mt_epqstate
Definition: execnodes.h:1371
TupleTableSlot ** ri_Slots
Definition: execnodes.h:515
int ri_NumSlotsInitialized
Definition: execnodes.h:513
TupleTableSlot ** ri_PlanSlots
Definition: execnodes.h:516
bool ri_usesFdwDirectModify
Definition: execnodes.h:509

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

Referenced by ExecEndNode().

◆ ExecGetInsertNewTuple()

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

Definition at line 667 of file nodeModifyTable.c.

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

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

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

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

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

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

3392 {
3393  ModifyTable *node = (ModifyTable *) mtstate->ps.plan;
3394  ResultRelInfo *rootRelInfo = mtstate->rootResultRelInfo;
3395  ResultRelInfo *resultRelInfo;
3396  ExprContext *econtext;
3397  ListCell *lc;
3398  int i;
3399 
3400  if (node->mergeActionLists == NIL)
3401  return;
3402 
3403  mtstate->mt_merge_subcommands = 0;
3404 
3405  if (mtstate->ps.ps_ExprContext == NULL)
3406  ExecAssignExprContext(estate, &mtstate->ps);
3407  econtext = mtstate->ps.ps_ExprContext;
3408 
3409  /*
3410  * Create a MergeActionState for each action on the mergeActionList and
3411  * add it to either a list of matched actions or not-matched actions.
3412  *
3413  * Similar logic appears in ExecInitPartitionInfo(), so if changing
3414  * anything here, do so there too.
3415  */
3416  i = 0;
3417  foreach(lc, node->mergeActionLists)
3418  {
3419  List *mergeActionList = lfirst(lc);
3420  Node *joinCondition;
3421  TupleDesc relationDesc;
3422  ListCell *l;
3423 
3424  joinCondition = (Node *) list_nth(node->mergeJoinConditions, i);
3425  resultRelInfo = mtstate->resultRelInfo + i;
3426  i++;
3427  relationDesc = RelationGetDescr(resultRelInfo->ri_RelationDesc);
3428 
3429  /* initialize slots for MERGE fetches from this rel */
3430  if (unlikely(!resultRelInfo->ri_projectNewInfoValid))
3431  ExecInitMergeTupleSlots(mtstate, resultRelInfo);
3432 
3433  /* initialize state for join condition checking */
3434  resultRelInfo->ri_MergeJoinCondition =
3435  ExecInitQual((List *) joinCondition, &mtstate->ps);
3436 
3437  foreach(l, mergeActionList)
3438  {
3440  MergeActionState *action_state;
3441  TupleTableSlot *tgtslot;
3442  TupleDesc tgtdesc;
3443 
3444  /*
3445  * Build action merge state for this rel. (For partitions,
3446  * equivalent code exists in ExecInitPartitionInfo.)
3447  */
3448  action_state = makeNode(MergeActionState);
3449  action_state->mas_action = action;
3450  action_state->mas_whenqual = ExecInitQual((List *) action->qual,
3451  &mtstate->ps);
3452 
3453  /*
3454  * We create three lists - one for each MergeMatchKind - and stick
3455  * the MergeActionState into the appropriate list.
3456  */
3457  resultRelInfo->ri_MergeActions[action->matchKind] =
3458  lappend(resultRelInfo->ri_MergeActions[action->matchKind],
3459  action_state);
3460 
3461  switch (action->commandType)
3462  {
3463  case CMD_INSERT:
3464  ExecCheckPlanOutput(rootRelInfo->ri_RelationDesc,
3465  action->targetList);
3466 
3467  /*
3468  * If the MERGE targets a partitioned table, any INSERT
3469  * actions must be routed through it, not the child
3470  * relations. Initialize the routing struct and the root
3471  * table's "new" tuple slot for that, if not already done.
3472  * The projection we prepare, for all relations, uses the
3473  * root relation descriptor, and targets the plan's root
3474  * slot. (This is consistent with the fact that we
3475  * checked the plan output to match the root relation,
3476  * above.)
3477  */
3478  if (rootRelInfo->ri_RelationDesc->rd_rel->relkind ==
3479  RELKIND_PARTITIONED_TABLE)
3480  {
3481  if (mtstate->mt_partition_tuple_routing == NULL)
3482  {
3483  /*
3484  * Initialize planstate for routing if not already
3485  * done.
3486  *
3487  * Note that the slot is managed as a standalone
3488  * slot belonging to ModifyTableState, so we pass
3489  * NULL for the 2nd argument.
3490  */
3491  mtstate->mt_root_tuple_slot =
3492  table_slot_create(rootRelInfo->ri_RelationDesc,
3493  NULL);
3494  mtstate->mt_partition_tuple_routing =
3496  rootRelInfo->ri_RelationDesc);
3497  }
3498  tgtslot = mtstate->mt_root_tuple_slot;
3499  tgtdesc = RelationGetDescr(rootRelInfo->ri_RelationDesc);
3500  }
3501  else
3502  {
3503  /* not partitioned? use the stock relation and slot */
3504  tgtslot = resultRelInfo->ri_newTupleSlot;
3505  tgtdesc = RelationGetDescr(resultRelInfo->ri_RelationDesc);
3506  }
3507 
3508  action_state->mas_proj =
3509  ExecBuildProjectionInfo(action->targetList, econtext,
3510  tgtslot,
3511  &mtstate->ps,
3512  tgtdesc);
3513 
3514  mtstate->mt_merge_subcommands |= MERGE_INSERT;
3515  break;
3516  case CMD_UPDATE:
3517  action_state->mas_proj =
3518  ExecBuildUpdateProjection(action->targetList,
3519  true,
3520  action->updateColnos,
3521  relationDesc,
3522  econtext,
3523  resultRelInfo->ri_newTupleSlot,
3524  &mtstate->ps);
3525  mtstate->mt_merge_subcommands |= MERGE_UPDATE;
3526  break;
3527  case CMD_DELETE:
3528  mtstate->mt_merge_subcommands |= MERGE_DELETE;
3529  break;
3530  case CMD_NOTHING:
3531  break;
3532  default:
3533  elog(ERROR, "unknown operation");
3534  break;
3535  }
3536  }
3537  }
3538 }
ProjectionInfo * ExecBuildUpdateProjection(List *targetList, bool evalTargetList, List *targetColnos, TupleDesc relDesc, ExprContext *econtext, TupleTableSlot *slot, PlanState *parent)
Definition: execExpr.c:521
ExprState * ExecInitQual(List *qual, PlanState *parent)
Definition: execExpr.c:220
#define MERGE_UPDATE
Definition: execnodes.h:1347
#define MERGE_INSERT
Definition: execnodes.h:1346
#define MERGE_DELETE
Definition: execnodes.h:1348
if(TABLE==NULL||TABLE_index==NULL)
Definition: isn.c:77
void ExecInitMergeTupleSlots(ModifyTableState *mtstate, ResultRelInfo *resultRelInfo)
@ CMD_INSERT
Definition: nodes.h:267
@ CMD_DELETE
Definition: nodes.h:268
@ CMD_NOTHING
Definition: nodes.h:272
#define makeNode(_type_)
Definition: nodes.h:155
static void * list_nth(const List *list, int n)
Definition: pg_list.h:299
MergeAction * mas_action
Definition: execnodes.h:425
ProjectionInfo * mas_proj
Definition: execnodes.h:426
ExprState * mas_whenqual
Definition: execnodes.h:428
int mt_merge_subcommands
Definition: execnodes.h:1401
List * mergeJoinConditions
Definition: plannodes.h:254
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, list_nth(), makeNode, MergeActionState::mas_action, MergeActionState::mas_proj, MergeActionState::mas_whenqual, MERGE_DELETE, MERGE_INSERT, MERGE_UPDATE, ModifyTable::mergeActionLists, ModifyTable::mergeJoinConditions, 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 3547 of file nodeModifyTable.c.

3549 {
3550  EState *estate = mtstate->ps.state;
3551 
3552  Assert(!resultRelInfo->ri_projectNewInfoValid);
3553 
3554  resultRelInfo->ri_oldTupleSlot =
3555  table_slot_create(resultRelInfo->ri_RelationDesc,
3556  &estate->es_tupleTable);
3557  resultRelInfo->ri_newTupleSlot =
3558  table_slot_create(resultRelInfo->ri_RelationDesc,
3559  &estate->es_tupleTable);
3560  resultRelInfo->ri_projectNewInfoValid = true;
3561 }

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

4196 {
4197  ModifyTableState *mtstate;
4198  Plan *subplan = outerPlan(node);
4199  CmdType operation = node->operation;
4200  int nrels = list_length(node->resultRelations);
4201  ResultRelInfo *resultRelInfo;
4202  List *arowmarks;
4203  ListCell *l;
4204  int i;
4205  Relation rel;
4206 
4207  /* check for unsupported flags */
4208  Assert(!(eflags & (EXEC_FLAG_BACKWARD | EXEC_FLAG_MARK)));
4209 
4210  /*
4211  * create state structure
4212  */
4213  mtstate = makeNode(ModifyTableState);
4214  mtstate->ps.plan = (Plan *) node;
4215  mtstate->ps.state = estate;
4216  mtstate->ps.ExecProcNode = ExecModifyTable;
4217 
4218  mtstate->operation = operation;
4219  mtstate->canSetTag = node->canSetTag;
4220  mtstate->mt_done = false;
4221 
4222  mtstate->mt_nrels = nrels;
4223  mtstate->resultRelInfo = (ResultRelInfo *)
4224  palloc(nrels * sizeof(ResultRelInfo));
4225 
4226  mtstate->mt_merge_pending_not_matched = NULL;
4227  mtstate->mt_merge_inserted = 0;
4228  mtstate->mt_merge_updated = 0;
4229  mtstate->mt_merge_deleted = 0;
4230 
4231  /*----------
4232  * Resolve the target relation. This is the same as:
4233  *
4234  * - the relation for which we will fire FOR STATEMENT triggers,
4235  * - the relation into whose tuple format all captured transition tuples
4236  * must be converted, and
4237  * - the root partitioned table used for tuple routing.
4238  *
4239  * If it's a partitioned or inherited table, the root partition or
4240  * appendrel RTE doesn't appear elsewhere in the plan and its RT index is
4241  * given explicitly in node->rootRelation. Otherwise, the target relation
4242  * is the sole relation in the node->resultRelations list.
4243  *----------
4244  */
4245  if (node->rootRelation > 0)
4246  {
4248  ExecInitResultRelation(estate, mtstate->rootResultRelInfo,
4249  node->rootRelation);
4250  }
4251  else
4252  {
4253  Assert(list_length(node->resultRelations) == 1);
4254  mtstate->rootResultRelInfo = mtstate->resultRelInfo;
4255  ExecInitResultRelation(estate, mtstate->resultRelInfo,
4256  linitial_int(node->resultRelations));
4257  }
4258 
4259  /* set up epqstate with dummy subplan data for the moment */
4260  EvalPlanQualInit(&mtstate->mt_epqstate, estate, NULL, NIL,
4261  node->epqParam, node->resultRelations);
4262  mtstate->fireBSTriggers = true;
4263 
4264  /*
4265  * Build state for collecting transition tuples. This requires having a
4266  * valid trigger query context, so skip it in explain-only mode.
4267  */
4268  if (!(eflags & EXEC_FLAG_EXPLAIN_ONLY))
4269  ExecSetupTransitionCaptureState(mtstate, estate);
4270 
4271  /*
4272  * Open all the result relations and initialize the ResultRelInfo structs.
4273  * (But root relation was initialized above, if it's part of the array.)
4274  * We must do this before initializing the subplan, because direct-modify
4275  * FDWs expect their ResultRelInfos to be available.
4276  */
4277  resultRelInfo = mtstate->resultRelInfo;
4278  i = 0;
4279  foreach(l, node->resultRelations)
4280  {
4281  Index resultRelation = lfirst_int(l);
4282  List *mergeActions = NIL;
4283 
4284  if (node->mergeActionLists)
4285  mergeActions = list_nth(node->mergeActionLists, i);
4286 
4287  if (resultRelInfo != mtstate->rootResultRelInfo)
4288  {
4289  ExecInitResultRelation(estate, resultRelInfo, resultRelation);
4290 
4291  /*
4292  * For child result relations, store the root result relation
4293  * pointer. We do so for the convenience of places that want to
4294  * look at the query's original target relation but don't have the
4295  * mtstate handy.
4296  */
4297  resultRelInfo->ri_RootResultRelInfo = mtstate->rootResultRelInfo;
4298  }
4299 
4300  /* Initialize the usesFdwDirectModify flag */
4301  resultRelInfo->ri_usesFdwDirectModify =
4303 
4304  /*
4305  * Verify result relation is a valid target for the current operation
4306  */
4307  CheckValidResultRel(resultRelInfo, operation, mergeActions);
4308 
4309  resultRelInfo++;
4310  i++;
4311  }
4312 
4313  /*
4314  * Now we may initialize the subplan.
4315  */
4316  outerPlanState(mtstate) = ExecInitNode(subplan, estate, eflags);
4317 
4318  /*
4319  * Do additional per-result-relation initialization.
4320  */
4321  for (i = 0; i < nrels; i++)
4322  {
4323  resultRelInfo = &mtstate->resultRelInfo[i];
4324 
4325  /* Let FDWs init themselves for foreign-table result rels */
4326  if (!resultRelInfo->ri_usesFdwDirectModify &&
4327  resultRelInfo->ri_FdwRoutine != NULL &&
4328  resultRelInfo->ri_FdwRoutine->BeginForeignModify != NULL)
4329  {
4330  List *fdw_private = (List *) list_nth(node->fdwPrivLists, i);
4331 
4332  resultRelInfo->ri_FdwRoutine->BeginForeignModify(mtstate,
4333  resultRelInfo,
4334  fdw_private,
4335  i,
4336  eflags);
4337  }
4338 
4339  /*
4340  * For UPDATE/DELETE/MERGE, find the appropriate junk attr now, either
4341  * a 'ctid' or 'wholerow' attribute depending on relkind. For foreign
4342  * tables, the FDW might have created additional junk attr(s), but
4343  * those are no concern of ours.
4344  */
4345  if (operation == CMD_UPDATE || operation == CMD_DELETE ||
4346  operation == CMD_MERGE)
4347  {
4348  char relkind;
4349 
4350  relkind = resultRelInfo->ri_RelationDesc->rd_rel->relkind;
4351  if (relkind == RELKIND_RELATION ||
4352  relkind == RELKIND_MATVIEW ||
4353  relkind == RELKIND_PARTITIONED_TABLE)
4354  {
4355  resultRelInfo->ri_RowIdAttNo =
4356  ExecFindJunkAttributeInTlist(subplan->targetlist, "ctid");
4357  if (!AttributeNumberIsValid(resultRelInfo->ri_RowIdAttNo))
4358  elog(ERROR, "could not find junk ctid column");
4359  }
4360  else if (relkind == RELKIND_FOREIGN_TABLE)
4361  {
4362  /*
4363  * We don't support MERGE with foreign tables for now. (It's
4364  * problematic because the implementation uses CTID.)
4365  */
4366  Assert(operation != CMD_MERGE);
4367 
4368  /*
4369  * When there is a row-level trigger, there should be a
4370  * wholerow attribute. We also require it to be present in
4371  * UPDATE and MERGE, so we can get the values of unchanged
4372  * columns.
4373  */
4374  resultRelInfo->ri_RowIdAttNo =
4376  "wholerow");
4377  if ((mtstate->operation == CMD_UPDATE || mtstate->operation == CMD_MERGE) &&
4378  !AttributeNumberIsValid(resultRelInfo->ri_RowIdAttNo))
4379  elog(ERROR, "could not find junk wholerow column");
4380  }
4381  else
4382  {
4383  /* Other valid target relkinds must provide wholerow */
4384  resultRelInfo->ri_RowIdAttNo =
4386  "wholerow");
4387  if (!AttributeNumberIsValid(resultRelInfo->ri_RowIdAttNo))
4388  elog(ERROR, "could not find junk wholerow column");
4389  }
4390  }
4391  }
4392 
4393  /*
4394  * If this is an inherited update/delete/merge, there will be a junk
4395  * attribute named "tableoid" present in the subplan's targetlist. It
4396  * will be used to identify the result relation for a given tuple to be
4397  * updated/deleted/merged.
4398  */
4399  mtstate->mt_resultOidAttno =
4400  ExecFindJunkAttributeInTlist(subplan->targetlist, "tableoid");
4401  Assert(AttributeNumberIsValid(mtstate->mt_resultOidAttno) || nrels == 1);
4402  mtstate->mt_lastResultOid = InvalidOid; /* force lookup at first tuple */
4403  mtstate->mt_lastResultIndex = 0; /* must be zero if no such attr */
4404 
4405  /* Get the root target relation */
4406  rel = mtstate->rootResultRelInfo->ri_RelationDesc;
4407 
4408  /*
4409  * Build state for tuple routing if it's a partitioned INSERT. An UPDATE
4410  * or MERGE might need this too, but only if it actually moves tuples
4411  * between partitions; in that case setup is done by
4412  * ExecCrossPartitionUpdate.
4413  */
4414  if (rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE &&
4415  operation == CMD_INSERT)
4416  mtstate->mt_partition_tuple_routing =
4417  ExecSetupPartitionTupleRouting(estate, rel);
4418 
4419  /*
4420  * Initialize any WITH CHECK OPTION constraints if needed.
4421  */
4422  resultRelInfo = mtstate->resultRelInfo;
4423  foreach(l, node->withCheckOptionLists)
4424  {
4425  List *wcoList = (List *) lfirst(l);
4426  List *wcoExprs = NIL;
4427  ListCell *ll;
4428 
4429  foreach(ll, wcoList)
4430  {
4431  WithCheckOption *wco = (WithCheckOption *) lfirst(ll);
4432  ExprState *wcoExpr = ExecInitQual((List *) wco->qual,
4433  &mtstate->ps);
4434 
4435  wcoExprs = lappend(wcoExprs, wcoExpr);
4436  }
4437 
4438  resultRelInfo->ri_WithCheckOptions = wcoList;
4439  resultRelInfo->ri_WithCheckOptionExprs = wcoExprs;
4440  resultRelInfo++;
4441  }
4442 
4443  /*
4444  * Initialize RETURNING projections if needed.
4445  */
4446  if (node->returningLists)
4447  {
4448  TupleTableSlot *slot;
4449  ExprContext *econtext;
4450 
4451  /*
4452  * Initialize result tuple slot and assign its rowtype using the first
4453  * RETURNING list. We assume the rest will look the same.
4454  */
4455  mtstate->ps.plan->targetlist = (List *) linitial(node->returningLists);
4456 
4457  /* Set up a slot for the output of the RETURNING projection(s) */
4459  slot = mtstate->ps.ps_ResultTupleSlot;
4460 
4461  /* Need an econtext too */
4462  if (mtstate->ps.ps_ExprContext == NULL)
4463  ExecAssignExprContext(estate, &mtstate->ps);
4464  econtext = mtstate->ps.ps_ExprContext;
4465 
4466  /*
4467  * Build a projection for each result rel.
4468  */
4469  resultRelInfo = mtstate->resultRelInfo;
4470  foreach(l, node->returningLists)
4471  {
4472  List *rlist = (List *) lfirst(l);
4473 
4474  resultRelInfo->ri_returningList = rlist;
4475  resultRelInfo->ri_projectReturning =
4476  ExecBuildProjectionInfo(rlist, econtext, slot, &mtstate->ps,
4477  resultRelInfo->ri_RelationDesc->rd_att);
4478  resultRelInfo++;
4479  }
4480  }
4481  else
4482  {
4483  /*
4484  * We still must construct a dummy result tuple type, because InitPlan
4485  * expects one (maybe should change that?).
4486  */
4487  mtstate->ps.plan->targetlist = NIL;
4488  ExecInitResultTypeTL(&mtstate->ps);
4489 
4490  mtstate->ps.ps_ExprContext = NULL;
4491  }
4492 
4493  /* Set the list of arbiter indexes if needed for ON CONFLICT */
4494  resultRelInfo = mtstate->resultRelInfo;
4495  if (node->onConflictAction != ONCONFLICT_NONE)
4496  {
4497  /* insert may only have one relation, inheritance is not expanded */
4498  Assert(nrels == 1);
4499  resultRelInfo->ri_onConflictArbiterIndexes = node->arbiterIndexes;
4500  }
4501 
4502  /*
4503  * If needed, Initialize target list, projection and qual for ON CONFLICT
4504  * DO UPDATE.
4505  */
4506  if (node->onConflictAction == ONCONFLICT_UPDATE)
4507  {
4509  ExprContext *econtext;
4510  TupleDesc relationDesc;
4511 
4512  /* already exists if created by RETURNING processing above */
4513  if (mtstate->ps.ps_ExprContext == NULL)
4514  ExecAssignExprContext(estate, &mtstate->ps);
4515 
4516  econtext = mtstate->ps.ps_ExprContext;
4517  relationDesc = resultRelInfo->ri_RelationDesc->rd_att;
4518 
4519  /* create state for DO UPDATE SET operation */
4520  resultRelInfo->ri_onConflict = onconfl;
4521 
4522  /* initialize slot for the existing tuple */
4523  onconfl->oc_Existing =
4524  table_slot_create(resultRelInfo->ri_RelationDesc,
4525  &mtstate->ps.state->es_tupleTable);
4526 
4527  /*
4528  * Create the tuple slot for the UPDATE SET projection. We want a slot
4529  * of the table's type here, because the slot will be used to insert
4530  * into the table, and for RETURNING processing - which may access
4531  * system attributes.
4532  */
4533  onconfl->oc_ProjSlot =
4534  table_slot_create(resultRelInfo->ri_RelationDesc,
4535  &mtstate->ps.state->es_tupleTable);
4536 
4537  /* build UPDATE SET projection state */
4538  onconfl->oc_ProjInfo =
4540  true,
4541  node->onConflictCols,
4542  relationDesc,
4543  econtext,
4544  onconfl->oc_ProjSlot,
4545  &mtstate->ps);
4546 
4547  /* initialize state to evaluate the WHERE clause, if any */
4548  if (node->onConflictWhere)
4549  {
4550  ExprState *qualexpr;
4551 
4552  qualexpr = ExecInitQual((List *) node->onConflictWhere,
4553  &mtstate->ps);
4554  onconfl->oc_WhereClause = qualexpr;
4555  }
4556  }
4557 
4558  /*
4559  * If we have any secondary relations in an UPDATE or DELETE, they need to
4560  * be treated like non-locked relations in SELECT FOR UPDATE, i.e., the
4561  * EvalPlanQual mechanism needs to be told about them. This also goes for
4562  * the source relations in a MERGE. Locate the relevant ExecRowMarks.
4563  */
4564  arowmarks = NIL;
4565  foreach(l, node->rowMarks)
4566  {
4568  ExecRowMark *erm;
4569  ExecAuxRowMark *aerm;
4570 
4571  /* ignore "parent" rowmarks; they are irrelevant at runtime */
4572  if (rc->isParent)
4573  continue;
4574 
4575  /* Find ExecRowMark and build ExecAuxRowMark */
4576  erm = ExecFindRowMark(estate, rc->rti, false);
4577  aerm = ExecBuildAuxRowMark(erm, subplan->targetlist);
4578  arowmarks = lappend(arowmarks, aerm);
4579  }
4580 
4581  /* For a MERGE command, initialize its state */
4582  if (mtstate->operation == CMD_MERGE)
4583  ExecInitMerge(mtstate, estate);
4584 
4585  EvalPlanQualSetPlan(&mtstate->mt_epqstate, subplan, arowmarks);
4586 
4587  /*
4588  * If there are a lot of result relations, use a hash table to speed the
4589  * lookups. If there are not a lot, a simple linear search is faster.
4590  *
4591  * It's not clear where the threshold is, but try 64 for starters. In a
4592  * debugging build, use a small threshold so that we get some test
4593  * coverage of both code paths.
4594  */
4595 #ifdef USE_ASSERT_CHECKING
4596 #define MT_NRELS_HASH 4
4597 #else
4598 #define MT_NRELS_HASH 64
4599 #endif
4600  if (nrels >= MT_NRELS_HASH)
4601  {
4602  HASHCTL hash_ctl;
4603 
4604  hash_ctl.keysize = sizeof(Oid);
4605  hash_ctl.entrysize = sizeof(MTTargetRelLookup);
4606  hash_ctl.hcxt = CurrentMemoryContext;
4607  mtstate->mt_resultOidHash =
4608  hash_create("ModifyTable target hash",
4609  nrels, &hash_ctl,
4611  for (i = 0; i < nrels; i++)
4612  {
4613  Oid hashkey;
4614  MTTargetRelLookup *mtlookup;
4615  bool found;
4616 
4617  resultRelInfo = &mtstate->resultRelInfo[i];
4618  hashkey = RelationGetRelid(resultRelInfo->ri_RelationDesc);
4619  mtlookup = (MTTargetRelLookup *)
4620  hash_search(mtstate->mt_resultOidHash, &hashkey,
4621  HASH_ENTER, &found);
4622  Assert(!found);
4623  mtlookup->relationIndex = i;
4624  }
4625  }
4626  else
4627  mtstate->mt_resultOidHash = NULL;
4628 
4629  /*
4630  * Determine if the FDW supports batch insert and determine the batch size
4631  * (a FDW may support batching, but it may be disabled for the
4632  * server/table).
4633  *
4634  * We only do this for INSERT, so that for UPDATE/DELETE the batch size
4635  * remains set to 0.
4636  */
4637  if (operation == CMD_INSERT)
4638  {
4639  /* insert may only have one relation, inheritance is not expanded */
4640  Assert(nrels == 1);
4641  resultRelInfo = mtstate->resultRelInfo;
4642  if (!resultRelInfo->ri_usesFdwDirectModify &&
4643  resultRelInfo->ri_FdwRoutine != NULL &&
4644  resultRelInfo->ri_FdwRoutine->GetForeignModifyBatchSize &&
4645  resultRelInfo->ri_FdwRoutine->ExecForeignBatchInsert)
4646  {
4647  resultRelInfo->ri_BatchSize =
4648  resultRelInfo->ri_FdwRoutine->GetForeignModifyBatchSize(resultRelInfo);
4649  Assert(resultRelInfo->ri_BatchSize >= 1);
4650  }
4651  else
4652  resultRelInfo->ri_BatchSize = 1;
4653  }
4654 
4655  /*
4656  * Lastly, if this is not the primary (canSetTag) ModifyTable node, add it
4657  * to estate->es_auxmodifytables so that it will be run to completion by
4658  * ExecPostprocessPlan. (It'd actually work fine to add the primary
4659  * ModifyTable node too, but there's no need.) Note the use of lcons not
4660  * lappend: we need later-initialized ModifyTable nodes to be shut down
4661  * before earlier ones. This ensures that we don't throw away RETURNING
4662  * rows that need to be seen by a later CTE subplan.
4663  */
4664  if (!mtstate->canSetTag)
4665  estate->es_auxmodifytables = lcons(mtstate,
4666  estate->es_auxmodifytables);
4667 
4668  return mtstate;
4669 }
#define AttributeNumberIsValid(attributeNumber)
Definition: attnum.h:34
bool bms_is_member(int x, const Bitmapset *a)
Definition: bitmapset.c:510
unsigned int Index
Definition: c.h:614
void * hash_search(HTAB *hashp, const void *keyPtr, HASHACTION action, bool *foundPtr)
Definition: dynahash.c:955
HTAB * hash_create(const char *tabname, long nelem, const HASHCTL *info, int flags)
Definition: dynahash.c:352
AttrNumber ExecFindJunkAttributeInTlist(List *targetlist, const char *attrName)
Definition: execJunk.c:222
void CheckValidResultRel(ResultRelInfo *resultRelInfo, CmdType operation, List *mergeActions)
Definition: execMain.c:1026
void EvalPlanQualInit(EPQState *epqstate, EState *parentestate, Plan *subplan, List *auxrowmarks, int epqParam, List *resultRelations)
Definition: execMain.c:2539
ExecAuxRowMark * ExecBuildAuxRowMark(ExecRowMark *erm, List *targetlist)
Definition: execMain.c:2400
void EvalPlanQualSetPlan(EPQState *epqstate, Plan *subplan, List *auxrowmarks)
Definition: execMain.c:2581
ExecRowMark * ExecFindRowMark(EState *estate, Index rti, bool missing_ok)
Definition: execMain.c:2377
PlanState * ExecInitNode(Plan *node, EState *estate, int eflags)
Definition: execProcnode.c:142
const TupleTableSlotOps TTSOpsVirtual
Definition: execTuples.c:84
void ExecInitResultTypeTL(PlanState *planstate)
Definition: execTuples.c:1842
void ExecInitResultTupleSlotTL(PlanState *planstate, const TupleTableSlotOps *tts_ops)
Definition: execTuples.c:1886
void ExecInitResultRelation(EState *estate, ResultRelInfo *resultRelInfo, Index rti)
Definition: execUtils.c:814
#define EXEC_FLAG_BACKWARD
Definition: executor.h:68
#define EXEC_FLAG_EXPLAIN_ONLY
Definition: executor.h:65
#define EXEC_FLAG_MARK
Definition: executor.h:69
@ HASH_ENTER
Definition: hsearch.h:114
#define HASH_CONTEXT
Definition: hsearch.h:102
#define HASH_ELEM
Definition: hsearch.h:95
#define HASH_BLOBS
Definition: hsearch.h:97
List * lcons(void *datum, List *list)
Definition: list.c:495
MemoryContext CurrentMemoryContext
Definition: mcxt.c:143
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:417
CmdType
Definition: nodes.h:263
#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
#define InvalidOid
Definition: postgres_ext.h:36
unsigned int Oid
Definition: postgres_ext.h:31
List * es_auxmodifytables
Definition: execnodes.h:684
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
TupleTableSlot * mt_merge_pending_not_matched
Definition: execnodes.h:1411
double mt_merge_deleted
Definition: execnodes.h:1416
double mt_merge_inserted
Definition: execnodes.h:1414
double mt_merge_updated
Definition: execnodes.h:1415
HTAB * mt_resultOidHash
Definition: execnodes.h:1383
List * arbiterIndexes
Definition: plannodes.h:246
List * onConflictCols
Definition: plannodes.h:248
CmdType operation
Definition: plannodes.h:232
int epqParam
Definition: plannodes.h:244
List * resultRelations
Definition: plannodes.h:237
Bitmapset * fdwDirectModifyPlans
Definition: plannodes.h:242
List * onConflictSet
Definition: plannodes.h:247
bool canSetTag
Definition: plannodes.h:233
List * fdwPrivLists
Definition: plannodes.h:241
List * returningLists
Definition: plannodes.h:240
List * withCheckOptionLists
Definition: plannodes.h:239
Index rootRelation
Definition: plannodes.h:235
Node * onConflictWhere
Definition: plannodes.h:249
List * rowMarks
Definition: plannodes.h:243
OnConflictAction onConflictAction
Definition: plannodes.h:245
TupleTableSlot * oc_ProjSlot
Definition: execnodes.h:410
TupleTableSlot * oc_Existing
Definition: execnodes.h:409
ExprState * oc_WhereClause
Definition: execnodes.h:412
ProjectionInfo * oc_ProjInfo
Definition: execnodes.h:411
bool isParent
Definition: plannodes.h:1389
TupleTableSlot * ps_ResultTupleSlot
Definition: execnodes.h:1156
ExecProcNodeMtd ExecProcNode
Definition: execnodes.h:1124
List * targetlist
Definition: plannodes.h:152
TupleDesc rd_att
Definition: rel.h:112
Form_pg_class rd_rel
Definition: rel.h:111
OnConflictSetState * ri_onConflict
Definition: execnodes.h:545
List * ri_onConflictArbiterIndexes
Definition: execnodes.h:542
List * ri_WithCheckOptionExprs
Definition: execnodes.h:522
List * ri_returningList
Definition: execnodes.h:536
AttrNumber ri_RowIdAttNo
Definition: execnodes.h:471
int ri_BatchSize
Definition: execnodes.h:514

References ModifyTable::arbiterIndexes, Assert, AttributeNumberIsValid, FdwRoutine::BeginForeignModify, bms_is_member(), ModifyTableState::canSetTag, ModifyTable::canSetTag, CheckValidResultRel(), CMD_DELETE, CMD_INSERT, CMD_MERGE, CMD_UPDATE, CurrentMemoryContext, elog, HASHCTL::entrysize, ModifyTable::epqParam, ERROR, EState::es_auxmodifytables, EState::es_tupleTable, EvalPlanQualInit(), EvalPlanQualSetPlan(), EXEC_FLAG_BACKWARD, EXEC_FLAG_EXPLAIN_ONLY, EXEC_FLAG_MARK, ExecAssignExprContext(), ExecBuildAuxRowMark(), ExecBuildProjectionInfo(), ExecBuildUpdateProjection(), ExecFindJunkAttributeInTlist(), ExecFindRowMark(), FdwRoutine::ExecForeignBatchInsert, ExecInitMerge(), ExecInitNode(), ExecInitQual(), ExecInitResultRelation(), ExecInitResultTupleSlotTL(), ExecInitResultTypeTL(), ExecModifyTable(), PlanState::ExecProcNode, ExecSetupPartitionTupleRouting(), ExecSetupTransitionCaptureState(), ModifyTable::fdwDirectModifyPlans, ModifyTable::fdwPrivLists, ModifyTableState::fireBSTriggers, FdwRoutine::GetForeignModifyBatchSize, HASH_BLOBS, HASH_CONTEXT, hash_create(), HASH_ELEM, HASH_ENTER, hash_search(), HASHCTL::hcxt, i, InvalidOid, PlanRowMark::isParent, HASHCTL::keysize, lappend(), lcons(), lfirst, lfirst_int, lfirst_node, linitial, linitial_int, list_length(), list_nth(), makeNode, ModifyTable::mergeActionLists, ModifyTableState::mt_done, ModifyTableState::mt_epqstate, ModifyTableState::mt_lastResultIndex, ModifyTableState::mt_lastResultOid, ModifyTableState::mt_merge_deleted, ModifyTableState::mt_merge_inserted, ModifyTableState::mt_merge_pending_not_matched, 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 343 of file nodeModifyTable.c.

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

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

Referenced by ExecComputeStoredGenerated(), and ExecGetExtraUpdatedCols().

◆ ExecInitUpdateProjection()

static void ExecInitUpdateProjection ( ModifyTableState mtstate,
ResultRelInfo resultRelInfo 
)
static

Definition at line 609 of file nodeModifyTable.c.

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

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

References Assert, CHECK_FOR_INTERRUPTS, CMD_INSERT, CMD_MERGE, CMD_UPDATE, MergeAction::commandType, TupleDescData::constr, context, CreateTupleDescCopy(), EState::es_insert_pending_modifytables, EState::es_insert_pending_result_relations, EState::es_output_cid, EState::es_processed, EState::es_query_cxt, 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_merge_action, ModifyTableState::mt_partition_tuple_routing, ModifyTableState::mt_transition_capture, NIL, ONCONFLICT_NONE, ONCONFLICT_NOTHING, ONCONFLICT_UPDATE, ModifyTable::onConflictAction, ModifyTableState::operation, palloc(), PlanState::plan, ModifyTableState::ps, RelationData::rd_att, RelationData::rd_rel, 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 4146 of file nodeModifyTable.c.

4148 {
4149  if (node->mt_resultOidHash)
4150  {
4151  /* Use the pre-built hash table to locate the rel */
4152  MTTargetRelLookup *mtlookup;
4153 
4154  mtlookup = (MTTargetRelLookup *)
4155  hash_search(node->mt_resultOidHash, &resultoid, HASH_FIND, NULL);
4156  if (mtlookup)
4157  {
4158  if (update_cache)
4159  {
4160  node->mt_lastResultOid = resultoid;
4161  node->mt_lastResultIndex = mtlookup->relationIndex;
4162  }
4163  return node->resultRelInfo + mtlookup->relationIndex;
4164  }
4165  }
4166  else
4167  {
4168  /* With few target rels, just search the ResultRelInfo array */
4169  for (int ndx = 0; ndx < node->mt_nrels; ndx++)
4170  {
4171  ResultRelInfo *rInfo = node->resultRelInfo + ndx;
4172 
4173  if (RelationGetRelid(rInfo->ri_RelationDesc) == resultoid)
4174  {
4175  if (update_cache)
4176  {
4177  node->mt_lastResultOid = resultoid;
4178  node->mt_lastResultIndex = ndx;
4179  }
4180  return rInfo;
4181  }
4182  }
4183  }
4184 
4185  if (!missing_ok)
4186  elog(ERROR, "incorrect result relation OID %u", resultoid);
4187  return NULL;
4188 }
@ 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,
HeapTuple  oldtuple,
bool  canSetTag 
)
static

Definition at line 2712 of file nodeModifyTable.c.

2714 {
2715  TupleTableSlot *rslot = NULL;
2716  bool matched;
2717 
2718  /*-----
2719  * If we are dealing with a WHEN MATCHED case, tupleid or oldtuple is
2720  * valid, depending on whether the result relation is a table or a view.
2721  * We execute the first action for which the additional WHEN MATCHED AND
2722  * quals pass. If an action without quals is found, that action is
2723  * executed.
2724  *
2725  * Similarly, in the WHEN NOT MATCHED BY SOURCE case, tupleid or oldtuple
2726  * is valid, and we look at the given WHEN NOT MATCHED BY SOURCE actions
2727  * in sequence until one passes. This is almost identical to the WHEN
2728  * MATCHED case, and both cases are handled by ExecMergeMatched().
2729  *
2730  * Finally, in the WHEN NOT MATCHED [BY TARGET] case, both tupleid and
2731  * oldtuple are invalid, and we look at the given WHEN NOT MATCHED [BY
2732  * TARGET] actions in sequence until one passes.
2733  *
2734  * Things get interesting in case of concurrent update/delete of the
2735  * target tuple. Such concurrent update/delete is detected while we are
2736  * executing a WHEN MATCHED or WHEN NOT MATCHED BY SOURCE action.
2737  *
2738  * A concurrent update can:
2739  *
2740  * 1. modify the target tuple so that the results from checking any
2741  * additional quals attached to WHEN MATCHED or WHEN NOT MATCHED BY
2742  * SOURCE actions potentially change, but the result from the join
2743  * quals does not change.
2744  *
2745  * In this case, we are still dealing with the same kind of match
2746  * (MATCHED or NOT MATCHED BY SOURCE). We recheck the same list of
2747  * actions from the start and choose the first one that satisfies the
2748  * new target tuple.
2749  *
2750  * 2. modify the target tuple in the WHEN MATCHED case so that the join
2751  * quals no longer pass and hence the source and target tuples no
2752  * longer match.
2753  *
2754  * In this case, we are now dealing with a NOT MATCHED case, and we
2755  * process both WHEN NOT MATCHED BY SOURCE and WHEN NOT MATCHED [BY
2756  * TARGET] actions. First ExecMergeMatched() processes the list of
2757  * WHEN NOT MATCHED BY SOURCE actions in sequence until one passes,
2758  * then ExecMergeNotMatched() processes any WHEN NOT MATCHED [BY
2759  * TARGET] actions in sequence until one passes. Thus we may execute
2760  * two actions; one of each kind.
2761  *
2762  * Thus we support concurrent updates that turn MATCHED candidate rows
2763  * into NOT MATCHED rows. However, we do not attempt to support cases
2764  * that would turn NOT MATCHED rows into MATCHED rows, or which would
2765  * cause a target row to match a different source row.
2766  *
2767  * A concurrent delete changes a WHEN MATCHED case to WHEN NOT MATCHED
2768  * [BY TARGET].
2769  *
2770  * ExecMergeMatched() takes care of following the update chain and
2771  * re-finding the qualifying WHEN MATCHED or WHEN NOT MATCHED BY SOURCE
2772  * action, as long as the target tuple still exists. If the target tuple
2773  * gets deleted or a concurrent update causes the join quals to fail, it
2774  * returns a matched status of false and we call ExecMergeNotMatched().
2775  * Given that ExecMergeMatched() always makes progress by following the
2776  * update chain and we never switch from ExecMergeNotMatched() to
2777  * ExecMergeMatched(), there is no risk of a livelock.
2778  */
2779  matched = tupleid != NULL || oldtuple != NULL;
2780  if (matched)
2781  rslot = ExecMergeMatched(context, resultRelInfo, tupleid, oldtuple,
2782  canSetTag, &matched);
2783 
2784  /*
2785  * Deal with the NOT MATCHED case (either a NOT MATCHED tuple from the
2786  * join, or a previously MATCHED tuple for which ExecMergeMatched() set
2787  * "matched" to false, indicating that it no longer matches).
2788  */
2789  if (!matched)
2790  {
2791  /*
2792  * If a concurrent update turned a MATCHED case into a NOT MATCHED
2793  * case, and we have both WHEN NOT MATCHED BY SOURCE and WHEN NOT
2794  * MATCHED [BY TARGET] actions, and there is a RETURNING clause,
2795  * ExecMergeMatched() may have already executed a WHEN NOT MATCHED BY
2796  * SOURCE action, and computed the row to return. If so, we cannot
2797  * execute a WHEN NOT MATCHED [BY TARGET] action now, so mark it as
2798  * pending (to be processed on the next call to ExecModifyTable()).
2799  * Otherwise, just process the action now.
2800  */
2801  if (rslot == NULL)
2802  rslot = ExecMergeNotMatched(context, resultRelInfo, canSetTag);
2803  else
2804  context->mtstate->mt_merge_pending_not_matched = context->planSlot;
2805  }
2806 
2807  return rslot;
2808 }
static TupleTableSlot * ExecMergeMatched(ModifyTableContext *context, ResultRelInfo *resultRelInfo, ItemPointer tupleid, HeapTuple oldtuple, bool canSetTag, bool *matched)
static TupleTableSlot * ExecMergeNotMatched(ModifyTableContext *context, ResultRelInfo *resultRelInfo, bool canSetTag)

References context, ExecMergeMatched(), and ExecMergeNotMatched().

Referenced by ExecModifyTable().

◆ ExecMergeMatched()

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

Definition at line 2838 of file nodeModifyTable.c.

2841 {
2842  ModifyTableState *mtstate = context->mtstate;
2843  List **mergeActions = resultRelInfo->ri_MergeActions;
2844  List *actionStates;
2845  TupleTableSlot *newslot = NULL;
2846  TupleTableSlot *rslot = NULL;
2847  EState *estate = context->estate;
2848  ExprContext *econtext = mtstate->ps.ps_ExprContext;
2849  bool isNull;
2850  EPQState *epqstate = &mtstate->mt_epqstate;
2851  ListCell *l;
2852 
2853  /* Expect matched to be true on entry */
2854  Assert(*matched);
2855 
2856  /*
2857  * If there are no WHEN MATCHED or WHEN NOT MATCHED BY SOURCE actions, we
2858  * are done.
2859  */
2860  if (mergeActions[MERGE_WHEN_MATCHED] == NIL &&
2861  mergeActions[MERGE_WHEN_NOT_MATCHED_BY_SOURCE] == NIL)
2862  return NULL;
2863 
2864  /*
2865  * Make tuple and any needed join variables available to ExecQual and
2866  * ExecProject. The target's existing tuple is installed in the scantuple.
2867  * This target relation's slot is required only in the case of a MATCHED
2868  * or NOT MATCHED BY SOURCE tuple and UPDATE/DELETE actions.
2869  */
2870  econtext->ecxt_scantuple = resultRelInfo->ri_oldTupleSlot;
2871  econtext->ecxt_innertuple = context->planSlot;
2872  econtext->ecxt_outertuple = NULL;
2873 
2874  /*
2875  * This routine is only invoked for matched target rows, so we should
2876  * either have the tupleid of the target row, or an old tuple from the
2877  * target wholerow junk attr.
2878  */
2879  Assert(tupleid != NULL || oldtuple != NULL);
2880  if (oldtuple != NULL)
2881  ExecForceStoreHeapTuple(oldtuple, resultRelInfo->ri_oldTupleSlot,
2882  false);
2883  else if (!table_tuple_fetch_row_version(resultRelInfo->ri_RelationDesc,
2884  tupleid,
2885  SnapshotAny,
2886  resultRelInfo->ri_oldTupleSlot))
2887  elog(ERROR, "failed to fetch the target tuple");
2888 
2889  /*
2890  * Test the join condition. If it's satisfied, perform a MATCHED action.
2891  * Otherwise, perform a NOT MATCHED BY SOURCE action.
2892  *
2893  * Note that this join condition will be NULL if there are no NOT MATCHED
2894  * BY SOURCE actions --- see transform_MERGE_to_join(). In that case, we
2895  * need only consider MATCHED actions here.
2896  */
2897  if (ExecQual(resultRelInfo->ri_MergeJoinCondition, econtext))
2898  actionStates = mergeActions[MERGE_WHEN_MATCHED];
2899  else
2900  actionStates = mergeActions[MERGE_WHEN_NOT_MATCHED_BY_SOURCE];
2901 
2902 lmerge_matched:
2903 
2904  foreach(l, actionStates)
2905  {
2906  MergeActionState *relaction = (MergeActionState *) lfirst(l);
2907  CmdType commandType = relaction->mas_action->commandType;
2908  TM_Result result;
2909  UpdateContext updateCxt = {0};
2910 
2911  /*
2912  * Test condition, if any.
2913  *
2914  * In the absence of any condition, we perform the action
2915  * unconditionally (no need to check separately since ExecQual() will
2916  * return true if there are no conditions to evaluate).
2917  */
2918  if (!ExecQual(relaction->mas_whenqual, econtext))
2919  continue;
2920 
2921  /*
2922  * Check if the existing target tuple meets the USING checks of
2923  * UPDATE/DELETE RLS policies. If those checks fail, we throw an
2924  * error.
2925  *
2926  * The WITH CHECK quals for UPDATE RLS policies are applied in
2927  * ExecUpdateAct() and hence we need not do anything special to handle
2928  * them.
2929  *
2930  * NOTE: We must do this after WHEN quals are evaluated, so that we
2931  * check policies only when they matter.
2932  */
2933  if (resultRelInfo->ri_WithCheckOptions && commandType != CMD_NOTHING)
2934  {
2935  ExecWithCheckOptions(commandType == CMD_UPDATE ?
2937  resultRelInfo,
2938  resultRelInfo->ri_oldTupleSlot,
2939  context->mtstate->ps.state);
2940  }
2941 
2942  /* Perform stated action */
2943  switch (commandType)
2944  {
2945  case CMD_UPDATE:
2946 
2947  /*
2948  * Project the output tuple, and use that to update the table.
2949  * We don't need to filter out junk attributes, because the
2950  * UPDATE action's targetlist doesn't have any.
2951  */
2952  newslot = ExecProject(relaction->mas_proj);
2953 
2954  mtstate->mt_merge_action = relaction;
2955  if (!ExecUpdatePrologue(context, resultRelInfo,
2956  tupleid, NULL, newslot, &result))
2957  {
2958  if (result == TM_Ok)
2959  return NULL; /* "do nothing" */
2960 
2961  break; /* concurrent update/delete */
2962  }
2963 
2964  /* INSTEAD OF ROW UPDATE Triggers */
2965  if (resultRelInfo->ri_TrigDesc &&
2966  resultRelInfo->ri_TrigDesc->trig_update_instead_row)
2967  {
2968  if (!ExecIRUpdateTriggers(estate, resultRelInfo,
2969  oldtuple, newslot))
2970  return NULL; /* "do nothing" */
2971  }
2972  else
2973  {
2974  result = ExecUpdateAct(context, resultRelInfo, tupleid,
2975  NULL, newslot, canSetTag,
2976  &updateCxt);
2977 
2978  /*
2979  * As in ExecUpdate(), if ExecUpdateAct() reports that a
2980  * cross-partition update was done, then there's nothing
2981  * else for us to do --- the UPDATE has been turned into a
2982  * DELETE and an INSERT, and we must not perform any of
2983  * the usual post-update tasks. Also, the RETURNING tuple
2984  * (if any) has been projected, so we can just return
2985  * that.
2986  */
2987  if (updateCxt.crossPartUpdate)
2988  {
2989  mtstate->mt_merge_updated += 1;
2990  return context->cpUpdateReturningSlot;
2991  }
2992  }
2993 
2994  if (result == TM_Ok)
2995  {
2996  ExecUpdateEpilogue(context, &updateCxt, resultRelInfo,
2997  tupleid, NULL, newslot);
2998  mtstate->mt_merge_updated += 1;
2999  }
3000  break;
3001 
3002  case CMD_DELETE:
3003  mtstate->mt_merge_action = relaction;
3004  if (!ExecDeletePrologue(context, resultRelInfo, tupleid,
3005  NULL, NULL, &result))
3006  {
3007  if (result == TM_Ok)
3008  return NULL; /* "do nothing" */
3009 
3010  break; /* concurrent update/delete */
3011  }
3012 
3013  /* INSTEAD OF ROW DELETE Triggers */
3014  if (resultRelInfo->ri_TrigDesc &&
3015  resultRelInfo->ri_TrigDesc->trig_delete_instead_row)
3016  {
3017  if (!ExecIRDeleteTriggers(estate, resultRelInfo,
3018  oldtuple))
3019  return NULL; /* "do nothing" */
3020  }
3021  else
3022  result = ExecDeleteAct(context, resultRelInfo, tupleid,
3023  false);
3024 
3025  if (result == TM_Ok)
3026  {
3027  ExecDeleteEpilogue(context, resultRelInfo, tupleid, NULL,
3028  false);
3029  mtstate->mt_merge_deleted += 1;
3030  }
3031  break;
3032 
3033  case CMD_NOTHING:
3034  /* Doing nothing is always OK */
3035  result = TM_Ok;
3036  break;
3037 
3038  default:
3039  elog(ERROR, "unknown action in MERGE WHEN clause");
3040  }
3041 
3042  switch (result)
3043  {
3044  case TM_Ok:
3045  /* all good; perform final actions */
3046  if (canSetTag && commandType != CMD_NOTHING)
3047  (estate->es_processed)++;
3048 
3049  break;
3050 
3051  case TM_SelfModified:
3052 
3053  /*
3054  * The target tuple was already updated or deleted by the
3055  * current command, or by a later command in the current
3056  * transaction. The former case is explicitly disallowed by
3057  * the SQL standard for MERGE, which insists that the MERGE
3058  * join condition should not join a target row to more than
3059  * one source row.
3060  *
3061  * The latter case arises if the tuple is modified by a
3062  * command in a BEFORE trigger, or perhaps by a command in a
3063  * volatile function used in the query. In such situations we
3064  * should not ignore the MERGE action, but it is equally
3065  * unsafe to proceed. We don't want to discard the original
3066  * MERGE action while keeping the triggered actions based on
3067  * it; and it would be no better to allow the original MERGE
3068  * action while discarding the updates that it triggered. So
3069  * throwing an error is the only safe course.
3070  */
3071  if (context->tmfd.cmax != estate->es_output_cid)
3072  ereport(ERROR,
3073  (errcode(ERRCODE_TRIGGERED_DATA_CHANGE_VIOLATION),
3074  errmsg("tuple to be updated or deleted was already modified by an operation triggered by the current command"),
3075  errhint("Consider using an AFTER trigger instead of a BEFORE trigger to propagate changes to other rows.")));
3076 
3078  ereport(ERROR,
3079  (errcode(ERRCODE_CARDINALITY_VIOLATION),
3080  /* translator: %s is a SQL command name */
3081  errmsg("%s command cannot affect row a second time",
3082  "MERGE"),
3083  errhint("Ensure that not more than one source row matches any one target row.")));
3084 
3085  /* This shouldn't happen */
3086  elog(ERROR, "attempted to update or delete invisible tuple");
3087  break;
3088 
3089  case TM_Deleted:
3091  ereport(ERROR,
3093  errmsg("could not serialize access due to concurrent delete")));
3094 
3095  /*
3096  * If the tuple was already deleted, set matched to false to
3097  * let caller handle it under NOT MATCHED [BY TARGET] clauses.
3098  */
3099  *matched = false;
3100  return NULL;
3101 
3102  case TM_Updated:
3103  {
3104  bool was_matched;
3105  Relation resultRelationDesc;
3106  TupleTableSlot *epqslot,
3107  *inputslot;
3108  LockTupleMode lockmode;
3109 
3110  /*
3111  * The target tuple was concurrently updated by some other
3112  * transaction. If we are currently processing a MATCHED
3113  * action, use EvalPlanQual() with the new version of the
3114  * tuple and recheck the join qual, to detect a change
3115  * from the MATCHED to the NOT MATCHED cases. If we are
3116  * already processing a NOT MATCHED BY SOURCE action, we
3117  * skip this (cannot switch from NOT MATCHED BY SOURCE to
3118  * MATCHED).
3119  */
3120  was_matched = relaction->mas_action->matchKind == MERGE_WHEN_MATCHED;
3121  resultRelationDesc = resultRelInfo->ri_RelationDesc;
3122  lockmode = ExecUpdateLockMode(estate, resultRelInfo);
3123 
3124  if (was_matched)
3125  inputslot = EvalPlanQualSlot(epqstate, resultRelationDesc,
3126  resultRelInfo->ri_RangeTableIndex);
3127  else
3128  inputslot = resultRelInfo->ri_oldTupleSlot;
3129 
3130  result = table_tuple_lock(resultRelationDesc, tupleid,
3131  estate->es_snapshot,
3132  inputslot, estate->es_output_cid,
3133  lockmode, LockWaitBlock,
3135  &context->tmfd);
3136  switch (result)
3137  {
3138  case TM_Ok:
3139 
3140  /*
3141  * If the tuple was updated and migrated to
3142  * another partition concurrently, the current
3143  * MERGE implementation can't follow. There's
3144  * probably a better way to handle this case, but
3145  * it'd require recognizing the relation to which
3146  * the tuple moved, and setting our current
3147  * resultRelInfo to that.
3148  */
3150  ereport(ERROR,
3152  errmsg("tuple to be merged was already moved to another partition due to concurrent update")));
3153 
3154  /*
3155  * If this was a MATCHED case, use EvalPlanQual()
3156  * to recheck the join condition.
3157  */
3158  if (was_matched)
3159  {
3160  epqslot = EvalPlanQual(epqstate,
3161  resultRelationDesc,
3162  resultRelInfo->ri_RangeTableIndex,
3163  inputslot);
3164 
3165  /*
3166  * If the subplan didn't return a tuple, then
3167  * we must be dealing with an inner join for
3168  * which the join condition no longer matches.
3169  * This can only happen if there are no NOT
3170  * MATCHED actions, and so there is nothing
3171  * more to do.
3172  */
3173  if (TupIsNull(epqslot))
3174  return NULL;
3175 
3176  /*
3177  * If we got a NULL ctid from the subplan, the
3178  * join quals no longer pass and we switch to
3179  * the NOT MATCHED BY SOURCE case.
3180  */
3181  (void) ExecGetJunkAttribute(epqslot,
3182  resultRelInfo->ri_RowIdAttNo,
3183  &isNull);
3184  if (isNull)
3185  *matched = false;
3186 
3187  /*
3188  * Otherwise, recheck the join quals to see if
3189  * we need to switch to the NOT MATCHED BY
3190  * SOURCE case.
3191  */
3192  if (!table_tuple_fetch_row_version(resultRelationDesc,
3193  &context->tmfd.ctid,
3194  SnapshotAny,
3195  resultRelInfo->ri_oldTupleSlot))
3196  elog(ERROR, "failed to fetch the target tuple");
3197 
3198  if (*matched)
3199  *matched = ExecQual(resultRelInfo->ri_MergeJoinCondition,
3200  econtext);
3201 
3202  /* Switch lists, if necessary */
3203  if (!*matched)
3204  actionStates = mergeActions[MERGE_WHEN_NOT_MATCHED_BY_SOURCE];
3205  }
3206 
3207  /*
3208  * Loop back and process the MATCHED or NOT
3209  * MATCHED BY SOURCE actions from the start.
3210  */
3211  goto lmerge_matched;
3212 
3213  case TM_Deleted:
3214 
3215  /*
3216  * tuple already deleted; tell caller to run NOT
3217  * MATCHED [BY TARGET] actions
3218  */
3219  *matched = false;
3220  return NULL;
3221 
3222  case TM_SelfModified:
3223 
3224  /*
3225  * This can be reached when following an update
3226  * chain from a tuple updated by another session,
3227  * reaching a tuple that was already updated or
3228  * deleted by the current command, or by a later
3229  * command in the current transaction. As above,
3230  * this should always be treated as an error.
3231  */
3232  if (context->tmfd.cmax != estate->es_output_cid)
3233  ereport(ERROR,
3234  (errcode(ERRCODE_TRIGGERED_DATA_CHANGE_VIOLATION),
3235  errmsg("tuple to be updated or deleted was already modified by an operation triggered by the current command"),
3236  errhint("Consider using an AFTER trigger instead of a BEFORE trigger to propagate changes to other rows.")));
3237 
3239  ereport(ERROR,
3240  (errcode(ERRCODE_CARDINALITY_VIOLATION),
3241  /* translator: %s is a SQL command name */
3242  errmsg("%s command cannot affect row a second time",
3243  "MERGE"),
3244  errhint("Ensure that not more than one source row matches any one target row.")));
3245 
3246  /* This shouldn't happen */
3247  elog(ERROR, "attempted to update or delete invisible tuple");
3248  return NULL;
3249 
3250  default:
3251  /* see table_tuple_lock call in ExecDelete() */
3252  elog(ERROR, "unexpected table_tuple_lock status: %u",
3253  result);
3254  return NULL;
3255  }
3256  }
3257 
3258  case TM_Invisible:
3259  case TM_WouldBlock:
3260  case TM_BeingModified:
3261  /* these should not occur */
3262  elog(ERROR, "unexpected tuple operation result: %d", result);
3263  break;
3264  }
3265 
3266  /* Process RETURNING if present */
3267  if (resultRelInfo->ri_projectReturning)
3268  {
3269  switch (commandType)
3270  {
3271  case CMD_UPDATE:
3272  rslot = ExecProcessReturning(resultRelInfo, newslot,
3273  context->planSlot);
3274  break;
3275 
3276  case CMD_DELETE:
3277  rslot = ExecProcessReturning(resultRelInfo,
3278  resultRelInfo->ri_oldTupleSlot,
3279  context->planSlot);
3280  break;
3281 
3282  case CMD_NOTHING:
3283  break;
3284 
3285  default:
3286  elog(ERROR, "unrecognized commandType: %d",
3287  (int) commandType);
3288  }
3289  }
3290 
3291  /*
3292  * We've activated one of the WHEN clauses, so we don't search
3293  * further. This is required behaviour, not an optimization.
3294  */
3295  break;
3296  }
3297 
3298  /*
3299  * Successfully executed an action or no qualifying action was found.
3300  */
3301  return rslot;
3302 }
LockTupleMode ExecUpdateLockMode(EState *estate, ResultRelInfo *relinfo)
Definition: execMain.c:2351
static bool ExecQual(ExprState *state, ExprContext *econtext)
Definition: executor.h:413
static Datum ExecGetJunkAttribute(TupleTableSlot *slot, AttrNumber attno, bool *isNull)
Definition: executor.h:190
static bool ItemPointerIndicatesMovedPartitions(const ItemPointerData *pointer)
Definition: itemptr.h:197
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:1367
@ WCO_RLS_MERGE_DELETE_CHECK
Definition: parsenodes.h:1368
@ MERGE_WHEN_NOT_MATCHED_BY_SOURCE
Definition: primnodes.h:1969
@ MERGE_WHEN_MATCHED
Definition: primnodes.h:1968
TupleTableSlot * ecxt_innertuple
Definition: execnodes.h:257
MergeMatchKind matchKind
Definition: primnodes.h:1976
List * ri_MergeActions[3]
Definition: execnodes.h:548
ExprState * ri_MergeJoinCondition
Definition: execnodes.h:551
bool trig_update_instead_row
Definition: reltrigger.h:63
@ TM_BeingModified
Definition: tableam.h:107
@ TM_WouldBlock
Definition: tableam.h:110
@ TM_Invisible
Definition: tableam.h:88
bool ExecIRUpdateTriggers(EState *estate, ResultRelInfo *relinfo, HeapTuple trigtuple, TupleTableSlot *newslot)
Definition: trigger.c:3156

References Assert, CMD_DELETE, CMD_NOTHING, CMD_UPDATE, MergeAction::commandType, context, UpdateContext::crossPartUpdate, 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, EvalPlanQual(), EvalPlanQualSlot(), ExecDeleteAct(), ExecDeleteEpilogue(), ExecDeletePrologue(), ExecForceStoreHeapTuple(), ExecGetJunkAttribute(), ExecIRDeleteTriggers(), ExecIRUpdateTriggers(), ExecProcessReturning(), ExecProject(), ExecQual(), ExecUpdateAct(), ExecUpdateEpilogue(), ExecUpdateLockMode(), ExecUpdatePrologue(), ExecWithCheckOptions(), IsolationUsesXactSnapshot, ItemPointerIndicatesMovedPartitions(), lfirst, LockWaitBlock, MergeActionState::mas_action, MergeActionState::mas_proj, MergeActionState::mas_whenqual, MergeAction::matchKind, MERGE_WHEN_MATCHED, MERGE_WHEN_NOT_MATCHED_BY_SOURCE, ModifyTableState::mt_epqstate, ModifyTableState::mt_merge_action, ModifyTableState::mt_merge_deleted, ModifyTableState::mt_merge_updated, NIL, ModifyTableState::ps, PlanState::ps_ExprContext, ResultRelInfo::ri_MergeActions, ResultRelInfo::ri_MergeJoinCondition, ResultRelInfo::ri_oldTupleSlot, ResultRelInfo::ri_projectReturning, ResultRelInfo::ri_RangeTableIndex, ResultRelInfo::ri_RelationDesc, ResultRelInfo::ri_RowIdAttNo, ResultRelInfo::ri_TrigDesc, ResultRelInfo::ri_WithCheckOptions, SnapshotAny, table_tuple_fetch_row_version(), table_tuple_lock(), TM_BeingModified, TM_Deleted, TM_Invisible, TM_Ok, TM_SelfModified, TM_Updated, TM_WouldBlock, TransactionIdIsCurrentTransactionId(), TriggerDesc::trig_delete_instead_row, TriggerDesc::trig_update_instead_row, TupIsNull, TUPLE_LOCK_FLAG_FIND_LAST_VERSION, WCO_RLS_MERGE_DELETE_CHECK, and WCO_RLS_MERGE_UPDATE_CHECK.

Referenced by ExecMerge().

◆ ExecMergeNotMatched()

static TupleTableSlot * ExecMergeNotMatched ( ModifyTableContext context,
ResultRelInfo resultRelInfo,
bool  canSetTag 
)
static

Definition at line 3308 of file nodeModifyTable.c.

3310 {
3311  ModifyTableState *mtstate = context->mtstate;
3312  ExprContext *econtext = mtstate->ps.ps_ExprContext;
3313  List *actionStates;
3314  TupleTableSlot *rslot = NULL;
3315  ListCell *l;
3316 
3317  /*
3318  * For INSERT actions, the root relation's merge action is OK since the
3319  * INSERT's targetlist and the WHEN conditions can only refer to the
3320  * source relation and hence it does not matter which result relation we
3321  * work with.
3322  *
3323  * XXX does this mean that we can avoid creating copies of actionStates on
3324  * partitioned tables, for not-matched actions?
3325  */
3326  actionStates = resultRelInfo->ri_MergeActions[MERGE_WHEN_NOT_MATCHED_BY_TARGET];
3327 
3328  /*
3329  * Make source tuple available to ExecQual and ExecProject. We don't need
3330  * the target tuple, since the WHEN quals and targetlist can't refer to
3331  * the target columns.
3332  */
3333  econtext->ecxt_scantuple = NULL;
3334  econtext->ecxt_innertuple = context->planSlot;
3335  econtext->ecxt_outertuple = NULL;
3336 
3337  foreach(l, actionStates)
3338  {
3340  CmdType commandType = action->mas_action->commandType;
3341  TupleTableSlot *newslot;
3342 
3343  /*
3344  * Test condition, if any.
3345  *
3346  * In the absence of any condition, we perform the action
3347  * unconditionally (no need to check separately since ExecQual() will
3348  * return true if there are no conditions to evaluate).
3349  */
3350  if (!ExecQual(action->mas_whenqual, econtext))
3351  continue;
3352 
3353  /* Perform stated action */
3354  switch (commandType)
3355  {
3356  case CMD_INSERT:
3357 
3358  /*
3359  * Project the tuple. In case of a partitioned table, the
3360  * projection was already built to use the root's descriptor,
3361  * so we don't need to map the tuple here.
3362  */
3363  newslot = ExecProject(action->mas_proj);
3364  mtstate->mt_merge_action = action;
3365 
3366  rslot = ExecInsert(context, mtstate->rootResultRelInfo,
3367  newslot, canSetTag, NULL, NULL);
3368  mtstate->mt_merge_inserted += 1;
3369  break;
3370  case CMD_NOTHING:
3371  /* Do nothing */
3372  break;
3373  default:
3374  elog(ERROR, "unknown action in MERGE WHEN NOT MATCHED clause");
3375  }
3376 
3377  /*
3378  * We've activated one of the WHEN clauses, so we don't search
3379  * further. This is required behaviour, not an optimization.
3380  */
3381  break;
3382  }
3383 
3384  return rslot;
3385 }
@ MERGE_WHEN_NOT_MATCHED_BY_TARGET
Definition: primnodes.h:1970

References generate_unaccent_rules::action, CMD_INSERT, CMD_NOTHING, context, ExprContext::ecxt_innertuple, ExprContext::ecxt_outertuple, ExprContext::ecxt_scantuple, elog, ERROR, ExecInsert(), ExecProject(), ExecQual(), lfirst, MERGE_WHEN_NOT_MATCHED_BY_TARGET, ModifyTableState::mt_merge_action, ModifyTableState::mt_merge_inserted, ModifyTableState::ps, PlanState::ps_ExprContext, ResultRelInfo::ri_MergeActions, and ModifyTableState::rootResultRelInfo.

Referenced by ExecMerge(), and ExecModifyTable().

◆ ExecModifyTable()

static TupleTableSlot* ExecModifyTable ( PlanState pstate)
static

Definition at line 3738 of file nodeModifyTable.c.

3739 {
3740  ModifyTableState *node = castNode(ModifyTableState, pstate);
3742  EState *estate = node->ps.state;
3743  CmdType operation = node->operation;
3744  ResultRelInfo *resultRelInfo;
3745  PlanState *subplanstate;
3746  TupleTableSlot *slot;
3747  TupleTableSlot *oldSlot;
3748  ItemPointerData tuple_ctid;
3749  HeapTupleData oldtupdata;
3750  HeapTuple oldtuple;
3751  ItemPointer tupleid;
3752 
3754 
3755  /*
3756  * This should NOT get called during EvalPlanQual; we should have passed a
3757  * subplan tree to EvalPlanQual, instead. Use a runtime test not just
3758  * Assert because this condition is easy to miss in testing. (Note:
3759  * although ModifyTable should not get executed within an EvalPlanQual
3760  * operation, we do have to allow it to be initialized and shut down in
3761  * case it is within a CTE subplan. Hence this test must be here, not in
3762  * ExecInitModifyTable.)
3763  */
3764  if (estate->es_epq_active != NULL)
3765  elog(ERROR, "ModifyTable should not be called during EvalPlanQual");
3766 
3767  /*
3768  * If we've already completed processing, don't try to do more. We need
3769  * this test because ExecPostprocessPlan might call us an extra time, and
3770  * our subplan's nodes aren't necessarily robust against being called
3771  * extra times.
3772  */
3773  if (node->mt_done)
3774  return NULL;
3775 
3776  /*
3777  * On first call, fire BEFORE STATEMENT triggers before proceeding.
3778  */
3779  if (node->fireBSTriggers)
3780  {
3781  fireBSTriggers(node);
3782  node->fireBSTriggers = false;
3783  }
3784 
3785  /* Preload local variables */
3786  resultRelInfo = node->resultRelInfo + node->mt_lastResultIndex;
3787  subplanstate = outerPlanState(node);
3788 
3789  /* Set global context */
3790  context.mtstate = node;
3791  context.epqstate = &node->mt_epqstate;
3792  context.estate = estate;
3793 
3794  /*
3795  * Fetch rows from subplan, and execute the required table modification
3796  * for each row.
3797  */
3798  for (;;)
3799  {
3800  /*
3801  * Reset the per-output-tuple exprcontext. This is needed because
3802  * triggers expect to use that context as workspace. It's a bit ugly
3803  * to do this below the top level of the plan, however. We might need
3804  * to rethink this later.
3805  */
3806  ResetPerTupleExprContext(estate);
3807 
3808  /*
3809  * Reset per-tuple memory context used for processing on conflict and
3810  * returning clauses, to free any expression evaluation storage
3811  * allocated in the previous cycle.
3812  */
3813  if (pstate->ps_ExprContext)
3815 
3816  /*
3817  * If there is a pending MERGE ... WHEN NOT MATCHED [BY TARGET] action
3818  * to execute, do so now --- see the comments in ExecMerge().
3819  */
3820  if (node->mt_merge_pending_not_matched != NULL)
3821  {
3822  context.planSlot = node->mt_merge_pending_not_matched;
3823 
3824  slot = ExecMergeNotMatched(&context, node->resultRelInfo,
3825  node->canSetTag);
3826 
3827  /* Clear the pending action */
3828  node->mt_merge_pending_not_matched = NULL;
3829 
3830  /*
3831  * If we got a RETURNING result, return it to the caller. We'll
3832  * continue the work on next call.
3833  */
3834  if (slot)
3835  return slot;
3836 
3837  continue; /* continue with the next tuple */
3838  }
3839 
3840  /* Fetch the next row from subplan */
3841  context.planSlot = ExecProcNode(subplanstate);
3842 
3843  /* No more tuples to process? */
3844  if (TupIsNull(context.planSlot))
3845  break;
3846 
3847  /*
3848  * When there are multiple result relations, each tuple contains a
3849  * junk column that gives the OID of the rel from which it came.
3850  * Extract it and select the correct result relation.
3851  */
3853  {
3854  Datum datum;
3855  bool isNull;
3856  Oid resultoid;
3857 
3858  datum = ExecGetJunkAttribute(context.planSlot, node->mt_resultOidAttno,
3859  &isNull);
3860  if (isNull)
3861  {
3862  /*
3863  * For commands other than MERGE, any tuples having InvalidOid
3864  * for tableoid are errors. For MERGE, we may need to handle
3865  * them as WHEN NOT MATCHED clauses if any, so do that.
3866  *
3867  * Note that we use the node's toplevel resultRelInfo, not any
3868  * specific partition's.
3869  */
3870  if (operation == CMD_MERGE)
3871  {
3872  EvalPlanQualSetSlot(&node->mt_epqstate, context.planSlot);
3873 
3874  slot = ExecMerge(&context, node->resultRelInfo,
3875  NULL, NULL, node->canSetTag);
3876 
3877  /*
3878  * If we got a RETURNING result, return it to the caller.
3879  * We'll continue the work on next call.
3880  */
3881  if (slot)
3882  return slot;
3883 
3884  continue; /* continue with the next tuple */
3885  }
3886 
3887  elog(ERROR, "tableoid is NULL");
3888  }
3889  resultoid = DatumGetObjectId(datum);
3890 
3891  /* If it's not the same as last time, we need to locate the rel */
3892  if (resultoid != node->mt_lastResultOid)
3893  resultRelInfo = ExecLookupResultRelByOid(node, resultoid,
3894  false, true);
3895  }
3896 
3897  /*
3898  * If resultRelInfo->ri_usesFdwDirectModify is true, all we need to do
3899  * here is compute the RETURNING expressions.
3900  */
3901  if (resultRelInfo->ri_usesFdwDirectModify)
3902  {
3903  Assert(resultRelInfo->ri_projectReturning);
3904 
3905  /*
3906  * A scan slot containing the data that was actually inserted,
3907  * updated or deleted has already been made available to
3908  * ExecProcessReturning by IterateDirectModify, so no need to
3909  * provide it here.
3910  */
3911  slot = ExecProcessReturning(resultRelInfo, NULL, context.planSlot);
3912 
3913  return slot;
3914  }
3915 
3916  EvalPlanQualSetSlot(&node->mt_epqstate, context.planSlot);
3917  slot = context.planSlot;
3918 
3919  tupleid = NULL;
3920  oldtuple = NULL;
3921 
3922  /*
3923  * For UPDATE/DELETE/MERGE, fetch the row identity info for the tuple
3924  * to be updated/deleted/merged. For a heap relation, that's a TID;
3925  * otherwise we may have a wholerow junk attr that carries the old
3926  * tuple in toto. Keep this in step with the part of
3927  * ExecInitModifyTable that sets up ri_RowIdAttNo.
3928  */
3929  if (operation == CMD_UPDATE || operation == CMD_DELETE ||
3930  operation == CMD_MERGE)
3931  {
3932  char relkind;
3933  Datum datum;
3934  bool isNull;
3935 
3936  relkind = resultRelInfo->ri_RelationDesc->rd_rel->relkind;
3937  if (relkind == RELKIND_RELATION ||
3938  relkind == RELKIND_MATVIEW ||
3939  relkind == RELKIND_PARTITIONED_TABLE)
3940  {
3941  /* ri_RowIdAttNo refers to a ctid attribute */
3942  Assert(AttributeNumberIsValid(resultRelInfo->ri_RowIdAttNo));
3943  datum = ExecGetJunkAttribute(slot,
3944  resultRelInfo->ri_RowIdAttNo,
3945  &isNull);
3946 
3947  /*
3948  * For commands other than MERGE, any tuples having a null row
3949  * identifier are errors. For MERGE, we may need to handle
3950  * them as WHEN NOT MATCHED clauses if any, so do that.
3951  *
3952  * Note that we use the node's toplevel resultRelInfo, not any
3953  * specific partition's.
3954  */
3955  if (isNull)
3956  {
3957  if (operation == CMD_MERGE)
3958  {
3959  EvalPlanQualSetSlot(&node->mt_epqstate, context.planSlot);
3960 
3961  slot = ExecMerge(&context, node->resultRelInfo,
3962  NULL, NULL, node->canSetTag);
3963 
3964  /*
3965  * If we got a RETURNING result, return it to the
3966  * caller. We'll continue the work on next call.
3967  */
3968  if (slot)
3969  return slot;
3970 
3971  continue; /* continue with the next tuple */
3972  }
3973 
3974  elog(ERROR, "ctid is NULL");
3975  }
3976 
3977  tupleid = (ItemPointer) DatumGetPointer(datum);
3978  tuple_ctid = *tupleid; /* be sure we don't free ctid!! */
3979  tupleid = &tuple_ctid;
3980  }
3981 
3982  /*
3983  * Use the wholerow attribute, when available, to reconstruct the
3984  * old relation tuple. The old tuple serves one or both of two
3985  * purposes: 1) it serves as the OLD tuple for row triggers, 2) it
3986  * provides values for any unchanged columns for the NEW tuple of
3987  * an UPDATE, because the subplan does not produce all the columns
3988  * of the target table.
3989  *
3990  * Note that the wholerow attribute does not carry system columns,
3991  * so foreign table triggers miss seeing those, except that we
3992  * know enough here to set t_tableOid. Quite separately from
3993  * this, the FDW may fetch its own junk attrs to identify the row.
3994  *
3995  * Other relevant relkinds, currently limited to views, always
3996  * have a wholerow attribute.
3997  */
3998  else if (AttributeNumberIsValid(resultRelInfo->ri_RowIdAttNo))
3999  {
4000  datum = ExecGetJunkAttribute(slot,
4001  resultRelInfo->ri_RowIdAttNo,
4002  &isNull);
4003 
4004  /*
4005  * For commands other than MERGE, any tuples having a null row
4006  * identifier are errors. For MERGE, we may need to handle
4007  * them as WHEN NOT MATCHED clauses if any, so do that.
4008  *
4009  * Note that we use the node's toplevel resultRelInfo, not any
4010  * specific partition's.
4011  */
4012  if (isNull)
4013  {
4014  if (operation == CMD_MERGE)
4015  {
4016  EvalPlanQualSetSlot(&node->mt_epqstate, context.planSlot);
4017 
4018  slot = ExecMerge(&context, node->resultRelInfo,
4019  NULL, NULL, node->canSetTag);
4020 
4021  /*
4022  * If we got a RETURNING result, return it to the
4023  * caller. We'll continue the work on next call.
4024  */
4025  if (slot)
4026  return slot;
4027 
4028  continue; /* continue with the next tuple */
4029  }
4030 
4031  elog(ERROR, "wholerow is NULL");
4032  }
4033 
4034  oldtupdata.t_data = DatumGetHeapTupleHeader(datum);
4035  oldtupdata.t_len =
4037  ItemPointerSetInvalid(&(oldtupdata.t_self));
4038  /* Historically, view triggers see invalid t_tableOid. */
4039  oldtupdata.t_tableOid =
4040  (relkind == RELKIND_VIEW) ? InvalidOid :
4041  RelationGetRelid(resultRelInfo->ri_RelationDesc);
4042 
4043  oldtuple = &oldtupdata;
4044  }
4045  else
4046  {
4047  /* Only foreign tables are allowed to omit a row-ID attr */
4048  Assert(relkind == RELKIND_FOREIGN_TABLE);
4049  }
4050  }
4051 
4052  switch (operation)
4053  {
4054  case CMD_INSERT:
4055  /* Initialize projection info if first time for this table */
4056  if (unlikely(!resultRelInfo->ri_projectNewInfoValid))
4057  ExecInitInsertProjection(node, resultRelInfo);
4058  slot = ExecGetInsertNewTuple(resultRelInfo, context.planSlot);
4059  slot = ExecInsert(&context, resultRelInfo, slot,
4060  node->canSetTag, NULL, NULL);
4061  break;
4062 
4063  case CMD_UPDATE:
4064  /* Initialize projection info if first time for this table */
4065  if (unlikely(!resultRelInfo->ri_projectNewInfoValid))
4066  ExecInitUpdateProjection(node, resultRelInfo);
4067 
4068  /*
4069  * Make the new tuple by combining plan's output tuple with
4070  * the old tuple being updated.
4071  */
4072  oldSlot = resultRelInfo->ri_oldTupleSlot;
4073  if (oldtuple != NULL)
4074  {
4075  /* Use the wholerow junk attr as the old tuple. */
4076  ExecForceStoreHeapTuple(oldtuple, oldSlot, false);
4077  }
4078  else
4079  {
4080  /* Fetch the most recent version of old tuple. */
4081  Relation relation = resultRelInfo->ri_RelationDesc;
4082 
4083  if (!table_tuple_fetch_row_version(relation, tupleid,
4084  SnapshotAny,
4085  oldSlot))
4086  elog(ERROR, "failed to fetch tuple being updated");
4087  }
4088  slot = ExecGetUpdateNewTuple(resultRelInfo, context.planSlot,
4089  oldSlot);
4090 
4091  /* Now apply the update. */
4092  slot = ExecUpdate(&context, resultRelInfo, tupleid, oldtuple,
4093  slot, node->canSetTag);
4094  break;
4095 
4096  case CMD_DELETE:
4097  slot = ExecDelete(&context, resultRelInfo, tupleid, oldtuple,
4098  true, false, node->canSetTag, NULL, NULL, NULL);
4099  break;
4100 
4101  case CMD_MERGE:
4102  slot = ExecMerge(&context, resultRelInfo, tupleid, oldtuple,
4103  node->canSetTag);
4104  break;
4105 
4106  default:
4107  elog(ERROR, "unknown operation");
4108  break;
4109  }
4110 
4111  /*
4112  * If we got a RETURNING result, return it to caller. We'll continue
4113  * the work on next call.
4114  */
4115  if (slot)
4116  return slot;
4117  }
4118 
4119  /*
4120  * Insert remaining tuples for batch insert.
4121  */
4122  if (estate->es_insert_pending_result_relations != NIL)
4123  ExecPendingInserts(estate);
4124 
4125  /*
4126  * We're done, but fire AFTER STATEMENT triggers before exiting.
4127  */
4128  fireASTriggers(node);
4129 
4130  node->mt_done = true;
4131 
4132  return NULL;
4133 }
#define ResetPerTupleExprContext(estate)
Definition: executor.h:559
#define ResetExprContext(econtext)
Definition: executor.h:544
#define EvalPlanQualSetSlot(epqstate, slot)
Definition: executor.h:244
static TupleTableSlot * ExecProcNode(PlanState *node)
Definition: executor.h:269
#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 * 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)
static TupleTableSlot * ExecMerge(ModifyTableContext *context, ResultRelInfo *resultRelInfo, ItemPointer tupleid, HeapTuple oldtuple, bool canSetTag)
#define castNode(_type_, nodeptr)
Definition: nodes.h:176
static Oid DatumGetObjectId(Datum X)
Definition: postgres.h:242
static Pointer DatumGetPointer(Datum X)
Definition: postgres.h:312
struct EPQState * es_epq_active
Definition: execnodes.h:699
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, context, DatumGetHeapTupleHeader, DatumGetObjectId(), DatumGetPointer(), elog, ERROR, EState::es_epq_active, EState::es_insert_pending_result_relations, EvalPlanQualSetSlot, ExecDelete(), ExecForceStoreHeapTuple(), ExecGetInsertNewTuple(), ExecGetJunkAttribute(), ExecGetUpdateNewTuple(), ExecInitInsertProjection(), ExecInitUpdateProjection(), ExecInsert(), ExecLookupResultRelByOid(), ExecMerge(), ExecMergeNotMatched(), 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_merge_pending_not_matched, ModifyTableState::mt_resultOidAttno, NIL, ModifyTableState::operation, outerPlanState, ModifyTableState::ps, PlanState::ps_ExprContext, RelationData::rd_rel, 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:1222
@ WCO_RLS_CONFLICT_CHECK
Definition: parsenodes.h:1366
static void test(void)
ItemPointerData ctid
Definition: tableam.h:150

References Assert, context, TM_FailureData::ctid, DatumGetTransactionId(), ExprContext::ecxt_innertuple, ExprContext::ecxt_outertuple, ExprContext::ecxt_scantuple, elog, ereport, errcode(), ERRCODE_T_R_SERIALIZATION_FAILURE, errhint(), errmsg(), ERROR, ExecCheckTupleVisible(), ExecClearTuple(), ExecProject(), ExecQual(), ExecUpdate(), ExecUpdateLockMode(), ExecWithCheckOptions(), InstrCountFiltered1, IsolationUsesXactSnapshot, ItemPointerIndicatesMovedPartitions(), LockWaitBlock, MinTransactionIdAttributeNumber, 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 1274 of file nodeModifyTable.c.

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

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

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

◆ ExecPrepareTupleRouting()

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

Definition at line 3678 of file nodeModifyTable.c.

3684 {
3685  ResultRelInfo *partrel;
3686  TupleConversionMap *map;
3687 
3688  /*
3689  * Lookup the target partition's ResultRelInfo. If ExecFindPartition does
3690  * not find a valid partition for the tuple in 'slot' then an error is
3691  * raised. An error may also be raised if the found partition is not a
3692  * valid target for INSERTs. This is required since a partitioned table
3693  * UPDATE to another partition becomes a DELETE+INSERT.
3694  */
3695  partrel = ExecFindPartition(mtstate, targetRelInfo, proute, slot, estate);
3696 
3697  /*
3698  * If we're capturing transition tuples, we might need to convert from the
3699  * partition rowtype to root partitioned table's rowtype. But if there
3700  * are no BEFORE triggers on the partition that could change the tuple, we
3701  * can just remember the original unconverted tuple to avoid a needless
3702  * round trip conversion.
3703  */
3704  if (mtstate->mt_transition_capture != NULL)
3705  {
3706  bool has_before_insert_row_trig;
3707 
3708  has_before_insert_row_trig = (partrel->ri_TrigDesc &&
3710 
3712  !has_before_insert_row_trig ? slot : NULL;
3713  }
3714 
3715  /*
3716  * Convert the tuple, if necessary.
3717  */
3718  map = ExecGetRootToChildMap(partrel, estate);
3719  if (map != NULL)
3720  {
3721  TupleTableSlot *new_slot = partrel->ri_PartitionTupleSlot;
3722 
3723  slot = execute_attr_map_slot(map->attrMap, slot, new_slot);
3724  }
3725 
3726  *partRelInfo = partrel;
3727  return slot;
3728 }
ResultRelInfo * ExecFindPartition(ModifyTableState *mtstate, ResultRelInfo *rootResultRelInfo, PartitionTupleRouting *proute, TupleTableSlot *slot, EState *estate)
TupleConversionMap * ExecGetRootToChildMap(ResultRelInfo *resultRelInfo, EState *estate)
Definition: execUtils.c:1232
TupleTableSlot * ri_PartitionTupleSlot
Definition: execnodes.h:583

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

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

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

◆ ExecReScanModifyTable()

void ExecReScanModifyTable ( ModifyTableState node)

Definition at line 4734 of file nodeModifyTable.c.

4735 {
4736  /*
4737  * Currently, we don't need to support rescan on ModifyTable nodes. The
4738  * semantics of that would be a bit debatable anyway.
4739  */
4740  elog(ERROR, "ExecReScanModifyTable is not implemented");
4741 }

References elog, and ERROR.

Referenced by ExecReScan().

◆ ExecSetupTransitionCaptureState()

static void ExecSetupTransitionCaptureState ( ModifyTableState mtstate,
EState estate 
)
static

Definition at line 3649 of file nodeModifyTable.c.

3650 {
3651  ModifyTable *plan = (ModifyTable *) mtstate->ps.plan;
3652  ResultRelInfo *targetRelInfo = mtstate->rootResultRelInfo;
3653 
3654  /* Check for transition tables on the directly targeted relation. */
3655  mtstate->mt_transition_capture =
3656  MakeTransitionCaptureState(targetRelInfo->ri_TrigDesc,
3657  RelationGetRelid(targetRelInfo->ri_RelationDesc),
3658  mtstate->operation);
3659  if (plan->operation == CMD_INSERT &&
3660  plan->onConflictAction == ONCONFLICT_UPDATE)
3661  mtstate->mt_oc_transition_capture =
3662  MakeTransitionCaptureState(targetRelInfo->ri_TrigDesc,
3663  RelationGetRelid(targetRelInfo->ri_RelationDesc),
3664  CMD_UPDATE);
3665 }
#define plan(x)
Definition: pg_regress.c:162
struct TransitionCaptureState * mt_oc_transition_capture
Definition: execnodes.h:1398
TransitionCaptureState * MakeTransitionCaptureState(TriggerDesc *trigdesc, Oid relid, CmdType cmdType)
Definition: trigger.c:4882

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:454
static void ExecUpdatePrepareSlot(ResultRelInfo *resultRelInfo, TupleTableSlot *slot, EState *estate)
ExecForeignUpdate_function ExecForeignUpdate
Definition: fdwapi.h:235
LockTupleMode lockmode

References Assert, context, UpdateContext::crossPartUpdate, elog, ereport, errcode(), ERRCODE_T_R_SERIALIZATION_FAILURE, errhint(), errmsg(), ERROR, EState::es_output_cid, EState::es_processed, EState::es_snapshot, EvalPlanQual(), EvalPlanQualSlot(), FdwRoutine::ExecForeignUpdate, ExecGetUpdateNewTuple(), ExecInitUpdateProjection(), ExecIRUpdateTriggers(), ExecProcessReturning(), ExecUpdateAct(), ExecUpdateEpilogue(), ExecUpdatePrepareSlot(), ExecUpdatePrologue(), IsBootstrapProcessingMode, IsolationUsesXactSnapshot, UpdateContext::lockmode, LockWaitBlock, 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, 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 1970 of file nodeModifyTable.c.

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

References CMD_MERGE, TupleDescData::constr, context, UpdateContext::crossPartUpdate, EState::es_crosscheck_snapshot, EState::es_output_cid, EState::es_snapshot, ExecConstraints(), ExecCrossPartitionUpdate(), ExecCrossPartitionUpdateForeignKey(), ExecMaterializeSlot(), ExecPartitionCheck(), ExecUpdatePrepareSlot(), ExecWithCheckOptions(), UpdateContext::lockmode, NIL, RelationData::rd_att, RelationData::rd_rel, ResultRelInfo::ri_RelationDesc, ResultRelInfo::ri_TrigDesc, ResultRelInfo::ri_WithCheckOptions, table_tuple_update(), TM_Ok, TriggerDesc::trig_update_after_row, 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:126
@ TU_None
Definition: tableam.h:120

References CMD_INSERT, context, ExecARUpdateTriggers(), ExecInsertIndexTuples(), ExecWithCheckOptions(), list_free(), ModifyTableState::mt_oc_transition_capture, ModifyTableState::mt_transition_capture, 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 1935 of file nodeModifyTable.c.

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

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

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

References context, ExecBRUpdateTriggers(), ExecMaterializeSlot(), ExecOpenIndices(), ExecPendingInserts(), NIL, RelationData::rd_rel, ResultRelInfo::ri_IndexRelationDescs, ResultRelInfo::ri_RelationDesc, ResultRelInfo::ri_TrigDesc, TM_Ok, and TriggerDesc::trig_update_before_row.

Referenced by ExecMergeMatched(), and ExecUpdate().

◆ fireASTriggers()

static void fireASTriggers ( ModifyTableState node)
static

Definition at line 3604 of file nodeModifyTable.c.

3605 {
3606  ModifyTable *plan = (ModifyTable *) node->ps.plan;
3607  ResultRelInfo *resultRelInfo = node->rootResultRelInfo;
3608 
3609  switch (node->operation)
3610  {
3611  case CMD_INSERT:
3612  if (plan->onConflictAction == ONCONFLICT_UPDATE)
3614  resultRelInfo,
3615  node->mt_oc_transition_capture);
3616  ExecASInsertTriggers(node->ps.state, resultRelInfo,
3617  node->mt_transition_capture);
3618  break;
3619  case CMD_UPDATE:
3620  ExecASUpdateTriggers(node->ps.state, resultRelInfo,
3621  node->mt_transition_capture);
3622  break;
3623  case CMD_DELETE:
3624  ExecASDeleteTriggers(node->ps.state, resultRelInfo,
3625  node->mt_transition_capture);
3626  break;
3627  case CMD_MERGE:
3628  if (node->mt_merge_subcommands & MERGE_DELETE)
3629  ExecASDeleteTriggers(node->ps.state, resultRelInfo,
3630  node->mt_transition_capture);
3631  if (node->mt_merge_subcommands & MERGE_UPDATE)
3632  ExecASUpdateTriggers(node->ps.state, resultRelInfo,
3633  node->mt_transition_capture);
3634  if (node->mt_merge_subcommands & MERGE_INSERT)
3635  ExecASInsertTriggers(node->ps.state, resultRelInfo,
3636  node->mt_transition_capture);
3637  break;
3638  default:
3639  elog(ERROR, "unknown operation");
3640  break;
3641  }
3642 }
void ExecASUpdateTriggers(EState *estate, ResultRelInfo *relinfo, TransitionCaptureState *transition_capture)
Definition: trigger.c:2916
void ExecASDeleteTriggers(EState *estate, ResultRelInfo *relinfo, TransitionCaptureState *transition_capture)
Definition: trigger.c:2663
void ExecASInsertTriggers(EState *estate, ResultRelInfo *relinfo, TransitionCaptureState *transition_capture)
Definition: trigger.c:2445

References CMD_DELETE, CMD_INSERT, CMD_MERGE, CMD_UPDATE, elog, ERROR, ExecASDeleteTriggers(), ExecASInsertTriggers(), ExecASUpdateTriggers(), MERGE_DELETE, MERGE_INSERT, MERGE_UPDATE, ModifyTableState::mt_merge_subcommands, ModifyTableState::mt_oc_transition_capture, ModifyTableState::mt_transition_capture, ONCONFLICT_UPDATE, ModifyTableState::operation, PlanState::plan, plan, ModifyTableState::ps, ModifyTableState::rootResultRelInfo, and PlanState::state.

Referenced by ExecModifyTable().

◆ fireBSTriggers()

static void fireBSTriggers ( ModifyTableState node)
static

Definition at line 3567 of file nodeModifyTable.c.

3568 {
3569  ModifyTable *plan = (ModifyTable *) node->ps.plan;
3570  ResultRelInfo *resultRelInfo = node->rootResultRelInfo;
3571 
3572  switch (node->operation)
3573  {
3574  case CMD_INSERT:
3575  ExecBSInsertTriggers(node->ps.state, resultRelInfo);
3576  if (plan->onConflictAction == ONCONFLICT_UPDATE)
3578  resultRelInfo);
3579  break;
3580  case CMD_UPDATE:
3581  ExecBSUpdateTriggers(node->ps.state, resultRelInfo);
3582  break;
3583  case CMD_DELETE:
3584  ExecBSDeleteTriggers(node->ps.state, resultRelInfo);
3585  break;
3586  case CMD_MERGE:
3587  if (node->mt_merge_subcommands & MERGE_INSERT)
3588  ExecBSInsertTriggers(node->ps.state, resultRelInfo);
3589  if (node->mt_merge_subcommands & MERGE_UPDATE)
3590  ExecBSUpdateTriggers(node->ps.state, resultRelInfo);
3591  if (node->mt_merge_subcommands & MERGE_DELETE)
3592  ExecBSDeleteTriggers(node->ps.state, resultRelInfo);
3593  break;
3594  default:
3595  elog(ERROR, "unknown operation");
3596  break;
3597  }
3598 }
void ExecBSInsertTriggers(EState *estate, ResultRelInfo *relinfo)
Definition: trigger.c:2394
void ExecBSDeleteTriggers(EState *estate, ResultRelInfo *relinfo)
Definition: trigger.c:2612
void ExecBSUpdateTriggers(EState *estate, ResultRelInfo *relinfo)
Definition: trigger.c:2858

References CMD_DELETE, CMD_INSERT, CMD_MERGE, CMD_UPDATE, elog, ERROR, ExecBSDeleteTriggers(), ExecBSInsertTriggers(), ExecBSUpdateTriggers(), MERGE_DELETE, MERGE_INSERT, MERGE_UPDATE, ModifyTableState::mt_merge_subcommands, ONCONFLICT_UPDATE, ModifyTableState::operation, PlanState::plan, plan, ModifyTableState::ps, ModifyTableState::rootResultRelInfo, and PlanState::state.

Referenced by ExecModifyTable().