PostgreSQL Source Code  git master
 All Data Structures Namespaces Files Functions Variables Typedefs Enumerations Enumerator Macros
nodeModifyTable.c File Reference
#include "postgres.h"
#include "access/htup_details.h"
#include "access/xact.h"
#include "commands/trigger.h"
#include "executor/executor.h"
#include "executor/nodeModifyTable.h"
#include "foreign/fdwapi.h"
#include "miscadmin.h"
#include "nodes/nodeFuncs.h"
#include "parser/parsetree.h"
#include "storage/bufmgr.h"
#include "storage/lmgr.h"
#include "utils/builtins.h"
#include "utils/memutils.h"
#include "utils/rel.h"
#include "utils/tqual.h"
Include dependency graph for nodeModifyTable.c:

Go to the source code of this file.

Functions

static bool ExecOnConflictUpdate (ModifyTableState *mtstate, ResultRelInfo *resultRelInfo, ItemPointer conflictTid, TupleTableSlot *planSlot, TupleTableSlot *excludedSlot, EState *estate, bool canSetTag, TupleTableSlot **returning)
 
static void ExecCheckPlanOutput (Relation resultRel, List *targetList)
 
static TupleTableSlotExecProcessReturning (ResultRelInfo *resultRelInfo, TupleTableSlot *tupleSlot, TupleTableSlot *planSlot)
 
static void ExecCheckHeapTupleVisible (EState *estate, HeapTuple tuple, Buffer buffer)
 
static void ExecCheckTIDVisible (EState *estate, ResultRelInfo *relinfo, ItemPointer tid)
 
static TupleTableSlotExecInsert (ModifyTableState *mtstate, TupleTableSlot *slot, TupleTableSlot *planSlot, List *arbiterIndexes, OnConflictAction onconflict, EState *estate, bool canSetTag)
 
static TupleTableSlotExecDelete (ModifyTableState *mtstate, ItemPointer tupleid, HeapTuple oldtuple, TupleTableSlot *planSlot, EPQState *epqstate, EState *estate, bool canSetTag)
 
static TupleTableSlotExecUpdate (ModifyTableState *mtstate, ItemPointer tupleid, HeapTuple oldtuple, TupleTableSlot *slot, TupleTableSlot *planSlot, EPQState *epqstate, EState *estate, bool canSetTag)
 
static void fireBSTriggers (ModifyTableState *node)
 
static ResultRelInfogetASTriggerResultRelInfo (ModifyTableState *node)
 
static void fireASTriggers (ModifyTableState *node)
 
static void ExecSetupTransitionCaptureState (ModifyTableState *mtstate, EState *estate)
 
static TupleTableSlotExecModifyTable (PlanState *pstate)
 
ModifyTableStateExecInitModifyTable (ModifyTable *node, EState *estate, int eflags)
 
void ExecEndModifyTable (ModifyTableState *node)
 
void ExecReScanModifyTable (ModifyTableState *node)
 

Function Documentation

static void ExecCheckHeapTupleVisible ( EState estate,
HeapTuple  tuple,
Buffer  buffer 
)
static

Definition at line 192 of file nodeModifyTable.c.

References BUFFER_LOCK_SHARE, BUFFER_LOCK_UNLOCK, ereport, errcode(), errmsg(), ERROR, EState::es_snapshot, HeapTupleHeaderGetXmin, HeapTupleSatisfiesVisibility, IsolationUsesXactSnapshot, LockBuffer(), HeapTupleData::t_data, and TransactionIdIsCurrentTransactionId().

Referenced by ExecCheckTIDVisible(), and ExecOnConflictUpdate().

195 {
197  return;
198 
199  /*
200  * We need buffer pin and lock to call HeapTupleSatisfiesVisibility.
201  * Caller should be holding pin, but not lock.
202  */
204  if (!HeapTupleSatisfiesVisibility(tuple, estate->es_snapshot, buffer))
205  {
206  /*
207  * We should not raise a serialization failure if the conflict is
208  * against a tuple inserted by our own transaction, even if it's not
209  * visible to our snapshot. (This would happen, for example, if
210  * conflicting keys are proposed for insertion in a single command.)
211  */
213  ereport(ERROR,
214  (errcode(ERRCODE_T_R_SERIALIZATION_FAILURE),
215  errmsg("could not serialize access due to concurrent update")));
216  }
218 }
#define BUFFER_LOCK_UNLOCK
Definition: bufmgr.h:87
bool TransactionIdIsCurrentTransactionId(TransactionId xid)
Definition: xact.c:774
#define IsolationUsesXactSnapshot()
Definition: xact.h:43
int errcode(int sqlerrcode)
Definition: elog.c:575
Snapshot es_snapshot
Definition: execnodes.h:429
#define HeapTupleSatisfiesVisibility(tuple, snapshot, buffer)
Definition: tqual.h:45
HeapTupleHeader t_data
Definition: htup.h:67
#define ERROR
Definition: elog.h:43
#define ereport(elevel, rest)
Definition: elog.h:122
void LockBuffer(Buffer buffer, int mode)
Definition: bufmgr.c:3546
WalTimeSample buffer[LAG_TRACKER_BUFFER_SIZE]
Definition: walsender.c:214
#define HeapTupleHeaderGetXmin(tup)
Definition: htup_details.h:307
int errmsg(const char *fmt,...)
Definition: elog.c:797
#define BUFFER_LOCK_SHARE
Definition: bufmgr.h:88
static void ExecCheckPlanOutput ( Relation  resultRel,
List targetList 
)
static

Definition at line 79 of file nodeModifyTable.c.

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

Referenced by ExecInitModifyTable().

80 {
81  TupleDesc resultDesc = RelationGetDescr(resultRel);
82  int attno = 0;
83  ListCell *lc;
84 
85  foreach(lc, targetList)
86  {
87  TargetEntry *tle = (TargetEntry *) lfirst(lc);
88  Form_pg_attribute attr;
89 
90  if (tle->resjunk)
91  continue; /* ignore junk tlist items */
92 
93  if (attno >= resultDesc->natts)
94  ereport(ERROR,
95  (errcode(ERRCODE_DATATYPE_MISMATCH),
96  errmsg("table row type and query-specified row type do not match"),
97  errdetail("Query has too many columns.")));
98  attr = TupleDescAttr(resultDesc, attno);
99  attno++;
100 
101  if (!attr->attisdropped)
102  {
103  /* Normal case: demand type match */
104  if (exprType((Node *) tle->expr) != attr->atttypid)
105  ereport(ERROR,
106  (errcode(ERRCODE_DATATYPE_MISMATCH),
107  errmsg("table row type and query-specified row type do not match"),
108  errdetail("Table has type %s at ordinal position %d, but query expects %s.",
109  format_type_be(attr->atttypid),
110  attno,
111  format_type_be(exprType((Node *) tle->expr)))));
112  }
113  else
114  {
115  /*
116  * For a dropped column, we can't check atttypid (it's likely 0).
117  * In any case the planner has most likely inserted an INT4 null.
118  * What we insist on is just *some* NULL constant.
119  */
120  if (!IsA(tle->expr, Const) ||
121  !((Const *) tle->expr)->constisnull)
122  ereport(ERROR,
123  (errcode(ERRCODE_DATATYPE_MISMATCH),
124  errmsg("table row type and query-specified row type do not match"),
125  errdetail("Query provides a value for a dropped column at ordinal position %d.",
126  attno)));
127  }
128  }
129  if (attno != resultDesc->natts)
130  ereport(ERROR,
131  (errcode(ERRCODE_DATATYPE_MISMATCH),
132  errmsg("table row type and query-specified row type do not match"),
133  errdetail("Query has too few columns.")));
134 }
#define IsA(nodeptr, _type_)
Definition: nodes.h:560
#define RelationGetDescr(relation)
Definition: rel.h:428
#define TupleDescAttr(tupdesc, i)
Definition: tupdesc.h:84
Definition: nodes.h:509
int errcode(int sqlerrcode)
Definition: elog.c:575
char * format_type_be(Oid type_oid)
Definition: format_type.c:94
int natts
Definition: tupdesc.h:73
bool resjunk
Definition: primnodes.h:1375
#define ERROR
Definition: elog.h:43
int errdetail(const char *fmt,...)
Definition: elog.c:873
FormData_pg_attribute * Form_pg_attribute
Definition: pg_attribute.h:187
#define ereport(elevel, rest)
Definition: elog.h:122
#define lfirst(lc)
Definition: pg_list.h:106
Expr * expr
Definition: primnodes.h:1368
Oid exprType(const Node *expr)
Definition: nodeFuncs.c:42
int errmsg(const char *fmt,...)
Definition: elog.c:797
static void ExecCheckTIDVisible ( EState estate,
ResultRelInfo relinfo,
ItemPointer  tid 
)
static

Definition at line 224 of file nodeModifyTable.c.

References buffer, elog, ERROR, ExecCheckHeapTupleVisible(), heap_fetch(), IsolationUsesXactSnapshot, ReleaseBuffer(), ResultRelInfo::ri_RelationDesc, SnapshotAny, and HeapTupleData::t_self.

Referenced by ExecInsert().

227 {
228  Relation rel = relinfo->ri_RelationDesc;
229  Buffer buffer;
230  HeapTupleData tuple;
231 
232  /* Redundantly check isolation level */
234  return;
235 
236  tuple.t_self = *tid;
237  if (!heap_fetch(rel, SnapshotAny, &tuple, &buffer, false, NULL))
238  elog(ERROR, "failed to fetch conflicting tuple for ON CONFLICT");
239  ExecCheckHeapTupleVisible(estate, &tuple, buffer);
240  ReleaseBuffer(buffer);
241 }
Relation ri_RelationDesc
Definition: execnodes.h:354
bool heap_fetch(Relation relation, Snapshot snapshot, HeapTuple tuple, Buffer *userbuf, bool keep_buf, Relation stats_relation)
Definition: heapam.c:1876
#define IsolationUsesXactSnapshot()
Definition: xact.h:43
void ReleaseBuffer(Buffer buffer)
Definition: bufmgr.c:3309
#define ERROR
Definition: elog.h:43
ItemPointerData t_self
Definition: htup.h:65
static void ExecCheckHeapTupleVisible(EState *estate, HeapTuple tuple, Buffer buffer)
#define SnapshotAny
Definition: tqual.h:28
WalTimeSample buffer[LAG_TRACKER_BUFFER_SIZE]
Definition: walsender.c:214
#define elog
Definition: elog.h:219
int Buffer
Definition: buf.h:23
static TupleTableSlot* ExecDelete ( ModifyTableState mtstate,
ItemPointer  tupleid,
HeapTuple  oldtuple,
TupleTableSlot planSlot,
EPQState epqstate,
EState estate,
bool  canSetTag 
)
static

Definition at line 674 of file nodeModifyTable.c.

References Assert, BufferIsValid, HeapUpdateFailureData::cmax, HeapUpdateFailureData::ctid, elog, ereport, errcode(), errhint(), errmsg(), ERROR, EState::es_crosscheck_snapshot, EState::es_output_cid, EState::es_processed, EState::es_result_relation_info, EState::es_trig_tuple_slot, EvalPlanQual(), ExecARDeleteTriggers(), ExecBRDeleteTriggers(), ExecClearTuple(), FdwRoutine::ExecForeignDelete, ExecIRDeleteTriggers(), ExecMaterializeSlot(), ExecProcessReturning(), ExecSetSlotDescriptor(), ExecStoreAllNullTuple(), ExecStoreTuple(), heap_delete(), heap_fetch(), HeapTupleMayBeUpdated, HeapTupleSelfUpdated, HeapTupleUpdated, InvalidBuffer, IsolationUsesXactSnapshot, ItemPointerEquals(), LockTupleExclusive, ModifyTableState::mt_transition_capture, RelationGetDescr, RelationGetRelid, ReleaseBuffer(), ResultRelInfo::ri_FdwRoutine, ResultRelInfo::ri_projectReturning, ResultRelInfo::ri_RangeTableIndex, ResultRelInfo::ri_RelationDesc, ResultRelInfo::ri_TrigDesc, SnapshotAny, HeapTupleData::t_self, HeapTupleData::t_tableOid, TriggerDesc::trig_delete_before_row, TriggerDesc::trig_delete_instead_row, TupleTableSlot::tts_isempty, TupleTableSlot::tts_tupleDescriptor, TupIsNull, and HeapUpdateFailureData::xmax.

Referenced by ExecModifyTable().

681 {
682  ResultRelInfo *resultRelInfo;
683  Relation resultRelationDesc;
684  HTSU_Result result;
686  TupleTableSlot *slot = NULL;
687 
688  /*
689  * get information on the (current) result relation
690  */
691  resultRelInfo = estate->es_result_relation_info;
692  resultRelationDesc = resultRelInfo->ri_RelationDesc;
693 
694  /* BEFORE ROW DELETE Triggers */
695  if (resultRelInfo->ri_TrigDesc &&
696  resultRelInfo->ri_TrigDesc->trig_delete_before_row)
697  {
698  bool dodelete;
699 
700  dodelete = ExecBRDeleteTriggers(estate, epqstate, resultRelInfo,
701  tupleid, oldtuple);
702 
703  if (!dodelete) /* "do nothing" */
704  return NULL;
705  }
706 
707  /* INSTEAD OF ROW DELETE Triggers */
708  if (resultRelInfo->ri_TrigDesc &&
709  resultRelInfo->ri_TrigDesc->trig_delete_instead_row)
710  {
711  bool dodelete;
712 
713  Assert(oldtuple != NULL);
714  dodelete = ExecIRDeleteTriggers(estate, resultRelInfo, oldtuple);
715 
716  if (!dodelete) /* "do nothing" */
717  return NULL;
718  }
719  else if (resultRelInfo->ri_FdwRoutine)
720  {
721  HeapTuple tuple;
722 
723  /*
724  * delete from foreign table: let the FDW do it
725  *
726  * We offer the trigger tuple slot as a place to store RETURNING data,
727  * although the FDW can return some other slot if it wants. Set up
728  * the slot's tupdesc so the FDW doesn't need to do that for itself.
729  */
730  slot = estate->es_trig_tuple_slot;
731  if (slot->tts_tupleDescriptor != RelationGetDescr(resultRelationDesc))
732  ExecSetSlotDescriptor(slot, RelationGetDescr(resultRelationDesc));
733 
734  slot = resultRelInfo->ri_FdwRoutine->ExecForeignDelete(estate,
735  resultRelInfo,
736  slot,
737  planSlot);
738 
739  if (slot == NULL) /* "do nothing" */
740  return NULL;
741 
742  /*
743  * RETURNING expressions might reference the tableoid column, so
744  * initialize t_tableOid before evaluating them.
745  */
746  if (slot->tts_isempty)
747  ExecStoreAllNullTuple(slot);
748  tuple = ExecMaterializeSlot(slot);
749  tuple->t_tableOid = RelationGetRelid(resultRelationDesc);
750  }
751  else
752  {
753  /*
754  * delete the tuple
755  *
756  * Note: if es_crosscheck_snapshot isn't InvalidSnapshot, we check
757  * that the row to be deleted is visible to that snapshot, and throw a
758  * can't-serialize error if not. This is a special-case behavior
759  * needed for referential integrity updates in transaction-snapshot
760  * mode transactions.
761  */
762 ldelete:;
763  result = heap_delete(resultRelationDesc, tupleid,
764  estate->es_output_cid,
765  estate->es_crosscheck_snapshot,
766  true /* wait for commit */ ,
767  &hufd);
768  switch (result)
769  {
771 
772  /*
773  * The target tuple was already updated or deleted by the
774  * current command, or by a later command in the current
775  * transaction. The former case is possible in a join DELETE
776  * where multiple tuples join to the same target tuple. This
777  * is somewhat questionable, but Postgres has always allowed
778  * it: we just ignore additional deletion attempts.
779  *
780  * The latter case arises if the tuple is modified by a
781  * command in a BEFORE trigger, or perhaps by a command in a
782  * volatile function used in the query. In such situations we
783  * should not ignore the deletion, but it is equally unsafe to
784  * proceed. We don't want to discard the original DELETE
785  * while keeping the triggered actions based on its deletion;
786  * and it would be no better to allow the original DELETE
787  * while discarding updates that it triggered. The row update
788  * carries some information that might be important according
789  * to business rules; so throwing an error is the only safe
790  * course.
791  *
792  * If a trigger actually intends this type of interaction, it
793  * can re-execute the DELETE and then return NULL to cancel
794  * the outer delete.
795  */
796  if (hufd.cmax != estate->es_output_cid)
797  ereport(ERROR,
798  (errcode(ERRCODE_TRIGGERED_DATA_CHANGE_VIOLATION),
799  errmsg("tuple to be updated was already modified by an operation triggered by the current command"),
800  errhint("Consider using an AFTER trigger instead of a BEFORE trigger to propagate changes to other rows.")));
801 
802  /* Else, already deleted by self; nothing to do */
803  return NULL;
804 
806  break;
807 
808  case HeapTupleUpdated:
810  ereport(ERROR,
811  (errcode(ERRCODE_T_R_SERIALIZATION_FAILURE),
812  errmsg("could not serialize access due to concurrent update")));
813  if (!ItemPointerEquals(tupleid, &hufd.ctid))
814  {
815  TupleTableSlot *epqslot;
816 
817  epqslot = EvalPlanQual(estate,
818  epqstate,
819  resultRelationDesc,
820  resultRelInfo->ri_RangeTableIndex,
822  &hufd.ctid,
823  hufd.xmax);
824  if (!TupIsNull(epqslot))
825  {
826  *tupleid = hufd.ctid;
827  goto ldelete;
828  }
829  }
830  /* tuple already deleted; nothing to do */
831  return NULL;
832 
833  default:
834  elog(ERROR, "unrecognized heap_delete status: %u", result);
835  return NULL;
836  }
837 
838  /*
839  * Note: Normally one would think that we have to delete index tuples
840  * associated with the heap tuple now...
841  *
842  * ... but in POSTGRES, we have no need to do this because VACUUM will
843  * take care of it later. We can't delete index tuples immediately
844  * anyway, since the tuple is still visible to other transactions.
845  */
846  }
847 
848  if (canSetTag)
849  (estate->es_processed)++;
850 
851  /* AFTER ROW DELETE Triggers */
852  ExecARDeleteTriggers(estate, resultRelInfo, tupleid, oldtuple,
853  mtstate->mt_transition_capture);
854 
855  /* Process RETURNING if present */
856  if (resultRelInfo->ri_projectReturning)
857  {
858  /*
859  * We have to put the target tuple into a slot, which means first we
860  * gotta fetch it. We can use the trigger tuple slot.
861  */
862  TupleTableSlot *rslot;
863  HeapTupleData deltuple;
864  Buffer delbuffer;
865 
866  if (resultRelInfo->ri_FdwRoutine)
867  {
868  /* FDW must have provided a slot containing the deleted row */
869  Assert(!TupIsNull(slot));
870  delbuffer = InvalidBuffer;
871  }
872  else
873  {
874  slot = estate->es_trig_tuple_slot;
875  if (oldtuple != NULL)
876  {
877  deltuple = *oldtuple;
878  delbuffer = InvalidBuffer;
879  }
880  else
881  {
882  deltuple.t_self = *tupleid;
883  if (!heap_fetch(resultRelationDesc, SnapshotAny,
884  &deltuple, &delbuffer, false, NULL))
885  elog(ERROR, "failed to fetch deleted tuple for DELETE RETURNING");
886  }
887 
888  if (slot->tts_tupleDescriptor != RelationGetDescr(resultRelationDesc))
889  ExecSetSlotDescriptor(slot, RelationGetDescr(resultRelationDesc));
890  ExecStoreTuple(&deltuple, slot, InvalidBuffer, false);
891  }
892 
893  rslot = ExecProcessReturning(resultRelInfo, slot, planSlot);
894 
895  /*
896  * Before releasing the target tuple again, make sure rslot has a
897  * local copy of any pass-by-reference values.
898  */
899  ExecMaterializeSlot(rslot);
900 
901  ExecClearTuple(slot);
902  if (BufferIsValid(delbuffer))
903  ReleaseBuffer(delbuffer);
904 
905  return rslot;
906  }
907 
908  return NULL;
909 }
ExecForeignDelete_function ExecForeignDelete
Definition: fdwapi.h:202
TupleTableSlot * ExecStoreTuple(HeapTuple tuple, TupleTableSlot *slot, Buffer buffer, bool shouldFree)
Definition: execTuples.c:320
Relation ri_RelationDesc
Definition: execnodes.h:354
bool tts_isempty
Definition: tuptable.h:116
bool ExecIRDeleteTriggers(EState *estate, ResultRelInfo *relinfo, HeapTuple trigtuple)
Definition: trigger.c:2604
int errhint(const char *fmt,...)
Definition: elog.c:987
CommandId es_output_cid
Definition: execnodes.h:438
TupleTableSlot * ExecStoreAllNullTuple(TupleTableSlot *slot)
Definition: execTuples.c:512
#define RelationGetDescr(relation)
Definition: rel.h:428
bool heap_fetch(Relation relation, Snapshot snapshot, HeapTuple tuple, Buffer *userbuf, bool keep_buf, Relation stats_relation)
Definition: heapam.c:1876
TupleTableSlot * EvalPlanQual(EState *estate, EPQState *epqstate, Relation relation, Index rti, int lockmode, ItemPointer tid, TransactionId priorXmax)
Definition: execMain.c:2479
TupleTableSlot * ExecClearTuple(TupleTableSlot *slot)
Definition: execTuples.c:439
#define IsolationUsesXactSnapshot()
Definition: xact.h:43
#define InvalidBuffer
Definition: buf.h:25
Snapshot es_crosscheck_snapshot
Definition: execnodes.h:430
int errcode(int sqlerrcode)
Definition: elog.c:575
void ReleaseBuffer(Buffer buffer)
Definition: bufmgr.c:3309
Index ri_RangeTableIndex
Definition: execnodes.h:351
void ExecARDeleteTriggers(EState *estate, ResultRelInfo *relinfo, ItemPointer tupleid, HeapTuple fdw_trigtuple, TransitionCaptureState *transition_capture)
Definition: trigger.c:2572
HTSU_Result heap_delete(Relation relation, ItemPointer tid, CommandId cid, Snapshot crosscheck, bool wait, HeapUpdateFailureData *hufd)
Definition: heapam.c:3028
#define ERROR
Definition: elog.h:43
ItemPointerData t_self
Definition: htup.h:65
struct TransitionCaptureState * mt_transition_capture
Definition: execnodes.h:985
CommandId cmax
Definition: heapam.h:72
HTSU_Result
Definition: snapshot.h:121
ProjectionInfo * ri_projectReturning
Definition: execnodes.h:399
#define TupIsNull(slot)
Definition: tuptable.h:138
struct FdwRoutine * ri_FdwRoutine
Definition: execnodes.h:378
Oid t_tableOid
Definition: htup.h:66
TupleTableSlot * es_trig_tuple_slot
Definition: execnodes.h:460
#define ereport(elevel, rest)
Definition: elog.h:122
TriggerDesc * ri_TrigDesc
Definition: execnodes.h:366
static TupleTableSlot * ExecProcessReturning(ResultRelInfo *resultRelInfo, TupleTableSlot *tupleSlot, TupleTableSlot *planSlot)
TransactionId xmax
Definition: heapam.h:71
TupleDesc tts_tupleDescriptor
Definition: tuptable.h:121
bool trig_delete_instead_row
Definition: reltrigger.h:67
void ExecSetSlotDescriptor(TupleTableSlot *slot, TupleDesc tupdesc)
Definition: execTuples.c:247
#define SnapshotAny
Definition: tqual.h:28
bool ExecBRDeleteTriggers(EState *estate, EPQState *epqstate, ResultRelInfo *relinfo, ItemPointer tupleid, HeapTuple fdw_trigtuple)
Definition: trigger.c:2503
#define Assert(condition)
Definition: c.h:664
uint64 es_processed
Definition: execnodes.h:477
#define BufferIsValid(bufnum)
Definition: bufmgr.h:114
HeapTuple ExecMaterializeSlot(TupleTableSlot *slot)
Definition: execTuples.c:725
bool ItemPointerEquals(ItemPointer pointer1, ItemPointer pointer2)
Definition: itemptr.c:29
int errmsg(const char *fmt,...)
Definition: elog.c:797
ItemPointerData ctid
Definition: heapam.h:70
#define elog
Definition: elog.h:219
int Buffer
Definition: buf.h:23
#define RelationGetRelid(relation)
Definition: rel.h:416
bool trig_delete_before_row
Definition: reltrigger.h:65
ResultRelInfo * es_result_relation_info
Definition: execnodes.h:443
void ExecEndModifyTable ( ModifyTableState node)

Definition at line 2344 of file nodeModifyTable.c.

References FdwRoutine::EndForeignModify, EvalPlanQualEnd(), ExecClearTuple(), ExecCloseIndices(), ExecDropSingleTupleTableSlot(), ExecEndNode(), ExecFreeExprContext(), heap_close, i, ModifyTableState::mt_epqstate, ModifyTableState::mt_nplans, ModifyTableState::mt_num_dispatch, ModifyTableState::mt_num_partitions, ModifyTableState::mt_partition_dispatch_info, ModifyTableState::mt_partition_tuple_slot, ModifyTableState::mt_partitions, ModifyTableState::mt_plans, NoLock, ModifyTableState::ps, PlanState::ps_ResultTupleSlot, PartitionDispatchData::reldesc, ModifyTableState::resultRelInfo, ResultRelInfo::ri_FdwRoutine, ResultRelInfo::ri_RelationDesc, ResultRelInfo::ri_usesFdwDirectModify, PlanState::state, and PartitionDispatchData::tupslot.

Referenced by ExecEndNode().

2345 {
2346  int i;
2347 
2348  /*
2349  * Allow any FDWs to shut down
2350  */
2351  for (i = 0; i < node->mt_nplans; i++)
2352  {
2353  ResultRelInfo *resultRelInfo = node->resultRelInfo + i;
2354 
2355  if (!resultRelInfo->ri_usesFdwDirectModify &&
2356  resultRelInfo->ri_FdwRoutine != NULL &&
2357  resultRelInfo->ri_FdwRoutine->EndForeignModify != NULL)
2358  resultRelInfo->ri_FdwRoutine->EndForeignModify(node->ps.state,
2359  resultRelInfo);
2360  }
2361 
2362  /*
2363  * Close all the partitioned tables, leaf partitions, and their indices
2364  *
2365  * Remember node->mt_partition_dispatch_info[0] corresponds to the root
2366  * partitioned table, which we must not try to close, because it is the
2367  * main target table of the query that will be closed by ExecEndPlan().
2368  * Also, tupslot is NULL for the root partitioned table.
2369  */
2370  for (i = 1; i < node->mt_num_dispatch; i++)
2371  {
2373 
2374  heap_close(pd->reldesc, NoLock);
2376  }
2377  for (i = 0; i < node->mt_num_partitions; i++)
2378  {
2379  ResultRelInfo *resultRelInfo = node->mt_partitions + i;
2380 
2381  ExecCloseIndices(resultRelInfo);
2382  heap_close(resultRelInfo->ri_RelationDesc, NoLock);
2383  }
2384 
2385  /* Release the standalone partition tuple descriptor, if any */
2386  if (node->mt_partition_tuple_slot)
2388 
2389  /*
2390  * Free the exprcontext
2391  */
2392  ExecFreeExprContext(&node->ps);
2393 
2394  /*
2395  * clean out the tuple table
2396  */
2398 
2399  /*
2400  * Terminate EPQ execution if active
2401  */
2402  EvalPlanQualEnd(&node->mt_epqstate);
2403 
2404  /*
2405  * shut down subplans
2406  */
2407  for (i = 0; i < node->mt_nplans; i++)
2408  ExecEndNode(node->mt_plans[i]);
2409 }
Relation ri_RelationDesc
Definition: execnodes.h:354
ResultRelInfo * mt_partitions
Definition: execnodes.h:981
void ExecEndNode(PlanState *node)
Definition: execProcnode.c:523
ResultRelInfo * resultRelInfo
Definition: execnodes.h:964
TupleTableSlot * ExecClearTuple(TupleTableSlot *slot)
Definition: execTuples.c:439
#define heap_close(r, l)
Definition: heapam.h:97
EState * state
Definition: execnodes.h:849
void ExecFreeExprContext(PlanState *planstate)
Definition: execUtils.c:521
void EvalPlanQualEnd(EPQState *epqstate)
Definition: execMain.c:3206
TupleTableSlot * ps_ResultTupleSlot
Definition: execnodes.h:880
PlanState ps
Definition: execnodes.h:957
bool ri_usesFdwDirectModify
Definition: execnodes.h:384
#define NoLock
Definition: lockdefs.h:34
void ExecDropSingleTupleTableSlot(TupleTableSlot *slot)
Definition: execTuples.c:216
EPQState mt_epqstate
Definition: execnodes.h:968
struct FdwRoutine * ri_FdwRoutine
Definition: execnodes.h:378
EndForeignModify_function EndForeignModify
Definition: fdwapi.h:203
PlanState ** mt_plans
Definition: execnodes.h:961
TupleTableSlot * tupslot
Definition: partition.h:66
TupleTableSlot * mt_partition_tuple_slot
Definition: execnodes.h:984
int i
struct PartitionDispatchData ** mt_partition_dispatch_info
Definition: execnodes.h:976
void ExecCloseIndices(ResultRelInfo *resultRelInfo)
Definition: execIndexing.c:224
ModifyTableState* ExecInitModifyTable ( ModifyTable node,
EState estate,
int  eflags 
)

Definition at line 1812 of file nodeModifyTable.c.

References ModifyTable::arbiterIndexes, Assert, AttributeNumberIsValid, FdwRoutine::BeginForeignModify, bms_is_member(), ModifyTable::canSetTag, ModifyTableState::canSetTag, castNode, CheckValidResultRel(), CMD_DELETE, CMD_INSERT, CMD_UPDATE, elog, ModifyTable::epqParam, ERROR, EState::es_auxmodifytables, EState::es_range_table, EState::es_result_relation_info, EState::es_result_relations, EState::es_root_result_relations, EState::es_trig_tuple_slot, EvalPlanQualInit(), EvalPlanQualSetPlan(), ModifyTable::exclRelTlist, EXEC_FLAG_BACKWARD, EXEC_FLAG_EXPLAIN_ONLY, EXEC_FLAG_MARK, ExecAssignExprContext(), ExecAssignResultType(), ExecBuildAuxRowMark(), ExecBuildProjectionInfo(), ExecCheckPlanOutput(), ExecFindJunkAttribute(), ExecFindRowMark(), ExecInitExtraTupleSlot(), ExecInitJunkFilter(), ExecInitNode(), ExecInitQual(), ExecInitResultTupleSlot(), ExecModifyTable(), ExecOpenIndices(), PlanState::ExecProcNode, ExecSetSlotDescriptor(), ExecSetupPartitionTupleRouting(), ExecSetupTransitionCaptureState(), ExecTypeFromTL(), ModifyTable::fdwDirectModifyPlans, ModifyTable::fdwPrivLists, ModifyTableState::fireBSTriggers, getrelid, heap_close, heap_open(), i, PlanRowMark::isParent, JunkFilter::jf_junkAttNo, lappend(), lcons(), lfirst, lfirst_node, linitial, linitial_int, list_length(), list_nth(), makeNode, map_partition_varattnos(), ModifyTableState::mt_arbiterindexes, ModifyTableState::mt_arowmarks, ModifyTableState::mt_conflproj, ModifyTableState::mt_done, ModifyTableState::mt_epqstate, ModifyTableState::mt_excludedtlist, ModifyTableState::mt_existing, ModifyTableState::mt_nplans, ModifyTableState::mt_num_dispatch, ModifyTableState::mt_num_partitions, ModifyTableState::mt_onconflict, ModifyTableState::mt_partition_dispatch_info, ModifyTableState::mt_partition_tupconv_maps, ModifyTableState::mt_partition_tuple_slot, ModifyTableState::mt_partitions, ModifyTableState::mt_plans, ModifyTableState::mt_whichplan, NIL, NoLock, ModifyTable::nominalRelation, ONCONFLICT_NONE, ONCONFLICT_UPDATE, ModifyTable::onConflictAction, ModifyTable::onConflictSet, ModifyTable::onConflictWhere, ModifyTable::operation, ModifyTableState::operation, palloc0(), ModifyTable::partitioned_rels, PlanState::plan, ModifyTable::plans, ModifyTableState::ps, PlanState::ps_ExprContext, PlanState::ps_ResultTupleSlot, WithCheckOption::qual, RelationData::rd_att, RelationData::rd_rel, RELKIND_FOREIGN_TABLE, RELKIND_MATVIEW, RELKIND_PARTITIONED_TABLE, RELKIND_RELATION, TargetEntry::resjunk, ModifyTable::resultRelIndex, ModifyTableState::resultRelInfo, ModifyTable::returningLists, ResultRelInfo::ri_FdwRoutine, ResultRelInfo::ri_IndexRelationDescs, ResultRelInfo::ri_junkFilter, ResultRelInfo::ri_onConflictSetProj, ResultRelInfo::ri_onConflictSetWhere, ResultRelInfo::ri_projectReturning, ResultRelInfo::ri_RelationDesc, ResultRelInfo::ri_usesFdwDirectModify, ResultRelInfo::ri_WithCheckOptionExprs, ResultRelInfo::ri_WithCheckOptions, ModifyTable::rootResultRelIndex, ModifyTableState::rootResultRelInfo, ModifyTable::rowMarks, PlanRowMark::rti, PlanState::state, Plan::targetlist, tupleDesc::tdhasoid, and ModifyTable::withCheckOptionLists.

Referenced by ExecInitNode().

1813 {
1814  ModifyTableState *mtstate;
1815  CmdType operation = node->operation;
1816  int nplans = list_length(node->plans);
1817  ResultRelInfo *saved_resultRelInfo;
1818  ResultRelInfo *resultRelInfo;
1819  TupleDesc tupDesc;
1820  Plan *subplan;
1821  ListCell *l;
1822  int i;
1823  Relation rel;
1824 
1825  /* check for unsupported flags */
1826  Assert(!(eflags & (EXEC_FLAG_BACKWARD | EXEC_FLAG_MARK)));
1827 
1828  /*
1829  * create state structure
1830  */
1831  mtstate = makeNode(ModifyTableState);
1832  mtstate->ps.plan = (Plan *) node;
1833  mtstate->ps.state = estate;
1834  mtstate->ps.ExecProcNode = ExecModifyTable;
1835 
1836  mtstate->operation = operation;
1837  mtstate->canSetTag = node->canSetTag;
1838  mtstate->mt_done = false;
1839 
1840  mtstate->mt_plans = (PlanState **) palloc0(sizeof(PlanState *) * nplans);
1841  mtstate->resultRelInfo = estate->es_result_relations + node->resultRelIndex;
1842 
1843  /* If modifying a partitioned table, initialize the root table info */
1844  if (node->rootResultRelIndex >= 0)
1845  mtstate->rootResultRelInfo = estate->es_root_result_relations +
1846  node->rootResultRelIndex;
1847 
1848  mtstate->mt_arowmarks = (List **) palloc0(sizeof(List *) * nplans);
1849  mtstate->mt_nplans = nplans;
1850  mtstate->mt_onconflict = node->onConflictAction;
1851  mtstate->mt_arbiterindexes = node->arbiterIndexes;
1852 
1853  /* set up epqstate with dummy subplan data for the moment */
1854  EvalPlanQualInit(&mtstate->mt_epqstate, estate, NULL, NIL, node->epqParam);
1855  mtstate->fireBSTriggers = true;
1856 
1857  /*
1858  * call ExecInitNode on each of the plans to be executed and save the
1859  * results into the array "mt_plans". This is also a convenient place to
1860  * verify that the proposed target relations are valid and open their
1861  * indexes for insertion of new index entries. Note we *must* set
1862  * estate->es_result_relation_info correctly while we initialize each
1863  * sub-plan; ExecContextForcesOids depends on that!
1864  */
1865  saved_resultRelInfo = estate->es_result_relation_info;
1866 
1867  resultRelInfo = mtstate->resultRelInfo;
1868  i = 0;
1869  foreach(l, node->plans)
1870  {
1871  subplan = (Plan *) lfirst(l);
1872 
1873  /* Initialize the usesFdwDirectModify flag */
1874  resultRelInfo->ri_usesFdwDirectModify = bms_is_member(i,
1875  node->fdwDirectModifyPlans);
1876 
1877  /*
1878  * Verify result relation is a valid target for the current operation
1879  */
1880  CheckValidResultRel(resultRelInfo, operation);
1881 
1882  /*
1883  * If there are indices on the result relation, open them and save
1884  * descriptors in the result relation info, so that we can add new
1885  * index entries for the tuples we add/update. We need not do this
1886  * for a DELETE, however, since deletion doesn't affect indexes. Also,
1887  * inside an EvalPlanQual operation, the indexes might be open
1888  * already, since we share the resultrel state with the original
1889  * query.
1890  */
1891  if (resultRelInfo->ri_RelationDesc->rd_rel->relhasindex &&
1892  operation != CMD_DELETE &&
1893  resultRelInfo->ri_IndexRelationDescs == NULL)
1894  ExecOpenIndices(resultRelInfo, mtstate->mt_onconflict != ONCONFLICT_NONE);
1895 
1896  /* Now init the plan for this result rel */
1897  estate->es_result_relation_info = resultRelInfo;
1898  mtstate->mt_plans[i] = ExecInitNode(subplan, estate, eflags);
1899 
1900  /* Also let FDWs init themselves for foreign-table result rels */
1901  if (!resultRelInfo->ri_usesFdwDirectModify &&
1902  resultRelInfo->ri_FdwRoutine != NULL &&
1903  resultRelInfo->ri_FdwRoutine->BeginForeignModify != NULL)
1904  {
1905  List *fdw_private = (List *) list_nth(node->fdwPrivLists, i);
1906 
1907  resultRelInfo->ri_FdwRoutine->BeginForeignModify(mtstate,
1908  resultRelInfo,
1909  fdw_private,
1910  i,
1911  eflags);
1912  }
1913 
1914  resultRelInfo++;
1915  i++;
1916  }
1917 
1918  estate->es_result_relation_info = saved_resultRelInfo;
1919 
1920  /* The root table RT index is at the head of the partitioned_rels list */
1921  if (node->partitioned_rels)
1922  {
1923  Index root_rti;
1924  Oid root_oid;
1925 
1926  root_rti = linitial_int(node->partitioned_rels);
1927  root_oid = getrelid(root_rti, estate->es_range_table);
1928  rel = heap_open(root_oid, NoLock); /* locked by InitPlan */
1929  }
1930  else
1931  rel = mtstate->resultRelInfo->ri_RelationDesc;
1932 
1933  /* Build state for INSERT tuple routing */
1934  if (operation == CMD_INSERT &&
1935  rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE)
1936  {
1937  PartitionDispatch *partition_dispatch_info;
1938  ResultRelInfo *partitions;
1939  TupleConversionMap **partition_tupconv_maps;
1940  TupleTableSlot *partition_tuple_slot;
1941  int num_parted,
1942  num_partitions;
1943 
1945  node->nominalRelation,
1946  estate,
1947  &partition_dispatch_info,
1948  &partitions,
1949  &partition_tupconv_maps,
1950  &partition_tuple_slot,
1951  &num_parted, &num_partitions);
1952  mtstate->mt_partition_dispatch_info = partition_dispatch_info;
1953  mtstate->mt_num_dispatch = num_parted;
1954  mtstate->mt_partitions = partitions;
1955  mtstate->mt_num_partitions = num_partitions;
1956  mtstate->mt_partition_tupconv_maps = partition_tupconv_maps;
1957  mtstate->mt_partition_tuple_slot = partition_tuple_slot;
1958  }
1959 
1960  /*
1961  * Build state for collecting transition tuples. This requires having a
1962  * valid trigger query context, so skip it in explain-only mode.
1963  */
1964  if (!(eflags & EXEC_FLAG_EXPLAIN_ONLY))
1965  ExecSetupTransitionCaptureState(mtstate, estate);
1966 
1967  /*
1968  * Initialize any WITH CHECK OPTION constraints if needed.
1969  */
1970  resultRelInfo = mtstate->resultRelInfo;
1971  i = 0;
1972  foreach(l, node->withCheckOptionLists)
1973  {
1974  List *wcoList = (List *) lfirst(l);
1975  List *wcoExprs = NIL;
1976  ListCell *ll;
1977 
1978  foreach(ll, wcoList)
1979  {
1980  WithCheckOption *wco = (WithCheckOption *) lfirst(ll);
1981  ExprState *wcoExpr = ExecInitQual((List *) wco->qual,
1982  mtstate->mt_plans[i]);
1983 
1984  wcoExprs = lappend(wcoExprs, wcoExpr);
1985  }
1986 
1987  resultRelInfo->ri_WithCheckOptions = wcoList;
1988  resultRelInfo->ri_WithCheckOptionExprs = wcoExprs;
1989  resultRelInfo++;
1990  i++;
1991  }
1992 
1993  /*
1994  * Build WITH CHECK OPTION constraints for each leaf partition rel. Note
1995  * that we didn't build the withCheckOptionList for each partition within
1996  * the planner, but simple translation of the varattnos for each partition
1997  * will suffice. This only occurs for the INSERT case; UPDATE/DELETE
1998  * cases are handled above.
1999  */
2000  if (node->withCheckOptionLists != NIL && mtstate->mt_num_partitions > 0)
2001  {
2002  List *wcoList;
2003  PlanState *plan;
2004 
2005  /*
2006  * In case of INSERT on partitioned tables, there is only one plan.
2007  * Likewise, there is only one WITH CHECK OPTIONS list, not one per
2008  * partition. We make a copy of the WCO qual for each partition; note
2009  * that, if there are SubPlans in there, they all end up attached to
2010  * the one parent Plan node.
2011  */
2012  Assert(operation == CMD_INSERT &&
2013  list_length(node->withCheckOptionLists) == 1 &&
2014  mtstate->mt_nplans == 1);
2015  wcoList = linitial(node->withCheckOptionLists);
2016  plan = mtstate->mt_plans[0];
2017  resultRelInfo = mtstate->mt_partitions;
2018  for (i = 0; i < mtstate->mt_num_partitions; i++)
2019  {
2020  Relation partrel = resultRelInfo->ri_RelationDesc;
2021  List *mapped_wcoList;
2022  List *wcoExprs = NIL;
2023  ListCell *ll;
2024 
2025  /* varno = node->nominalRelation */
2026  mapped_wcoList = map_partition_varattnos(wcoList,
2027  node->nominalRelation,
2028  partrel, rel, NULL);
2029  foreach(ll, mapped_wcoList)
2030  {
2032  ExprState *wcoExpr = ExecInitQual(castNode(List, wco->qual),
2033  plan);
2034 
2035  wcoExprs = lappend(wcoExprs, wcoExpr);
2036  }
2037 
2038  resultRelInfo->ri_WithCheckOptions = mapped_wcoList;
2039  resultRelInfo->ri_WithCheckOptionExprs = wcoExprs;
2040  resultRelInfo++;
2041  }
2042  }
2043 
2044  /*
2045  * Initialize RETURNING projections if needed.
2046  */
2047  if (node->returningLists)
2048  {
2049  TupleTableSlot *slot;
2050  ExprContext *econtext;
2051  List *returningList;
2052 
2053  /*
2054  * Initialize result tuple slot and assign its rowtype using the first
2055  * RETURNING list. We assume the rest will look the same.
2056  */
2057  tupDesc = ExecTypeFromTL((List *) linitial(node->returningLists),
2058  false);
2059 
2060  /* Set up a slot for the output of the RETURNING projection(s) */
2061  ExecInitResultTupleSlot(estate, &mtstate->ps);
2062  ExecAssignResultType(&mtstate->ps, tupDesc);
2063  slot = mtstate->ps.ps_ResultTupleSlot;
2064 
2065  /* Need an econtext too */
2066  if (mtstate->ps.ps_ExprContext == NULL)
2067  ExecAssignExprContext(estate, &mtstate->ps);
2068  econtext = mtstate->ps.ps_ExprContext;
2069 
2070  /*
2071  * Build a projection for each result rel.
2072  */
2073  resultRelInfo = mtstate->resultRelInfo;
2074  foreach(l, node->returningLists)
2075  {
2076  List *rlist = (List *) lfirst(l);
2077 
2078  resultRelInfo->ri_projectReturning =
2079  ExecBuildProjectionInfo(rlist, econtext, slot, &mtstate->ps,
2080  resultRelInfo->ri_RelationDesc->rd_att);
2081  resultRelInfo++;
2082  }
2083 
2084  /*
2085  * Build a projection for each leaf partition rel. Note that we
2086  * didn't build the returningList for each partition within the
2087  * planner, but simple translation of the varattnos for each partition
2088  * will suffice. This only occurs for the INSERT case; UPDATE/DELETE
2089  * are handled above.
2090  */
2091  resultRelInfo = mtstate->mt_partitions;
2092  returningList = linitial(node->returningLists);
2093  for (i = 0; i < mtstate->mt_num_partitions; i++)
2094  {
2095  Relation partrel = resultRelInfo->ri_RelationDesc;
2096  List *rlist;
2097 
2098  /* varno = node->nominalRelation */
2099  rlist = map_partition_varattnos(returningList,
2100  node->nominalRelation,
2101  partrel, rel, NULL);
2102  resultRelInfo->ri_projectReturning =
2103  ExecBuildProjectionInfo(rlist, econtext, slot, &mtstate->ps,
2104  resultRelInfo->ri_RelationDesc->rd_att);
2105  resultRelInfo++;
2106  }
2107  }
2108  else
2109  {
2110  /*
2111  * We still must construct a dummy result tuple type, because InitPlan
2112  * expects one (maybe should change that?).
2113  */
2114  tupDesc = ExecTypeFromTL(NIL, false);
2115  ExecInitResultTupleSlot(estate, &mtstate->ps);
2116  ExecAssignResultType(&mtstate->ps, tupDesc);
2117 
2118  mtstate->ps.ps_ExprContext = NULL;
2119  }
2120 
2121  /* Close the root partitioned rel if we opened it above. */
2122  if (rel != mtstate->resultRelInfo->ri_RelationDesc)
2123  heap_close(rel, NoLock);
2124 
2125  /*
2126  * If needed, Initialize target list, projection and qual for ON CONFLICT
2127  * DO UPDATE.
2128  */
2129  resultRelInfo = mtstate->resultRelInfo;
2130  if (node->onConflictAction == ONCONFLICT_UPDATE)
2131  {
2132  ExprContext *econtext;
2133  TupleDesc tupDesc;
2134 
2135  /* insert may only have one plan, inheritance is not expanded */
2136  Assert(nplans == 1);
2137 
2138  /* already exists if created by RETURNING processing above */
2139  if (mtstate->ps.ps_ExprContext == NULL)
2140  ExecAssignExprContext(estate, &mtstate->ps);
2141 
2142  econtext = mtstate->ps.ps_ExprContext;
2143 
2144  /* initialize slot for the existing tuple */
2145  mtstate->mt_existing = ExecInitExtraTupleSlot(mtstate->ps.state);
2147  resultRelInfo->ri_RelationDesc->rd_att);
2148 
2149  /* carried forward solely for the benefit of explain */
2150  mtstate->mt_excludedtlist = node->exclRelTlist;
2151 
2152  /* create target slot for UPDATE SET projection */
2153  tupDesc = ExecTypeFromTL((List *) node->onConflictSet,
2154  resultRelInfo->ri_RelationDesc->rd_rel->relhasoids);
2155  mtstate->mt_conflproj = ExecInitExtraTupleSlot(mtstate->ps.state);
2156  ExecSetSlotDescriptor(mtstate->mt_conflproj, tupDesc);
2157 
2158  /* build UPDATE SET projection state */
2159  resultRelInfo->ri_onConflictSetProj =
2160  ExecBuildProjectionInfo(node->onConflictSet, econtext,
2161  mtstate->mt_conflproj, &mtstate->ps,
2162  resultRelInfo->ri_RelationDesc->rd_att);
2163 
2164  /* build DO UPDATE WHERE clause expression */
2165  if (node->onConflictWhere)
2166  {
2167  ExprState *qualexpr;
2168 
2169  qualexpr = ExecInitQual((List *) node->onConflictWhere,
2170  &mtstate->ps);
2171 
2172  resultRelInfo->ri_onConflictSetWhere = qualexpr;
2173  }
2174  }
2175 
2176  /*
2177  * If we have any secondary relations in an UPDATE or DELETE, they need to
2178  * be treated like non-locked relations in SELECT FOR UPDATE, ie, the
2179  * EvalPlanQual mechanism needs to be told about them. Locate the
2180  * relevant ExecRowMarks.
2181  */
2182  foreach(l, node->rowMarks)
2183  {
2185  ExecRowMark *erm;
2186 
2187  /* ignore "parent" rowmarks; they are irrelevant at runtime */
2188  if (rc->isParent)
2189  continue;
2190 
2191  /* find ExecRowMark (same for all subplans) */
2192  erm = ExecFindRowMark(estate, rc->rti, false);
2193 
2194  /* build ExecAuxRowMark for each subplan */
2195  for (i = 0; i < nplans; i++)
2196  {
2197  ExecAuxRowMark *aerm;
2198 
2199  subplan = mtstate->mt_plans[i]->plan;
2200  aerm = ExecBuildAuxRowMark(erm, subplan->targetlist);
2201  mtstate->mt_arowmarks[i] = lappend(mtstate->mt_arowmarks[i], aerm);
2202  }
2203  }
2204 
2205  /* select first subplan */
2206  mtstate->mt_whichplan = 0;
2207  subplan = (Plan *) linitial(node->plans);
2208  EvalPlanQualSetPlan(&mtstate->mt_epqstate, subplan,
2209  mtstate->mt_arowmarks[0]);
2210 
2211  /*
2212  * Initialize the junk filter(s) if needed. INSERT queries need a filter
2213  * if there are any junk attrs in the tlist. UPDATE and DELETE always
2214  * need a filter, since there's always at least one junk attribute present
2215  * --- no need to look first. Typically, this will be a 'ctid' or
2216  * 'wholerow' attribute, but in the case of a foreign data wrapper it
2217  * might be a set of junk attributes sufficient to identify the remote
2218  * row.
2219  *
2220  * If there are multiple result relations, each one needs its own junk
2221  * filter. Note multiple rels are only possible for UPDATE/DELETE, so we
2222  * can't be fooled by some needing a filter and some not.
2223  *
2224  * This section of code is also a convenient place to verify that the
2225  * output of an INSERT or UPDATE matches the target table(s).
2226  */
2227  {
2228  bool junk_filter_needed = false;
2229 
2230  switch (operation)
2231  {
2232  case CMD_INSERT:
2233  foreach(l, subplan->targetlist)
2234  {
2235  TargetEntry *tle = (TargetEntry *) lfirst(l);
2236 
2237  if (tle->resjunk)
2238  {
2239  junk_filter_needed = true;
2240  break;
2241  }
2242  }
2243  break;
2244  case CMD_UPDATE:
2245  case CMD_DELETE:
2246  junk_filter_needed = true;
2247  break;
2248  default:
2249  elog(ERROR, "unknown operation");
2250  break;
2251  }
2252 
2253  if (junk_filter_needed)
2254  {
2255  resultRelInfo = mtstate->resultRelInfo;
2256  for (i = 0; i < nplans; i++)
2257  {
2258  JunkFilter *j;
2259 
2260  subplan = mtstate->mt_plans[i]->plan;
2261  if (operation == CMD_INSERT || operation == CMD_UPDATE)
2262  ExecCheckPlanOutput(resultRelInfo->ri_RelationDesc,
2263  subplan->targetlist);
2264 
2265  j = ExecInitJunkFilter(subplan->targetlist,
2266  resultRelInfo->ri_RelationDesc->rd_att->tdhasoid,
2267  ExecInitExtraTupleSlot(estate));
2268 
2269  if (operation == CMD_UPDATE || operation == CMD_DELETE)
2270  {
2271  /* For UPDATE/DELETE, find the appropriate junk attr now */
2272  char relkind;
2273 
2274  relkind = resultRelInfo->ri_RelationDesc->rd_rel->relkind;
2275  if (relkind == RELKIND_RELATION ||
2276  relkind == RELKIND_MATVIEW ||
2277  relkind == RELKIND_PARTITIONED_TABLE)
2278  {
2279  j->jf_junkAttNo = ExecFindJunkAttribute(j, "ctid");
2281  elog(ERROR, "could not find junk ctid column");
2282  }
2283  else if (relkind == RELKIND_FOREIGN_TABLE)
2284  {
2285  /*
2286  * When there is a row-level trigger, there should be
2287  * a wholerow attribute.
2288  */
2289  j->jf_junkAttNo = ExecFindJunkAttribute(j, "wholerow");
2290  }
2291  else
2292  {
2293  j->jf_junkAttNo = ExecFindJunkAttribute(j, "wholerow");
2295  elog(ERROR, "could not find junk wholerow column");
2296  }
2297  }
2298 
2299  resultRelInfo->ri_junkFilter = j;
2300  resultRelInfo++;
2301  }
2302  }
2303  else
2304  {
2305  if (operation == CMD_INSERT)
2307  subplan->targetlist);
2308  }
2309  }
2310 
2311  /*
2312  * Set up a tuple table slot for use for trigger output tuples. In a plan
2313  * containing multiple ModifyTable nodes, all can share one such slot, so
2314  * we keep it in the estate.
2315  */
2316  if (estate->es_trig_tuple_slot == NULL)
2317  estate->es_trig_tuple_slot = ExecInitExtraTupleSlot(estate);
2318 
2319  /*
2320  * Lastly, if this is not the primary (canSetTag) ModifyTable node, add it
2321  * to estate->es_auxmodifytables so that it will be run to completion by
2322  * ExecPostprocessPlan. (It'd actually work fine to add the primary
2323  * ModifyTable node too, but there's no need.) Note the use of lcons not
2324  * lappend: we need later-initialized ModifyTable nodes to be shut down
2325  * before earlier ones. This ensures that we don't throw away RETURNING
2326  * rows that need to be seen by a later CTE subplan.
2327  */
2328  if (!mtstate->canSetTag)
2329  estate->es_auxmodifytables = lcons(mtstate,
2330  estate->es_auxmodifytables);
2331 
2332  return mtstate;
2333 }
AttrNumber jf_junkAttNo
Definition: execnodes.h:336
#define NIL
Definition: pg_list.h:69
JunkFilter * ri_junkFilter
Definition: execnodes.h:396
List * arbiterIndexes
Definition: plannodes.h:233
Relation ri_RelationDesc
Definition: execnodes.h:354
Bitmapset * fdwDirectModifyPlans
Definition: plannodes.h:229
ExprState * ri_onConflictSetWhere
Definition: execnodes.h:405
TupleTableSlot * ExecInitExtraTupleSlot(EState *estate)
Definition: execTuples.c:852
Index nominalRelation
Definition: plannodes.h:219
bool tdhasoid
Definition: tupdesc.h:76
ProjectionInfo * ri_onConflictSetProj
Definition: execnodes.h:402
ResultRelInfo * mt_partitions
Definition: execnodes.h:981
List * withCheckOptionLists
Definition: plannodes.h:226
#define castNode(_type_, nodeptr)
Definition: nodes.h:578
int resultRelIndex
Definition: plannodes.h:223
ResultRelInfo * resultRelInfo
Definition: execnodes.h:964
AttrNumber ExecFindJunkAttribute(JunkFilter *junkfilter, const char *attrName)
Definition: execJunk.c:209
ExprContext * ps_ExprContext
Definition: execnodes.h:881
TupleTableSlot * mt_conflproj
Definition: execnodes.h:975
#define RELKIND_MATVIEW
Definition: pg_class.h:165
bool canSetTag
Definition: plannodes.h:218
CmdType operation
Definition: execnodes.h:958
ResultRelInfo * rootResultRelInfo
Definition: execnodes.h:965
void EvalPlanQualSetPlan(EPQState *epqstate, Plan *subplan, List *auxrowmarks)
Definition: execMain.c:2814
#define heap_close(r, l)
Definition: heapam.h:97
EState * state
Definition: execnodes.h:849
List * es_range_table
Definition: execnodes.h:431
Form_pg_class rd_rel
Definition: rel.h:114
unsigned int Oid
Definition: postgres_ext.h:31
List * plans
Definition: plannodes.h:225
void ExecAssignResultType(PlanState *planstate, TupleDesc tupDesc)
Definition: execUtils.c:433
ExprState * ExecInitQual(List *qual, PlanState *parent)
Definition: execExpr.c:160
List * map_partition_varattnos(List *expr, int target_varno, Relation partrel, Relation parent, bool *found_whole_row)
Definition: partition.c:1121
List * onConflictSet
Definition: plannodes.h:234
int rootResultRelIndex
Definition: plannodes.h:224
void ExecOpenIndices(ResultRelInfo *resultRelInfo, bool speculative)
Definition: execIndexing.c:149
TupleTableSlot * mt_existing
Definition: execnodes.h:973
List * ri_WithCheckOptionExprs
Definition: execnodes.h:390
#define linitial_int(l)
Definition: pg_list.h:112
OnConflictAction mt_onconflict
Definition: execnodes.h:970
TupleTableSlot * ps_ResultTupleSlot
Definition: execnodes.h:880
List * rowMarks
Definition: plannodes.h:230
bool resjunk
Definition: primnodes.h:1375
#define linitial(l)
Definition: pg_list.h:111
#define ERROR
Definition: elog.h:43
PlanState ps
Definition: execnodes.h:957
void ExecInitResultTupleSlot(EState *estate, PlanState *planstate)
Definition: execTuples.c:832
bool ri_usesFdwDirectModify
Definition: execnodes.h:384
static void ExecSetupTransitionCaptureState(ModifyTableState *mtstate, EState *estate)
void CheckValidResultRel(ResultRelInfo *resultRelInfo, CmdType operation)
Definition: execMain.c:1100
#define EXEC_FLAG_BACKWARD
Definition: executor.h:60
#define lfirst_node(type, lc)
Definition: pg_list.h:109
void * list_nth(const List *list, int n)
Definition: list.c:410
#define NoLock
Definition: lockdefs.h:34
ResultRelInfo * es_result_relations
Definition: execnodes.h:441
JunkFilter * ExecInitJunkFilter(List *targetList, bool hasoid, TupleTableSlot *slot)
Definition: execJunk.c:61
List * fdwPrivLists
Definition: plannodes.h:228
EPQState mt_epqstate
Definition: execnodes.h:968
ProjectionInfo * ri_projectReturning
Definition: execnodes.h:399
struct FdwRoutine * ri_FdwRoutine
Definition: execnodes.h:378
#define RELKIND_FOREIGN_TABLE
Definition: pg_class.h:167
List * partitioned_rels
Definition: plannodes.h:221
TupleTableSlot * es_trig_tuple_slot
Definition: execnodes.h:460
TupleDesc ExecTypeFromTL(List *targetList, bool hasoid)
Definition: execTuples.c:888
List * lappend(List *list, void *datum)
Definition: list.c:128
PlanState ** mt_plans
Definition: execnodes.h:961
#define AttributeNumberIsValid(attributeNumber)
Definition: attnum.h:34
static TupleTableSlot * ExecModifyTable(PlanState *pstate)
#define RELKIND_PARTITIONED_TABLE
Definition: pg_class.h:168
void * palloc0(Size size)
Definition: mcxt.c:877
List * es_auxmodifytables
Definition: execnodes.h:488
ExecProcNodeMtd ExecProcNode
Definition: execnodes.h:853
void ExecSetSlotDescriptor(TupleTableSlot *slot, TupleDesc tupdesc)
Definition: execTuples.c:247
List * ri_WithCheckOptions
Definition: execnodes.h:387
TupleTableSlot * mt_partition_tuple_slot
Definition: execnodes.h:984
Relation heap_open(Oid relationId, LOCKMODE lockmode)
Definition: heapam.c:1290
unsigned int Index
Definition: c.h:359
TupleDesc rd_att
Definition: rel.h:115
void EvalPlanQualInit(EPQState *epqstate, EState *estate, Plan *subplan, List *auxrowmarks, int epqParam)
Definition: execMain.c:2795
Plan * plan
Definition: execnodes.h:847
List * lcons(void *datum, List *list)
Definition: list.c:259
#define makeNode(_type_)
Definition: nodes.h:557
static void ExecCheckPlanOutput(Relation resultRel, List *targetList)
#define Assert(condition)
Definition: c.h:664
#define lfirst(lc)
Definition: pg_list.h:106
#define EXEC_FLAG_MARK
Definition: executor.h:61
OnConflictAction onConflictAction
Definition: plannodes.h:232
void ExecAssignExprContext(EState *estate, PlanState *planstate)
Definition: execUtils.c:423
static int list_length(const List *l)
Definition: pg_list.h:89
List * targetlist
Definition: plannodes.h:144
List * mt_arbiterindexes
Definition: execnodes.h:971
List * mt_excludedtlist
Definition: execnodes.h:974
ProjectionInfo * ExecBuildProjectionInfo(List *targetList, ExprContext *econtext, TupleTableSlot *slot, PlanState *parent, TupleDesc inputDesc)
Definition: execExpr.c:301
#define getrelid(rangeindex, rangetable)
Definition: parsetree.h:41
CmdType operation
Definition: plannodes.h:217
ResultRelInfo * es_root_result_relations
Definition: execnodes.h:452
int i
struct PartitionDispatchData ** mt_partition_dispatch_info
Definition: execnodes.h:976
List * returningLists
Definition: plannodes.h:227
bool isParent
Definition: plannodes.h:1020
TupleConversionMap ** mt_partition_tupconv_maps
Definition: execnodes.h:982
void ExecSetupPartitionTupleRouting(Relation rel, Index resultRTindex, EState *estate, PartitionDispatch **pd, ResultRelInfo **partitions, TupleConversionMap ***tup_conv_maps, TupleTableSlot **partition_tuple_slot, int *num_parted, int *num_partitions)
Definition: execMain.c:3268
#define elog
Definition: elog.h:219
BeginForeignModify_function BeginForeignModify
Definition: fdwapi.h:199
#define RELKIND_RELATION
Definition: pg_class.h:160
PlanState * ExecInitNode(Plan *node, EState *estate, int eflags)
Definition: execProcnode.c:139
Definition: pg_list.h:45
bool bms_is_member(int x, const Bitmapset *a)
Definition: bitmapset.c:420
#define EXEC_FLAG_EXPLAIN_ONLY
Definition: executor.h:58
CmdType
Definition: nodes.h:649
RelationPtr ri_IndexRelationDescs
Definition: execnodes.h:360
ExecAuxRowMark * ExecBuildAuxRowMark(ExecRowMark *erm, List *targetlist)
Definition: execMain.c:2408
List * exclRelTlist
Definition: plannodes.h:237
List ** mt_arowmarks
Definition: execnodes.h:967
int epqParam
Definition: plannodes.h:231
Node * onConflictWhere
Definition: plannodes.h:235
ExecRowMark * ExecFindRowMark(EState *estate, Index rti, bool missing_ok)
Definition: execMain.c:2384
ResultRelInfo * es_result_relation_info
Definition: execnodes.h:443
static TupleTableSlot* ExecInsert ( ModifyTableState mtstate,
TupleTableSlot slot,
TupleTableSlot planSlot,
List arbiterIndexes,
OnConflictAction  onconflict,
EState estate,
bool  canSetTag 
)
static

Definition at line 253 of file nodeModifyTable.c.

References Assert, tupleDesc::constr, do_convert_tuple(), ereport, errcode(), errmsg(), ERROR, EState::es_lastoid, EState::es_output_cid, EState::es_processed, EState::es_result_relation_info, ExecARInsertTriggers(), ExecBRInsertTriggers(), ExecCheckIndexConstraints(), ExecCheckTIDVisible(), ExecConstraints(), ExecFindPartition(), FdwRoutine::ExecForeignInsert, ExecInsertIndexTuples(), ExecIRInsertTriggers(), ExecMaterializeSlot(), ExecOnConflictUpdate(), ExecProcessReturning(), ExecSetSlotDescriptor(), ExecStoreTuple(), ExecWithCheckOptions(), GetCurrentTransactionId(), heap_abort_speculative(), heap_finish_speculative(), heap_insert(), HEAP_INSERT_SPECULATIVE, HeapTupleHeaderSetSpeculativeToken, HeapTupleSetOid, InstrCountFiltered2, InvalidBuffer, InvalidOid, list_free(), ModifyTableState::mt_oc_transition_capture, ModifyTableState::mt_partition_dispatch_info, ModifyTableState::mt_partition_tupconv_maps, ModifyTableState::mt_partition_tuple_slot, ModifyTableState::mt_partitions, ModifyTableState::mt_transition_capture, ModifyTableState::mt_transition_tupconv_maps, NIL, ONCONFLICT_NONE, ONCONFLICT_NOTHING, ONCONFLICT_UPDATE, ModifyTableState::ps, RelationData::rd_att, RelationData::rd_rel, RelationGetDescr, RelationGetRelid, ResultRelInfo::ri_FdwRoutine, ResultRelInfo::ri_NumIndices, ResultRelInfo::ri_PartitionCheck, ResultRelInfo::ri_projectReturning, ResultRelInfo::ri_RelationDesc, ResultRelInfo::ri_TrigDesc, ResultRelInfo::ri_WithCheckOptions, setLastTid(), SpeculativeInsertionLockAcquire(), SpeculativeInsertionLockRelease(), HeapTupleData::t_data, HeapTupleData::t_self, HeapTupleData::t_tableOid, TransitionCaptureState::tcs_map, TransitionCaptureState::tcs_original_insert_tuple, TriggerDesc::trig_insert_before_row, TriggerDesc::trig_insert_instead_row, WCO_RLS_INSERT_CHECK, and WCO_VIEW_CHECK.

Referenced by ExecModifyTable().

260 {
261  HeapTuple tuple;
262  ResultRelInfo *resultRelInfo;
263  ResultRelInfo *saved_resultRelInfo = NULL;
264  Relation resultRelationDesc;
265  Oid newId;
266  List *recheckIndexes = NIL;
267  TupleTableSlot *result = NULL;
268 
269  /*
270  * get the heap tuple out of the tuple table slot, making sure we have a
271  * writable copy
272  */
273  tuple = ExecMaterializeSlot(slot);
274 
275  /*
276  * get information on the (current) result relation
277  */
278  resultRelInfo = estate->es_result_relation_info;
279 
280  /* Determine the partition to heap_insert the tuple into */
281  if (mtstate->mt_partition_dispatch_info)
282  {
283  int leaf_part_index;
284  TupleConversionMap *map;
285 
286  /*
287  * Away we go ... If we end up not finding a partition after all,
288  * ExecFindPartition() does not return and errors out instead.
289  * Otherwise, the returned value is to be used as an index into arrays
290  * mt_partitions[] and mt_partition_tupconv_maps[] that will get us
291  * the ResultRelInfo and TupleConversionMap for the partition,
292  * respectively.
293  */
294  leaf_part_index = ExecFindPartition(resultRelInfo,
296  slot,
297  estate);
298  Assert(leaf_part_index >= 0 &&
299  leaf_part_index < mtstate->mt_num_partitions);
300 
301  /*
302  * Save the old ResultRelInfo and switch to the one corresponding to
303  * the selected partition.
304  */
305  saved_resultRelInfo = resultRelInfo;
306  resultRelInfo = mtstate->mt_partitions + leaf_part_index;
307 
308  /* We do not yet have a way to insert into a foreign partition */
309  if (resultRelInfo->ri_FdwRoutine)
310  ereport(ERROR,
311  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
312  errmsg("cannot route inserted tuples to a foreign table")));
313 
314  /* For ExecInsertIndexTuples() to work on the partition's indexes */
315  estate->es_result_relation_info = resultRelInfo;
316 
317  /*
318  * If we're capturing transition tuples, we might need to convert from
319  * the partition rowtype to parent rowtype.
320  */
321  if (mtstate->mt_transition_capture != NULL)
322  {
323  if (resultRelInfo->ri_TrigDesc &&
324  (resultRelInfo->ri_TrigDesc->trig_insert_before_row ||
325  resultRelInfo->ri_TrigDesc->trig_insert_instead_row))
326  {
327  /*
328  * If there are any BEFORE or INSTEAD triggers on the
329  * partition, we'll have to be ready to convert their result
330  * back to tuplestore format.
331  */
333  mtstate->mt_transition_capture->tcs_map =
334  mtstate->mt_transition_tupconv_maps[leaf_part_index];
335  }
336  else
337  {
338  /*
339  * Otherwise, just remember the original unconverted tuple, to
340  * avoid a needless round trip conversion.
341  */
343  mtstate->mt_transition_capture->tcs_map = NULL;
344  }
345  }
346  if (mtstate->mt_oc_transition_capture != NULL)
348  mtstate->mt_transition_tupconv_maps[leaf_part_index];
349 
350  /*
351  * We might need to convert from the parent rowtype to the partition
352  * rowtype.
353  */
354  map = mtstate->mt_partition_tupconv_maps[leaf_part_index];
355  if (map)
356  {
357  Relation partrel = resultRelInfo->ri_RelationDesc;
358 
359  tuple = do_convert_tuple(tuple, map);
360 
361  /*
362  * We must use the partition's tuple descriptor from this point
363  * on, until we're finished dealing with the partition. Use the
364  * dedicated slot for that.
365  */
366  slot = mtstate->mt_partition_tuple_slot;
367  Assert(slot != NULL);
368  ExecSetSlotDescriptor(slot, RelationGetDescr(partrel));
369  ExecStoreTuple(tuple, slot, InvalidBuffer, true);
370  }
371  }
372 
373  resultRelationDesc = resultRelInfo->ri_RelationDesc;
374 
375  /*
376  * If the result relation has OIDs, force the tuple's OID to zero so that
377  * heap_insert will assign a fresh OID. Usually the OID already will be
378  * zero at this point, but there are corner cases where the plan tree can
379  * return a tuple extracted literally from some table with the same
380  * rowtype.
381  *
382  * XXX if we ever wanted to allow users to assign their own OIDs to new
383  * rows, this'd be the place to do it. For the moment, we make a point of
384  * doing this before calling triggers, so that a user-supplied trigger
385  * could hack the OID if desired.
386  */
387  if (resultRelationDesc->rd_rel->relhasoids)
388  HeapTupleSetOid(tuple, InvalidOid);
389 
390  /*
391  * BEFORE ROW INSERT Triggers.
392  *
393  * Note: We fire BEFORE ROW TRIGGERS for every attempted insertion in an
394  * INSERT ... ON CONFLICT statement. We cannot check for constraint
395  * violations before firing these triggers, because they can change the
396  * values to insert. Also, they can run arbitrary user-defined code with
397  * side-effects that we can't cancel by just not inserting the tuple.
398  */
399  if (resultRelInfo->ri_TrigDesc &&
400  resultRelInfo->ri_TrigDesc->trig_insert_before_row)
401  {
402  slot = ExecBRInsertTriggers(estate, resultRelInfo, slot);
403 
404  if (slot == NULL) /* "do nothing" */
405  return NULL;
406 
407  /* trigger might have changed tuple */
408  tuple = ExecMaterializeSlot(slot);
409  }
410 
411  /* INSTEAD OF ROW INSERT Triggers */
412  if (resultRelInfo->ri_TrigDesc &&
413  resultRelInfo->ri_TrigDesc->trig_insert_instead_row)
414  {
415  slot = ExecIRInsertTriggers(estate, resultRelInfo, slot);
416 
417  if (slot == NULL) /* "do nothing" */
418  return NULL;
419 
420  /* trigger might have changed tuple */
421  tuple = ExecMaterializeSlot(slot);
422 
423  newId = InvalidOid;
424  }
425  else if (resultRelInfo->ri_FdwRoutine)
426  {
427  /*
428  * insert into foreign table: let the FDW do it
429  */
430  slot = resultRelInfo->ri_FdwRoutine->ExecForeignInsert(estate,
431  resultRelInfo,
432  slot,
433  planSlot);
434 
435  if (slot == NULL) /* "do nothing" */
436  return NULL;
437 
438  /* FDW might have changed tuple */
439  tuple = ExecMaterializeSlot(slot);
440 
441  /*
442  * AFTER ROW Triggers or RETURNING expressions might reference the
443  * tableoid column, so initialize t_tableOid before evaluating them.
444  */
445  tuple->t_tableOid = RelationGetRelid(resultRelationDesc);
446 
447  newId = InvalidOid;
448  }
449  else
450  {
451  /*
452  * We always check the partition constraint, including when the tuple
453  * got here via tuple-routing. However we don't need to in the latter
454  * case if no BR trigger is defined on the partition. Note that a BR
455  * trigger might modify the tuple such that the partition constraint
456  * is no longer satisfied, so we need to check in that case.
457  */
458  bool check_partition_constr =
459  (resultRelInfo->ri_PartitionCheck != NIL);
460 
461  /*
462  * Constraints might reference the tableoid column, so initialize
463  * t_tableOid before evaluating them.
464  */
465  tuple->t_tableOid = RelationGetRelid(resultRelationDesc);
466 
467  /*
468  * Check any RLS INSERT WITH CHECK policies
469  *
470  * ExecWithCheckOptions() will skip any WCOs which are not of the kind
471  * we are looking for at this point.
472  */
473  if (resultRelInfo->ri_WithCheckOptions != NIL)
475  resultRelInfo, slot, estate);
476 
477  /*
478  * No need though if the tuple has been routed, and a BR trigger
479  * doesn't exist.
480  */
481  if (saved_resultRelInfo != NULL &&
482  !(resultRelInfo->ri_TrigDesc &&
483  resultRelInfo->ri_TrigDesc->trig_insert_before_row))
484  check_partition_constr = false;
485 
486  /* Check the constraints of the tuple */
487  if (resultRelationDesc->rd_att->constr || check_partition_constr)
488  ExecConstraints(resultRelInfo, slot, estate);
489 
490  if (onconflict != ONCONFLICT_NONE && resultRelInfo->ri_NumIndices > 0)
491  {
492  /* Perform a speculative insertion. */
493  uint32 specToken;
494  ItemPointerData conflictTid;
495  bool specConflict;
496 
497  /*
498  * Do a non-conclusive check for conflicts first.
499  *
500  * We're not holding any locks yet, so this doesn't guarantee that
501  * the later insert won't conflict. But it avoids leaving behind
502  * a lot of canceled speculative insertions, if you run a lot of
503  * INSERT ON CONFLICT statements that do conflict.
504  *
505  * We loop back here if we find a conflict below, either during
506  * the pre-check, or when we re-check after inserting the tuple
507  * speculatively.
508  */
509  vlock:
510  specConflict = false;
511  if (!ExecCheckIndexConstraints(slot, estate, &conflictTid,
512  arbiterIndexes))
513  {
514  /* committed conflict tuple found */
515  if (onconflict == ONCONFLICT_UPDATE)
516  {
517  /*
518  * In case of ON CONFLICT DO UPDATE, execute the UPDATE
519  * part. Be prepared to retry if the UPDATE fails because
520  * of another concurrent UPDATE/DELETE to the conflict
521  * tuple.
522  */
523  TupleTableSlot *returning = NULL;
524 
525  if (ExecOnConflictUpdate(mtstate, resultRelInfo,
526  &conflictTid, planSlot, slot,
527  estate, canSetTag, &returning))
528  {
529  InstrCountFiltered2(&mtstate->ps, 1);
530  return returning;
531  }
532  else
533  goto vlock;
534  }
535  else
536  {
537  /*
538  * In case of ON CONFLICT DO NOTHING, do nothing. However,
539  * verify that the tuple is visible to the executor's MVCC
540  * snapshot at higher isolation levels.
541  */
542  Assert(onconflict == ONCONFLICT_NOTHING);
543  ExecCheckTIDVisible(estate, resultRelInfo, &conflictTid);
544  InstrCountFiltered2(&mtstate->ps, 1);
545  return NULL;
546  }
547  }
548 
549  /*
550  * Before we start insertion proper, acquire our "speculative
551  * insertion lock". Others can use that to wait for us to decide
552  * if we're going to go ahead with the insertion, instead of
553  * waiting for the whole transaction to complete.
554  */
556  HeapTupleHeaderSetSpeculativeToken(tuple->t_data, specToken);
557 
558  /* insert the tuple, with the speculative token */
559  newId = heap_insert(resultRelationDesc, tuple,
560  estate->es_output_cid,
562  NULL);
563 
564  /* insert index entries for tuple */
565  recheckIndexes = ExecInsertIndexTuples(slot, &(tuple->t_self),
566  estate, true, &specConflict,
567  arbiterIndexes);
568 
569  /* adjust the tuple's state accordingly */
570  if (!specConflict)
571  heap_finish_speculative(resultRelationDesc, tuple);
572  else
573  heap_abort_speculative(resultRelationDesc, tuple);
574 
575  /*
576  * Wake up anyone waiting for our decision. They will re-check
577  * the tuple, see that it's no longer speculative, and wait on our
578  * XID as if this was a regularly inserted tuple all along. Or if
579  * we killed the tuple, they will see it's dead, and proceed as if
580  * the tuple never existed.
581  */
583 
584  /*
585  * If there was a conflict, start from the beginning. We'll do
586  * the pre-check again, which will now find the conflicting tuple
587  * (unless it aborts before we get there).
588  */
589  if (specConflict)
590  {
591  list_free(recheckIndexes);
592  goto vlock;
593  }
594 
595  /* Since there was no insertion conflict, we're done */
596  }
597  else
598  {
599  /*
600  * insert the tuple normally.
601  *
602  * Note: heap_insert returns the tid (location) of the new tuple
603  * in the t_self field.
604  */
605  newId = heap_insert(resultRelationDesc, tuple,
606  estate->es_output_cid,
607  0, NULL);
608 
609  /* insert index entries for tuple */
610  if (resultRelInfo->ri_NumIndices > 0)
611  recheckIndexes = ExecInsertIndexTuples(slot, &(tuple->t_self),
612  estate, false, NULL,
613  arbiterIndexes);
614  }
615  }
616 
617  if (canSetTag)
618  {
619  (estate->es_processed)++;
620  estate->es_lastoid = newId;
621  setLastTid(&(tuple->t_self));
622  }
623 
624  /* AFTER ROW INSERT Triggers */
625  ExecARInsertTriggers(estate, resultRelInfo, tuple, recheckIndexes,
626  mtstate->mt_transition_capture);
627 
628  list_free(recheckIndexes);
629 
630  /*
631  * Check any WITH CHECK OPTION constraints from parent views. We are
632  * required to do this after testing all constraints and uniqueness
633  * violations per the SQL spec, so we do it after actually inserting the
634  * record into the heap and all indexes.
635  *
636  * ExecWithCheckOptions will elog(ERROR) if a violation is found, so the
637  * tuple will never be seen, if it violates the WITH CHECK OPTION.
638  *
639  * ExecWithCheckOptions() will skip any WCOs which are not of the kind we
640  * are looking for at this point.
641  */
642  if (resultRelInfo->ri_WithCheckOptions != NIL)
643  ExecWithCheckOptions(WCO_VIEW_CHECK, resultRelInfo, slot, estate);
644 
645  /* Process RETURNING if present */
646  if (resultRelInfo->ri_projectReturning)
647  result = ExecProcessReturning(resultRelInfo, slot, planSlot);
648 
649  if (saved_resultRelInfo)
650  estate->es_result_relation_info = saved_resultRelInfo;
651 
652  return result;
653 }
int ri_NumIndices
Definition: execnodes.h:357
#define NIL
Definition: pg_list.h:69
TupleTableSlot * ExecStoreTuple(HeapTuple tuple, TupleTableSlot *slot, Buffer buffer, bool shouldFree)
Definition: execTuples.c:320
struct TransitionCaptureState * mt_oc_transition_capture
Definition: execnodes.h:987
Relation ri_RelationDesc
Definition: execnodes.h:354
void SpeculativeInsertionLockRelease(TransactionId xid)
Definition: lmgr.c:669
static bool ExecOnConflictUpdate(ModifyTableState *mtstate, ResultRelInfo *resultRelInfo, ItemPointer conflictTid, TupleTableSlot *planSlot, TupleTableSlot *excludedSlot, EState *estate, bool canSetTag, TupleTableSlot **returning)
void ExecWithCheckOptions(WCOKind kind, ResultRelInfo *resultRelInfo, TupleTableSlot *slot, EState *estate)
Definition: execMain.c:2074
void heap_abort_speculative(Relation relation, HeapTuple tuple)
Definition: heapam.c:6105
CommandId es_output_cid
Definition: execnodes.h:438
List * ExecInsertIndexTuples(TupleTableSlot *slot, ItemPointer tupleid, EState *estate, bool noDupErr, bool *specConflict, List *arbiterIndexes)
Definition: execIndexing.c:271
ResultRelInfo * mt_partitions
Definition: execnodes.h:981
#define RelationGetDescr(relation)
Definition: rel.h:428
Oid es_lastoid
Definition: execnodes.h:478
ExecForeignInsert_function ExecForeignInsert
Definition: fdwapi.h:200
TupleTableSlot * ExecIRInsertTriggers(EState *estate, ResultRelInfo *relinfo, TupleTableSlot *slot)
Definition: trigger.c:2369
void ExecConstraints(ResultRelInfo *resultRelInfo, TupleTableSlot *slot, EState *estate)
Definition: execMain.c:1942
#define HeapTupleHeaderSetSpeculativeToken(tup, token)
Definition: htup_details.h:434
#define InvalidBuffer
Definition: buf.h:25
int errcode(int sqlerrcode)
Definition: elog.c:575
uint32 SpeculativeInsertionLockAcquire(TransactionId xid)
Definition: lmgr.c:643
void ExecARInsertTriggers(EState *estate, ResultRelInfo *relinfo, HeapTuple trigtuple, List *recheckIndexes, TransitionCaptureState *transition_capture)
Definition: trigger.c:2354
Form_pg_class rd_rel
Definition: rel.h:114
unsigned int Oid
Definition: postgres_ext.h:31
bool ExecCheckIndexConstraints(TupleTableSlot *slot, EState *estate, ItemPointer conflictTid, List *arbiterIndexes)
Definition: execIndexing.c:475
HeapTuple tcs_original_insert_tuple
Definition: trigger.h:82
#define HEAP_INSERT_SPECULATIVE
Definition: heapam.h:31
HeapTupleHeader t_data
Definition: htup.h:67
#define HeapTupleSetOid(tuple, oid)
Definition: htup_details.h:698
bool trig_insert_instead_row
Definition: reltrigger.h:57
#define ERROR
Definition: elog.h:43
PlanState ps
Definition: execnodes.h:957
static void ExecCheckTIDVisible(EState *estate, ResultRelInfo *relinfo, ItemPointer tid)
TupleConversionMap * tcs_map
Definition: trigger.h:73
ItemPointerData t_self
Definition: htup.h:65
TransactionId GetCurrentTransactionId(void)
Definition: xact.c:418
struct TransitionCaptureState * mt_transition_capture
Definition: execnodes.h:985
ProjectionInfo * ri_projectReturning
Definition: execnodes.h:399
struct FdwRoutine * ri_FdwRoutine
Definition: execnodes.h:378
unsigned int uint32
Definition: c.h:258
Oid t_tableOid
Definition: htup.h:66
void setLastTid(const ItemPointer tid)
Definition: tid.c:254
#define ereport(elevel, rest)
Definition: elog.h:122
Oid heap_insert(Relation relation, HeapTuple tup, CommandId cid, int options, BulkInsertState bistate)
Definition: heapam.c:2413
TriggerDesc * ri_TrigDesc
Definition: execnodes.h:366
static TupleTableSlot * ExecProcessReturning(ResultRelInfo *resultRelInfo, TupleTableSlot *tupleSlot, TupleTableSlot *planSlot)
bool trig_insert_before_row
Definition: reltrigger.h:55
void ExecSetSlotDescriptor(TupleTableSlot *slot, TupleDesc tupdesc)
Definition: execTuples.c:247
List * ri_WithCheckOptions
Definition: execnodes.h:387
int ExecFindPartition(ResultRelInfo *resultRelInfo, PartitionDispatch *pd, TupleTableSlot *slot, EState *estate)
Definition: execMain.c:3365
TupleTableSlot * mt_partition_tuple_slot
Definition: execnodes.h:984
List * ri_PartitionCheck
Definition: execnodes.h:408
TupleDesc rd_att
Definition: rel.h:115
#define InvalidOid
Definition: postgres_ext.h:36
#define Assert(condition)
Definition: c.h:664
#define InstrCountFiltered2(node, delta)
Definition: execnodes.h:901
void heap_finish_speculative(Relation relation, HeapTuple tuple)
Definition: heapam.c:6014
uint64 es_processed
Definition: execnodes.h:477
TupleConstr * constr
Definition: tupdesc.h:78
HeapTuple ExecMaterializeSlot(TupleTableSlot *slot)
Definition: execTuples.c:725
HeapTuple do_convert_tuple(HeapTuple tuple, TupleConversionMap *map)
Definition: tupconvert.c:354
TupleConversionMap ** mt_transition_tupconv_maps
Definition: execnodes.h:989
int errmsg(const char *fmt,...)
Definition: elog.c:797
void list_free(List *list)
Definition: list.c:1133
struct PartitionDispatchData ** mt_partition_dispatch_info
Definition: execnodes.h:976
TupleTableSlot * ExecBRInsertTriggers(EState *estate, ResultRelInfo *relinfo, TupleTableSlot *slot)
Definition: trigger.c:2288
TupleConversionMap ** mt_partition_tupconv_maps
Definition: execnodes.h:982
Definition: pg_list.h:45
#define RelationGetRelid(relation)
Definition: rel.h:416
ResultRelInfo * es_result_relation_info
Definition: execnodes.h:443
static TupleTableSlot* ExecModifyTable ( PlanState pstate)
static

Definition at line 1557 of file nodeModifyTable.c.

References Assert, AttributeNumberIsValid, ModifyTableState::canSetTag, castNode, CHECK_FOR_INTERRUPTS, CMD_DELETE, CMD_INSERT, CMD_UPDATE, DatumGetHeapTupleHeader, DatumGetPointer, elog, ERROR, EState::es_epqTuple, EState::es_result_relation_info, EvalPlanQualSetPlan(), EvalPlanQualSetSlot, ExecDelete(), ExecFilterJunk(), ExecGetJunkAttribute(), ExecInsert(), ExecProcessReturning(), ExecProcNode(), ExecUpdate(), fireASTriggers(), ModifyTableState::fireBSTriggers, fireBSTriggers(), HeapTupleHeaderGetDatumLength, InvalidOid, ItemPointerSetInvalid, JunkFilter::jf_junkAttNo, ModifyTableState::mt_arbiterindexes, ModifyTableState::mt_arowmarks, ModifyTableState::mt_done, ModifyTableState::mt_epqstate, ModifyTableState::mt_nplans, ModifyTableState::mt_oc_transition_capture, ModifyTableState::mt_onconflict, ModifyTableState::mt_plans, ModifyTableState::mt_transition_capture, ModifyTableState::mt_transition_tupconv_maps, ModifyTableState::mt_whichplan, ModifyTableState::operation, PlanState::plan, ModifyTableState::ps, RelationData::rd_rel, RelationGetRelid, RELKIND_FOREIGN_TABLE, RELKIND_MATVIEW, RELKIND_RELATION, RELKIND_VIEW, ResetPerTupleExprContext, ModifyTableState::resultRelInfo, ResultRelInfo::ri_junkFilter, ResultRelInfo::ri_projectReturning, ResultRelInfo::ri_RelationDesc, ResultRelInfo::ri_usesFdwDirectModify, PlanState::state, HeapTupleData::t_data, HeapTupleData::t_len, HeapTupleData::t_self, HeapTupleData::t_tableOid, TransitionCaptureState::tcs_map, and TupIsNull.

Referenced by ExecInitModifyTable().

1558 {
1559  ModifyTableState *node = castNode(ModifyTableState, pstate);
1560  EState *estate = node->ps.state;
1561  CmdType operation = node->operation;
1562  ResultRelInfo *saved_resultRelInfo;
1563  ResultRelInfo *resultRelInfo;
1564  PlanState *subplanstate;
1565  JunkFilter *junkfilter;
1566  TupleTableSlot *slot;
1567  TupleTableSlot *planSlot;
1568  ItemPointer tupleid = NULL;
1569  ItemPointerData tuple_ctid;
1570  HeapTupleData oldtupdata;
1571  HeapTuple oldtuple;
1572 
1574 
1575  /*
1576  * This should NOT get called during EvalPlanQual; we should have passed a
1577  * subplan tree to EvalPlanQual, instead. Use a runtime test not just
1578  * Assert because this condition is easy to miss in testing. (Note:
1579  * although ModifyTable should not get executed within an EvalPlanQual
1580  * operation, we do have to allow it to be initialized and shut down in
1581  * case it is within a CTE subplan. Hence this test must be here, not in
1582  * ExecInitModifyTable.)
1583  */
1584  if (estate->es_epqTuple != NULL)
1585  elog(ERROR, "ModifyTable should not be called during EvalPlanQual");
1586 
1587  /*
1588  * If we've already completed processing, don't try to do more. We need
1589  * this test because ExecPostprocessPlan might call us an extra time, and
1590  * our subplan's nodes aren't necessarily robust against being called
1591  * extra times.
1592  */
1593  if (node->mt_done)
1594  return NULL;
1595 
1596  /*
1597  * On first call, fire BEFORE STATEMENT triggers before proceeding.
1598  */
1599  if (node->fireBSTriggers)
1600  {
1601  fireBSTriggers(node);
1602  node->fireBSTriggers = false;
1603  }
1604 
1605  /* Preload local variables */
1606  resultRelInfo = node->resultRelInfo + node->mt_whichplan;
1607  subplanstate = node->mt_plans[node->mt_whichplan];
1608  junkfilter = resultRelInfo->ri_junkFilter;
1609 
1610  /*
1611  * es_result_relation_info must point to the currently active result
1612  * relation while we are within this ModifyTable node. Even though
1613  * ModifyTable nodes can't be nested statically, they can be nested
1614  * dynamically (since our subplan could include a reference to a modifying
1615  * CTE). So we have to save and restore the caller's value.
1616  */
1617  saved_resultRelInfo = estate->es_result_relation_info;
1618 
1619  estate->es_result_relation_info = resultRelInfo;
1620 
1621  /*
1622  * Fetch rows from subplan(s), and execute the required table modification
1623  * for each row.
1624  */
1625  for (;;)
1626  {
1627  /*
1628  * Reset the per-output-tuple exprcontext. This is needed because
1629  * triggers expect to use that context as workspace. It's a bit ugly
1630  * to do this below the top level of the plan, however. We might need
1631  * to rethink this later.
1632  */
1633  ResetPerTupleExprContext(estate);
1634 
1635  planSlot = ExecProcNode(subplanstate);
1636 
1637  if (TupIsNull(planSlot))
1638  {
1639  /* advance to next subplan if any */
1640  node->mt_whichplan++;
1641  if (node->mt_whichplan < node->mt_nplans)
1642  {
1643  resultRelInfo++;
1644  subplanstate = node->mt_plans[node->mt_whichplan];
1645  junkfilter = resultRelInfo->ri_junkFilter;
1646  estate->es_result_relation_info = resultRelInfo;
1647  EvalPlanQualSetPlan(&node->mt_epqstate, subplanstate->plan,
1648  node->mt_arowmarks[node->mt_whichplan]);
1649  /* Prepare to convert transition tuples from this child. */
1650  if (node->mt_transition_capture != NULL)
1651  {
1652  Assert(node->mt_transition_tupconv_maps != NULL);
1655  }
1656  if (node->mt_oc_transition_capture != NULL)
1657  {
1658  Assert(node->mt_transition_tupconv_maps != NULL);
1661  }
1662  continue;
1663  }
1664  else
1665  break;
1666  }
1667 
1668  /*
1669  * If resultRelInfo->ri_usesFdwDirectModify is true, all we need to do
1670  * here is compute the RETURNING expressions.
1671  */
1672  if (resultRelInfo->ri_usesFdwDirectModify)
1673  {
1674  Assert(resultRelInfo->ri_projectReturning);
1675 
1676  /*
1677  * A scan slot containing the data that was actually inserted,
1678  * updated or deleted has already been made available to
1679  * ExecProcessReturning by IterateDirectModify, so no need to
1680  * provide it here.
1681  */
1682  slot = ExecProcessReturning(resultRelInfo, NULL, planSlot);
1683 
1684  estate->es_result_relation_info = saved_resultRelInfo;
1685  return slot;
1686  }
1687 
1688  EvalPlanQualSetSlot(&node->mt_epqstate, planSlot);
1689  slot = planSlot;
1690 
1691  oldtuple = NULL;
1692  if (junkfilter != NULL)
1693  {
1694  /*
1695  * extract the 'ctid' or 'wholerow' junk attribute.
1696  */
1697  if (operation == CMD_UPDATE || operation == CMD_DELETE)
1698  {
1699  char relkind;
1700  Datum datum;
1701  bool isNull;
1702 
1703  relkind = resultRelInfo->ri_RelationDesc->rd_rel->relkind;
1704  if (relkind == RELKIND_RELATION || relkind == RELKIND_MATVIEW)
1705  {
1706  datum = ExecGetJunkAttribute(slot,
1707  junkfilter->jf_junkAttNo,
1708  &isNull);
1709  /* shouldn't ever get a null result... */
1710  if (isNull)
1711  elog(ERROR, "ctid is NULL");
1712 
1713  tupleid = (ItemPointer) DatumGetPointer(datum);
1714  tuple_ctid = *tupleid; /* be sure we don't free ctid!! */
1715  tupleid = &tuple_ctid;
1716  }
1717 
1718  /*
1719  * Use the wholerow attribute, when available, to reconstruct
1720  * the old relation tuple.
1721  *
1722  * Foreign table updates have a wholerow attribute when the
1723  * relation has a row-level trigger. Note that the wholerow
1724  * attribute does not carry system columns. Foreign table
1725  * triggers miss seeing those, except that we know enough here
1726  * to set t_tableOid. Quite separately from this, the FDW may
1727  * fetch its own junk attrs to identify the row.
1728  *
1729  * Other relevant relkinds, currently limited to views, always
1730  * have a wholerow attribute.
1731  */
1732  else if (AttributeNumberIsValid(junkfilter->jf_junkAttNo))
1733  {
1734  datum = ExecGetJunkAttribute(slot,
1735  junkfilter->jf_junkAttNo,
1736  &isNull);
1737  /* shouldn't ever get a null result... */
1738  if (isNull)
1739  elog(ERROR, "wholerow is NULL");
1740 
1741  oldtupdata.t_data = DatumGetHeapTupleHeader(datum);
1742  oldtupdata.t_len =
1744  ItemPointerSetInvalid(&(oldtupdata.t_self));
1745  /* Historically, view triggers see invalid t_tableOid. */
1746  oldtupdata.t_tableOid =
1747  (relkind == RELKIND_VIEW) ? InvalidOid :
1748  RelationGetRelid(resultRelInfo->ri_RelationDesc);
1749 
1750  oldtuple = &oldtupdata;
1751  }
1752  else
1753  Assert(relkind == RELKIND_FOREIGN_TABLE);
1754  }
1755 
1756  /*
1757  * apply the junkfilter if needed.
1758  */
1759  if (operation != CMD_DELETE)
1760  slot = ExecFilterJunk(junkfilter, slot);
1761  }
1762 
1763  switch (operation)
1764  {
1765  case CMD_INSERT:
1766  slot = ExecInsert(node, slot, planSlot,
1767  node->mt_arbiterindexes, node->mt_onconflict,
1768  estate, node->canSetTag);
1769  break;
1770  case CMD_UPDATE:
1771  slot = ExecUpdate(node, tupleid, oldtuple, slot, planSlot,
1772  &node->mt_epqstate, estate, node->canSetTag);
1773  break;
1774  case CMD_DELETE:
1775  slot = ExecDelete(node, tupleid, oldtuple, planSlot,
1776  &node->mt_epqstate, estate, node->canSetTag);
1777  break;
1778  default:
1779  elog(ERROR, "unknown operation");
1780  break;
1781  }
1782 
1783  /*
1784  * If we got a RETURNING result, return it to caller. We'll continue
1785  * the work on next call.
1786  */
1787  if (slot)
1788  {
1789  estate->es_result_relation_info = saved_resultRelInfo;
1790  return slot;
1791  }
1792  }
1793 
1794  /* Restore es_result_relation_info before exiting */
1795  estate->es_result_relation_info = saved_resultRelInfo;
1796 
1797  /*
1798  * We're done, but fire AFTER STATEMENT triggers before exiting.
1799  */
1800  fireASTriggers(node);
1801 
1802  node->mt_done = true;
1803 
1804  return NULL;
1805 }
AttrNumber jf_junkAttNo
Definition: execnodes.h:336
JunkFilter * ri_junkFilter
Definition: execnodes.h:396
HeapTuple * es_epqTuple
Definition: execnodes.h:506
struct TransitionCaptureState * mt_oc_transition_capture
Definition: execnodes.h:987
Relation ri_RelationDesc
Definition: execnodes.h:354
#define ResetPerTupleExprContext(estate)
Definition: executor.h:485
#define castNode(_type_, nodeptr)
Definition: nodes.h:578
ResultRelInfo * resultRelInfo
Definition: execnodes.h:964
static TupleTableSlot * ExecUpdate(ModifyTableState *mtstate, ItemPointer tupleid, HeapTuple oldtuple, TupleTableSlot *slot, TupleTableSlot *planSlot, EPQState *epqstate, EState *estate, bool canSetTag)
static void fireBSTriggers(ModifyTableState *node)
#define RELKIND_MATVIEW
Definition: pg_class.h:165
CmdType operation
Definition: execnodes.h:958
void EvalPlanQualSetPlan(EPQState *epqstate, Plan *subplan, List *auxrowmarks)
Definition: execMain.c:2814
EState * state
Definition: execnodes.h:849
Form_pg_class rd_rel
Definition: rel.h:114
#define DatumGetHeapTupleHeader(X)
Definition: fmgr.h:259
ItemPointerData * ItemPointer
Definition: itemptr.h:49
HeapTupleHeader t_data
Definition: htup.h:67
OnConflictAction mt_onconflict
Definition: execnodes.h:970
#define ERROR
Definition: elog.h:43
PlanState ps
Definition: execnodes.h:957
TupleConversionMap * tcs_map
Definition: trigger.h:73
ItemPointerData t_self
Definition: htup.h:65
bool ri_usesFdwDirectModify
Definition: execnodes.h:384
uint32 t_len
Definition: htup.h:64
struct TransitionCaptureState * mt_transition_capture
Definition: execnodes.h:985
EPQState mt_epqstate
Definition: execnodes.h:968
ProjectionInfo * ri_projectReturning
Definition: execnodes.h:399
#define TupIsNull(slot)
Definition: tuptable.h:138
Oid t_tableOid
Definition: htup.h:66
#define RELKIND_FOREIGN_TABLE
Definition: pg_class.h:167
static TupleTableSlot * ExecProcessReturning(ResultRelInfo *resultRelInfo, TupleTableSlot *tupleSlot, TupleTableSlot *planSlot)
PlanState ** mt_plans
Definition: execnodes.h:961
#define AttributeNumberIsValid(attributeNumber)
Definition: attnum.h:34
static void fireASTriggers(ModifyTableState *node)
static TupleTableSlot * ExecDelete(ModifyTableState *mtstate, ItemPointer tupleid, HeapTuple oldtuple, TupleTableSlot *planSlot, EPQState *epqstate, EState *estate, bool canSetTag)
uintptr_t Datum
Definition: postgres.h:372
TupleTableSlot * ExecFilterJunk(JunkFilter *junkfilter, TupleTableSlot *slot)
Definition: execJunk.c:262
static TupleTableSlot * ExecProcNode(PlanState *node)
Definition: executor.h:246
Plan * plan
Definition: execnodes.h:847
#define InvalidOid
Definition: postgres_ext.h:36
#define Assert(condition)
Definition: c.h:664
static TupleTableSlot * ExecInsert(ModifyTableState *mtstate, TupleTableSlot *slot, TupleTableSlot *planSlot, List *arbiterIndexes, OnConflictAction onconflict, EState *estate, bool canSetTag)
#define DatumGetPointer(X)
Definition: postgres.h:555
TupleConversionMap ** mt_transition_tupconv_maps
Definition: execnodes.h:989
List * mt_arbiterindexes
Definition: execnodes.h:971
#define ItemPointerSetInvalid(pointer)
Definition: itemptr.h:150
Datum ExecGetJunkAttribute(TupleTableSlot *slot, AttrNumber attno, bool *isNull)
Definition: execJunk.c:248
#define RELKIND_VIEW
Definition: pg_class.h:164
#define CHECK_FOR_INTERRUPTS()
Definition: miscadmin.h:98
#define elog
Definition: elog.h:219
#define RELKIND_RELATION
Definition: pg_class.h:160
#define RelationGetRelid(relation)
Definition: rel.h:416
CmdType
Definition: nodes.h:649
List ** mt_arowmarks
Definition: execnodes.h:967
#define EvalPlanQualSetSlot(epqstate, slot)
Definition: executor.h:222
#define HeapTupleHeaderGetDatumLength(tup)
Definition: htup_details.h:439
ResultRelInfo * es_result_relation_info
Definition: execnodes.h:443
static bool ExecOnConflictUpdate ( ModifyTableState mtstate,
ResultRelInfo resultRelInfo,
ItemPointer  conflictTid,
TupleTableSlot planSlot,
TupleTableSlot excludedSlot,
EState estate,
bool  canSetTag,
TupleTableSlot **  returning 
)
static

Definition at line 1201 of file nodeModifyTable.c.

References buffer, ExprContext::ecxt_innertuple, ExprContext::ecxt_outertuple, ExprContext::ecxt_scantuple, elog, ereport, errcode(), errhint(), errmsg(), ERROR, EState::es_output_cid, ExecCheckHeapTupleVisible(), ExecProject(), ExecQual(), ExecStoreTuple(), ExecUpdate(), ExecUpdateLockMode(), ExecWithCheckOptions(), heap_lock_tuple(), HeapTupleHeaderGetXmin, HeapTupleInvisible, HeapTupleMayBeUpdated, HeapTupleSelfUpdated, HeapTupleUpdated, InstrCountFiltered1, IsolationUsesXactSnapshot, LockWaitBlock, ModifyTableState::mt_conflproj, ModifyTableState::mt_epqstate, ModifyTableState::mt_existing, NIL, ModifyTableState::ps, PlanState::ps_ExprContext, ReleaseBuffer(), ResetExprContext, ResultRelInfo::ri_onConflictSetProj, ResultRelInfo::ri_onConflictSetWhere, ResultRelInfo::ri_RelationDesc, ResultRelInfo::ri_WithCheckOptions, PlanState::state, HeapTupleData::t_data, HeapTupleData::t_self, test(), TransactionIdIsCurrentTransactionId(), and WCO_RLS_CONFLICT_CHECK.

Referenced by ExecInsert().

1209 {
1210  ExprContext *econtext = mtstate->ps.ps_ExprContext;
1211  Relation relation = resultRelInfo->ri_RelationDesc;
1212  ExprState *onConflictSetWhere = resultRelInfo->ri_onConflictSetWhere;
1213  HeapTupleData tuple;
1214  HeapUpdateFailureData hufd;
1215  LockTupleMode lockmode;
1216  HTSU_Result test;
1217  Buffer buffer;
1218 
1219  /* Determine lock mode to use */
1220  lockmode = ExecUpdateLockMode(estate, resultRelInfo);
1221 
1222  /*
1223  * Lock tuple for update. Don't follow updates when tuple cannot be
1224  * locked without doing so. A row locking conflict here means our
1225  * previous conclusion that the tuple is conclusively committed is not
1226  * true anymore.
1227  */
1228  tuple.t_self = *conflictTid;
1229  test = heap_lock_tuple(relation, &tuple, estate->es_output_cid,
1230  lockmode, LockWaitBlock, false, &buffer,
1231  &hufd);
1232  switch (test)
1233  {
1234  case HeapTupleMayBeUpdated:
1235  /* success! */
1236  break;
1237 
1238  case HeapTupleInvisible:
1239 
1240  /*
1241  * This can occur when a just inserted tuple is updated again in
1242  * the same command. E.g. because multiple rows with the same
1243  * conflicting key values are inserted.
1244  *
1245  * This is somewhat similar to the ExecUpdate()
1246  * HeapTupleSelfUpdated case. We do not want to proceed because
1247  * it would lead to the same row being updated a second time in
1248  * some unspecified order, and in contrast to plain UPDATEs
1249  * there's no historical behavior to break.
1250  *
1251  * It is the user's responsibility to prevent this situation from
1252  * occurring. These problems are why SQL-2003 similarly specifies
1253  * that for SQL MERGE, an exception must be raised in the event of
1254  * an attempt to update the same row twice.
1255  */
1257  ereport(ERROR,
1258  (errcode(ERRCODE_CARDINALITY_VIOLATION),
1259  errmsg("ON CONFLICT DO UPDATE command cannot affect row a second time"),
1260  errhint("Ensure that no rows proposed for insertion within the same command have duplicate constrained values.")));
1261 
1262  /* This shouldn't happen */
1263  elog(ERROR, "attempted to lock invisible tuple");
1264 
1265  case HeapTupleSelfUpdated:
1266 
1267  /*
1268  * This state should never be reached. As a dirty snapshot is used
1269  * to find conflicting tuples, speculative insertion wouldn't have
1270  * seen this row to conflict with.
1271  */
1272  elog(ERROR, "unexpected self-updated tuple");
1273 
1274  case HeapTupleUpdated:
1276  ereport(ERROR,
1277  (errcode(ERRCODE_T_R_SERIALIZATION_FAILURE),
1278  errmsg("could not serialize access due to concurrent update")));
1279 
1280  /*
1281  * Tell caller to try again from the very start.
1282  *
1283  * It does not make sense to use the usual EvalPlanQual() style
1284  * loop here, as the new version of the row might not conflict
1285  * anymore, or the conflicting tuple has actually been deleted.
1286  */
1287  ReleaseBuffer(buffer);
1288  return false;
1289 
1290  default:
1291  elog(ERROR, "unrecognized heap_lock_tuple status: %u", test);
1292  }
1293 
1294  /*
1295  * Success, the tuple is locked.
1296  *
1297  * Reset per-tuple memory context to free any expression evaluation
1298  * storage allocated in the previous cycle.
1299  */
1300  ResetExprContext(econtext);
1301 
1302  /*
1303  * Verify that the tuple is visible to our MVCC snapshot if the current
1304  * isolation level mandates that.
1305  *
1306  * It's not sufficient to rely on the check within ExecUpdate() as e.g.
1307  * CONFLICT ... WHERE clause may prevent us from reaching that.
1308  *
1309  * This means we only ever continue when a new command in the current
1310  * transaction could see the row, even though in READ COMMITTED mode the
1311  * tuple will not be visible according to the current statement's
1312  * snapshot. This is in line with the way UPDATE deals with newer tuple
1313  * versions.
1314  */
1315  ExecCheckHeapTupleVisible(estate, &tuple, buffer);
1316 
1317  /* Store target's existing tuple in the state's dedicated slot */
1318  ExecStoreTuple(&tuple, mtstate->mt_existing, buffer, false);
1319 
1320  /*
1321  * Make tuple and any needed join variables available to ExecQual and
1322  * ExecProject. The EXCLUDED tuple is installed in ecxt_innertuple, while
1323  * the target's existing tuple is installed in the scantuple. EXCLUDED
1324  * has been made to reference INNER_VAR in setrefs.c, but there is no
1325  * other redirection.
1326  */
1327  econtext->ecxt_scantuple = mtstate->mt_existing;
1328  econtext->ecxt_innertuple = excludedSlot;
1329  econtext->ecxt_outertuple = NULL;
1330 
1331  if (!ExecQual(onConflictSetWhere, econtext))
1332  {
1333  ReleaseBuffer(buffer);
1334  InstrCountFiltered1(&mtstate->ps, 1);
1335  return true; /* done with the tuple */
1336  }
1337 
1338  if (resultRelInfo->ri_WithCheckOptions != NIL)
1339  {
1340  /*
1341  * Check target's existing tuple against UPDATE-applicable USING
1342  * security barrier quals (if any), enforced here as RLS checks/WCOs.
1343  *
1344  * The rewriter creates UPDATE RLS checks/WCOs for UPDATE security
1345  * quals, and stores them as WCOs of "kind" WCO_RLS_CONFLICT_CHECK,
1346  * but that's almost the extent of its special handling for ON
1347  * CONFLICT DO UPDATE.
1348  *
1349  * The rewriter will also have associated UPDATE applicable straight
1350  * RLS checks/WCOs for the benefit of the ExecUpdate() call that
1351  * follows. INSERTs and UPDATEs naturally have mutually exclusive WCO
1352  * kinds, so there is no danger of spurious over-enforcement in the
1353  * INSERT or UPDATE path.
1354  */
1356  mtstate->mt_existing,
1357  mtstate->ps.state);
1358  }
1359 
1360  /* Project the new tuple version */
1361  ExecProject(resultRelInfo->ri_onConflictSetProj);
1362 
1363  /*
1364  * Note that it is possible that the target tuple has been modified in
1365  * this session, after the above heap_lock_tuple. We choose to not error
1366  * out in that case, in line with ExecUpdate's treatment of similar cases.
1367  * This can happen if an UPDATE is triggered from within ExecQual(),
1368  * ExecWithCheckOptions() or ExecProject() above, e.g. by selecting from a
1369  * wCTE in the ON CONFLICT's SET.
1370  */
1371 
1372  /* Execute UPDATE with projection */
1373  *returning = ExecUpdate(mtstate, &tuple.t_self, NULL,
1374  mtstate->mt_conflproj, planSlot,
1375  &mtstate->mt_epqstate, mtstate->ps.state,
1376  canSetTag);
1377 
1378  ReleaseBuffer(buffer);
1379  return true;
1380 }
#define NIL
Definition: pg_list.h:69
TupleTableSlot * ExecStoreTuple(HeapTuple tuple, TupleTableSlot *slot, Buffer buffer, bool shouldFree)
Definition: execTuples.c:320
Relation ri_RelationDesc
Definition: execnodes.h:354
ExprState * ri_onConflictSetWhere
Definition: execnodes.h:405
int errhint(const char *fmt,...)
Definition: elog.c:987
void ExecWithCheckOptions(WCOKind kind, ResultRelInfo *resultRelInfo, TupleTableSlot *slot, EState *estate)
Definition: execMain.c:2074
CommandId es_output_cid
Definition: execnodes.h:438
ProjectionInfo * ri_onConflictSetProj
Definition: execnodes.h:402
static void test(void)
bool TransactionIdIsCurrentTransactionId(TransactionId xid)
Definition: xact.c:774
HTSU_Result heap_lock_tuple(Relation relation, HeapTuple tuple, CommandId cid, LockTupleMode mode, LockWaitPolicy wait_policy, bool follow_updates, Buffer *buffer, HeapUpdateFailureData *hufd)
Definition: heapam.c:4558
static TupleTableSlot * ExecUpdate(ModifyTableState *mtstate, ItemPointer tupleid, HeapTuple oldtuple, TupleTableSlot *slot, TupleTableSlot *planSlot, EPQState *epqstate, EState *estate, bool canSetTag)
ExprContext * ps_ExprContext
Definition: execnodes.h:881
TupleTableSlot * mt_conflproj
Definition: execnodes.h:975
#define IsolationUsesXactSnapshot()
Definition: xact.h:43
int errcode(int sqlerrcode)
Definition: elog.c:575
void ReleaseBuffer(Buffer buffer)
Definition: bufmgr.c:3309
EState * state
Definition: execnodes.h:849
static bool ExecQual(ExprState *state, ExprContext *econtext)
Definition: executor.h:366
TupleTableSlot * mt_existing
Definition: execnodes.h:973
HeapTupleHeader t_data
Definition: htup.h:67
LockTupleMode
Definition: heapam.h:38
#define ERROR
Definition: elog.h:43
PlanState ps
Definition: execnodes.h:957
ItemPointerData t_self
Definition: htup.h:65
static void ExecCheckHeapTupleVisible(EState *estate, HeapTuple tuple, Buffer buffer)
EPQState mt_epqstate
Definition: execnodes.h:968
TupleTableSlot * ecxt_innertuple
Definition: execnodes.h:198
HTSU_Result
Definition: snapshot.h:121
#define InstrCountFiltered1(node, delta)
Definition: execnodes.h:896
#define ereport(elevel, rest)
Definition: elog.h:122
List * ri_WithCheckOptions
Definition: execnodes.h:387
TupleTableSlot * ecxt_outertuple
Definition: execnodes.h:199
LockTupleMode ExecUpdateLockMode(EState *estate, ResultRelInfo *relinfo)
Definition: execMain.c:2358
WalTimeSample buffer[LAG_TRACKER_BUFFER_SIZE]
Definition: walsender.c:214
#define HeapTupleHeaderGetXmin(tup)
Definition: htup_details.h:307
TupleTableSlot * ecxt_scantuple
Definition: execnodes.h:197
int errmsg(const char *fmt,...)
Definition: elog.c:797
#define elog
Definition: elog.h:219
int Buffer
Definition: buf.h:23
static TupleTableSlot * ExecProject(ProjectionInfo *projInfo)
Definition: executor.h:329
#define ResetExprContext(econtext)
Definition: executor.h:470
static TupleTableSlot* ExecProcessReturning ( ResultRelInfo resultRelInfo,
TupleTableSlot tupleSlot,
TupleTableSlot planSlot 
)
static

Definition at line 149 of file nodeModifyTable.c.

References Assert, ExprContext::ecxt_outertuple, ExprContext::ecxt_scantuple, ExecMaterializeSlot(), ExecProject(), ProjectionInfo::pi_exprContext, RelationGetRelid, ResetExprContext, ResultRelInfo::ri_projectReturning, ResultRelInfo::ri_RelationDesc, HeapTupleData::t_tableOid, and TupIsNull.

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

152 {
153  ProjectionInfo *projectReturning = resultRelInfo->ri_projectReturning;
154  ExprContext *econtext = projectReturning->pi_exprContext;
155 
156  /*
157  * Reset per-tuple memory context to free any expression evaluation
158  * storage allocated in the previous cycle.
159  */
160  ResetExprContext(econtext);
161 
162  /* Make tuple and any needed join variables available to ExecProject */
163  if (tupleSlot)
164  econtext->ecxt_scantuple = tupleSlot;
165  else
166  {
167  HeapTuple tuple;
168 
169  /*
170  * RETURNING expressions might reference the tableoid column, so
171  * initialize t_tableOid before evaluating them.
172  */
173  Assert(!TupIsNull(econtext->ecxt_scantuple));
174  tuple = ExecMaterializeSlot(econtext->ecxt_scantuple);
175  tuple->t_tableOid = RelationGetRelid(resultRelInfo->ri_RelationDesc);
176  }
177  econtext->ecxt_outertuple = planSlot;
178 
179  /* Compute the RETURNING expressions */
180  return ExecProject(projectReturning);
181 }
Relation ri_RelationDesc
Definition: execnodes.h:354
ProjectionInfo * ri_projectReturning
Definition: execnodes.h:399
#define TupIsNull(slot)
Definition: tuptable.h:138
Oid t_tableOid
Definition: htup.h:66
TupleTableSlot * ecxt_outertuple
Definition: execnodes.h:199
#define Assert(condition)
Definition: c.h:664
TupleTableSlot * ecxt_scantuple
Definition: execnodes.h:197
HeapTuple ExecMaterializeSlot(TupleTableSlot *slot)
Definition: execTuples.c:725
ExprContext * pi_exprContext
Definition: execnodes.h:298
#define RelationGetRelid(relation)
Definition: rel.h:416
static TupleTableSlot * ExecProject(ProjectionInfo *projInfo)
Definition: executor.h:329
#define ResetExprContext(econtext)
Definition: executor.h:470
void ExecReScanModifyTable ( ModifyTableState node)

Definition at line 2412 of file nodeModifyTable.c.

References elog, and ERROR.

Referenced by ExecReScan().

2413 {
2414  /*
2415  * Currently, we don't need to support rescan on ModifyTable nodes. The
2416  * semantics of that would be a bit debatable anyway.
2417  */
2418  elog(ERROR, "ExecReScanModifyTable is not implemented");
2419 }
#define ERROR
Definition: elog.h:43
#define elog
Definition: elog.h:219
static void ExecSetupTransitionCaptureState ( ModifyTableState mtstate,
EState estate 
)
static

Definition at line 1475 of file nodeModifyTable.c.

References CMD_INSERT, CMD_UPDATE, convert_tuples_by_name(), getASTriggerResultRelInfo(), gettext_noop, i, MakeTransitionCaptureState(), ModifyTableState::mt_nplans, ModifyTableState::mt_num_partitions, ModifyTableState::mt_oc_transition_capture, ModifyTableState::mt_onconflict, ModifyTableState::mt_partition_dispatch_info, ModifyTableState::mt_partitions, ModifyTableState::mt_transition_capture, ModifyTableState::mt_transition_tupconv_maps, ONCONFLICT_UPDATE, ModifyTableState::operation, palloc0(), RelationGetDescr, RelationGetRelid, ModifyTableState::resultRelInfo, ResultRelInfo::ri_RelationDesc, ResultRelInfo::ri_TrigDesc, and TransitionCaptureState::tcs_map.

Referenced by ExecInitModifyTable().

1476 {
1477  ResultRelInfo *targetRelInfo = getASTriggerResultRelInfo(mtstate);
1478  int i;
1479 
1480  /* Check for transition tables on the directly targeted relation. */
1481  mtstate->mt_transition_capture =
1482  MakeTransitionCaptureState(targetRelInfo->ri_TrigDesc,
1483  RelationGetRelid(targetRelInfo->ri_RelationDesc),
1484  mtstate->operation);
1485  if (mtstate->operation == CMD_INSERT &&
1486  mtstate->mt_onconflict == ONCONFLICT_UPDATE)
1487  mtstate->mt_oc_transition_capture =
1488  MakeTransitionCaptureState(targetRelInfo->ri_TrigDesc,
1489  RelationGetRelid(targetRelInfo->ri_RelationDesc),
1490  CMD_UPDATE);
1491 
1492  /*
1493  * If we found that we need to collect transition tuples then we may also
1494  * need tuple conversion maps for any children that have TupleDescs that
1495  * aren't compatible with the tuplestores. (We can share these maps
1496  * between the regular and ON CONFLICT cases.)
1497  */
1498  if (mtstate->mt_transition_capture != NULL ||
1499  mtstate->mt_oc_transition_capture != NULL)
1500  {
1501  ResultRelInfo *resultRelInfos;
1502  int numResultRelInfos;
1503 
1504  /* Find the set of partitions so that we can find their TupleDescs. */
1505  if (mtstate->mt_partition_dispatch_info != NULL)
1506  {
1507  /*
1508  * For INSERT via partitioned table, so we need TupleDescs based
1509  * on the partition routing table.
1510  */
1511  resultRelInfos = mtstate->mt_partitions;
1512  numResultRelInfos = mtstate->mt_num_partitions;
1513  }
1514  else
1515  {
1516  /* Otherwise we need the ResultRelInfo for each subplan. */
1517  resultRelInfos = mtstate->resultRelInfo;
1518  numResultRelInfos = mtstate->mt_nplans;
1519  }
1520 
1521  /*
1522  * Build array of conversion maps from each child's TupleDesc to the
1523  * one used in the tuplestore. The map pointers may be NULL when no
1524  * conversion is necessary, which is hopefully a common case for
1525  * partitions.
1526  */
1528  palloc0(sizeof(TupleConversionMap *) * numResultRelInfos);
1529  for (i = 0; i < numResultRelInfos; ++i)
1530  {
1531  mtstate->mt_transition_tupconv_maps[i] =
1532  convert_tuples_by_name(RelationGetDescr(resultRelInfos[i].ri_RelationDesc),
1533  RelationGetDescr(targetRelInfo->ri_RelationDesc),
1534  gettext_noop("could not convert row type"));
1535  }
1536 
1537  /*
1538  * Install the conversion map for the first plan for UPDATE and DELETE
1539  * operations. It will be advanced each time we switch to the next
1540  * plan. (INSERT operations set it every time, so we need not update
1541  * mtstate->mt_oc_transition_capture here.)
1542  */
1543  if (mtstate->mt_transition_capture)
1544  mtstate->mt_transition_capture->tcs_map =
1545  mtstate->mt_transition_tupconv_maps[0];
1546  }
1547 }
static ResultRelInfo * getASTriggerResultRelInfo(ModifyTableState *node)
struct TransitionCaptureState * mt_oc_transition_capture
Definition: execnodes.h:987
Relation ri_RelationDesc
Definition: execnodes.h:354
ResultRelInfo * mt_partitions
Definition: execnodes.h:981
#define RelationGetDescr(relation)
Definition: rel.h:428
ResultRelInfo * resultRelInfo
Definition: execnodes.h:964
#define gettext_noop(x)
Definition: c.h:139
CmdType operation
Definition: execnodes.h:958
OnConflictAction mt_onconflict
Definition: execnodes.h:970
TupleConversionMap * tcs_map
Definition: trigger.h:73
struct TransitionCaptureState * mt_transition_capture
Definition: execnodes.h:985
TriggerDesc * ri_TrigDesc
Definition: execnodes.h:366
TupleConversionMap * convert_tuples_by_name(TupleDesc indesc, TupleDesc outdesc, const char *msg)
Definition: tupconvert.c:210
void * palloc0(Size size)
Definition: mcxt.c:877
TransitionCaptureState * MakeTransitionCaptureState(TriggerDesc *trigdesc, Oid relid, CmdType cmdType)
Definition: trigger.c:4411
TupleConversionMap ** mt_transition_tupconv_maps
Definition: execnodes.h:989
int i
struct PartitionDispatchData ** mt_partition_dispatch_info
Definition: execnodes.h:976
#define RelationGetRelid(relation)
Definition: rel.h:416
static TupleTableSlot* ExecUpdate ( ModifyTableState mtstate,
ItemPointer  tupleid,
HeapTuple  oldtuple,
TupleTableSlot slot,
TupleTableSlot planSlot,
EPQState epqstate,
EState estate,
bool  canSetTag 
)
static

Definition at line 934 of file nodeModifyTable.c.

References HeapUpdateFailureData::cmax, CMD_INSERT, tupleDesc::constr, HeapUpdateFailureData::ctid, elog, ereport, errcode(), errhint(), errmsg(), ERROR, EState::es_crosscheck_snapshot, EState::es_output_cid, EState::es_processed, EState::es_result_relation_info, EvalPlanQual(), ExecARUpdateTriggers(), ExecBRUpdateTriggers(), ExecConstraints(), ExecFilterJunk(), FdwRoutine::ExecForeignUpdate, ExecInsertIndexTuples(), ExecIRUpdateTriggers(), ExecMaterializeSlot(), ExecProcessReturning(), ExecWithCheckOptions(), heap_update(), HeapTupleIsHeapOnly, HeapTupleMayBeUpdated, HeapTupleSelfUpdated, HeapTupleUpdated, IsBootstrapProcessingMode, IsolationUsesXactSnapshot, ItemPointerEquals(), list_free(), ModifyTableState::mt_oc_transition_capture, ModifyTableState::mt_transition_capture, NIL, ModifyTableState::operation, RelationData::rd_att, RelationGetRelid, ResultRelInfo::ri_FdwRoutine, ResultRelInfo::ri_junkFilter, ResultRelInfo::ri_NumIndices, ResultRelInfo::ri_PartitionCheck, ResultRelInfo::ri_projectReturning, ResultRelInfo::ri_RangeTableIndex, ResultRelInfo::ri_RelationDesc, ResultRelInfo::ri_TrigDesc, ResultRelInfo::ri_WithCheckOptions, HeapTupleData::t_self, HeapTupleData::t_tableOid, TriggerDesc::trig_update_before_row, TriggerDesc::trig_update_instead_row, TupIsNull, WCO_RLS_UPDATE_CHECK, WCO_VIEW_CHECK, and HeapUpdateFailureData::xmax.

Referenced by ExecModifyTable(), and ExecOnConflictUpdate().

942 {
943  HeapTuple tuple;
944  ResultRelInfo *resultRelInfo;
945  Relation resultRelationDesc;
946  HTSU_Result result;
948  List *recheckIndexes = NIL;
949 
950  /*
951  * abort the operation if not running transactions
952  */
954  elog(ERROR, "cannot UPDATE during bootstrap");
955 
956  /*
957  * get the heap tuple out of the tuple table slot, making sure we have a
958  * writable copy
959  */
960  tuple = ExecMaterializeSlot(slot);
961 
962  /*
963  * get information on the (current) result relation
964  */
965  resultRelInfo = estate->es_result_relation_info;
966  resultRelationDesc = resultRelInfo->ri_RelationDesc;
967 
968  /* BEFORE ROW UPDATE Triggers */
969  if (resultRelInfo->ri_TrigDesc &&
970  resultRelInfo->ri_TrigDesc->trig_update_before_row)
971  {
972  slot = ExecBRUpdateTriggers(estate, epqstate, resultRelInfo,
973  tupleid, oldtuple, slot);
974 
975  if (slot == NULL) /* "do nothing" */
976  return NULL;
977 
978  /* trigger might have changed tuple */
979  tuple = ExecMaterializeSlot(slot);
980  }
981 
982  /* INSTEAD OF ROW UPDATE Triggers */
983  if (resultRelInfo->ri_TrigDesc &&
984  resultRelInfo->ri_TrigDesc->trig_update_instead_row)
985  {
986  slot = ExecIRUpdateTriggers(estate, resultRelInfo,
987  oldtuple, slot);
988 
989  if (slot == NULL) /* "do nothing" */
990  return NULL;
991 
992  /* trigger might have changed tuple */
993  tuple = ExecMaterializeSlot(slot);
994  }
995  else if (resultRelInfo->ri_FdwRoutine)
996  {
997  /*
998  * update in foreign table: let the FDW do it
999  */
1000  slot = resultRelInfo->ri_FdwRoutine->ExecForeignUpdate(estate,
1001  resultRelInfo,
1002  slot,
1003  planSlot);
1004 
1005  if (slot == NULL) /* "do nothing" */
1006  return NULL;
1007 
1008  /* FDW might have changed tuple */
1009  tuple = ExecMaterializeSlot(slot);
1010 
1011  /*
1012  * AFTER ROW Triggers or RETURNING expressions might reference the
1013  * tableoid column, so initialize t_tableOid before evaluating them.
1014  */
1015  tuple->t_tableOid = RelationGetRelid(resultRelationDesc);
1016  }
1017  else
1018  {
1019  LockTupleMode lockmode;
1020 
1021  /*
1022  * Constraints might reference the tableoid column, so initialize
1023  * t_tableOid before evaluating them.
1024  */
1025  tuple->t_tableOid = RelationGetRelid(resultRelationDesc);
1026 
1027  /*
1028  * Check any RLS UPDATE WITH CHECK policies
1029  *
1030  * If we generate a new candidate tuple after EvalPlanQual testing, we
1031  * must loop back here and recheck any RLS policies and constraints.
1032  * (We don't need to redo triggers, however. If there are any BEFORE
1033  * triggers then trigger.c will have done heap_lock_tuple to lock the
1034  * correct tuple, so there's no need to do them again.)
1035  *
1036  * ExecWithCheckOptions() will skip any WCOs which are not of the kind
1037  * we are looking for at this point.
1038  */
1039 lreplace:;
1040  if (resultRelInfo->ri_WithCheckOptions != NIL)
1042  resultRelInfo, slot, estate);
1043 
1044  /*
1045  * Check the constraints of the tuple. Note that we pass the same
1046  * slot for the orig_slot argument, because unlike ExecInsert(), no
1047  * tuple-routing is performed here, hence the slot remains unchanged.
1048  */
1049  if (resultRelationDesc->rd_att->constr || resultRelInfo->ri_PartitionCheck)
1050  ExecConstraints(resultRelInfo, slot, estate);
1051 
1052  /*
1053  * replace the heap tuple
1054  *
1055  * Note: if es_crosscheck_snapshot isn't InvalidSnapshot, we check
1056  * that the row to be updated is visible to that snapshot, and throw a
1057  * can't-serialize error if not. This is a special-case behavior
1058  * needed for referential integrity updates in transaction-snapshot
1059  * mode transactions.
1060  */
1061  result = heap_update(resultRelationDesc, tupleid, tuple,
1062  estate->es_output_cid,
1063  estate->es_crosscheck_snapshot,
1064  true /* wait for commit */ ,
1065  &hufd, &lockmode);
1066  switch (result)
1067  {
1068  case HeapTupleSelfUpdated:
1069 
1070  /*
1071  * The target tuple was already updated or deleted by the
1072  * current command, or by a later command in the current
1073  * transaction. The former case is possible in a join UPDATE
1074  * where multiple tuples join to the same target tuple. This
1075  * is pretty questionable, but Postgres has always allowed it:
1076  * we just execute the first update action and ignore
1077  * additional update attempts.
1078  *
1079  * The latter case arises if the tuple is modified by a
1080  * command in a BEFORE trigger, or perhaps by a command in a
1081  * volatile function used in the query. In such situations we
1082  * should not ignore the update, but it is equally unsafe to
1083  * proceed. We don't want to discard the original UPDATE
1084  * while keeping the triggered actions based on it; and we
1085  * have no principled way to merge this update with the
1086  * previous ones. So throwing an error is the only safe
1087  * course.
1088  *
1089  * If a trigger actually intends this type of interaction, it
1090  * can re-execute the UPDATE (assuming it can figure out how)
1091  * and then return NULL to cancel the outer update.
1092  */
1093  if (hufd.cmax != estate->es_output_cid)
1094  ereport(ERROR,
1095  (errcode(ERRCODE_TRIGGERED_DATA_CHANGE_VIOLATION),
1096  errmsg("tuple to be updated was already modified by an operation triggered by the current command"),
1097  errhint("Consider using an AFTER trigger instead of a BEFORE trigger to propagate changes to other rows.")));
1098 
1099  /* Else, already updated by self; nothing to do */
1100  return NULL;
1101 
1102  case HeapTupleMayBeUpdated:
1103  break;
1104 
1105  case HeapTupleUpdated:
1107  ereport(ERROR,
1108  (errcode(ERRCODE_T_R_SERIALIZATION_FAILURE),
1109  errmsg("could not serialize access due to concurrent update")));
1110  if (!ItemPointerEquals(tupleid, &hufd.ctid))
1111  {
1112  TupleTableSlot *epqslot;
1113 
1114  epqslot = EvalPlanQual(estate,
1115  epqstate,
1116  resultRelationDesc,
1117  resultRelInfo->ri_RangeTableIndex,
1118  lockmode,
1119  &hufd.ctid,
1120  hufd.xmax);
1121  if (!TupIsNull(epqslot))
1122  {
1123  *tupleid = hufd.ctid;
1124  slot = ExecFilterJunk(resultRelInfo->ri_junkFilter, epqslot);
1125  tuple = ExecMaterializeSlot(slot);
1126  goto lreplace;
1127  }
1128  }
1129  /* tuple already deleted; nothing to do */
1130  return NULL;
1131 
1132  default:
1133  elog(ERROR, "unrecognized heap_update status: %u", result);
1134  return NULL;
1135  }
1136 
1137  /*
1138  * Note: instead of having to update the old index tuples associated
1139  * with the heap tuple, all we do is form and insert new index tuples.
1140  * This is because UPDATEs are actually DELETEs and INSERTs, and index
1141  * tuple deletion is done later by VACUUM (see notes in ExecDelete).
1142  * All we do here is insert new index tuples. -cim 9/27/89
1143  */
1144 
1145  /*
1146  * insert index entries for tuple
1147  *
1148  * Note: heap_update returns the tid (location) of the new tuple in
1149  * the t_self field.
1150  *
1151  * If it's a HOT update, we mustn't insert new index entries.
1152  */
1153  if (resultRelInfo->ri_NumIndices > 0 && !HeapTupleIsHeapOnly(tuple))
1154  recheckIndexes = ExecInsertIndexTuples(slot, &(tuple->t_self),
1155  estate, false, NULL, NIL);
1156  }
1157 
1158  if (canSetTag)
1159  (estate->es_processed)++;
1160 
1161  /* AFTER ROW UPDATE Triggers */
1162  ExecARUpdateTriggers(estate, resultRelInfo, tupleid, oldtuple, tuple,
1163  recheckIndexes,
1164  mtstate->operation == CMD_INSERT ?
1165  mtstate->mt_oc_transition_capture :
1166  mtstate->mt_transition_capture);
1167 
1168  list_free(recheckIndexes);
1169 
1170  /*
1171  * Check any WITH CHECK OPTION constraints from parent views. We are
1172  * required to do this after testing all constraints and uniqueness
1173  * violations per the SQL spec, so we do it after actually updating the
1174  * record in the heap and all indexes.
1175  *
1176  * ExecWithCheckOptions() will skip any WCOs which are not of the kind we
1177  * are looking for at this point.
1178  */
1179  if (resultRelInfo->ri_WithCheckOptions != NIL)
1180  ExecWithCheckOptions(WCO_VIEW_CHECK, resultRelInfo, slot, estate);
1181 
1182  /* Process RETURNING if present */
1183  if (resultRelInfo->ri_projectReturning)
1184  return ExecProcessReturning(resultRelInfo, slot, planSlot);
1185 
1186  return NULL;
1187 }
int ri_NumIndices
Definition: execnodes.h:357
#define NIL
Definition: pg_list.h:69
JunkFilter * ri_junkFilter
Definition: execnodes.h:396
struct TransitionCaptureState * mt_oc_transition_capture
Definition: execnodes.h:987
Relation ri_RelationDesc
Definition: execnodes.h:354
int errhint(const char *fmt,...)
Definition: elog.c:987
void ExecWithCheckOptions(WCOKind kind, ResultRelInfo *resultRelInfo, TupleTableSlot *slot, EState *estate)
Definition: execMain.c:2074
CommandId es_output_cid
Definition: execnodes.h:438
List * ExecInsertIndexTuples(TupleTableSlot *slot, ItemPointer tupleid, EState *estate, bool noDupErr, bool *specConflict, List *arbiterIndexes)
Definition: execIndexing.c:271
TupleTableSlot * EvalPlanQual(EState *estate, EPQState *epqstate, Relation relation, Index rti, int lockmode, ItemPointer tid, TransactionId priorXmax)
Definition: execMain.c:2479
TupleTableSlot * ExecBRUpdateTriggers(EState *estate, EPQState *epqstate, ResultRelInfo *relinfo, ItemPointer tupleid, HeapTuple fdw_trigtuple, TupleTableSlot *slot)
Definition: trigger.c:2724
void ExecConstraints(ResultRelInfo *resultRelInfo, TupleTableSlot *slot, EState *estate)
Definition: execMain.c:1942
#define IsolationUsesXactSnapshot()
Definition: xact.h:43
Snapshot es_crosscheck_snapshot
Definition: execnodes.h:430
int errcode(int sqlerrcode)
Definition: elog.c:575
CmdType operation
Definition: execnodes.h:958
Index ri_RangeTableIndex
Definition: execnodes.h:351
TupleTableSlot * ExecIRUpdateTriggers(EState *estate, ResultRelInfo *relinfo, HeapTuple trigtuple, TupleTableSlot *slot)
Definition: trigger.c:2878
LockTupleMode
Definition: heapam.h:38
#define ERROR
Definition: elog.h:43
ItemPointerData t_self
Definition: htup.h:65
struct TransitionCaptureState * mt_transition_capture
Definition: execnodes.h:985
CommandId cmax
Definition: heapam.h:72
bool trig_update_before_row
Definition: reltrigger.h:60
HTSU_Result
Definition: snapshot.h:121
ProjectionInfo * ri_projectReturning
Definition: execnodes.h:399
#define TupIsNull(slot)
Definition: tuptable.h:138
struct FdwRoutine * ri_FdwRoutine
Definition: execnodes.h:378
Oid t_tableOid
Definition: htup.h:66
#define ereport(elevel, rest)
Definition: elog.h:122
TriggerDesc * ri_TrigDesc
Definition: execnodes.h:366
void ExecARUpdateTriggers(EState *estate, ResultRelInfo *relinfo, ItemPointer tupleid, HeapTuple fdw_trigtuple, HeapTuple newtuple, List *recheckIndexes, TransitionCaptureState *transition_capture)
Definition: trigger.c:2841
bool trig_update_instead_row
Definition: reltrigger.h:62
static TupleTableSlot * ExecProcessReturning(ResultRelInfo *resultRelInfo, TupleTableSlot *tupleSlot, TupleTableSlot *planSlot)
TransactionId xmax
Definition: heapam.h:71
TupleTableSlot * ExecFilterJunk(JunkFilter *junkfilter, TupleTableSlot *slot)
Definition: execJunk.c:262
List * ri_WithCheckOptions
Definition: execnodes.h:387
List * ri_PartitionCheck
Definition: execnodes.h:408
TupleDesc rd_att
Definition: rel.h:115
HTSU_Result heap_update(Relation relation, ItemPointer otid, HeapTuple newtup, CommandId cid, Snapshot crosscheck, bool wait, HeapUpdateFailureData *hufd, LockTupleMode *lockmode)
Definition: heapam.c:3479
ExecForeignUpdate_function ExecForeignUpdate
Definition: fdwapi.h:201
#define HeapTupleIsHeapOnly(tuple)
Definition: htup_details.h:686
uint64 es_processed
Definition: execnodes.h:477
TupleConstr * constr
Definition: tupdesc.h:78
HeapTuple ExecMaterializeSlot(TupleTableSlot *slot)
Definition: execTuples.c:725
bool ItemPointerEquals(ItemPointer pointer1, ItemPointer pointer2)
Definition: itemptr.c:29
#define IsBootstrapProcessingMode()
Definition: miscadmin.h:368
int errmsg(const char *fmt,...)
Definition: elog.c:797
void list_free(List *list)
Definition: list.c:1133
ItemPointerData ctid
Definition: heapam.h:70
#define elog
Definition: elog.h:219
Definition: pg_list.h:45
#define RelationGetRelid(relation)
Definition: rel.h:416
ResultRelInfo * es_result_relation_info
Definition: execnodes.h:443
static void fireASTriggers ( ModifyTableState node)
static

Definition at line 1442 of file nodeModifyTable.c.

References CMD_DELETE, CMD_INSERT, CMD_UPDATE, elog, ERROR, ExecASDeleteTriggers(), ExecASInsertTriggers(), ExecASUpdateTriggers(), getASTriggerResultRelInfo(), ModifyTableState::mt_oc_transition_capture, ModifyTableState::mt_onconflict, ModifyTableState::mt_transition_capture, ONCONFLICT_UPDATE, ModifyTableState::operation, ModifyTableState::ps, and PlanState::state.

Referenced by ExecModifyTable().

1443 {
1444  ResultRelInfo *resultRelInfo = getASTriggerResultRelInfo(node);
1445 
1446  switch (node->operation)
1447  {
1448  case CMD_INSERT:
1449  if (node->mt_onconflict == ONCONFLICT_UPDATE)
1451  resultRelInfo,
1452  node->mt_oc_transition_capture);
1453  ExecASInsertTriggers(node->ps.state, resultRelInfo,
1454  node->mt_transition_capture);
1455  break;
1456  case CMD_UPDATE:
1457  ExecASUpdateTriggers(node->ps.state, resultRelInfo,
1458  node->mt_transition_capture);
1459  break;
1460  case CMD_DELETE:
1461  ExecASDeleteTriggers(node->ps.state, resultRelInfo,
1462  node->mt_transition_capture);
1463  break;
1464  default:
1465  elog(ERROR, "unknown operation");
1466  break;
1467  }
1468 }
static ResultRelInfo * getASTriggerResultRelInfo(ModifyTableState *node)
struct TransitionCaptureState * mt_oc_transition_capture
Definition: execnodes.h:987
CmdType operation
Definition: execnodes.h:958
EState * state
Definition: execnodes.h:849
void ExecASDeleteTriggers(EState *estate, ResultRelInfo *relinfo, TransitionCaptureState *transition_capture)
Definition: trigger.c:2492
OnConflictAction mt_onconflict
Definition: execnodes.h:970
#define ERROR
Definition: elog.h:43
PlanState ps
Definition: execnodes.h:957
struct TransitionCaptureState * mt_transition_capture
Definition: execnodes.h:985
void ExecASUpdateTriggers(EState *estate, ResultRelInfo *relinfo, TransitionCaptureState *transition_capture)
Definition: trigger.c:2711
void ExecASInsertTriggers(EState *estate, ResultRelInfo *relinfo, TransitionCaptureState *transition_capture)
Definition: trigger.c:2277
#define elog
Definition: elog.h:219
static void fireBSTriggers ( ModifyTableState node)
static

Definition at line 1387 of file nodeModifyTable.c.

References CMD_DELETE, CMD_INSERT, CMD_UPDATE, elog, ERROR, ExecBSDeleteTriggers(), ExecBSInsertTriggers(), ExecBSUpdateTriggers(), ModifyTableState::mt_onconflict, ONCONFLICT_UPDATE, ModifyTableState::operation, ModifyTableState::ps, ModifyTableState::resultRelInfo, ModifyTableState::rootResultRelInfo, and PlanState::state.

Referenced by ExecModifyTable().

1388 {
1389  ResultRelInfo *resultRelInfo = node->resultRelInfo;
1390 
1391  /*
1392  * If the node modifies a partitioned table, we must fire its triggers.
1393  * Note that in that case, node->resultRelInfo points to the first leaf
1394  * partition, not the root table.
1395  */
1396  if (node->rootResultRelInfo != NULL)
1397  resultRelInfo = node->rootResultRelInfo;
1398 
1399  switch (node->operation)
1400  {
1401  case CMD_INSERT:
1402  ExecBSInsertTriggers(node->ps.state, resultRelInfo);
1403  if (node->mt_onconflict == ONCONFLICT_UPDATE)
1405  resultRelInfo);
1406  break;
1407  case CMD_UPDATE:
1408  ExecBSUpdateTriggers(node->ps.state, resultRelInfo);
1409  break;
1410  case CMD_DELETE:
1411  ExecBSDeleteTriggers(node->ps.state, resultRelInfo);
1412  break;
1413  default:
1414  elog(ERROR, "unknown operation");
1415  break;
1416  }
1417 }
void ExecBSDeleteTriggers(EState *estate, ResultRelInfo *relinfo)
Definition: trigger.c:2435
ResultRelInfo * resultRelInfo
Definition: execnodes.h:964
CmdType operation
Definition: execnodes.h:958
ResultRelInfo * rootResultRelInfo
Definition: execnodes.h:965
EState * state
Definition: execnodes.h:849
OnConflictAction mt_onconflict
Definition: execnodes.h:970
#define ERROR
Definition: elog.h:43
PlanState ps
Definition: execnodes.h:957
void ExecBSInsertTriggers(EState *estate, ResultRelInfo *relinfo)
Definition: trigger.c:2220
void ExecBSUpdateTriggers(EState *estate, ResultRelInfo *relinfo)
Definition: trigger.c:2651
#define elog
Definition: elog.h:219
static ResultRelInfo* getASTriggerResultRelInfo ( ModifyTableState node)
static

Definition at line 1425 of file nodeModifyTable.c.

References ModifyTableState::resultRelInfo, and ModifyTableState::rootResultRelInfo.

Referenced by ExecSetupTransitionCaptureState(), and fireASTriggers().

1426 {
1427  /*
1428  * If the node modifies a partitioned table, we must fire its triggers.
1429  * Note that in that case, node->resultRelInfo points to the first leaf
1430  * partition, not the root table.
1431  */
1432  if (node->rootResultRelInfo != NULL)
1433  return node->rootResultRelInfo;
1434  else
1435  return node->resultRelInfo;
1436 }
ResultRelInfo * resultRelInfo
Definition: execnodes.h:964
ResultRelInfo * rootResultRelInfo
Definition: execnodes.h:965