PostgreSQL Source Code  git master
nodeModifyTable.c
Go to the documentation of this file.
1 /*-------------------------------------------------------------------------
2  *
3  * nodeModifyTable.c
4  * routines to handle ModifyTable nodes.
5  *
6  * Portions Copyright (c) 1996-2022, PostgreSQL Global Development Group
7  * Portions Copyright (c) 1994, Regents of the University of California
8  *
9  *
10  * IDENTIFICATION
11  * src/backend/executor/nodeModifyTable.c
12  *
13  *-------------------------------------------------------------------------
14  */
15 /* INTERFACE ROUTINES
16  * ExecInitModifyTable - initialize the ModifyTable node
17  * ExecModifyTable - retrieve the next tuple from the node
18  * ExecEndModifyTable - shut down the ModifyTable node
19  * ExecReScanModifyTable - rescan the ModifyTable node
20  *
21  * NOTES
22  * The ModifyTable node receives input from its outerPlan, which is
23  * the data to insert for INSERT cases, the changed columns' new
24  * values plus row-locating info for UPDATE and MERGE cases, or just the
25  * row-locating info for DELETE cases.
26  *
27  * MERGE runs a join between the source relation and the target
28  * table; if any WHEN NOT MATCHED clauses are present, then the
29  * join is an outer join. In this case, any unmatched tuples will
30  * have NULL row-locating info, and only INSERT can be run. But for
31  * matched tuples, then row-locating info is used to determine the
32  * tuple to UPDATE or DELETE. When all clauses are WHEN MATCHED,
33  * then an inner join is used, so all tuples contain row-locating info.
34  *
35  * If the query specifies RETURNING, then the ModifyTable returns a
36  * RETURNING tuple after completing each row insert, update, or delete.
37  * It must be called again to continue the operation. Without RETURNING,
38  * we just loop within the node until all the work is done, then
39  * return NULL. This avoids useless call/return overhead. (MERGE does
40  * not support RETURNING.)
41  */
42 
43 #include "postgres.h"
44 
45 #include "access/heapam.h"
46 #include "access/htup_details.h"
47 #include "access/tableam.h"
48 #include "access/xact.h"
49 #include "catalog/catalog.h"
50 #include "commands/trigger.h"
51 #include "executor/execPartition.h"
52 #include "executor/executor.h"
54 #include "foreign/fdwapi.h"
55 #include "miscadmin.h"
56 #include "nodes/nodeFuncs.h"
57 #include "rewrite/rewriteHandler.h"
58 #include "storage/bufmgr.h"
59 #include "storage/lmgr.h"
60 #include "utils/builtins.h"
61 #include "utils/datum.h"
62 #include "utils/memutils.h"
63 #include "utils/rel.h"
64 
65 
66 typedef struct MTTargetRelLookup
67 {
68  Oid relationOid; /* hash key, must be first */
69  int relationIndex; /* rel's index in resultRelInfo[] array */
71 
72 /*
73  * Context struct for a ModifyTable operation, containing basic execution
74  * state and some output variables populated by ExecUpdateAct() and
75  * ExecDeleteAct() to report the result of their actions to callers.
76  */
77 typedef struct ModifyTableContext
78 {
79  /* Operation state */
83 
84  /*
85  * Slot containing tuple obtained from ModifyTable's subplan. Used to
86  * access "junk" columns that are not going to be stored.
87  */
89 
90  /*
91  * During EvalPlanQual, project and return the new version of the new
92  * tuple
93  */
94  TupleTableSlot *(*GetUpdateNewTuple) (ResultRelInfo *resultRelInfo,
95  TupleTableSlot *epqslot,
96  TupleTableSlot *oldSlot,
98 
99  /* MERGE specific */
100  MergeActionState *relaction; /* MERGE action in progress */
101 
102  /*
103  * Information about the changes that were made concurrently to a tuple
104  * being updated or deleted
105  */
107 
108  /*
109  * The tuple produced by EvalPlanQual to retry from, if a cross-partition
110  * UPDATE requires it
111  */
113 
114  /*
115  * The tuple projected by the INSERT's RETURNING clause, when doing a
116  * cross-partition UPDATE
117  */
120 
121 /*
122  * Context struct containing output data specific to UPDATE operations.
123  */
124 typedef struct UpdateContext
125 {
126  bool updated; /* did UPDATE actually occur? */
127  bool updateIndexes; /* index update required? */
128  bool crossPartUpdate; /* was it a cross-partition update? */
129 
130  /*
131  * Lock mode to acquire on the latest tuple version before performing
132  * EvalPlanQual on it
133  */
136 
137 
138 static void ExecBatchInsert(ModifyTableState *mtstate,
139  ResultRelInfo *resultRelInfo,
140  TupleTableSlot **slots,
141  TupleTableSlot **planSlots,
142  int numSlots,
143  EState *estate,
144  bool canSetTag);
146  ResultRelInfo *sourcePartInfo,
147  ResultRelInfo *destPartInfo,
148  ItemPointer tupleid,
149  TupleTableSlot *oldslot,
150  TupleTableSlot *newslot);
151 static bool ExecOnConflictUpdate(ModifyTableContext *context,
152  ResultRelInfo *resultRelInfo,
153  ItemPointer conflictTid,
154  TupleTableSlot *excludedSlot,
155  bool canSetTag,
156  TupleTableSlot **returning);
158  EState *estate,
159  PartitionTupleRouting *proute,
160  ResultRelInfo *targetRelInfo,
161  TupleTableSlot *slot,
162  ResultRelInfo **partRelInfo);
164  TupleTableSlot *planSlot,
165  TupleTableSlot *oldSlot,
166  MergeActionState *relaction);
167 
169  ResultRelInfo *resultRelInfo,
170  ItemPointer tupleid,
171  bool canSetTag);
172 static void ExecInitMerge(ModifyTableState *mtstate, EState *estate);
173 static bool ExecMergeMatched(ModifyTableContext *context,
174  ResultRelInfo *resultRelInfo,
175  ItemPointer tupleid,
176  bool canSetTag);
177 static void ExecMergeNotMatched(ModifyTableContext *context,
178  ResultRelInfo *resultRelInfo,
179  bool canSetTag);
181  TupleTableSlot *planSlot,
182  TupleTableSlot *oldSlot,
183  MergeActionState *relaction);
184 
185 
186 /*
187  * Verify that the tuples to be produced by INSERT match the
188  * target relation's rowtype
189  *
190  * We do this to guard against stale plans. If plan invalidation is
191  * functioning properly then we should never get a failure here, but better
192  * safe than sorry. Note that this is called after we have obtained lock
193  * on the target rel, so the rowtype can't change underneath us.
194  *
195  * The plan output is represented by its targetlist, because that makes
196  * handling the dropped-column case easier.
197  *
198  * We used to use this for UPDATE as well, but now the equivalent checks
199  * are done in ExecBuildUpdateProjection.
200  */
201 static void
202 ExecCheckPlanOutput(Relation resultRel, List *targetList)
203 {
204  TupleDesc resultDesc = RelationGetDescr(resultRel);
205  int attno = 0;
206  ListCell *lc;
207 
208  foreach(lc, targetList)
209  {
210  TargetEntry *tle = (TargetEntry *) lfirst(lc);
211  Form_pg_attribute attr;
212 
213  Assert(!tle->resjunk); /* caller removed junk items already */
214 
215  if (attno >= resultDesc->natts)
216  ereport(ERROR,
217  (errcode(ERRCODE_DATATYPE_MISMATCH),
218  errmsg("table row type and query-specified row type do not match"),
219  errdetail("Query has too many columns.")));
220  attr = TupleDescAttr(resultDesc, attno);
221  attno++;
222 
223  if (!attr->attisdropped)
224  {
225  /* Normal case: demand type match */
226  if (exprType((Node *) tle->expr) != attr->atttypid)
227  ereport(ERROR,
228  (errcode(ERRCODE_DATATYPE_MISMATCH),
229  errmsg("table row type and query-specified row type do not match"),
230  errdetail("Table has type %s at ordinal position %d, but query expects %s.",
231  format_type_be(attr->atttypid),
232  attno,
233  format_type_be(exprType((Node *) tle->expr)))));
234  }
235  else
236  {
237  /*
238  * For a dropped column, we can't check atttypid (it's likely 0).
239  * In any case the planner has most likely inserted an INT4 null.
240  * What we insist on is just *some* NULL constant.
241  */
242  if (!IsA(tle->expr, Const) ||
243  !((Const *) tle->expr)->constisnull)
244  ereport(ERROR,
245  (errcode(ERRCODE_DATATYPE_MISMATCH),
246  errmsg("table row type and query-specified row type do not match"),
247  errdetail("Query provides a value for a dropped column at ordinal position %d.",
248  attno)));
249  }
250  }
251  if (attno != resultDesc->natts)
252  ereport(ERROR,
253  (errcode(ERRCODE_DATATYPE_MISMATCH),
254  errmsg("table row type and query-specified row type do not match"),
255  errdetail("Query has too few columns.")));
256 }
257 
258 /*
259  * ExecProcessReturning --- evaluate a RETURNING list
260  *
261  * resultRelInfo: current result rel
262  * tupleSlot: slot holding tuple actually inserted/updated/deleted
263  * planSlot: slot holding tuple returned by top subplan node
264  *
265  * Note: If tupleSlot is NULL, the FDW should have already provided econtext's
266  * scan tuple.
267  *
268  * Returns a slot holding the result tuple
269  */
270 static TupleTableSlot *
272  TupleTableSlot *tupleSlot,
273  TupleTableSlot *planSlot)
274 {
275  ProjectionInfo *projectReturning = resultRelInfo->ri_projectReturning;
276  ExprContext *econtext = projectReturning->pi_exprContext;
277 
278  /* Make tuple and any needed join variables available to ExecProject */
279  if (tupleSlot)
280  econtext->ecxt_scantuple = tupleSlot;
281  econtext->ecxt_outertuple = planSlot;
282 
283  /*
284  * RETURNING expressions might reference the tableoid column, so
285  * reinitialize tts_tableOid before evaluating them.
286  */
287  econtext->ecxt_scantuple->tts_tableOid =
288  RelationGetRelid(resultRelInfo->ri_RelationDesc);
289 
290  /* Compute the RETURNING expressions */
291  return ExecProject(projectReturning);
292 }
293 
294 /*
295  * ExecCheckTupleVisible -- verify tuple is visible
296  *
297  * It would not be consistent with guarantees of the higher isolation levels to
298  * proceed with avoiding insertion (taking speculative insertion's alternative
299  * path) on the basis of another tuple that is not visible to MVCC snapshot.
300  * Check for the need to raise a serialization failure, and do so as necessary.
301  */
302 static void
304  Relation rel,
305  TupleTableSlot *slot)
306 {
308  return;
309 
310  if (!table_tuple_satisfies_snapshot(rel, slot, estate->es_snapshot))
311  {
312  Datum xminDatum;
313  TransactionId xmin;
314  bool isnull;
315 
316  xminDatum = slot_getsysattr(slot, MinTransactionIdAttributeNumber, &isnull);
317  Assert(!isnull);
318  xmin = DatumGetTransactionId(xminDatum);
319 
320  /*
321  * We should not raise a serialization failure if the conflict is
322  * against a tuple inserted by our own transaction, even if it's not
323  * visible to our snapshot. (This would happen, for example, if
324  * conflicting keys are proposed for insertion in a single command.)
325  */
327  ereport(ERROR,
329  errmsg("could not serialize access due to concurrent update")));
330  }
331 }
332 
333 /*
334  * ExecCheckTIDVisible -- convenience variant of ExecCheckTupleVisible()
335  */
336 static void
338  ResultRelInfo *relinfo,
339  ItemPointer tid,
340  TupleTableSlot *tempSlot)
341 {
342  Relation rel = relinfo->ri_RelationDesc;
343 
344  /* Redundantly check isolation level */
346  return;
347 
348  if (!table_tuple_fetch_row_version(rel, tid, SnapshotAny, tempSlot))
349  elog(ERROR, "failed to fetch conflicting tuple for ON CONFLICT");
350  ExecCheckTupleVisible(estate, rel, tempSlot);
351  ExecClearTuple(tempSlot);
352 }
353 
354 /*
355  * Compute stored generated columns for a tuple
356  */
357 void
359  EState *estate, TupleTableSlot *slot,
360  CmdType cmdtype)
361 {
362  Relation rel = resultRelInfo->ri_RelationDesc;
363  TupleDesc tupdesc = RelationGetDescr(rel);
364  int natts = tupdesc->natts;
365  MemoryContext oldContext;
366  Datum *values;
367  bool *nulls;
368 
369  Assert(tupdesc->constr && tupdesc->constr->has_generated_stored);
370 
371  /*
372  * If first time through for this result relation, build expression
373  * nodetrees for rel's stored generation expressions. Keep them in the
374  * per-query memory context so they'll survive throughout the query.
375  */
376  if (resultRelInfo->ri_GeneratedExprs == NULL)
377  {
378  oldContext = MemoryContextSwitchTo(estate->es_query_cxt);
379 
380  resultRelInfo->ri_GeneratedExprs =
381  (ExprState **) palloc(natts * sizeof(ExprState *));
382  resultRelInfo->ri_NumGeneratedNeeded = 0;
383 
384  for (int i = 0; i < natts; i++)
385  {
386  if (TupleDescAttr(tupdesc, i)->attgenerated == ATTRIBUTE_GENERATED_STORED)
387  {
388  Expr *expr;
389 
390  /*
391  * If it's an update and the current column was not marked as
392  * being updated, then we can skip the computation. But if
393  * there is a BEFORE ROW UPDATE trigger, we cannot skip
394  * because the trigger might affect additional columns.
395  */
396  if (cmdtype == CMD_UPDATE &&
397  !(rel->trigdesc && rel->trigdesc->trig_update_before_row) &&
399  ExecGetExtraUpdatedCols(resultRelInfo, estate)))
400  {
401  resultRelInfo->ri_GeneratedExprs[i] = NULL;
402  continue;
403  }
404 
405  expr = (Expr *) build_column_default(rel, i + 1);
406  if (expr == NULL)
407  elog(ERROR, "no generation expression found for column number %d of table \"%s\"",
408  i + 1, RelationGetRelationName(rel));
409 
410  resultRelInfo->ri_GeneratedExprs[i] = ExecPrepareExpr(expr, estate);
411  resultRelInfo->ri_NumGeneratedNeeded++;
412  }
413  }
414 
415  MemoryContextSwitchTo(oldContext);
416  }
417 
418  /*
419  * If no generated columns have been affected by this change, then skip
420  * the rest.
421  */
422  if (resultRelInfo->ri_NumGeneratedNeeded == 0)
423  return;
424 
425  oldContext = MemoryContextSwitchTo(GetPerTupleMemoryContext(estate));
426 
427  values = palloc(sizeof(*values) * natts);
428  nulls = palloc(sizeof(*nulls) * natts);
429 
430  slot_getallattrs(slot);
431  memcpy(nulls, slot->tts_isnull, sizeof(*nulls) * natts);
432 
433  for (int i = 0; i < natts; i++)
434  {
435  Form_pg_attribute attr = TupleDescAttr(tupdesc, i);
436 
437  if (attr->attgenerated == ATTRIBUTE_GENERATED_STORED &&
438  resultRelInfo->ri_GeneratedExprs[i])
439  {
440  ExprContext *econtext;
441  Datum val;
442  bool isnull;
443 
444  econtext = GetPerTupleExprContext(estate);
445  econtext->ecxt_scantuple = slot;
446 
447  val = ExecEvalExpr(resultRelInfo->ri_GeneratedExprs[i], econtext, &isnull);
448 
449  /*
450  * We must make a copy of val as we have no guarantees about where
451  * memory for a pass-by-reference Datum is located.
452  */
453  if (!isnull)
454  val = datumCopy(val, attr->attbyval, attr->attlen);
455 
456  values[i] = val;
457  nulls[i] = isnull;
458  }
459  else
460  {
461  if (!nulls[i])
462  values[i] = datumCopy(slot->tts_values[i], attr->attbyval, attr->attlen);
463  }
464  }
465 
466  ExecClearTuple(slot);
467  memcpy(slot->tts_values, values, sizeof(*values) * natts);
468  memcpy(slot->tts_isnull, nulls, sizeof(*nulls) * natts);
469  ExecStoreVirtualTuple(slot);
470  ExecMaterializeSlot(slot);
471 
472  MemoryContextSwitchTo(oldContext);
473 }
474 
475 /*
476  * ExecInitInsertProjection
477  * Do one-time initialization of projection data for INSERT tuples.
478  *
479  * INSERT queries may need a projection to filter out junk attrs in the tlist.
480  *
481  * This is also a convenient place to verify that the
482  * output of an INSERT matches the target table.
483  */
484 static void
486  ResultRelInfo *resultRelInfo)
487 {
488  ModifyTable *node = (ModifyTable *) mtstate->ps.plan;
489  Plan *subplan = outerPlan(node);
490  EState *estate = mtstate->ps.state;
491  List *insertTargetList = NIL;
492  bool need_projection = false;
493  ListCell *l;
494 
495  /* Extract non-junk columns of the subplan's result tlist. */
496  foreach(l, subplan->targetlist)
497  {
498  TargetEntry *tle = (TargetEntry *) lfirst(l);
499 
500  if (!tle->resjunk)
501  insertTargetList = lappend(insertTargetList, tle);
502  else
503  need_projection = true;
504  }
505 
506  /*
507  * The junk-free list must produce a tuple suitable for the result
508  * relation.
509  */
510  ExecCheckPlanOutput(resultRelInfo->ri_RelationDesc, insertTargetList);
511 
512  /* We'll need a slot matching the table's format. */
513  resultRelInfo->ri_newTupleSlot =
514  table_slot_create(resultRelInfo->ri_RelationDesc,
515  &estate->es_tupleTable);
516 
517  /* Build ProjectionInfo if needed (it probably isn't). */
518  if (need_projection)
519  {
520  TupleDesc relDesc = RelationGetDescr(resultRelInfo->ri_RelationDesc);
521 
522  /* need an expression context to do the projection */
523  if (mtstate->ps.ps_ExprContext == NULL)
524  ExecAssignExprContext(estate, &mtstate->ps);
525 
526  resultRelInfo->ri_projectNew =
527  ExecBuildProjectionInfo(insertTargetList,
528  mtstate->ps.ps_ExprContext,
529  resultRelInfo->ri_newTupleSlot,
530  &mtstate->ps,
531  relDesc);
532  }
533 
534  resultRelInfo->ri_projectNewInfoValid = true;
535 }
536 
537 /*
538  * ExecInitUpdateProjection
539  * Do one-time initialization of projection data for UPDATE tuples.
540  *
541  * UPDATE always needs a projection, because (1) there's always some junk
542  * attrs, and (2) we may need to merge values of not-updated columns from
543  * the old tuple into the final tuple. In UPDATE, the tuple arriving from
544  * the subplan contains only new values for the changed columns, plus row
545  * identity info in the junk attrs.
546  *
547  * This is "one-time" for any given result rel, but we might touch more than
548  * one result rel in the course of an inherited UPDATE, and each one needs
549  * its own projection due to possible column order variation.
550  *
551  * This is also a convenient place to verify that the output of an UPDATE
552  * matches the target table (ExecBuildUpdateProjection does that).
553  */
554 static void
556  ResultRelInfo *resultRelInfo)
557 {
558  ModifyTable *node = (ModifyTable *) mtstate->ps.plan;
559  Plan *subplan = outerPlan(node);
560  EState *estate = mtstate->ps.state;
561  TupleDesc relDesc = RelationGetDescr(resultRelInfo->ri_RelationDesc);
562  int whichrel;
563  List *updateColnos;
564 
565  /*
566  * Usually, mt_lastResultIndex matches the target rel. If it happens not
567  * to, we can get the index the hard way with an integer division.
568  */
569  whichrel = mtstate->mt_lastResultIndex;
570  if (resultRelInfo != mtstate->resultRelInfo + whichrel)
571  {
572  whichrel = resultRelInfo - mtstate->resultRelInfo;
573  Assert(whichrel >= 0 && whichrel < mtstate->mt_nrels);
574  }
575 
576  updateColnos = (List *) list_nth(node->updateColnosLists, whichrel);
577 
578  /*
579  * For UPDATE, we use the old tuple to fill up missing values in the tuple
580  * produced by the subplan to get the new tuple. We need two slots, both
581  * matching the table's desired format.
582  */
583  resultRelInfo->ri_oldTupleSlot =
584  table_slot_create(resultRelInfo->ri_RelationDesc,
585  &estate->es_tupleTable);
586  resultRelInfo->ri_newTupleSlot =
587  table_slot_create(resultRelInfo->ri_RelationDesc,
588  &estate->es_tupleTable);
589 
590  /* need an expression context to do the projection */
591  if (mtstate->ps.ps_ExprContext == NULL)
592  ExecAssignExprContext(estate, &mtstate->ps);
593 
594  resultRelInfo->ri_projectNew =
595  ExecBuildUpdateProjection(subplan->targetlist,
596  false, /* subplan did the evaluation */
597  updateColnos,
598  relDesc,
599  mtstate->ps.ps_ExprContext,
600  resultRelInfo->ri_newTupleSlot,
601  &mtstate->ps);
602 
603  resultRelInfo->ri_projectNewInfoValid = true;
604 }
605 
606 /*
607  * ExecGetInsertNewTuple
608  * This prepares a "new" tuple ready to be inserted into given result
609  * relation, by removing any junk columns of the plan's output tuple
610  * and (if necessary) coercing the tuple to the right tuple format.
611  */
612 static TupleTableSlot *
614  TupleTableSlot *planSlot)
615 {
616  ProjectionInfo *newProj = relinfo->ri_projectNew;
617  ExprContext *econtext;
618 
619  /*
620  * If there's no projection to be done, just make sure the slot is of the
621  * right type for the target rel. If the planSlot is the right type we
622  * can use it as-is, else copy the data into ri_newTupleSlot.
623  */
624  if (newProj == NULL)
625  {
626  if (relinfo->ri_newTupleSlot->tts_ops != planSlot->tts_ops)
627  {
628  ExecCopySlot(relinfo->ri_newTupleSlot, planSlot);
629  return relinfo->ri_newTupleSlot;
630  }
631  else
632  return planSlot;
633  }
634 
635  /*
636  * Else project; since the projection output slot is ri_newTupleSlot, this
637  * will also fix any slot-type problem.
638  *
639  * Note: currently, this is dead code, because INSERT cases don't receive
640  * any junk columns so there's never a projection to be done.
641  */
642  econtext = newProj->pi_exprContext;
643  econtext->ecxt_outertuple = planSlot;
644  return ExecProject(newProj);
645 }
646 
647 /*
648  * ExecGetUpdateNewTuple
649  * This prepares a "new" tuple by combining an UPDATE subplan's output
650  * tuple (which contains values of changed columns) with unchanged
651  * columns taken from the old tuple.
652  *
653  * The subplan tuple might also contain junk columns, which are ignored.
654  * Note that the projection also ensures we have a slot of the right type.
655  */
658  TupleTableSlot *planSlot,
659  TupleTableSlot *oldSlot)
660 {
661  /* Use a few extra Asserts to protect against outside callers */
662  Assert(relinfo->ri_projectNewInfoValid);
663  Assert(planSlot != NULL && !TTS_EMPTY(planSlot));
664  Assert(oldSlot != NULL && !TTS_EMPTY(oldSlot));
665 
666  return internalGetUpdateNewTuple(relinfo, planSlot, oldSlot, NULL);
667 }
668 
669 /*
670  * Callback for ModifyTableState->GetUpdateNewTuple for use by regular UPDATE.
671  */
672 static TupleTableSlot *
674  TupleTableSlot *planSlot,
675  TupleTableSlot *oldSlot,
676  MergeActionState *relaction)
677 {
678  ProjectionInfo *newProj = relinfo->ri_projectNew;
679  ExprContext *econtext;
680 
681  econtext = newProj->pi_exprContext;
682  econtext->ecxt_outertuple = planSlot;
683  econtext->ecxt_scantuple = oldSlot;
684  return ExecProject(newProj);
685 }
686 
687 /* ----------------------------------------------------------------
688  * ExecInsert
689  *
690  * For INSERT, we have to insert the tuple into the target relation
691  * (or partition thereof) and insert appropriate tuples into the index
692  * relations.
693  *
694  * slot contains the new tuple value to be stored.
695  *
696  * Returns RETURNING result if any, otherwise NULL.
697  * *inserted_tuple is the tuple that's effectively inserted;
698  * *inserted_destrel is the relation where it was inserted.
699  * These are only set on success.
700  *
701  * This may change the currently active tuple conversion map in
702  * mtstate->mt_transition_capture, so the callers must take care to
703  * save the previous value to avoid losing track of it.
704  * ----------------------------------------------------------------
705  */
706 static TupleTableSlot *
708  ResultRelInfo *resultRelInfo,
709  TupleTableSlot *slot,
710  bool canSetTag,
711  TupleTableSlot **inserted_tuple,
712  ResultRelInfo **insert_destrel)
713 {
714  ModifyTableState *mtstate = context->mtstate;
715  EState *estate = context->estate;
716  Relation resultRelationDesc;
717  List *recheckIndexes = NIL;
718  TupleTableSlot *planSlot = context->planSlot;
719  TupleTableSlot *result = NULL;
720  TransitionCaptureState *ar_insert_trig_tcs;
721  ModifyTable *node = (ModifyTable *) mtstate->ps.plan;
722  OnConflictAction onconflict = node->onConflictAction;
724  MemoryContext oldContext;
725 
726  /*
727  * If the input result relation is a partitioned table, find the leaf
728  * partition to insert the tuple into.
729  */
730  if (proute)
731  {
732  ResultRelInfo *partRelInfo;
733 
734  slot = ExecPrepareTupleRouting(mtstate, estate, proute,
735  resultRelInfo, slot,
736  &partRelInfo);
737  resultRelInfo = partRelInfo;
738  }
739 
740  ExecMaterializeSlot(slot);
741 
742  resultRelationDesc = resultRelInfo->ri_RelationDesc;
743 
744  /*
745  * Open the table's indexes, if we have not done so already, so that we
746  * can add new index entries for the inserted tuple.
747  */
748  if (resultRelationDesc->rd_rel->relhasindex &&
749  resultRelInfo->ri_IndexRelationDescs == NULL)
750  ExecOpenIndices(resultRelInfo, onconflict != ONCONFLICT_NONE);
751 
752  /*
753  * BEFORE ROW INSERT Triggers.
754  *
755  * Note: We fire BEFORE ROW TRIGGERS for every attempted insertion in an
756  * INSERT ... ON CONFLICT statement. We cannot check for constraint
757  * violations before firing these triggers, because they can change the
758  * values to insert. Also, they can run arbitrary user-defined code with
759  * side-effects that we can't cancel by just not inserting the tuple.
760  */
761  if (resultRelInfo->ri_TrigDesc &&
762  resultRelInfo->ri_TrigDesc->trig_insert_before_row)
763  {
764  if (!ExecBRInsertTriggers(estate, resultRelInfo, slot))
765  return NULL; /* "do nothing" */
766  }
767 
768  /* INSTEAD OF ROW INSERT Triggers */
769  if (resultRelInfo->ri_TrigDesc &&
770  resultRelInfo->ri_TrigDesc->trig_insert_instead_row)
771  {
772  if (!ExecIRInsertTriggers(estate, resultRelInfo, slot))
773  return NULL; /* "do nothing" */
774  }
775  else if (resultRelInfo->ri_FdwRoutine)
776  {
777  /*
778  * GENERATED expressions might reference the tableoid column, so
779  * (re-)initialize tts_tableOid before evaluating them.
780  */
781  slot->tts_tableOid = RelationGetRelid(resultRelInfo->ri_RelationDesc);
782 
783  /*
784  * Compute stored generated columns
785  */
786  if (resultRelationDesc->rd_att->constr &&
787  resultRelationDesc->rd_att->constr->has_generated_stored)
788  ExecComputeStoredGenerated(resultRelInfo, estate, slot,
789  CMD_INSERT);
790 
791  /*
792  * If the FDW supports batching, and batching is requested, accumulate
793  * rows and insert them in batches. Otherwise use the per-row inserts.
794  */
795  if (resultRelInfo->ri_BatchSize > 1)
796  {
797  /*
798  * If a certain number of tuples have already been accumulated, or
799  * a tuple has come for a different relation than that for the
800  * accumulated tuples, perform the batch insert
801  */
802  if (resultRelInfo->ri_NumSlots == resultRelInfo->ri_BatchSize)
803  {
804  ExecBatchInsert(mtstate, resultRelInfo,
805  resultRelInfo->ri_Slots,
806  resultRelInfo->ri_PlanSlots,
807  resultRelInfo->ri_NumSlots,
808  estate, canSetTag);
809  resultRelInfo->ri_NumSlots = 0;
810  }
811 
812  oldContext = MemoryContextSwitchTo(estate->es_query_cxt);
813 
814  if (resultRelInfo->ri_Slots == NULL)
815  {
816  resultRelInfo->ri_Slots = palloc(sizeof(TupleTableSlot *) *
817  resultRelInfo->ri_BatchSize);
818  resultRelInfo->ri_PlanSlots = palloc(sizeof(TupleTableSlot *) *
819  resultRelInfo->ri_BatchSize);
820  }
821 
822  /*
823  * Initialize the batch slots. We don't know how many slots will
824  * be needed, so we initialize them as the batch grows, and we
825  * keep them across batches. To mitigate an inefficiency in how
826  * resource owner handles objects with many references (as with
827  * many slots all referencing the same tuple descriptor) we copy
828  * the appropriate tuple descriptor for each slot.
829  */
830  if (resultRelInfo->ri_NumSlots >= resultRelInfo->ri_NumSlotsInitialized)
831  {
833  TupleDesc plan_tdesc =
835 
836  resultRelInfo->ri_Slots[resultRelInfo->ri_NumSlots] =
837  MakeSingleTupleTableSlot(tdesc, slot->tts_ops);
838 
839  resultRelInfo->ri_PlanSlots[resultRelInfo->ri_NumSlots] =
840  MakeSingleTupleTableSlot(plan_tdesc, planSlot->tts_ops);
841 
842  /* remember how many batch slots we initialized */
843  resultRelInfo->ri_NumSlotsInitialized++;
844  }
845 
846  ExecCopySlot(resultRelInfo->ri_Slots[resultRelInfo->ri_NumSlots],
847  slot);
848 
849  ExecCopySlot(resultRelInfo->ri_PlanSlots[resultRelInfo->ri_NumSlots],
850  planSlot);
851 
852  resultRelInfo->ri_NumSlots++;
853 
854  MemoryContextSwitchTo(oldContext);
855 
856  return NULL;
857  }
858 
859  /*
860  * insert into foreign table: let the FDW do it
861  */
862  slot = resultRelInfo->ri_FdwRoutine->ExecForeignInsert(estate,
863  resultRelInfo,
864  slot,
865  planSlot);
866 
867  if (slot == NULL) /* "do nothing" */
868  return NULL;
869 
870  /*
871  * AFTER ROW Triggers or RETURNING expressions might reference the
872  * tableoid column, so (re-)initialize tts_tableOid before evaluating
873  * them. (This covers the case where the FDW replaced the slot.)
874  */
875  slot->tts_tableOid = RelationGetRelid(resultRelInfo->ri_RelationDesc);
876  }
877  else
878  {
879  WCOKind wco_kind;
880 
881  /*
882  * Constraints and GENERATED expressions might reference the tableoid
883  * column, so (re-)initialize tts_tableOid before evaluating them.
884  */
885  slot->tts_tableOid = RelationGetRelid(resultRelationDesc);
886 
887  /*
888  * Compute stored generated columns
889  */
890  if (resultRelationDesc->rd_att->constr &&
891  resultRelationDesc->rd_att->constr->has_generated_stored)
892  ExecComputeStoredGenerated(resultRelInfo, estate, slot,
893  CMD_INSERT);
894 
895  /*
896  * Check any RLS WITH CHECK policies.
897  *
898  * Normally we should check INSERT policies. But if the insert is the
899  * result of a partition key update that moved the tuple to a new
900  * partition, we should instead check UPDATE policies, because we are
901  * executing policies defined on the target table, and not those
902  * defined on the child partitions.
903  *
904  * If we're running MERGE, we refer to the action that we're executing
905  * to know if we're doing an INSERT or UPDATE to a partition table.
906  */
907  if (mtstate->operation == CMD_UPDATE)
908  wco_kind = WCO_RLS_UPDATE_CHECK;
909  else if (mtstate->operation == CMD_MERGE)
910  wco_kind = (context->relaction->mas_action->commandType == CMD_UPDATE) ?
912  else
913  wco_kind = WCO_RLS_INSERT_CHECK;
914 
915  /*
916  * ExecWithCheckOptions() will skip any WCOs which are not of the kind
917  * we are looking for at this point.
918  */
919  if (resultRelInfo->ri_WithCheckOptions != NIL)
920  ExecWithCheckOptions(wco_kind, resultRelInfo, slot, estate);
921 
922  /*
923  * Check the constraints of the tuple.
924  */
925  if (resultRelationDesc->rd_att->constr)
926  ExecConstraints(resultRelInfo, slot, estate);
927 
928  /*
929  * Also check the tuple against the partition constraint, if there is
930  * one; except that if we got here via tuple-routing, we don't need to
931  * if there's no BR trigger defined on the partition.
932  */
933  if (resultRelationDesc->rd_rel->relispartition &&
934  (resultRelInfo->ri_RootResultRelInfo == NULL ||
935  (resultRelInfo->ri_TrigDesc &&
936  resultRelInfo->ri_TrigDesc->trig_insert_before_row)))
937  ExecPartitionCheck(resultRelInfo, slot, estate, true);
938 
939  if (onconflict != ONCONFLICT_NONE && resultRelInfo->ri_NumIndices > 0)
940  {
941  /* Perform a speculative insertion. */
942  uint32 specToken;
943  ItemPointerData conflictTid;
944  bool specConflict;
945  List *arbiterIndexes;
946 
947  arbiterIndexes = resultRelInfo->ri_onConflictArbiterIndexes;
948 
949  /*
950  * Do a non-conclusive check for conflicts first.
951  *
952  * We're not holding any locks yet, so this doesn't guarantee that
953  * the later insert won't conflict. But it avoids leaving behind
954  * a lot of canceled speculative insertions, if you run a lot of
955  * INSERT ON CONFLICT statements that do conflict.
956  *
957  * We loop back here if we find a conflict below, either during
958  * the pre-check, or when we re-check after inserting the tuple
959  * speculatively.
960  */
961  vlock:
962  specConflict = false;
963  if (!ExecCheckIndexConstraints(resultRelInfo, slot, estate,
964  &conflictTid, arbiterIndexes))
965  {
966  /* committed conflict tuple found */
967  if (onconflict == ONCONFLICT_UPDATE)
968  {
969  /*
970  * In case of ON CONFLICT DO UPDATE, execute the UPDATE
971  * part. Be prepared to retry if the UPDATE fails because
972  * of another concurrent UPDATE/DELETE to the conflict
973  * tuple.
974  */
975  TupleTableSlot *returning = NULL;
976 
977  if (ExecOnConflictUpdate(context, resultRelInfo,
978  &conflictTid, slot, canSetTag,
979  &returning))
980  {
981  InstrCountTuples2(&mtstate->ps, 1);
982  return returning;
983  }
984  else
985  goto vlock;
986  }
987  else
988  {
989  /*
990  * In case of ON CONFLICT DO NOTHING, do nothing. However,
991  * verify that the tuple is visible to the executor's MVCC
992  * snapshot at higher isolation levels.
993  *
994  * Using ExecGetReturningSlot() to store the tuple for the
995  * recheck isn't that pretty, but we can't trivially use
996  * the input slot, because it might not be of a compatible
997  * type. As there's no conflicting usage of
998  * ExecGetReturningSlot() in the DO NOTHING case...
999  */
1000  Assert(onconflict == ONCONFLICT_NOTHING);
1001  ExecCheckTIDVisible(estate, resultRelInfo, &conflictTid,
1002  ExecGetReturningSlot(estate, resultRelInfo));
1003  InstrCountTuples2(&mtstate->ps, 1);
1004  return NULL;
1005  }
1006  }
1007 
1008  /*
1009  * Before we start insertion proper, acquire our "speculative
1010  * insertion lock". Others can use that to wait for us to decide
1011  * if we're going to go ahead with the insertion, instead of
1012  * waiting for the whole transaction to complete.
1013  */
1015 
1016  /* insert the tuple, with the speculative token */
1017  table_tuple_insert_speculative(resultRelationDesc, slot,
1018  estate->es_output_cid,
1019  0,
1020  NULL,
1021  specToken);
1022 
1023  /* insert index entries for tuple */
1024  recheckIndexes = ExecInsertIndexTuples(resultRelInfo,
1025  slot, estate, false, true,
1026  &specConflict,
1027  arbiterIndexes);
1028 
1029  /* adjust the tuple's state accordingly */
1030  table_tuple_complete_speculative(resultRelationDesc, slot,
1031  specToken, !specConflict);
1032 
1033  /*
1034  * Wake up anyone waiting for our decision. They will re-check
1035  * the tuple, see that it's no longer speculative, and wait on our
1036  * XID as if this was a regularly inserted tuple all along. Or if
1037  * we killed the tuple, they will see it's dead, and proceed as if
1038  * the tuple never existed.
1039  */
1041 
1042  /*
1043  * If there was a conflict, start from the beginning. We'll do
1044  * the pre-check again, which will now find the conflicting tuple
1045  * (unless it aborts before we get there).
1046  */
1047  if (specConflict)
1048  {
1049  list_free(recheckIndexes);
1050  goto vlock;
1051  }
1052 
1053  /* Since there was no insertion conflict, we're done */
1054  }
1055  else
1056  {
1057  /* insert the tuple normally */
1058  table_tuple_insert(resultRelationDesc, slot,
1059  estate->es_output_cid,
1060  0, NULL);
1061 
1062  /* insert index entries for tuple */
1063  if (resultRelInfo->ri_NumIndices > 0)
1064  recheckIndexes = ExecInsertIndexTuples(resultRelInfo,
1065  slot, estate, false,
1066  false, NULL, NIL);
1067  }
1068  }
1069 
1070  if (canSetTag)
1071  (estate->es_processed)++;
1072 
1073  /*
1074  * If this insert is the result of a partition key update that moved the
1075  * tuple to a new partition, put this row into the transition NEW TABLE,
1076  * if there is one. We need to do this separately for DELETE and INSERT
1077  * because they happen on different tables.
1078  */
1079  ar_insert_trig_tcs = mtstate->mt_transition_capture;
1080  if (mtstate->operation == CMD_UPDATE && mtstate->mt_transition_capture
1082  {
1083  ExecARUpdateTriggers(estate, resultRelInfo,
1084  NULL, NULL,
1085  NULL,
1086  NULL,
1087  slot,
1088  NULL,
1089  mtstate->mt_transition_capture,
1090  false);
1091 
1092  /*
1093  * We've already captured the NEW TABLE row, so make sure any AR
1094  * INSERT trigger fired below doesn't capture it again.
1095  */
1096  ar_insert_trig_tcs = NULL;
1097  }
1098 
1099  /* AFTER ROW INSERT Triggers */
1100  ExecARInsertTriggers(estate, resultRelInfo, slot, recheckIndexes,
1101  ar_insert_trig_tcs);
1102 
1103  list_free(recheckIndexes);
1104 
1105  /*
1106  * Check any WITH CHECK OPTION constraints from parent views. We are
1107  * required to do this after testing all constraints and uniqueness
1108  * violations per the SQL spec, so we do it after actually inserting the
1109  * record into the heap and all indexes.
1110  *
1111  * ExecWithCheckOptions will elog(ERROR) if a violation is found, so the
1112  * tuple will never be seen, if it violates the WITH CHECK OPTION.
1113  *
1114  * ExecWithCheckOptions() will skip any WCOs which are not of the kind we
1115  * are looking for at this point.
1116  */
1117  if (resultRelInfo->ri_WithCheckOptions != NIL)
1118  ExecWithCheckOptions(WCO_VIEW_CHECK, resultRelInfo, slot, estate);
1119 
1120  /* Process RETURNING if present */
1121  if (resultRelInfo->ri_projectReturning)
1122  result = ExecProcessReturning(resultRelInfo, slot, planSlot);
1123 
1124  if (inserted_tuple)
1125  *inserted_tuple = slot;
1126  if (insert_destrel)
1127  *insert_destrel = resultRelInfo;
1128 
1129  return result;
1130 }
1131 
1132 /* ----------------------------------------------------------------
1133  * ExecBatchInsert
1134  *
1135  * Insert multiple tuples in an efficient way.
1136  * Currently, this handles inserting into a foreign table without
1137  * RETURNING clause.
1138  * ----------------------------------------------------------------
1139  */
1140 static void
1142  ResultRelInfo *resultRelInfo,
1143  TupleTableSlot **slots,
1144  TupleTableSlot **planSlots,
1145  int numSlots,
1146  EState *estate,
1147  bool canSetTag)
1148 {
1149  int i;
1150  int numInserted = numSlots;
1151  TupleTableSlot *slot = NULL;
1152  TupleTableSlot **rslots;
1153 
1154  /*
1155  * insert into foreign table: let the FDW do it
1156  */
1157  rslots = resultRelInfo->ri_FdwRoutine->ExecForeignBatchInsert(estate,
1158  resultRelInfo,
1159  slots,
1160  planSlots,
1161  &numInserted);
1162 
1163  for (i = 0; i < numInserted; i++)
1164  {
1165  slot = rslots[i];
1166 
1167  /*
1168  * AFTER ROW Triggers or RETURNING expressions might reference the
1169  * tableoid column, so (re-)initialize tts_tableOid before evaluating
1170  * them.
1171  */
1172  slot->tts_tableOid = RelationGetRelid(resultRelInfo->ri_RelationDesc);
1173 
1174  /* AFTER ROW INSERT Triggers */
1175  ExecARInsertTriggers(estate, resultRelInfo, slot, NIL,
1176  mtstate->mt_transition_capture);
1177 
1178  /*
1179  * Check any WITH CHECK OPTION constraints from parent views. See the
1180  * comment in ExecInsert.
1181  */
1182  if (resultRelInfo->ri_WithCheckOptions != NIL)
1183  ExecWithCheckOptions(WCO_VIEW_CHECK, resultRelInfo, slot, estate);
1184  }
1185 
1186  if (canSetTag && numInserted > 0)
1187  estate->es_processed += numInserted;
1188 }
1189 
1190 /*
1191  * ExecDeletePrologue -- subroutine for ExecDelete
1192  *
1193  * Prepare executor state for DELETE. Actually, the only thing we have to do
1194  * here is execute BEFORE ROW triggers. We return false if one of them makes
1195  * the delete a no-op; otherwise, return true.
1196  */
1197 static bool
1199  ItemPointer tupleid, HeapTuple oldtuple,
1200  TupleTableSlot **epqreturnslot)
1201 {
1202  /* BEFORE ROW DELETE triggers */
1203  if (resultRelInfo->ri_TrigDesc &&
1204  resultRelInfo->ri_TrigDesc->trig_delete_before_row)
1205  return ExecBRDeleteTriggers(context->estate, context->epqstate,
1206  resultRelInfo, tupleid, oldtuple,
1207  epqreturnslot);
1208 
1209  return true;
1210 }
1211 
1212 /*
1213  * ExecDeleteAct -- subroutine for ExecDelete
1214  *
1215  * Actually delete the tuple from a plain table.
1216  *
1217  * Caller is in charge of doing EvalPlanQual as necessary
1218  */
1219 static TM_Result
1221  ItemPointer tupleid, bool changingPart)
1222 {
1223  EState *estate = context->estate;
1224 
1225  return table_tuple_delete(resultRelInfo->ri_RelationDesc, tupleid,
1226  estate->es_output_cid,
1227  estate->es_snapshot,
1228  estate->es_crosscheck_snapshot,
1229  true /* wait for commit */ ,
1230  &context->tmfd,
1231  changingPart);
1232 }
1233 
1234 /*
1235  * ExecDeleteEpilogue -- subroutine for ExecDelete
1236  *
1237  * Closing steps of tuple deletion; this invokes AFTER FOR EACH ROW triggers,
1238  * including the UPDATE triggers if the deletion is being done as part of a
1239  * cross-partition tuple move.
1240  */
1241 static void
1243  ItemPointer tupleid, HeapTuple oldtuple, bool changingPart)
1244 {
1245  ModifyTableState *mtstate = context->mtstate;
1246  EState *estate = context->estate;
1247  TransitionCaptureState *ar_delete_trig_tcs;
1248 
1249  /*
1250  * If this delete is the result of a partition key update that moved the
1251  * tuple to a new partition, put this row into the transition OLD TABLE,
1252  * if there is one. We need to do this separately for DELETE and INSERT
1253  * because they happen on different tables.
1254  */
1255  ar_delete_trig_tcs = mtstate->mt_transition_capture;
1256  if (mtstate->operation == CMD_UPDATE && mtstate->mt_transition_capture &&
1258  {
1259  ExecARUpdateTriggers(estate, resultRelInfo,
1260  NULL, NULL,
1261  tupleid, oldtuple,
1262  NULL, NULL, mtstate->mt_transition_capture,
1263  false);
1264 
1265  /*
1266  * We've already captured the NEW TABLE row, so make sure any AR
1267  * DELETE trigger fired below doesn't capture it again.
1268  */
1269  ar_delete_trig_tcs = NULL;
1270  }
1271 
1272  /* AFTER ROW DELETE Triggers */
1273  ExecARDeleteTriggers(estate, resultRelInfo, tupleid, oldtuple,
1274  ar_delete_trig_tcs, changingPart);
1275 }
1276 
1277 /* ----------------------------------------------------------------
1278  * ExecDelete
1279  *
1280  * DELETE is like UPDATE, except that we delete the tuple and no
1281  * index modifications are needed.
1282  *
1283  * When deleting from a table, tupleid identifies the tuple to
1284  * delete and oldtuple is NULL. When deleting from a view,
1285  * oldtuple is passed to the INSTEAD OF triggers and identifies
1286  * what to delete, and tupleid is invalid. When deleting from a
1287  * foreign table, tupleid is invalid; the FDW has to figure out
1288  * which row to delete using data from the planSlot. oldtuple is
1289  * passed to foreign table triggers; it is NULL when the foreign
1290  * table has no relevant triggers. We use tupleDeleted to indicate
1291  * whether the tuple is actually deleted, callers can use it to
1292  * decide whether to continue the operation. When this DELETE is a
1293  * part of an UPDATE of partition-key, then the slot returned by
1294  * EvalPlanQual() is passed back using output parameter epqreturnslot.
1295  *
1296  * Returns RETURNING result if any, otherwise NULL.
1297  * ----------------------------------------------------------------
1298  */
1299 static TupleTableSlot *
1301  ResultRelInfo *resultRelInfo,
1302  ItemPointer tupleid,
1303  HeapTuple oldtuple,
1304  bool processReturning,
1305  bool changingPart,
1306  bool canSetTag,
1307  bool *tupleDeleted,
1308  TupleTableSlot **epqreturnslot)
1309 {
1310  EState *estate = context->estate;
1311  Relation resultRelationDesc = resultRelInfo->ri_RelationDesc;
1312  TupleTableSlot *slot = NULL;
1313  TM_Result result;
1314 
1315  if (tupleDeleted)
1316  *tupleDeleted = false;
1317 
1318  /*
1319  * Prepare for the delete. This includes BEFORE ROW triggers, so we're
1320  * done if it says we are.
1321  */
1322  if (!ExecDeletePrologue(context, resultRelInfo, tupleid, oldtuple,
1323  epqreturnslot))
1324  return NULL;
1325 
1326  /* INSTEAD OF ROW DELETE Triggers */
1327  if (resultRelInfo->ri_TrigDesc &&
1328  resultRelInfo->ri_TrigDesc->trig_delete_instead_row)
1329  {
1330  bool dodelete;
1331 
1332  Assert(oldtuple != NULL);
1333  dodelete = ExecIRDeleteTriggers(estate, resultRelInfo, oldtuple);
1334 
1335  if (!dodelete) /* "do nothing" */
1336  return NULL;
1337  }
1338  else if (resultRelInfo->ri_FdwRoutine)
1339  {
1340  /*
1341  * delete from foreign table: let the FDW do it
1342  *
1343  * We offer the returning slot as a place to store RETURNING data,
1344  * although the FDW can return some other slot if it wants.
1345  */
1346  slot = ExecGetReturningSlot(estate, resultRelInfo);
1347  slot = resultRelInfo->ri_FdwRoutine->ExecForeignDelete(estate,
1348  resultRelInfo,
1349  slot,
1350  context->planSlot);
1351 
1352  if (slot == NULL) /* "do nothing" */
1353  return NULL;
1354 
1355  /*
1356  * RETURNING expressions might reference the tableoid column, so
1357  * (re)initialize tts_tableOid before evaluating them.
1358  */
1359  if (TTS_EMPTY(slot))
1360  ExecStoreAllNullTuple(slot);
1361 
1362  slot->tts_tableOid = RelationGetRelid(resultRelationDesc);
1363  }
1364  else
1365  {
1366  /*
1367  * delete the tuple
1368  *
1369  * Note: if context->estate->es_crosscheck_snapshot isn't
1370  * InvalidSnapshot, we check that the row to be deleted is visible to
1371  * that snapshot, and throw a can't-serialize error if not. This is a
1372  * special-case behavior needed for referential integrity updates in
1373  * transaction-snapshot mode transactions.
1374  */
1375 ldelete:;
1376  result = ExecDeleteAct(context, resultRelInfo, tupleid, changingPart);
1377 
1378  switch (result)
1379  {
1380  case TM_SelfModified:
1381 
1382  /*
1383  * The target tuple was already updated or deleted by the
1384  * current command, or by a later command in the current
1385  * transaction. The former case is possible in a join DELETE
1386  * where multiple tuples join to the same target tuple. This
1387  * is somewhat questionable, but Postgres has always allowed
1388  * it: we just ignore additional deletion attempts.
1389  *
1390  * The latter case arises if the tuple is modified by a
1391  * command in a BEFORE trigger, or perhaps by a command in a
1392  * volatile function used in the query. In such situations we
1393  * should not ignore the deletion, but it is equally unsafe to
1394  * proceed. We don't want to discard the original DELETE
1395  * while keeping the triggered actions based on its deletion;
1396  * and it would be no better to allow the original DELETE
1397  * while discarding updates that it triggered. The row update
1398  * carries some information that might be important according
1399  * to business rules; so throwing an error is the only safe
1400  * course.
1401  *
1402  * If a trigger actually intends this type of interaction, it
1403  * can re-execute the DELETE and then return NULL to cancel
1404  * the outer delete.
1405  */
1406  if (context->tmfd.cmax != estate->es_output_cid)
1407  ereport(ERROR,
1408  (errcode(ERRCODE_TRIGGERED_DATA_CHANGE_VIOLATION),
1409  errmsg("tuple to be deleted was already modified by an operation triggered by the current command"),
1410  errhint("Consider using an AFTER trigger instead of a BEFORE trigger to propagate changes to other rows.")));
1411 
1412  /* Else, already deleted by self; nothing to do */
1413  return NULL;
1414 
1415  case TM_Ok:
1416  break;
1417 
1418  case TM_Updated:
1419  {
1420  TupleTableSlot *inputslot;
1421  TupleTableSlot *epqslot;
1422 
1424  ereport(ERROR,
1426  errmsg("could not serialize access due to concurrent update")));
1427 
1428  /*
1429  * Already know that we're going to need to do EPQ, so
1430  * fetch tuple directly into the right slot.
1431  */
1432  EvalPlanQualBegin(context->epqstate);
1433  inputslot = EvalPlanQualSlot(context->epqstate, resultRelationDesc,
1434  resultRelInfo->ri_RangeTableIndex);
1435 
1436  result = table_tuple_lock(resultRelationDesc, tupleid,
1437  estate->es_snapshot,
1438  inputslot, estate->es_output_cid,
1441  &context->tmfd);
1442 
1443  switch (result)
1444  {
1445  case TM_Ok:
1446  Assert(context->tmfd.traversed);
1447  epqslot = EvalPlanQual(context->epqstate,
1448  resultRelationDesc,
1449  resultRelInfo->ri_RangeTableIndex,
1450  inputslot);
1451  if (TupIsNull(epqslot))
1452  /* Tuple not passing quals anymore, exiting... */
1453  return NULL;
1454 
1455  /*
1456  * If requested, skip delete and pass back the
1457  * updated row.
1458  */
1459  if (epqreturnslot)
1460  {
1461  *epqreturnslot = epqslot;
1462  return NULL;
1463  }
1464  else
1465  goto ldelete;
1466 
1467  case TM_SelfModified:
1468 
1469  /*
1470  * This can be reached when following an update
1471  * chain from a tuple updated by another session,
1472  * reaching a tuple that was already updated in
1473  * this transaction. If previously updated by this
1474  * command, ignore the delete, otherwise error
1475  * out.
1476  *
1477  * See also TM_SelfModified response to
1478  * table_tuple_delete() above.
1479  */
1480  if (context->tmfd.cmax != estate->es_output_cid)
1481  ereport(ERROR,
1482  (errcode(ERRCODE_TRIGGERED_DATA_CHANGE_VIOLATION),
1483  errmsg("tuple to be deleted was already modified by an operation triggered by the current command"),
1484  errhint("Consider using an AFTER trigger instead of a BEFORE trigger to propagate changes to other rows.")));
1485  return NULL;
1486 
1487  case TM_Deleted:
1488  /* tuple already deleted; nothing to do */
1489  return NULL;
1490 
1491  default:
1492 
1493  /*
1494  * TM_Invisible should be impossible because we're
1495  * waiting for updated row versions, and would
1496  * already have errored out if the first version
1497  * is invisible.
1498  *
1499  * TM_Updated should be impossible, because we're
1500  * locking the latest version via
1501  * TUPLE_LOCK_FLAG_FIND_LAST_VERSION.
1502  */
1503  elog(ERROR, "unexpected table_tuple_lock status: %u",
1504  result);
1505  return NULL;
1506  }
1507 
1508  Assert(false);
1509  break;
1510  }
1511 
1512  case TM_Deleted:
1514  ereport(ERROR,
1516  errmsg("could not serialize access due to concurrent delete")));
1517 
1518  /*
1519  * tuple already deleted; nothing to do. But MERGE might want
1520  * to handle it differently. We've already filled-in
1521  * actionInfo with sufficient information for MERGE to look
1522  * at.
1523  */
1524  return NULL;
1525 
1526  default:
1527  elog(ERROR, "unrecognized table_tuple_delete status: %u",
1528  result);
1529  return NULL;
1530  }
1531 
1532  /*
1533  * Note: Normally one would think that we have to delete index tuples
1534  * associated with the heap tuple now...
1535  *
1536  * ... but in POSTGRES, we have no need to do this because VACUUM will
1537  * take care of it later. We can't delete index tuples immediately
1538  * anyway, since the tuple is still visible to other transactions.
1539  */
1540  }
1541 
1542  if (canSetTag)
1543  (estate->es_processed)++;
1544 
1545  /* Tell caller that the delete actually happened. */
1546  if (tupleDeleted)
1547  *tupleDeleted = true;
1548 
1549  ExecDeleteEpilogue(context, resultRelInfo, tupleid, oldtuple, changingPart);
1550 
1551  /* Process RETURNING if present and if requested */
1552  if (processReturning && resultRelInfo->ri_projectReturning)
1553  {
1554  /*
1555  * We have to put the target tuple into a slot, which means first we
1556  * gotta fetch it. We can use the trigger tuple slot.
1557  */
1558  TupleTableSlot *rslot;
1559 
1560  if (resultRelInfo->ri_FdwRoutine)
1561  {
1562  /* FDW must have provided a slot containing the deleted row */
1563  Assert(!TupIsNull(slot));
1564  }
1565  else
1566  {
1567  slot = ExecGetReturningSlot(estate, resultRelInfo);
1568  if (oldtuple != NULL)
1569  {
1570  ExecForceStoreHeapTuple(oldtuple, slot, false);
1571  }
1572  else
1573  {
1574  if (!table_tuple_fetch_row_version(resultRelationDesc, tupleid,
1575  SnapshotAny, slot))
1576  elog(ERROR, "failed to fetch deleted tuple for DELETE RETURNING");
1577  }
1578  }
1579 
1580  rslot = ExecProcessReturning(resultRelInfo, slot, context->planSlot);
1581 
1582  /*
1583  * Before releasing the target tuple again, make sure rslot has a
1584  * local copy of any pass-by-reference values.
1585  */
1586  ExecMaterializeSlot(rslot);
1587 
1588  ExecClearTuple(slot);
1589 
1590  return rslot;
1591  }
1592 
1593  return NULL;
1594 }
1595 
1596 /*
1597  * ExecCrossPartitionUpdate --- Move an updated tuple to another partition.
1598  *
1599  * This works by first deleting the old tuple from the current partition,
1600  * followed by inserting the new tuple into the root parent table, that is,
1601  * mtstate->rootResultRelInfo. It will be re-routed from there to the
1602  * correct partition.
1603  *
1604  * Returns true if the tuple has been successfully moved, or if it's found
1605  * that the tuple was concurrently deleted so there's nothing more to do
1606  * for the caller.
1607  *
1608  * False is returned if the tuple we're trying to move is found to have been
1609  * concurrently updated. In that case, the caller must check if the updated
1610  * tuple (in updateCxt->cpUpdateRetrySlot) still needs to be re-routed, and
1611  * call this function again or perform a regular update accordingly.
1612  */
1613 static bool
1615  ResultRelInfo *resultRelInfo,
1616  ItemPointer tupleid, HeapTuple oldtuple,
1617  TupleTableSlot *slot,
1618  bool canSetTag,
1619  UpdateContext *updateCxt,
1620  TupleTableSlot **inserted_tuple,
1621  ResultRelInfo **insert_destrel)
1622 {
1623  ModifyTableState *mtstate = context->mtstate;
1624  EState *estate = mtstate->ps.state;
1625  TupleConversionMap *tupconv_map;
1626  bool tuple_deleted;
1627  TupleTableSlot *epqslot = NULL;
1628 
1629  context->cpUpdateReturningSlot = NULL;
1630  context->cpUpdateRetrySlot = NULL;
1631 
1632  /*
1633  * Disallow an INSERT ON CONFLICT DO UPDATE that causes the original row
1634  * to migrate to a different partition. Maybe this can be implemented
1635  * some day, but it seems a fringe feature with little redeeming value.
1636  */
1637  if (((ModifyTable *) mtstate->ps.plan)->onConflictAction == ONCONFLICT_UPDATE)
1638  ereport(ERROR,
1639  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1640  errmsg("invalid ON UPDATE specification"),
1641  errdetail("The result tuple would appear in a different partition than the original tuple.")));
1642 
1643  /*
1644  * When an UPDATE is run directly on a leaf partition, simply fail with a
1645  * partition constraint violation error.
1646  */
1647  if (resultRelInfo == mtstate->rootResultRelInfo)
1648  ExecPartitionCheckEmitError(resultRelInfo, slot, estate);
1649 
1650  /* Initialize tuple routing info if not already done. */
1651  if (mtstate->mt_partition_tuple_routing == NULL)
1652  {
1653  Relation rootRel = mtstate->rootResultRelInfo->ri_RelationDesc;
1654  MemoryContext oldcxt;
1655 
1656  /* Things built here have to last for the query duration. */
1657  oldcxt = MemoryContextSwitchTo(estate->es_query_cxt);
1658 
1659  mtstate->mt_partition_tuple_routing =
1660  ExecSetupPartitionTupleRouting(estate, rootRel);
1661 
1662  /*
1663  * Before a partition's tuple can be re-routed, it must first be
1664  * converted to the root's format, so we'll need a slot for storing
1665  * such tuples.
1666  */
1667  Assert(mtstate->mt_root_tuple_slot == NULL);
1668  mtstate->mt_root_tuple_slot = table_slot_create(rootRel, NULL);
1669 
1670  MemoryContextSwitchTo(oldcxt);
1671  }
1672 
1673  /*
1674  * Row movement, part 1. Delete the tuple, but skip RETURNING processing.
1675  * We want to return rows from INSERT.
1676  */
1677  ExecDelete(context, resultRelInfo,
1678  tupleid, oldtuple,
1679  false, /* processReturning */
1680  true, /* changingPart */
1681  false, /* canSetTag */
1682  &tuple_deleted, &epqslot);
1683 
1684  /*
1685  * For some reason if DELETE didn't happen (e.g. trigger prevented it, or
1686  * it was already deleted by self, or it was concurrently deleted by
1687  * another transaction), then we should skip the insert as well;
1688  * otherwise, an UPDATE could cause an increase in the total number of
1689  * rows across all partitions, which is clearly wrong.
1690  *
1691  * For a normal UPDATE, the case where the tuple has been the subject of a
1692  * concurrent UPDATE or DELETE would be handled by the EvalPlanQual
1693  * machinery, but for an UPDATE that we've translated into a DELETE from
1694  * this partition and an INSERT into some other partition, that's not
1695  * available, because CTID chains can't span relation boundaries. We
1696  * mimic the semantics to a limited extent by skipping the INSERT if the
1697  * DELETE fails to find a tuple. This ensures that two concurrent
1698  * attempts to UPDATE the same tuple at the same time can't turn one tuple
1699  * into two, and that an UPDATE of a just-deleted tuple can't resurrect
1700  * it.
1701  */
1702  if (!tuple_deleted)
1703  {
1704  /*
1705  * epqslot will be typically NULL. But when ExecDelete() finds that
1706  * another transaction has concurrently updated the same row, it
1707  * re-fetches the row, skips the delete, and epqslot is set to the
1708  * re-fetched tuple slot. In that case, we need to do all the checks
1709  * again.
1710  */
1711  if (TupIsNull(epqslot))
1712  return true;
1713  else
1714  {
1715  /* Fetch the most recent version of old tuple. */
1716  TupleTableSlot *oldSlot;
1717 
1718  /* ... but first, make sure ri_oldTupleSlot is initialized. */
1719  if (unlikely(!resultRelInfo->ri_projectNewInfoValid))
1720  ExecInitUpdateProjection(mtstate, resultRelInfo);
1721  oldSlot = resultRelInfo->ri_oldTupleSlot;
1722  if (!table_tuple_fetch_row_version(resultRelInfo->ri_RelationDesc,
1723  tupleid,
1724  SnapshotAny,
1725  oldSlot))
1726  elog(ERROR, "failed to fetch tuple being updated");
1727  /* and project the new tuple to retry the UPDATE with */
1728  context->cpUpdateRetrySlot =
1729  context->GetUpdateNewTuple(resultRelInfo, epqslot, oldSlot,
1730  context->relaction);
1731  return false;
1732  }
1733  }
1734 
1735  /*
1736  * resultRelInfo is one of the per-relation resultRelInfos. So we should
1737  * convert the tuple into root's tuple descriptor if needed, since
1738  * ExecInsert() starts the search from root.
1739  */
1740  tupconv_map = ExecGetChildToRootMap(resultRelInfo);
1741  if (tupconv_map != NULL)
1742  slot = execute_attr_map_slot(tupconv_map->attrMap,
1743  slot,
1744  mtstate->mt_root_tuple_slot);
1745 
1746  /* Tuple routing starts from the root table. */
1747  context->cpUpdateReturningSlot =
1748  ExecInsert(context, mtstate->rootResultRelInfo, slot, canSetTag,
1749  inserted_tuple, insert_destrel);
1750 
1751  /*
1752  * Reset the transition state that may possibly have been written by
1753  * INSERT.
1754  */
1755  if (mtstate->mt_transition_capture)
1757 
1758  /* We're done moving. */
1759  return true;
1760 }
1761 
1762 /*
1763  * ExecUpdatePrologue -- subroutine for ExecUpdate
1764  *
1765  * Prepare executor state for UPDATE. This includes running BEFORE ROW
1766  * triggers. We return false if one of them makes the update a no-op;
1767  * otherwise, return true.
1768  */
1769 static bool
1771  ItemPointer tupleid, HeapTuple oldtuple, TupleTableSlot *slot)
1772 {
1773  Relation resultRelationDesc = resultRelInfo->ri_RelationDesc;
1774 
1775  ExecMaterializeSlot(slot);
1776 
1777  /*
1778  * Open the table's indexes, if we have not done so already, so that we
1779  * can add new index entries for the updated tuple.
1780  */
1781  if (resultRelationDesc->rd_rel->relhasindex &&
1782  resultRelInfo->ri_IndexRelationDescs == NULL)
1783  ExecOpenIndices(resultRelInfo, false);
1784 
1785  /* BEFORE ROW UPDATE triggers */
1786  if (resultRelInfo->ri_TrigDesc &&
1787  resultRelInfo->ri_TrigDesc->trig_update_before_row)
1788  return ExecBRUpdateTriggers(context->estate, context->epqstate,
1789  resultRelInfo, tupleid, oldtuple, slot,
1790  &context->tmfd);
1791 
1792  return true;
1793 }
1794 
1795 /*
1796  * ExecUpdatePrepareSlot -- subroutine for ExecUpdate
1797  *
1798  * Apply the final modifications to the tuple slot before the update.
1799  */
1800 static void
1802  TupleTableSlot *slot,
1803  EState *estate)
1804 {
1805  Relation resultRelationDesc = resultRelInfo->ri_RelationDesc;
1806 
1807  /*
1808  * Constraints and GENERATED expressions might reference the tableoid
1809  * column, so (re-)initialize tts_tableOid before evaluating them.
1810  */
1811  slot->tts_tableOid = RelationGetRelid(resultRelationDesc);
1812 
1813  /*
1814  * Compute stored generated columns
1815  */
1816  if (resultRelationDesc->rd_att->constr &&
1817  resultRelationDesc->rd_att->constr->has_generated_stored)
1818  ExecComputeStoredGenerated(resultRelInfo, estate, slot,
1819  CMD_UPDATE);
1820 }
1821 
1822 /*
1823  * ExecUpdateAct -- subroutine for ExecUpdate
1824  *
1825  * Actually update the tuple, when operating on a plain table. If the
1826  * table is a partition, and the command was called referencing an ancestor
1827  * partitioned table, this routine migrates the resulting tuple to another
1828  * partition.
1829  *
1830  * The caller is in charge of keeping indexes current as necessary. The
1831  * caller is also in charge of doing EvalPlanQual if the tuple is found to
1832  * be concurrently updated. However, in case of a cross-partition update,
1833  * this routine does it.
1834  *
1835  * Caller is in charge of doing EvalPlanQual as necessary, and of keeping
1836  * indexes current for the update.
1837  */
1838 static TM_Result
1840  ItemPointer tupleid, HeapTuple oldtuple, TupleTableSlot *slot,
1841  bool canSetTag, UpdateContext *updateCxt)
1842 {
1843  EState *estate = context->estate;
1844  Relation resultRelationDesc = resultRelInfo->ri_RelationDesc;
1845  bool partition_constraint_failed;
1846  TM_Result result;
1847 
1848  updateCxt->crossPartUpdate = false;
1849 
1850  /*
1851  * If we generate a new candidate tuple after EvalPlanQual testing, we
1852  * must loop back here and recheck any RLS policies and constraints. (We
1853  * don't need to redo triggers, however. If there are any BEFORE triggers
1854  * then trigger.c will have done table_tuple_lock to lock the correct
1855  * tuple, so there's no need to do them again.)
1856  */
1857 lreplace:;
1858 
1859  /* ensure slot is independent, consider e.g. EPQ */
1860  ExecMaterializeSlot(slot);
1861 
1862  /*
1863  * If partition constraint fails, this row might get moved to another
1864  * partition, in which case we should check the RLS CHECK policy just
1865  * before inserting into the new partition, rather than doing it here.
1866  * This is because a trigger on that partition might again change the row.
1867  * So skip the WCO checks if the partition constraint fails.
1868  */
1869  partition_constraint_failed =
1870  resultRelationDesc->rd_rel->relispartition &&
1871  !ExecPartitionCheck(resultRelInfo, slot, estate, false);
1872 
1873  /* Check any RLS UPDATE WITH CHECK policies */
1874  if (!partition_constraint_failed &&
1875  resultRelInfo->ri_WithCheckOptions != NIL)
1876  {
1877  /*
1878  * ExecWithCheckOptions() will skip any WCOs which are not of the kind
1879  * we are looking for at this point.
1880  */
1882  resultRelInfo, slot, estate);
1883  }
1884 
1885  /*
1886  * If a partition check failed, try to move the row into the right
1887  * partition.
1888  */
1889  if (partition_constraint_failed)
1890  {
1891  TupleTableSlot *inserted_tuple;
1892  ResultRelInfo *insert_destrel = NULL;
1893 
1894  /*
1895  * ExecCrossPartitionUpdate will first DELETE the row from the
1896  * partition it's currently in and then insert it back into the root
1897  * table, which will re-route it to the correct partition. However,
1898  * if the tuple has been concurrently updated, a retry is needed.
1899  */
1900  if (ExecCrossPartitionUpdate(context, resultRelInfo,
1901  tupleid, oldtuple, slot,
1902  canSetTag, updateCxt,
1903  &inserted_tuple,
1904  &insert_destrel))
1905  {
1906  /* success! */
1907  updateCxt->updated = true;
1908  updateCxt->crossPartUpdate = true;
1909 
1910  /*
1911  * If the partitioned table being updated is referenced in foreign
1912  * keys, queue up trigger events to check that none of them were
1913  * violated. No special treatment is needed in
1914  * non-cross-partition update situations, because the leaf
1915  * partition's AR update triggers will take care of that. During
1916  * cross-partition updates implemented as delete on the source
1917  * partition followed by insert on the destination partition,
1918  * AR-UPDATE triggers of the root table (that is, the table
1919  * mentioned in the query) must be fired.
1920  *
1921  * NULL insert_destrel means that the move failed to occur, that
1922  * is, the update failed, so no need to anything in that case.
1923  */
1924  if (insert_destrel &&
1925  resultRelInfo->ri_TrigDesc &&
1926  resultRelInfo->ri_TrigDesc->trig_update_after_row)
1928  resultRelInfo,
1929  insert_destrel,
1930  tupleid, slot,
1931  inserted_tuple);
1932 
1933  return TM_Ok;
1934  }
1935 
1936  /*
1937  * No luck, a retry is needed. If running MERGE, we do not do so
1938  * here; instead let it handle that on its own rules.
1939  */
1940  if (context->relaction != NULL)
1941  return TM_Updated;
1942 
1943  /*
1944  * ExecCrossPartitionUpdate installed an updated version of the new
1945  * tuple in the retry slot; start over.
1946  */
1947  slot = context->cpUpdateRetrySlot;
1948  goto lreplace;
1949  }
1950 
1951  /*
1952  * Check the constraints of the tuple. We've already checked the
1953  * partition constraint above; however, we must still ensure the tuple
1954  * passes all other constraints, so we will call ExecConstraints() and
1955  * have it validate all remaining checks.
1956  */
1957  if (resultRelationDesc->rd_att->constr)
1958  ExecConstraints(resultRelInfo, slot, estate);
1959 
1960  /*
1961  * replace the heap tuple
1962  *
1963  * Note: if es_crosscheck_snapshot isn't InvalidSnapshot, we check that
1964  * the row to be updated is visible to that snapshot, and throw a
1965  * can't-serialize error if not. This is a special-case behavior needed
1966  * for referential integrity updates in transaction-snapshot mode
1967  * transactions.
1968  */
1969  result = table_tuple_update(resultRelationDesc, tupleid, slot,
1970  estate->es_output_cid,
1971  estate->es_snapshot,
1972  estate->es_crosscheck_snapshot,
1973  true /* wait for commit */ ,
1974  &context->tmfd, &updateCxt->lockmode,
1975  &updateCxt->updateIndexes);
1976  if (result == TM_Ok)
1977  updateCxt->updated = true;
1978 
1979  return result;
1980 }
1981 
1982 /*
1983  * ExecUpdateEpilogue -- subroutine for ExecUpdate
1984  *
1985  * Closing steps of updating a tuple. Must be called if ExecUpdateAct
1986  * returns indicating that the tuple was updated.
1987  */
1988 static void
1990  ResultRelInfo *resultRelInfo, ItemPointer tupleid,
1991  HeapTuple oldtuple, TupleTableSlot *slot,
1992  List *recheckIndexes)
1993 {
1994  ModifyTableState *mtstate = context->mtstate;
1995 
1996  /* insert index entries for tuple if necessary */
1997  if (resultRelInfo->ri_NumIndices > 0 && updateCxt->updateIndexes)
1998  recheckIndexes = ExecInsertIndexTuples(resultRelInfo,
1999  slot, context->estate,
2000  true, false,
2001  NULL, NIL);
2002 
2003  /* AFTER ROW UPDATE Triggers */
2004  ExecARUpdateTriggers(context->estate, resultRelInfo,
2005  NULL, NULL,
2006  tupleid, oldtuple, slot,
2007  recheckIndexes,
2008  mtstate->operation == CMD_INSERT ?
2009  mtstate->mt_oc_transition_capture :
2010  mtstate->mt_transition_capture,
2011  false);
2012 
2013  /*
2014  * Check any WITH CHECK OPTION constraints from parent views. We are
2015  * required to do this after testing all constraints and uniqueness
2016  * violations per the SQL spec, so we do it after actually updating the
2017  * record in the heap and all indexes.
2018  *
2019  * ExecWithCheckOptions() will skip any WCOs which are not of the kind we
2020  * are looking for at this point.
2021  */
2022  if (resultRelInfo->ri_WithCheckOptions != NIL)
2023  ExecWithCheckOptions(WCO_VIEW_CHECK, resultRelInfo,
2024  slot, context->estate);
2025 }
2026 
2027 /*
2028  * Queues up an update event using the target root partitioned table's
2029  * trigger to check that a cross-partition update hasn't broken any foreign
2030  * keys pointing into it.
2031  */
2032 static void
2034  ResultRelInfo *sourcePartInfo,
2035  ResultRelInfo *destPartInfo,
2036  ItemPointer tupleid,
2037  TupleTableSlot *oldslot,
2038  TupleTableSlot *newslot)
2039 {
2040  ListCell *lc;
2041  ResultRelInfo *rootRelInfo;
2042  List *ancestorRels;
2043 
2044  rootRelInfo = sourcePartInfo->ri_RootResultRelInfo;
2045  ancestorRels = ExecGetAncestorResultRels(context->estate, sourcePartInfo);
2046 
2047  /*
2048  * For any foreign keys that point directly into a non-root ancestors of
2049  * the source partition, we can in theory fire an update event to enforce
2050  * those constraints using their triggers, if we could tell that both the
2051  * source and the destination partitions are under the same ancestor. But
2052  * for now, we simply report an error that those cannot be enforced.
2053  */
2054  foreach(lc, ancestorRels)
2055  {
2056  ResultRelInfo *rInfo = lfirst(lc);
2057  TriggerDesc *trigdesc = rInfo->ri_TrigDesc;
2058  bool has_noncloned_fkey = false;
2059 
2060  /* Root ancestor's triggers will be processed. */
2061  if (rInfo == rootRelInfo)
2062  continue;
2063 
2064  if (trigdesc && trigdesc->trig_update_after_row)
2065  {
2066  for (int i = 0; i < trigdesc->numtriggers; i++)
2067  {
2068  Trigger *trig = &trigdesc->triggers[i];
2069 
2070  if (!trig->tgisclone &&
2072  {
2073  has_noncloned_fkey = true;
2074  break;
2075  }
2076  }
2077  }
2078 
2079  if (has_noncloned_fkey)
2080  ereport(ERROR,
2081  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2082  errmsg("cannot move tuple across partitions when a non-root ancestor of the source partition is directly referenced in a foreign key"),
2083  errdetail("A foreign key points to ancestor \"%s\", but not the root ancestor \"%s\".",
2086  errhint("Consider defining the foreign key on \"%s\".",
2087  RelationGetRelationName(rootRelInfo->ri_RelationDesc))));
2088  }
2089 
2090  /* Perform the root table's triggers. */
2091  ExecARUpdateTriggers(context->estate,
2092  rootRelInfo, sourcePartInfo, destPartInfo,
2093  tupleid, NULL, newslot, NIL, NULL, true);
2094 }
2095 
2096 /* ----------------------------------------------------------------
2097  * ExecUpdate
2098  *
2099  * note: we can't run UPDATE queries with transactions
2100  * off because UPDATEs are actually INSERTs and our
2101  * scan will mistakenly loop forever, updating the tuple
2102  * it just inserted.. This should be fixed but until it
2103  * is, we don't want to get stuck in an infinite loop
2104  * which corrupts your database..
2105  *
2106  * When updating a table, tupleid identifies the tuple to
2107  * update and oldtuple is NULL. When updating a view, oldtuple
2108  * is passed to the INSTEAD OF triggers and identifies what to
2109  * update, and tupleid is invalid. When updating a foreign table,
2110  * tupleid is invalid; the FDW has to figure out which row to
2111  * update using data from the planSlot. oldtuple is passed to
2112  * foreign table triggers; it is NULL when the foreign table has
2113  * no relevant triggers.
2114  *
2115  * slot contains the new tuple value to be stored.
2116  * planSlot is the output of the ModifyTable's subplan; we use it
2117  * to access values from other input tables (for RETURNING),
2118  * row-ID junk columns, etc.
2119  *
2120  * Returns RETURNING result if any, otherwise NULL.
2121  * ----------------------------------------------------------------
2122  */
2123 static TupleTableSlot *
2125  ItemPointer tupleid, HeapTuple oldtuple, TupleTableSlot *slot,
2126  bool canSetTag)
2127 {
2128  EState *estate = context->estate;
2129  Relation resultRelationDesc = resultRelInfo->ri_RelationDesc;
2130  UpdateContext updateCxt = {0};
2131  List *recheckIndexes = NIL;
2132  TM_Result result;
2133 
2134  /*
2135  * abort the operation if not running transactions
2136  */
2138  elog(ERROR, "cannot UPDATE during bootstrap");
2139 
2140  /*
2141  * Prepare for the update. This includes BEFORE ROW triggers, so we're
2142  * done if it says we are.
2143  */
2144  if (!ExecUpdatePrologue(context, resultRelInfo, tupleid, oldtuple, slot))
2145  return NULL;
2146 
2147  /* INSTEAD OF ROW UPDATE Triggers */
2148  if (resultRelInfo->ri_TrigDesc &&
2149  resultRelInfo->ri_TrigDesc->trig_update_instead_row)
2150  {
2151  if (!ExecIRUpdateTriggers(estate, resultRelInfo,
2152  oldtuple, slot))
2153  return NULL; /* "do nothing" */
2154  }
2155  else if (resultRelInfo->ri_FdwRoutine)
2156  {
2157  ExecUpdatePrepareSlot(resultRelInfo, slot, estate);
2158 
2159  /*
2160  * update in foreign table: let the FDW do it
2161  */
2162  slot = resultRelInfo->ri_FdwRoutine->ExecForeignUpdate(estate,
2163  resultRelInfo,
2164  slot,
2165  context->planSlot);
2166 
2167  if (slot == NULL) /* "do nothing" */
2168  return NULL;
2169 
2170  /*
2171  * AFTER ROW Triggers or RETURNING expressions might reference the
2172  * tableoid column, so (re-)initialize tts_tableOid before evaluating
2173  * them. (This covers the case where the FDW replaced the slot.)
2174  */
2175  slot->tts_tableOid = RelationGetRelid(resultRelationDesc);
2176  }
2177  else
2178  {
2179  /* Fill in the slot appropriately */
2180  ExecUpdatePrepareSlot(resultRelInfo, slot, estate);
2181 
2182 redo_act:
2183  result = ExecUpdateAct(context, resultRelInfo, tupleid, oldtuple, slot,
2184  canSetTag, &updateCxt);
2185 
2186  /*
2187  * If ExecUpdateAct reports that a cross-partition update was done,
2188  * then the RETURNING tuple (if any) has been projected and there's
2189  * nothing else for us to do.
2190  */
2191  if (updateCxt.crossPartUpdate)
2192  return context->cpUpdateReturningSlot;
2193 
2194  switch (result)
2195  {
2196  case TM_SelfModified:
2197 
2198  /*
2199  * The target tuple was already updated or deleted by the
2200  * current command, or by a later command in the current
2201  * transaction. The former case is possible in a join UPDATE
2202  * where multiple tuples join to the same target tuple. This
2203  * is pretty questionable, but Postgres has always allowed it:
2204  * we just execute the first update action and ignore
2205  * additional update attempts.
2206  *
2207  * The latter case arises if the tuple is modified by a
2208  * command in a BEFORE trigger, or perhaps by a command in a
2209  * volatile function used in the query. In such situations we
2210  * should not ignore the update, but it is equally unsafe to
2211  * proceed. We don't want to discard the original UPDATE
2212  * while keeping the triggered actions based on it; and we
2213  * have no principled way to merge this update with the
2214  * previous ones. So throwing an error is the only safe
2215  * course.
2216  *
2217  * If a trigger actually intends this type of interaction, it
2218  * can re-execute the UPDATE (assuming it can figure out how)
2219  * and then return NULL to cancel the outer update.
2220  */
2221  if (context->tmfd.cmax != estate->es_output_cid)
2222  ereport(ERROR,
2223  (errcode(ERRCODE_TRIGGERED_DATA_CHANGE_VIOLATION),
2224  errmsg("tuple to be updated was already modified by an operation triggered by the current command"),
2225  errhint("Consider using an AFTER trigger instead of a BEFORE trigger to propagate changes to other rows.")));
2226 
2227  /* Else, already updated by self; nothing to do */
2228  return NULL;
2229 
2230  case TM_Ok:
2231  break;
2232 
2233  case TM_Updated:
2234  {
2235  TupleTableSlot *inputslot;
2236  TupleTableSlot *epqslot;
2237  TupleTableSlot *oldSlot;
2238 
2240  ereport(ERROR,
2242  errmsg("could not serialize access due to concurrent update")));
2243 
2244  /*
2245  * Already know that we're going to need to do EPQ, so
2246  * fetch tuple directly into the right slot.
2247  */
2248  inputslot = EvalPlanQualSlot(context->epqstate, resultRelationDesc,
2249  resultRelInfo->ri_RangeTableIndex);
2250 
2251  result = table_tuple_lock(resultRelationDesc, tupleid,
2252  estate->es_snapshot,
2253  inputslot, estate->es_output_cid,
2254  updateCxt.lockmode, LockWaitBlock,
2256  &context->tmfd);
2257 
2258  switch (result)
2259  {
2260  case TM_Ok:
2261  Assert(context->tmfd.traversed);
2262 
2263  epqslot = EvalPlanQual(context->epqstate,
2264  resultRelationDesc,
2265  resultRelInfo->ri_RangeTableIndex,
2266  inputslot);
2267  if (TupIsNull(epqslot))
2268  /* Tuple not passing quals anymore, exiting... */
2269  return NULL;
2270 
2271  /* Make sure ri_oldTupleSlot is initialized. */
2272  if (unlikely(!resultRelInfo->ri_projectNewInfoValid))
2274  resultRelInfo);
2275 
2276  /* Fetch the most recent version of old tuple. */
2277  oldSlot = resultRelInfo->ri_oldTupleSlot;
2278  if (!table_tuple_fetch_row_version(resultRelationDesc,
2279  tupleid,
2280  SnapshotAny,
2281  oldSlot))
2282  elog(ERROR, "failed to fetch tuple being updated");
2283  slot = ExecGetUpdateNewTuple(resultRelInfo,
2284  epqslot, oldSlot);
2285  goto redo_act;
2286 
2287  case TM_Deleted:
2288  /* tuple already deleted; nothing to do */
2289  return NULL;
2290 
2291  case TM_SelfModified:
2292 
2293  /*
2294  * This can be reached when following an update
2295  * chain from a tuple updated by another session,
2296  * reaching a tuple that was already updated in
2297  * this transaction. If previously modified by
2298  * this command, ignore the redundant update,
2299  * otherwise error out.
2300  *
2301  * See also TM_SelfModified response to
2302  * table_tuple_update() above.
2303  */
2304  if (context->tmfd.cmax != estate->es_output_cid)
2305  ereport(ERROR,
2306  (errcode(ERRCODE_TRIGGERED_DATA_CHANGE_VIOLATION),
2307  errmsg("tuple to be updated was already modified by an operation triggered by the current command"),
2308  errhint("Consider using an AFTER trigger instead of a BEFORE trigger to propagate changes to other rows.")));
2309  return NULL;
2310 
2311  default:
2312  /* see table_tuple_lock call in ExecDelete() */
2313  elog(ERROR, "unexpected table_tuple_lock status: %u",
2314  result);
2315  return NULL;
2316  }
2317  }
2318 
2319  break;
2320 
2321  case TM_Deleted:
2323  ereport(ERROR,
2325  errmsg("could not serialize access due to concurrent delete")));
2326  /* tuple already deleted; nothing to do */
2327  return NULL;
2328 
2329  default:
2330  elog(ERROR, "unrecognized table_tuple_update status: %u",
2331  result);
2332  return NULL;
2333  }
2334  }
2335 
2336  if (canSetTag)
2337  (estate->es_processed)++;
2338 
2339  ExecUpdateEpilogue(context, &updateCxt, resultRelInfo, tupleid, oldtuple,
2340  slot, recheckIndexes);
2341 
2342  list_free(recheckIndexes);
2343 
2344  /* Process RETURNING if present */
2345  if (resultRelInfo->ri_projectReturning)
2346  return ExecProcessReturning(resultRelInfo, slot, context->planSlot);
2347 
2348  return NULL;
2349 }
2350 
2351 /*
2352  * ExecOnConflictUpdate --- execute UPDATE of INSERT ON CONFLICT DO UPDATE
2353  *
2354  * Try to lock tuple for update as part of speculative insertion. If
2355  * a qual originating from ON CONFLICT DO UPDATE is satisfied, update
2356  * (but still lock row, even though it may not satisfy estate's
2357  * snapshot).
2358  *
2359  * Returns true if we're done (with or without an update), or false if
2360  * the caller must retry the INSERT from scratch.
2361  */
2362 static bool
2364  ResultRelInfo *resultRelInfo,
2365  ItemPointer conflictTid,
2366  TupleTableSlot *excludedSlot,
2367  bool canSetTag,
2368  TupleTableSlot **returning)
2369 {
2370  ModifyTableState *mtstate = context->mtstate;
2371  ExprContext *econtext = mtstate->ps.ps_ExprContext;
2372  Relation relation = resultRelInfo->ri_RelationDesc;
2373  ExprState *onConflictSetWhere = resultRelInfo->ri_onConflict->oc_WhereClause;
2374  TupleTableSlot *existing = resultRelInfo->ri_onConflict->oc_Existing;
2375  TM_FailureData tmfd;
2376  LockTupleMode lockmode;
2377  TM_Result test;
2378  Datum xminDatum;
2379  TransactionId xmin;
2380  bool isnull;
2381 
2382  /* Determine lock mode to use */
2383  lockmode = ExecUpdateLockMode(context->estate, resultRelInfo);
2384 
2385  /*
2386  * Lock tuple for update. Don't follow updates when tuple cannot be
2387  * locked without doing so. A row locking conflict here means our
2388  * previous conclusion that the tuple is conclusively committed is not
2389  * true anymore.
2390  */
2391  test = table_tuple_lock(relation, conflictTid,
2392  context->estate->es_snapshot,
2393  existing, context->estate->es_output_cid,
2394  lockmode, LockWaitBlock, 0,
2395  &tmfd);
2396  switch (test)
2397  {
2398  case TM_Ok:
2399  /* success! */
2400  break;
2401 
2402  case TM_Invisible:
2403 
2404  /*
2405  * This can occur when a just inserted tuple is updated again in
2406  * the same command. E.g. because multiple rows with the same
2407  * conflicting key values are inserted.
2408  *
2409  * This is somewhat similar to the ExecUpdate() TM_SelfModified
2410  * case. We do not want to proceed because it would lead to the
2411  * same row being updated a second time in some unspecified order,
2412  * and in contrast to plain UPDATEs there's no historical behavior
2413  * to break.
2414  *
2415  * It is the user's responsibility to prevent this situation from
2416  * occurring. These problems are why the SQL standard similarly
2417  * specifies that for SQL MERGE, an exception must be raised in
2418  * the event of an attempt to update the same row twice.
2419  */
2420  xminDatum = slot_getsysattr(existing,
2422  &isnull);
2423  Assert(!isnull);
2424  xmin = DatumGetTransactionId(xminDatum);
2425 
2427  ereport(ERROR,
2428  (errcode(ERRCODE_CARDINALITY_VIOLATION),
2429  /* translator: %s is a SQL command name */
2430  errmsg("%s command cannot affect row a second time",
2431  "ON CONFLICT DO UPDATE"),
2432  errhint("Ensure that no rows proposed for insertion within the same command have duplicate constrained values.")));
2433 
2434  /* This shouldn't happen */
2435  elog(ERROR, "attempted to lock invisible tuple");
2436  break;
2437 
2438  case TM_SelfModified:
2439 
2440  /*
2441  * This state should never be reached. As a dirty snapshot is used
2442  * to find conflicting tuples, speculative insertion wouldn't have
2443  * seen this row to conflict with.
2444  */
2445  elog(ERROR, "unexpected self-updated tuple");
2446  break;
2447 
2448  case TM_Updated:
2450  ereport(ERROR,
2452  errmsg("could not serialize access due to concurrent update")));
2453 
2454  /*
2455  * As long as we don't support an UPDATE of INSERT ON CONFLICT for
2456  * a partitioned table we shouldn't reach to a case where tuple to
2457  * be lock is moved to another partition due to concurrent update
2458  * of the partition key.
2459  */
2461 
2462  /*
2463  * Tell caller to try again from the very start.
2464  *
2465  * It does not make sense to use the usual EvalPlanQual() style
2466  * loop here, as the new version of the row might not conflict
2467  * anymore, or the conflicting tuple has actually been deleted.
2468  */
2469  ExecClearTuple(existing);
2470  return false;
2471 
2472  case TM_Deleted:
2474  ereport(ERROR,
2476  errmsg("could not serialize access due to concurrent delete")));
2477 
2478  /* see TM_Updated case */
2480  ExecClearTuple(existing);
2481  return false;
2482 
2483  default:
2484  elog(ERROR, "unrecognized table_tuple_lock status: %u", test);
2485  }
2486 
2487  /* Success, the tuple is locked. */
2488 
2489  /*
2490  * Verify that the tuple is visible to our MVCC snapshot if the current
2491  * isolation level mandates that.
2492  *
2493  * It's not sufficient to rely on the check within ExecUpdate() as e.g.
2494  * CONFLICT ... WHERE clause may prevent us from reaching that.
2495  *
2496  * This means we only ever continue when a new command in the current
2497  * transaction could see the row, even though in READ COMMITTED mode the
2498  * tuple will not be visible according to the current statement's
2499  * snapshot. This is in line with the way UPDATE deals with newer tuple
2500  * versions.
2501  */
2502  ExecCheckTupleVisible(context->estate, relation, existing);
2503 
2504  /*
2505  * Make tuple and any needed join variables available to ExecQual and
2506  * ExecProject. The EXCLUDED tuple is installed in ecxt_innertuple, while
2507  * the target's existing tuple is installed in the scantuple. EXCLUDED
2508  * has been made to reference INNER_VAR in setrefs.c, but there is no
2509  * other redirection.
2510  */
2511  econtext->ecxt_scantuple = existing;
2512  econtext->ecxt_innertuple = excludedSlot;
2513  econtext->ecxt_outertuple = NULL;
2514 
2515  if (!ExecQual(onConflictSetWhere, econtext))
2516  {
2517  ExecClearTuple(existing); /* see return below */
2518  InstrCountFiltered1(&mtstate->ps, 1);
2519  return true; /* done with the tuple */
2520  }
2521 
2522  if (resultRelInfo->ri_WithCheckOptions != NIL)
2523  {
2524  /*
2525  * Check target's existing tuple against UPDATE-applicable USING
2526  * security barrier quals (if any), enforced here as RLS checks/WCOs.
2527  *
2528  * The rewriter creates UPDATE RLS checks/WCOs for UPDATE security
2529  * quals, and stores them as WCOs of "kind" WCO_RLS_CONFLICT_CHECK,
2530  * but that's almost the extent of its special handling for ON
2531  * CONFLICT DO UPDATE.
2532  *
2533  * The rewriter will also have associated UPDATE applicable straight
2534  * RLS checks/WCOs for the benefit of the ExecUpdate() call that
2535  * follows. INSERTs and UPDATEs naturally have mutually exclusive WCO
2536  * kinds, so there is no danger of spurious over-enforcement in the
2537  * INSERT or UPDATE path.
2538  */
2540  existing,
2541  mtstate->ps.state);
2542  }
2543 
2544  /* Project the new tuple version */
2545  ExecProject(resultRelInfo->ri_onConflict->oc_ProjInfo);
2546 
2547  /*
2548  * Note that it is possible that the target tuple has been modified in
2549  * this session, after the above table_tuple_lock. We choose to not error
2550  * out in that case, in line with ExecUpdate's treatment of similar cases.
2551  * This can happen if an UPDATE is triggered from within ExecQual(),
2552  * ExecWithCheckOptions() or ExecProject() above, e.g. by selecting from a
2553  * wCTE in the ON CONFLICT's SET.
2554  */
2555 
2556  /* Execute UPDATE with projection */
2557  *returning = ExecUpdate(context, resultRelInfo,
2558  conflictTid, NULL,
2559  resultRelInfo->ri_onConflict->oc_ProjSlot,
2560  canSetTag);
2561 
2562  /*
2563  * Clear out existing tuple, as there might not be another conflict among
2564  * the next input rows. Don't want to hold resources till the end of the
2565  * query.
2566  */
2567  ExecClearTuple(existing);
2568  return true;
2569 }
2570 
2571 /*
2572  * Perform MERGE.
2573  */
2574 static TupleTableSlot *
2575 ExecMerge(ModifyTableContext *context, ResultRelInfo *resultRelInfo,
2576  ItemPointer tupleid, bool canSetTag)
2577 {
2578  bool matched;
2579 
2580  /*-----
2581  * If we are dealing with a WHEN MATCHED case (tupleid is valid), we
2582  * execute the first action for which the additional WHEN MATCHED AND
2583  * quals pass. If an action without quals is found, that action is
2584  * executed.
2585  *
2586  * Similarly, if we are dealing with WHEN NOT MATCHED case, we look at
2587  * the given WHEN NOT MATCHED actions in sequence until one passes.
2588  *
2589  * Things get interesting in case of concurrent update/delete of the
2590  * target tuple. Such concurrent update/delete is detected while we are
2591  * executing a WHEN MATCHED action.
2592  *
2593  * A concurrent update can:
2594  *
2595  * 1. modify the target tuple so that it no longer satisfies the
2596  * additional quals attached to the current WHEN MATCHED action
2597  *
2598  * In this case, we are still dealing with a WHEN MATCHED case.
2599  * We recheck the list of WHEN MATCHED actions from the start and
2600  * choose the first one that satisfies the new target tuple.
2601  *
2602  * 2. modify the target tuple so that the join quals no longer pass and
2603  * hence the source tuple no longer has a match.
2604  *
2605  * In this case, the source tuple no longer matches the target tuple,
2606  * so we now instead find a qualifying WHEN NOT MATCHED action to
2607  * execute.
2608  *
2609  * XXX Hmmm, what if the updated tuple would now match one that was
2610  * considered NOT MATCHED so far?
2611  *
2612  * A concurrent delete changes a WHEN MATCHED case to WHEN NOT MATCHED.
2613  *
2614  * ExecMergeMatched takes care of following the update chain and
2615  * re-finding the qualifying WHEN MATCHED action, as long as the updated
2616  * target tuple still satisfies the join quals, i.e., it remains a WHEN
2617  * MATCHED case. If the tuple gets deleted or the join quals fail, it
2618  * returns and we try ExecMergeNotMatched. Given that ExecMergeMatched
2619  * always make progress by following the update chain and we never switch
2620  * from ExecMergeNotMatched to ExecMergeMatched, there is no risk of a
2621  * livelock.
2622  */
2623  matched = tupleid != NULL;
2624  if (matched)
2625  matched = ExecMergeMatched(context, resultRelInfo, tupleid, canSetTag);
2626 
2627  /*
2628  * Either we were dealing with a NOT MATCHED tuple or ExecMergeMatched()
2629  * returned "false", indicating the previously MATCHED tuple no longer
2630  * matches.
2631  */
2632  if (!matched)
2633  ExecMergeNotMatched(context, resultRelInfo, canSetTag);
2634 
2635  /* No RETURNING support yet */
2636  return NULL;
2637 }
2638 
2639 /*
2640  * Check and execute the first qualifying MATCHED action. The current target
2641  * tuple is identified by tupleid.
2642  *
2643  * We start from the first WHEN MATCHED action and check if the WHEN quals
2644  * pass, if any. If the WHEN quals for the first action do not pass, we
2645  * check the second, then the third and so on. If we reach to the end, no
2646  * action is taken and we return true, indicating that no further action is
2647  * required for this tuple.
2648  *
2649  * If we do find a qualifying action, then we attempt to execute the action.
2650  *
2651  * If the tuple is concurrently updated, EvalPlanQual is run with the updated
2652  * tuple to recheck the join quals. Note that the additional quals associated
2653  * with individual actions are evaluated by this routine via ExecQual, while
2654  * EvalPlanQual checks for the join quals. If EvalPlanQual tells us that the
2655  * updated tuple still passes the join quals, then we restart from the first
2656  * action to look for a qualifying action. Otherwise, we return false --
2657  * meaning that a NOT MATCHED action must now be executed for the current
2658  * source tuple.
2659  */
2660 static bool
2662  ItemPointer tupleid, bool canSetTag)
2663 {
2664  ModifyTableState *mtstate = context->mtstate;
2665  TupleTableSlot *newslot;
2666  EState *estate = context->estate;
2667  ExprContext *econtext = mtstate->ps.ps_ExprContext;
2668  bool isNull;
2669  EPQState *epqstate = &mtstate->mt_epqstate;
2670  ListCell *l;
2671 
2672  /*
2673  * If there are no WHEN MATCHED actions, we are done.
2674  */
2675  if (resultRelInfo->ri_matchedMergeAction == NIL)
2676  return true;
2677 
2678  /*
2679  * Make tuple and any needed join variables available to ExecQual and
2680  * ExecProject. The target's existing tuple is installed in the scantuple.
2681  * Again, this target relation's slot is required only in the case of a
2682  * MATCHED tuple and UPDATE/DELETE actions.
2683  */
2684  econtext->ecxt_scantuple = resultRelInfo->ri_oldTupleSlot;
2685  econtext->ecxt_innertuple = context->planSlot;
2686  econtext->ecxt_outertuple = NULL;
2687 
2688 lmerge_matched:;
2689 
2690  /*
2691  * This routine is only invoked for matched rows, and we must have found
2692  * the tupleid of the target row in that case; fetch that tuple.
2693  *
2694  * We use SnapshotAny for this because we might get called again after
2695  * EvalPlanQual returns us a new tuple, which may not be visible to our
2696  * MVCC snapshot.
2697  */
2698 
2699  if (!table_tuple_fetch_row_version(resultRelInfo->ri_RelationDesc,
2700  tupleid,
2701  SnapshotAny,
2702  resultRelInfo->ri_oldTupleSlot))
2703  elog(ERROR, "failed to fetch the target tuple");
2704 
2705  foreach(l, resultRelInfo->ri_matchedMergeAction)
2706  {
2707  MergeActionState *relaction = (MergeActionState *) lfirst(l);
2708  CmdType commandType = relaction->mas_action->commandType;
2709  List *recheckIndexes = NIL;
2710  TM_Result result;
2711  UpdateContext updateCxt = {0};
2712 
2713  /*
2714  * Test condition, if any.
2715  *
2716  * In the absence of any condition, we perform the action
2717  * unconditionally (no need to check separately since ExecQual() will
2718  * return true if there are no conditions to evaluate).
2719  */
2720  if (!ExecQual(relaction->mas_whenqual, econtext))
2721  continue;
2722 
2723  /*
2724  * Check if the existing target tuple meets the USING checks of
2725  * UPDATE/DELETE RLS policies. If those checks fail, we throw an
2726  * error.
2727  *
2728  * The WITH CHECK quals are applied in ExecUpdate() and hence we need
2729  * not do anything special to handle them.
2730  *
2731  * NOTE: We must do this after WHEN quals are evaluated, so that we
2732  * check policies only when they matter.
2733  */
2734  if (resultRelInfo->ri_WithCheckOptions)
2735  {
2736  ExecWithCheckOptions(commandType == CMD_UPDATE ?
2738  resultRelInfo,
2739  resultRelInfo->ri_oldTupleSlot,
2740  context->mtstate->ps.state);
2741  }
2742 
2743  /* Perform stated action */
2744  switch (commandType)
2745  {
2746  case CMD_UPDATE:
2747 
2748  /*
2749  * Project the output tuple, and use that to update the table.
2750  * We don't need to filter out junk attributes, because the
2751  * UPDATE action's targetlist doesn't have any.
2752  */
2753  newslot = ExecProject(relaction->mas_proj);
2754 
2755  context->relaction = relaction;
2757  context->cpUpdateRetrySlot = NULL;
2758 
2759  if (!ExecUpdatePrologue(context, resultRelInfo,
2760  tupleid, NULL, newslot))
2761  {
2762  result = TM_Ok;
2763  break;
2764  }
2765  ExecUpdatePrepareSlot(resultRelInfo, newslot, context->estate);
2766  result = ExecUpdateAct(context, resultRelInfo, tupleid, NULL,
2767  newslot, mtstate->canSetTag, &updateCxt);
2768  if (result == TM_Ok && updateCxt.updated)
2769  {
2770  ExecUpdateEpilogue(context, &updateCxt, resultRelInfo,
2771  tupleid, NULL, newslot, recheckIndexes);
2772  mtstate->mt_merge_updated += 1;
2773  }
2774 
2775  break;
2776 
2777  case CMD_DELETE:
2778  context->relaction = relaction;
2779  if (!ExecDeletePrologue(context, resultRelInfo, tupleid,
2780  NULL, NULL))
2781  {
2782  result = TM_Ok;
2783  break;
2784  }
2785  result = ExecDeleteAct(context, resultRelInfo, tupleid, false);
2786  if (result == TM_Ok)
2787  {
2788  ExecDeleteEpilogue(context, resultRelInfo, tupleid, NULL,
2789  false);
2790  mtstate->mt_merge_deleted += 1;
2791  }
2792  break;
2793 
2794  case CMD_NOTHING:
2795  /* Doing nothing is always OK */
2796  result = TM_Ok;
2797  break;
2798 
2799  default:
2800  elog(ERROR, "unknown action in MERGE WHEN MATCHED clause");
2801  }
2802 
2803  switch (result)
2804  {
2805  case TM_Ok:
2806  /* all good; perform final actions */
2807  if (canSetTag)
2808  (estate->es_processed)++;
2809 
2810  break;
2811 
2812  case TM_SelfModified:
2813 
2814  /*
2815  * The SQL standard disallows this for MERGE.
2816  */
2818  ereport(ERROR,
2819  (errcode(ERRCODE_CARDINALITY_VIOLATION),
2820  /* translator: %s is a SQL command name */
2821  errmsg("%s command cannot affect row a second time",
2822  "MERGE"),
2823  errhint("Ensure that not more than one source row matches any one target row.")));
2824  /* This shouldn't happen */
2825  elog(ERROR, "attempted to update or delete invisible tuple");
2826  break;
2827 
2828  case TM_Deleted:
2830  ereport(ERROR,
2832  errmsg("could not serialize access due to concurrent delete")));
2833 
2834  /*
2835  * If the tuple was already deleted, return to let caller
2836  * handle it under NOT MATCHED clauses.
2837  */
2838  return false;
2839 
2840  case TM_Updated:
2841  {
2842  Relation resultRelationDesc;
2843  TupleTableSlot *epqslot,
2844  *inputslot;
2845  LockTupleMode lockmode;
2846 
2847  /*
2848  * The target tuple was concurrently updated by some other
2849  * transaction.
2850  */
2851 
2852  /*
2853  * If cpUpdateRetrySlot is set, ExecCrossPartitionUpdate()
2854  * must have detected that the tuple was concurrently
2855  * updated, so we restart the search for an appropriate
2856  * WHEN MATCHED clause to process the updated tuple.
2857  *
2858  * In this case, ExecDelete() would already have performed
2859  * EvalPlanQual() on the latest version of the tuple,
2860  * which in turn would already have been loaded into
2861  * ri_oldTupleSlot, so no need to do either of those
2862  * things.
2863  *
2864  * XXX why do we not check the WHEN NOT MATCHED list in
2865  * this case?
2866  */
2867  if (!TupIsNull(context->cpUpdateRetrySlot))
2868  goto lmerge_matched;
2869 
2870  /*
2871  * Otherwise, we run the EvalPlanQual() with the new
2872  * version of the tuple. If EvalPlanQual() does not return
2873  * a tuple, then we switch to the NOT MATCHED list of
2874  * actions. If it does return a tuple and the join qual is
2875  * still satisfied, then we just need to recheck the
2876  * MATCHED actions, starting from the top, and execute the
2877  * first qualifying action.
2878  */
2879  resultRelationDesc = resultRelInfo->ri_RelationDesc;
2880  lockmode = ExecUpdateLockMode(estate, resultRelInfo);
2881 
2882  inputslot = EvalPlanQualSlot(epqstate, resultRelationDesc,
2883  resultRelInfo->ri_RangeTableIndex);
2884 
2885  result = table_tuple_lock(resultRelationDesc, tupleid,
2886  estate->es_snapshot,
2887  inputslot, estate->es_output_cid,
2888  lockmode, LockWaitBlock,
2890  &context->tmfd);
2891  switch (result)
2892  {
2893  case TM_Ok:
2894  epqslot = EvalPlanQual(epqstate,
2895  resultRelationDesc,
2896  resultRelInfo->ri_RangeTableIndex,
2897  inputslot);
2898 
2899  /*
2900  * If we got no tuple, or the tuple we get has a
2901  * NULL ctid, go back to caller: this one is not a
2902  * MATCHED tuple anymore, so they can retry with
2903  * NOT MATCHED actions.
2904  */
2905  if (TupIsNull(epqslot))
2906  return false;
2907 
2908  (void) ExecGetJunkAttribute(epqslot,
2909  resultRelInfo->ri_RowIdAttNo,
2910  &isNull);
2911  if (isNull)
2912  return false;
2913 
2914  /*
2915  * When a tuple was updated and migrated to
2916  * another partition concurrently, the current
2917  * MERGE implementation can't follow. There's
2918  * probably a better way to handle this case, but
2919  * it'd require recognizing the relation to which
2920  * the tuple moved, and setting our current
2921  * resultRelInfo to that.
2922  */
2924  ereport(ERROR,
2926  errmsg("tuple to be deleted was already moved to another partition due to concurrent update")));
2927 
2928  /*
2929  * A non-NULL ctid means that we are still dealing
2930  * with MATCHED case. Restart the loop so that we
2931  * apply all the MATCHED rules again, to ensure
2932  * that the first qualifying WHEN MATCHED action
2933  * is executed.
2934  *
2935  * Update tupleid to that of the new tuple, for
2936  * the refetch we do at the top.
2937  */
2938  ItemPointerCopy(&context->tmfd.ctid, tupleid);
2939  goto lmerge_matched;
2940 
2941  case TM_Deleted:
2942 
2943  /*
2944  * tuple already deleted; tell caller to run NOT
2945  * MATCHED actions
2946  */
2947  return false;
2948 
2949  case TM_SelfModified:
2950 
2951  /*
2952  * This can be reached when following an update
2953  * chain from a tuple updated by another session,
2954  * reaching a tuple that was already updated in
2955  * this transaction. If previously modified by
2956  * this command, ignore the redundant update,
2957  * otherwise error out.
2958  *
2959  * See also response to TM_SelfModified in
2960  * ExecUpdate().
2961  */
2962  if (context->tmfd.cmax != estate->es_output_cid)
2963  ereport(ERROR,
2964  (errcode(ERRCODE_TRIGGERED_DATA_CHANGE_VIOLATION),
2965  errmsg("tuple to be updated or deleted was already modified by an operation triggered by the current command"),
2966  errhint("Consider using an AFTER trigger instead of a BEFORE trigger to propagate changes to other rows.")));
2967  return false;
2968 
2969  default:
2970  /* see table_tuple_lock call in ExecDelete() */
2971  elog(ERROR, "unexpected table_tuple_lock status: %u",
2972  result);
2973  return false;
2974  }
2975  }
2976 
2977  case TM_Invisible:
2978  case TM_WouldBlock:
2979  case TM_BeingModified:
2980  /* these should not occur */
2981  elog(ERROR, "unexpected tuple operation result: %d", result);
2982  break;
2983  }
2984 
2985  /*
2986  * We've activated one of the WHEN clauses, so we don't search
2987  * further. This is required behaviour, not an optimization.
2988  */
2989  break;
2990  }
2991 
2992  /*
2993  * Successfully executed an action or no qualifying action was found.
2994  */
2995  return true;
2996 }
2997 
2998 /*
2999  * Execute the first qualifying NOT MATCHED action.
3000  */
3001 static void
3003  bool canSetTag)
3004 {
3005  ModifyTableState *mtstate = context->mtstate;
3006  ExprContext *econtext = mtstate->ps.ps_ExprContext;
3007  List *actionStates = NIL;
3008  ListCell *l;
3009 
3010  /*
3011  * For INSERT actions, the root relation's merge action is OK since the
3012  * INSERT's targetlist and the WHEN conditions can only refer to the
3013  * source relation and hence it does not matter which result relation we
3014  * work with.
3015  *
3016  * XXX does this mean that we can avoid creating copies of actionStates on
3017  * partitioned tables, for not-matched actions?
3018  */
3019  actionStates = resultRelInfo->ri_notMatchedMergeAction;
3020 
3021  /*
3022  * Make source tuple available to ExecQual and ExecProject. We don't need
3023  * the target tuple, since the WHEN quals and targetlist can't refer to
3024  * the target columns.
3025  */
3026  econtext->ecxt_scantuple = NULL;
3027  econtext->ecxt_innertuple = context->planSlot;
3028  econtext->ecxt_outertuple = NULL;
3029 
3030  foreach(l, actionStates)
3031  {
3033  CmdType commandType = action->mas_action->commandType;
3034  TupleTableSlot *newslot;
3035 
3036  /*
3037  * Test condition, if any.
3038  *
3039  * In the absence of any condition, we perform the action
3040  * unconditionally (no need to check separately since ExecQual() will
3041  * return true if there are no conditions to evaluate).
3042  */
3043  if (!ExecQual(action->mas_whenqual, econtext))
3044  continue;
3045 
3046  /* Perform stated action */
3047  switch (commandType)
3048  {
3049  case CMD_INSERT:
3050 
3051  /*
3052  * Project the tuple. In case of a partitioned table, the
3053  * projection was already built to use the root's descriptor,
3054  * so we don't need to map the tuple here.
3055  */
3056  newslot = ExecProject(action->mas_proj);
3057  context->relaction = action;
3058 
3059  (void) ExecInsert(context, mtstate->rootResultRelInfo, newslot,
3060  canSetTag, NULL, NULL);
3061  mtstate->mt_merge_inserted += 1;
3062  break;
3063  case CMD_NOTHING:
3064  /* Do nothing */
3065  break;
3066  default:
3067  elog(ERROR, "unknown action in MERGE WHEN NOT MATCHED clause");
3068  }
3069 
3070  /*
3071  * We've activated one of the WHEN clauses, so we don't search
3072  * further. This is required behaviour, not an optimization.
3073  */
3074  break;
3075  }
3076 }
3077 
3078 /*
3079  * Initialize state for execution of MERGE.
3080  */
3081 void
3083 {
3084  ModifyTable *node = (ModifyTable *) mtstate->ps.plan;
3085  ResultRelInfo *rootRelInfo = mtstate->rootResultRelInfo;
3086  ResultRelInfo *resultRelInfo;
3087  ExprContext *econtext;
3088  ListCell *lc;
3089  int i;
3090 
3091  if (node->mergeActionLists == NIL)
3092  return;
3093 
3094  mtstate->mt_merge_subcommands = 0;
3095 
3096  if (mtstate->ps.ps_ExprContext == NULL)
3097  ExecAssignExprContext(estate, &mtstate->ps);
3098  econtext = mtstate->ps.ps_ExprContext;
3099 
3100  /*
3101  * Create a MergeActionState for each action on the mergeActionList and
3102  * add it to either a list of matched actions or not-matched actions.
3103  *
3104  * Similar logic appears in ExecInitPartitionInfo(), so if changing
3105  * anything here, do so there too.
3106  */
3107  i = 0;
3108  foreach(lc, node->mergeActionLists)
3109  {
3110  List *mergeActionList = lfirst(lc);
3111  TupleDesc relationDesc;
3112  ListCell *l;
3113 
3114  resultRelInfo = mtstate->resultRelInfo + i;
3115  i++;
3116  relationDesc = RelationGetDescr(resultRelInfo->ri_RelationDesc);
3117 
3118  /* initialize slots for MERGE fetches from this rel */
3119  if (unlikely(!resultRelInfo->ri_projectNewInfoValid))
3120  ExecInitMergeTupleSlots(mtstate, resultRelInfo);
3121 
3122  foreach(l, mergeActionList)
3123  {
3125  MergeActionState *action_state;
3126  TupleTableSlot *tgtslot;
3127  TupleDesc tgtdesc;
3128  List **list;
3129 
3130  /*
3131  * Build action merge state for this rel. (For partitions,
3132  * equivalent code exists in ExecInitPartitionInfo.)
3133  */
3134  action_state = makeNode(MergeActionState);
3135  action_state->mas_action = action;
3136  action_state->mas_whenqual = ExecInitQual((List *) action->qual,
3137  &mtstate->ps);
3138 
3139  /*
3140  * We create two lists - one for WHEN MATCHED actions and one for
3141  * WHEN NOT MATCHED actions - and stick the MergeActionState into
3142  * the appropriate list.
3143  */
3144  if (action_state->mas_action->matched)
3145  list = &resultRelInfo->ri_matchedMergeAction;
3146  else
3147  list = &resultRelInfo->ri_notMatchedMergeAction;
3148  *list = lappend(*list, action_state);
3149 
3150  switch (action->commandType)
3151  {
3152  case CMD_INSERT:
3153  ExecCheckPlanOutput(rootRelInfo->ri_RelationDesc,
3154  action->targetList);
3155 
3156  /*
3157  * If the MERGE targets a partitioned table, any INSERT
3158  * actions must be routed through it, not the child
3159  * relations. Initialize the routing struct and the root
3160  * table's "new" tuple slot for that, if not already done.
3161  * The projection we prepare, for all relations, uses the
3162  * root relation descriptor, and targets the plan's root
3163  * slot. (This is consistent with the fact that we
3164  * checked the plan output to match the root relation,
3165  * above.)
3166  */
3167  if (rootRelInfo->ri_RelationDesc->rd_rel->relkind ==
3168  RELKIND_PARTITIONED_TABLE)
3169  {
3170  if (mtstate->mt_partition_tuple_routing == NULL)
3171  {
3172  /*
3173  * Initialize planstate for routing if not already
3174  * done.
3175  *
3176  * Note that the slot is managed as a standalone
3177  * slot belonging to ModifyTableState, so we pass
3178  * NULL for the 2nd argument.
3179  */
3180  mtstate->mt_root_tuple_slot =
3181  table_slot_create(rootRelInfo->ri_RelationDesc,
3182  NULL);
3183  mtstate->mt_partition_tuple_routing =
3185  rootRelInfo->ri_RelationDesc);
3186  }
3187  tgtslot = mtstate->mt_root_tuple_slot;
3188  tgtdesc = RelationGetDescr(rootRelInfo->ri_RelationDesc);
3189  }
3190  else
3191  {
3192  /* not partitioned? use the stock relation and slot */
3193  tgtslot = resultRelInfo->ri_newTupleSlot;
3194  tgtdesc = RelationGetDescr(resultRelInfo->ri_RelationDesc);
3195  }
3196 
3197  action_state->mas_proj =
3198  ExecBuildProjectionInfo(action->targetList, econtext,
3199  tgtslot,
3200  &mtstate->ps,
3201  tgtdesc);
3202 
3203  mtstate->mt_merge_subcommands |= MERGE_INSERT;
3204  break;
3205  case CMD_UPDATE:
3206  action_state->mas_proj =
3207  ExecBuildUpdateProjection(action->targetList,
3208  true,
3209  action->updateColnos,
3210  relationDesc,
3211  econtext,
3212  resultRelInfo->ri_newTupleSlot,
3213  &mtstate->ps);
3214  mtstate->mt_merge_subcommands |= MERGE_UPDATE;
3215  break;
3216  case CMD_DELETE:
3217  mtstate->mt_merge_subcommands |= MERGE_DELETE;
3218  break;
3219  case CMD_NOTHING:
3220  break;
3221  default:
3222  elog(ERROR, "unknown operation");
3223  break;
3224  }
3225  }
3226  }
3227 }
3228 
3229 /*
3230  * Initializes the tuple slots in a ResultRelInfo for any MERGE action.
3231  *
3232  * We mark 'projectNewInfoValid' even though the projections themselves
3233  * are not initialized here.
3234  */
3235 void
3237  ResultRelInfo *resultRelInfo)
3238 {
3239  EState *estate = mtstate->ps.state;
3240 
3241  Assert(!resultRelInfo->ri_projectNewInfoValid);
3242 
3243  resultRelInfo->ri_oldTupleSlot =
3244  table_slot_create(resultRelInfo->ri_RelationDesc,
3245  &estate->es_tupleTable);
3246  resultRelInfo->ri_newTupleSlot =
3247  table_slot_create(resultRelInfo->ri_RelationDesc,
3248  &estate->es_tupleTable);
3249  resultRelInfo->ri_projectNewInfoValid = true;
3250 }
3251 
3252 /*
3253  * Callback for ModifyTableContext->GetUpdateNewTuple for use by MERGE. It
3254  * computes the updated tuple by projecting from the current merge action's
3255  * projection.
3256  */
3257 static TupleTableSlot *
3259  TupleTableSlot *planSlot,
3260  TupleTableSlot *oldSlot,
3261  MergeActionState *relaction)
3262 {
3263  ExprContext *econtext = relaction->mas_proj->pi_exprContext;
3264 
3265  econtext->ecxt_scantuple = oldSlot;
3266  econtext->ecxt_innertuple = planSlot;
3267 
3268  return ExecProject(relaction->mas_proj);
3269 }
3270 
3271 /*
3272  * Process BEFORE EACH STATEMENT triggers
3273  */
3274 static void
3276 {
3277  ModifyTable *plan = (ModifyTable *) node->ps.plan;
3278  ResultRelInfo *resultRelInfo = node->rootResultRelInfo;
3279 
3280  switch (node->operation)
3281  {
3282  case CMD_INSERT:
3283  ExecBSInsertTriggers(node->ps.state, resultRelInfo);
3284  if (plan->onConflictAction == ONCONFLICT_UPDATE)
3286  resultRelInfo);
3287  break;
3288  case CMD_UPDATE:
3289  ExecBSUpdateTriggers(node->ps.state, resultRelInfo);
3290  break;
3291  case CMD_DELETE:
3292  ExecBSDeleteTriggers(node->ps.state, resultRelInfo);
3293  break;
3294  case CMD_MERGE:
3295  if (node->mt_merge_subcommands & MERGE_INSERT)
3296  ExecBSInsertTriggers(node->ps.state, resultRelInfo);
3297  if (node->mt_merge_subcommands & MERGE_UPDATE)
3298  ExecBSUpdateTriggers(node->ps.state, resultRelInfo);
3299  if (node->mt_merge_subcommands & MERGE_DELETE)
3300  ExecBSDeleteTriggers(node->ps.state, resultRelInfo);
3301  break;
3302  default:
3303  elog(ERROR, "unknown operation");
3304  break;
3305  }
3306 }
3307 
3308 /*
3309  * Process AFTER EACH STATEMENT triggers
3310  */
3311 static void
3313 {
3314  ModifyTable *plan = (ModifyTable *) node->ps.plan;
3315  ResultRelInfo *resultRelInfo = node->rootResultRelInfo;
3316 
3317  switch (node->operation)
3318  {
3319  case CMD_INSERT:
3320  if (plan->onConflictAction == ONCONFLICT_UPDATE)
3322  resultRelInfo,
3323  node->mt_oc_transition_capture);
3324  ExecASInsertTriggers(node->ps.state, resultRelInfo,
3325  node->mt_transition_capture);
3326  break;
3327  case CMD_UPDATE:
3328  ExecASUpdateTriggers(node->ps.state, resultRelInfo,
3329  node->mt_transition_capture);
3330  break;
3331  case CMD_DELETE:
3332  ExecASDeleteTriggers(node->ps.state, resultRelInfo,
3333  node->mt_transition_capture);
3334  break;
3335  case CMD_MERGE:
3336  if (node->mt_merge_subcommands & MERGE_DELETE)
3337  ExecASDeleteTriggers(node->ps.state, resultRelInfo,
3338  node->mt_transition_capture);
3339  if (node->mt_merge_subcommands & MERGE_UPDATE)
3340  ExecASUpdateTriggers(node->ps.state, resultRelInfo,
3341  node->mt_transition_capture);
3342  if (node->mt_merge_subcommands & MERGE_INSERT)
3343  ExecASInsertTriggers(node->ps.state, resultRelInfo,
3344  node->mt_transition_capture);
3345  break;
3346  default:
3347  elog(ERROR, "unknown operation");
3348  break;
3349  }
3350 }
3351 
3352 /*
3353  * Set up the state needed for collecting transition tuples for AFTER
3354  * triggers.
3355  */
3356 static void
3358 {
3359  ModifyTable *plan = (ModifyTable *) mtstate->ps.plan;
3360  ResultRelInfo *targetRelInfo = mtstate->rootResultRelInfo;
3361 
3362  /* Check for transition tables on the directly targeted relation. */
3363  mtstate->mt_transition_capture =
3364  MakeTransitionCaptureState(targetRelInfo->ri_TrigDesc,
3365  RelationGetRelid(targetRelInfo->ri_RelationDesc),
3366  mtstate->operation);
3367  if (plan->operation == CMD_INSERT &&
3369  mtstate->mt_oc_transition_capture =
3370  MakeTransitionCaptureState(targetRelInfo->ri_TrigDesc,
3371  RelationGetRelid(targetRelInfo->ri_RelationDesc),
3372  CMD_UPDATE);
3373 }
3374 
3375 /*
3376  * ExecPrepareTupleRouting --- prepare for routing one tuple
3377  *
3378  * Determine the partition in which the tuple in slot is to be inserted,
3379  * and return its ResultRelInfo in *partRelInfo. The return value is
3380  * a slot holding the tuple of the partition rowtype.
3381  *
3382  * This also sets the transition table information in mtstate based on the
3383  * selected partition.
3384  */
3385 static TupleTableSlot *
3387  EState *estate,
3388  PartitionTupleRouting *proute,
3389  ResultRelInfo *targetRelInfo,
3390  TupleTableSlot *slot,
3391  ResultRelInfo **partRelInfo)
3392 {
3393  ResultRelInfo *partrel;
3394  TupleConversionMap *map;
3395 
3396  /*
3397  * Lookup the target partition's ResultRelInfo. If ExecFindPartition does
3398  * not find a valid partition for the tuple in 'slot' then an error is
3399  * raised. An error may also be raised if the found partition is not a
3400  * valid target for INSERTs. This is required since a partitioned table
3401  * UPDATE to another partition becomes a DELETE+INSERT.
3402  */
3403  partrel = ExecFindPartition(mtstate, targetRelInfo, proute, slot, estate);
3404 
3405  /*
3406  * If we're capturing transition tuples, we might need to convert from the
3407  * partition rowtype to root partitioned table's rowtype. But if there
3408  * are no BEFORE triggers on the partition that could change the tuple, we
3409  * can just remember the original unconverted tuple to avoid a needless
3410  * round trip conversion.
3411  */
3412  if (mtstate->mt_transition_capture != NULL)
3413  {
3414  bool has_before_insert_row_trig;
3415 
3416  has_before_insert_row_trig = (partrel->ri_TrigDesc &&
3418 
3420  !has_before_insert_row_trig ? slot : NULL;
3421  }
3422 
3423  /*
3424  * Convert the tuple, if necessary.
3425  */
3426  map = partrel->ri_RootToPartitionMap;
3427  if (map != NULL)
3428  {
3429  TupleTableSlot *new_slot = partrel->ri_PartitionTupleSlot;
3430 
3431  slot = execute_attr_map_slot(map->attrMap, slot, new_slot);
3432  }
3433 
3434  *partRelInfo = partrel;
3435  return slot;
3436 }
3437 
3438 /* ----------------------------------------------------------------
3439  * ExecModifyTable
3440  *
3441  * Perform table modifications as required, and return RETURNING results
3442  * if needed.
3443  * ----------------------------------------------------------------
3444  */
3445 static TupleTableSlot *
3447 {
3448  ModifyTableState *node = castNode(ModifyTableState, pstate);
3449  ModifyTableContext context;
3450  EState *estate = node->ps.state;
3451  CmdType operation = node->operation;
3452  ResultRelInfo *resultRelInfo;
3453  PlanState *subplanstate;
3454  TupleTableSlot *slot;
3455  TupleTableSlot *oldSlot;
3456  ItemPointerData tuple_ctid;
3457  HeapTupleData oldtupdata;
3458  HeapTuple oldtuple;
3459  ItemPointer tupleid;
3461  List *relinfos = NIL;
3462  ListCell *lc;
3463 
3465 
3466  /*
3467  * This should NOT get called during EvalPlanQual; we should have passed a
3468  * subplan tree to EvalPlanQual, instead. Use a runtime test not just
3469  * Assert because this condition is easy to miss in testing. (Note:
3470  * although ModifyTable should not get executed within an EvalPlanQual
3471  * operation, we do have to allow it to be initialized and shut down in
3472  * case it is within a CTE subplan. Hence this test must be here, not in
3473  * ExecInitModifyTable.)
3474  */
3475  if (estate->es_epq_active != NULL)
3476  elog(ERROR, "ModifyTable should not be called during EvalPlanQual");
3477 
3478  /*
3479  * If we've already completed processing, don't try to do more. We need
3480  * this test because ExecPostprocessPlan might call us an extra time, and
3481  * our subplan's nodes aren't necessarily robust against being called
3482  * extra times.
3483  */
3484  if (node->mt_done)
3485  return NULL;
3486 
3487  /*
3488  * On first call, fire BEFORE STATEMENT triggers before proceeding.
3489  */
3490  if (node->fireBSTriggers)
3491  {
3492  fireBSTriggers(node);
3493  node->fireBSTriggers = false;
3494  }
3495 
3496  /* Preload local variables */
3497  resultRelInfo = node->resultRelInfo + node->mt_lastResultIndex;
3498  subplanstate = outerPlanState(node);
3499 
3500  /* Set global context */
3501  context.mtstate = node;
3502  context.epqstate = &node->mt_epqstate;
3503  context.estate = estate;
3504 
3505  /*
3506  * Fetch rows from subplan, and execute the required table modification
3507  * for each row.
3508  */
3509  for (;;)
3510  {
3511  /*
3512  * Reset the per-output-tuple exprcontext. This is needed because
3513  * triggers expect to use that context as workspace. It's a bit ugly
3514  * to do this below the top level of the plan, however. We might need
3515  * to rethink this later.
3516  */
3517  ResetPerTupleExprContext(estate);
3518 
3519  /*
3520  * Reset per-tuple memory context used for processing on conflict and
3521  * returning clauses, to free any expression evaluation storage
3522  * allocated in the previous cycle.
3523  */
3524  if (pstate->ps_ExprContext)
3526 
3527  context.planSlot = ExecProcNode(subplanstate);
3528 
3529  /* No more tuples to process? */
3530  if (TupIsNull(context.planSlot))
3531  break;
3532 
3533  /*
3534  * When there are multiple result relations, each tuple contains a
3535  * junk column that gives the OID of the rel from which it came.
3536  * Extract it and select the correct result relation.
3537  */
3539  {
3540  Datum datum;
3541  bool isNull;
3542  Oid resultoid;
3543 
3544  datum = ExecGetJunkAttribute(context.planSlot, node->mt_resultOidAttno,
3545  &isNull);
3546  if (isNull)
3547  {
3548  /*
3549  * For commands other than MERGE, any tuples having InvalidOid
3550  * for tableoid are errors. For MERGE, we may need to handle
3551  * them as WHEN NOT MATCHED clauses if any, so do that.
3552  *
3553  * Note that we use the node's toplevel resultRelInfo, not any
3554  * specific partition's.
3555  */
3556  if (operation == CMD_MERGE)
3557  {
3558  EvalPlanQualSetSlot(&node->mt_epqstate, context.planSlot);
3559 
3560  ExecMerge(&context, node->resultRelInfo, NULL, node->canSetTag);
3561  continue; /* no RETURNING support yet */
3562  }
3563 
3564  elog(ERROR, "tableoid is NULL");
3565  }
3566  resultoid = DatumGetObjectId(datum);
3567 
3568  /* If it's not the same as last time, we need to locate the rel */
3569  if (resultoid != node->mt_lastResultOid)
3570  resultRelInfo = ExecLookupResultRelByOid(node, resultoid,
3571  false, true);
3572  }
3573 
3574  /*
3575  * If resultRelInfo->ri_usesFdwDirectModify is true, all we need to do
3576  * here is compute the RETURNING expressions.
3577  */
3578  if (resultRelInfo->ri_usesFdwDirectModify)
3579  {
3580  Assert(resultRelInfo->ri_projectReturning);
3581 
3582  /*
3583  * A scan slot containing the data that was actually inserted,
3584  * updated or deleted has already been made available to
3585  * ExecProcessReturning by IterateDirectModify, so no need to
3586  * provide it here.
3587  */
3588  slot = ExecProcessReturning(resultRelInfo, NULL, context.planSlot);
3589 
3590  return slot;
3591  }
3592 
3593  EvalPlanQualSetSlot(&node->mt_epqstate, context.planSlot);
3594  slot = context.planSlot;
3595 
3596  tupleid = NULL;
3597  oldtuple = NULL;
3598 
3599  /*
3600  * For UPDATE/DELETE/MERGE, fetch the row identity info for the tuple
3601  * to be updated/deleted/merged. For a heap relation, that's a TID;
3602  * otherwise we may have a wholerow junk attr that carries the old
3603  * tuple in toto. Keep this in step with the part of
3604  * ExecInitModifyTable that sets up ri_RowIdAttNo.
3605  */
3606  if (operation == CMD_UPDATE || operation == CMD_DELETE ||
3607  operation == CMD_MERGE)
3608  {
3609  char relkind;
3610  Datum datum;
3611  bool isNull;
3612 
3613  relkind = resultRelInfo->ri_RelationDesc->rd_rel->relkind;
3614  if (relkind == RELKIND_RELATION ||
3615  relkind == RELKIND_MATVIEW ||
3616  relkind == RELKIND_PARTITIONED_TABLE)
3617  {
3618  /* ri_RowIdAttNo refers to a ctid attribute */
3619  Assert(AttributeNumberIsValid(resultRelInfo->ri_RowIdAttNo));
3620  datum = ExecGetJunkAttribute(slot,
3621  resultRelInfo->ri_RowIdAttNo,
3622  &isNull);
3623 
3624  /*
3625  * For commands other than MERGE, any tuples having a null row
3626  * identifier are errors. For MERGE, we may need to handle
3627  * them as WHEN NOT MATCHED clauses if any, so do that.
3628  *
3629  * Note that we use the node's toplevel resultRelInfo, not any
3630  * specific partition's.
3631  */
3632  if (isNull)
3633  {
3634  if (operation == CMD_MERGE)
3635  {
3636  EvalPlanQualSetSlot(&node->mt_epqstate, context.planSlot);
3637 
3638  ExecMerge(&context, node->resultRelInfo, NULL, node->canSetTag);
3639  continue; /* no RETURNING support yet */
3640  }
3641 
3642  elog(ERROR, "ctid is NULL");
3643  }
3644 
3645  tupleid = (ItemPointer) DatumGetPointer(datum);
3646  tuple_ctid = *tupleid; /* be sure we don't free ctid!! */
3647  tupleid = &tuple_ctid;
3648  }
3649 
3650  /*
3651  * Use the wholerow attribute, when available, to reconstruct the
3652  * old relation tuple. The old tuple serves one or both of two
3653  * purposes: 1) it serves as the OLD tuple for row triggers, 2) it
3654  * provides values for any unchanged columns for the NEW tuple of
3655  * an UPDATE, because the subplan does not produce all the columns
3656  * of the target table.
3657  *
3658  * Note that the wholerow attribute does not carry system columns,
3659  * so foreign table triggers miss seeing those, except that we
3660  * know enough here to set t_tableOid. Quite separately from
3661  * this, the FDW may fetch its own junk attrs to identify the row.
3662  *
3663  * Other relevant relkinds, currently limited to views, always
3664  * have a wholerow attribute.
3665  */
3666  else if (AttributeNumberIsValid(resultRelInfo->ri_RowIdAttNo))
3667  {
3668  datum = ExecGetJunkAttribute(slot,
3669  resultRelInfo->ri_RowIdAttNo,
3670  &isNull);
3671  /* shouldn't ever get a null result... */
3672  if (isNull)
3673  elog(ERROR, "wholerow is NULL");
3674 
3675  oldtupdata.t_data = DatumGetHeapTupleHeader(datum);
3676  oldtupdata.t_len =
3678  ItemPointerSetInvalid(&(oldtupdata.t_self));
3679  /* Historically, view triggers see invalid t_tableOid. */
3680  oldtupdata.t_tableOid =
3681  (relkind == RELKIND_VIEW) ? InvalidOid :
3682  RelationGetRelid(resultRelInfo->ri_RelationDesc);
3683 
3684  oldtuple = &oldtupdata;
3685  }
3686  else
3687  {
3688  /* Only foreign tables are allowed to omit a row-ID attr */
3689  Assert(relkind == RELKIND_FOREIGN_TABLE);
3690  }
3691  }
3692 
3693  switch (operation)
3694  {
3695  case CMD_INSERT:
3696  /* Initialize projection info if first time for this table */
3697  if (unlikely(!resultRelInfo->ri_projectNewInfoValid))
3698  ExecInitInsertProjection(node, resultRelInfo);
3699  slot = ExecGetInsertNewTuple(resultRelInfo, context.planSlot);
3700  slot = ExecInsert(&context, resultRelInfo, slot,
3701  node->canSetTag, NULL, NULL);
3702  break;
3703 
3704  case CMD_UPDATE:
3705  /* Initialize projection info if first time for this table */
3706  if (unlikely(!resultRelInfo->ri_projectNewInfoValid))
3707  ExecInitUpdateProjection(node, resultRelInfo);
3708 
3709  /*
3710  * Make the new tuple by combining plan's output tuple with
3711  * the old tuple being updated.
3712  */
3713  oldSlot = resultRelInfo->ri_oldTupleSlot;
3714  if (oldtuple != NULL)
3715  {
3716  /* Use the wholerow junk attr as the old tuple. */
3717  ExecForceStoreHeapTuple(oldtuple, oldSlot, false);
3718  }
3719  else
3720  {
3721  /* Fetch the most recent version of old tuple. */
3722  Relation relation = resultRelInfo->ri_RelationDesc;
3723 
3724  if (!table_tuple_fetch_row_version(relation, tupleid,
3725  SnapshotAny,
3726  oldSlot))
3727  elog(ERROR, "failed to fetch tuple being updated");
3728  }
3729  slot = internalGetUpdateNewTuple(resultRelInfo, context.planSlot,
3730  oldSlot, NULL);
3732  context.relaction = NULL;
3733 
3734  /* Now apply the update. */
3735  slot = ExecUpdate(&context, resultRelInfo, tupleid, oldtuple,
3736  slot, node->canSetTag);
3737  break;
3738 
3739  case CMD_DELETE:
3740  slot = ExecDelete(&context, resultRelInfo, tupleid, oldtuple,
3741  true, false, node->canSetTag, NULL, NULL);
3742  break;
3743 
3744  case CMD_MERGE:
3745  slot = ExecMerge(&context, resultRelInfo, tupleid, node->canSetTag);
3746  break;
3747 
3748  default:
3749  elog(ERROR, "unknown operation");
3750  break;
3751  }
3752 
3753  /*
3754  * If we got a RETURNING result, return it to caller. We'll continue
3755  * the work on next call.
3756  */
3757  if (slot)
3758  return slot;
3759  }
3760 
3761  /*
3762  * Insert remaining tuples for batch insert.
3763  */
3764  if (proute)
3765  relinfos = estate->es_tuple_routing_result_relations;
3766  else
3767  relinfos = estate->es_opened_result_relations;
3768 
3769  foreach(lc, relinfos)
3770  {
3771  resultRelInfo = lfirst(lc);
3772  if (resultRelInfo->ri_NumSlots > 0)
3773  ExecBatchInsert(node, resultRelInfo,
3774  resultRelInfo->ri_Slots,
3775  resultRelInfo->ri_PlanSlots,
3776  resultRelInfo->ri_NumSlots,
3777  estate, node->canSetTag);
3778  }
3779 
3780  /*
3781  * We're done, but fire AFTER STATEMENT triggers before exiting.
3782  */
3783  fireASTriggers(node);
3784 
3785  node->mt_done = true;
3786 
3787  return NULL;
3788 }
3789 
3790 /*
3791  * ExecLookupResultRelByOid
3792  * If the table with given OID is among the result relations to be
3793  * updated by the given ModifyTable node, return its ResultRelInfo.
3794  *
3795  * If not found, return NULL if missing_ok, else raise error.
3796  *
3797  * If update_cache is true, then upon successful lookup, update the node's
3798  * one-element cache. ONLY ExecModifyTable may pass true for this.
3799  */
3800 ResultRelInfo *
3802  bool missing_ok, bool update_cache)
3803 {
3804  if (node->mt_resultOidHash)
3805  {
3806  /* Use the pre-built hash table to locate the rel */
3807  MTTargetRelLookup *mtlookup;
3808 
3809  mtlookup = (MTTargetRelLookup *)
3810  hash_search(node->mt_resultOidHash, &resultoid, HASH_FIND, NULL);
3811  if (mtlookup)
3812  {
3813  if (update_cache)
3814  {
3815  node->mt_lastResultOid = resultoid;
3816  node->mt_lastResultIndex = mtlookup->relationIndex;
3817  }
3818  return node->resultRelInfo + mtlookup->relationIndex;
3819  }
3820  }
3821  else
3822  {
3823  /* With few target rels, just search the ResultRelInfo array */
3824  for (int ndx = 0; ndx < node->mt_nrels; ndx++)
3825  {
3826  ResultRelInfo *rInfo = node->resultRelInfo + ndx;
3827 
3828  if (RelationGetRelid(rInfo->ri_RelationDesc) == resultoid)
3829  {
3830  if (update_cache)
3831  {
3832  node->mt_lastResultOid = resultoid;
3833  node->mt_lastResultIndex = ndx;
3834  }
3835  return rInfo;
3836  }
3837  }
3838  }
3839 
3840  if (!missing_ok)
3841  elog(ERROR, "incorrect result relation OID %u", resultoid);
3842  return NULL;
3843 }
3844 
3845 /* ----------------------------------------------------------------
3846  * ExecInitModifyTable
3847  * ----------------------------------------------------------------
3848  */
3850 ExecInitModifyTable(ModifyTable *node, EState *estate, int eflags)
3851 {
3852  ModifyTableState *mtstate;
3853  Plan *subplan = outerPlan(node);
3854  CmdType operation = node->operation;
3855  int nrels = list_length(node->resultRelations);
3856  ResultRelInfo *resultRelInfo;
3857  List *arowmarks;
3858  ListCell *l;
3859  int i;
3860  Relation rel;
3861 
3862  /* check for unsupported flags */
3863  Assert(!(eflags & (EXEC_FLAG_BACKWARD | EXEC_FLAG_MARK)));
3864 
3865  /*
3866  * create state structure
3867  */
3868  mtstate = makeNode(ModifyTableState);
3869  mtstate->ps.plan = (Plan *) node;
3870  mtstate->ps.state = estate;
3871  mtstate->ps.ExecProcNode = ExecModifyTable;
3872 
3873  mtstate->operation = operation;
3874  mtstate->canSetTag = node->canSetTag;
3875  mtstate->mt_done = false;
3876 
3877  mtstate->mt_nrels = nrels;
3878  mtstate->resultRelInfo = (ResultRelInfo *)
3879  palloc(nrels * sizeof(ResultRelInfo));
3880 
3881  mtstate->mt_merge_inserted = 0;
3882  mtstate->mt_merge_updated = 0;
3883  mtstate->mt_merge_deleted = 0;
3884 
3885  /*----------
3886  * Resolve the target relation. This is the same as:
3887  *
3888  * - the relation for which we will fire FOR STATEMENT triggers,
3889  * - the relation into whose tuple format all captured transition tuples
3890  * must be converted, and
3891  * - the root partitioned table used for tuple routing.
3892  *
3893  * If it's a partitioned table, the root partition doesn't appear
3894  * elsewhere in the plan and its RT index is given explicitly in
3895  * node->rootRelation. Otherwise (i.e. table inheritance) the target
3896  * relation is the first relation in the node->resultRelations list.
3897  *----------
3898  */
3899  if (node->rootRelation > 0)
3900  {
3902  ExecInitResultRelation(estate, mtstate->rootResultRelInfo,
3903  node->rootRelation);
3904  }
3905  else
3906  {
3907  mtstate->rootResultRelInfo = mtstate->resultRelInfo;
3908  ExecInitResultRelation(estate, mtstate->resultRelInfo,
3909  linitial_int(node->resultRelations));
3910  }
3911 
3912  /* set up epqstate with dummy subplan data for the moment */
3913  EvalPlanQualInit(&mtstate->mt_epqstate, estate, NULL, NIL, node->epqParam);
3914  mtstate->fireBSTriggers = true;
3915 
3916  /*
3917  * Build state for collecting transition tuples. This requires having a
3918  * valid trigger query context, so skip it in explain-only mode.
3919  */
3920  if (!(eflags & EXEC_FLAG_EXPLAIN_ONLY))
3921  ExecSetupTransitionCaptureState(mtstate, estate);
3922 
3923  /*
3924  * Open all the result relations and initialize the ResultRelInfo structs.
3925  * (But root relation was initialized above, if it's part of the array.)
3926  * We must do this before initializing the subplan, because direct-modify
3927  * FDWs expect their ResultRelInfos to be available.
3928  */
3929  resultRelInfo = mtstate->resultRelInfo;
3930  i = 0;
3931  foreach(l, node->resultRelations)
3932  {
3933  Index resultRelation = lfirst_int(l);
3934 
3935  if (resultRelInfo != mtstate->rootResultRelInfo)
3936  {
3937  ExecInitResultRelation(estate, resultRelInfo, resultRelation);
3938 
3939  /*
3940  * For child result relations, store the root result relation
3941  * pointer. We do so for the convenience of places that want to
3942  * look at the query's original target relation but don't have the
3943  * mtstate handy.
3944  */
3945  resultRelInfo->ri_RootResultRelInfo = mtstate->rootResultRelInfo;
3946  }
3947 
3948  /* Initialize the usesFdwDirectModify flag */
3949  resultRelInfo->ri_usesFdwDirectModify =
3951 
3952  /*
3953  * Verify result relation is a valid target for the current operation
3954  */
3955  CheckValidResultRel(resultRelInfo, operation);
3956 
3957  resultRelInfo++;
3958  i++;
3959  }
3960 
3961  /*
3962  * Now we may initialize the subplan.
3963  */
3964  outerPlanState(mtstate) = ExecInitNode(subplan, estate, eflags);
3965 
3966  /*
3967  * Do additional per-result-relation initialization.
3968  */
3969  for (i = 0; i < nrels; i++)
3970  {
3971  resultRelInfo = &mtstate->resultRelInfo[i];
3972 
3973  /* Let FDWs init themselves for foreign-table result rels */
3974  if (!resultRelInfo->ri_usesFdwDirectModify &&
3975  resultRelInfo->ri_FdwRoutine != NULL &&
3976  resultRelInfo->ri_FdwRoutine->BeginForeignModify != NULL)
3977  {
3978  List *fdw_private = (List *) list_nth(node->fdwPrivLists, i);
3979 
3980  resultRelInfo->ri_FdwRoutine->BeginForeignModify(mtstate,
3981  resultRelInfo,
3982  fdw_private,
3983  i,
3984  eflags);
3985  }
3986 
3987  /*
3988  * For UPDATE/DELETE/MERGE, find the appropriate junk attr now, either
3989  * a 'ctid' or 'wholerow' attribute depending on relkind. For foreign
3990  * tables, the FDW might have created additional junk attr(s), but
3991  * those are no concern of ours.
3992  */
3993  if (operation == CMD_UPDATE || operation == CMD_DELETE ||
3994  operation == CMD_MERGE)
3995  {
3996  char relkind;
3997 
3998  relkind = resultRelInfo->ri_RelationDesc->rd_rel->relkind;
3999  if (relkind == RELKIND_RELATION ||
4000  relkind == RELKIND_MATVIEW ||
4001  relkind == RELKIND_PARTITIONED_TABLE)
4002  {
4003  resultRelInfo->ri_RowIdAttNo =
4004  ExecFindJunkAttributeInTlist(subplan->targetlist, "ctid");
4005  if (!AttributeNumberIsValid(resultRelInfo->ri_RowIdAttNo))
4006  elog(ERROR, "could not find junk ctid column");
4007  }
4008  else if (relkind == RELKIND_FOREIGN_TABLE)
4009  {
4010  /*
4011  * We don't support MERGE with foreign tables for now. (It's
4012  * problematic because the implementation uses CTID.)
4013  */
4014  Assert(operation != CMD_MERGE);
4015 
4016  /*
4017  * When there is a row-level trigger, there should be a
4018  * wholerow attribute. We also require it to be present in
4019  * UPDATE and MERGE, so we can get the values of unchanged
4020  * columns.
4021  */
4022  resultRelInfo->ri_RowIdAttNo =
4024  "wholerow");
4025  if ((mtstate->operation == CMD_UPDATE || mtstate->operation == CMD_MERGE) &&
4026  !AttributeNumberIsValid(resultRelInfo->ri_RowIdAttNo))
4027  elog(ERROR, "could not find junk wholerow column");
4028  }
4029  else
4030  {
4031  /* No support for MERGE */
4032  Assert(operation != CMD_MERGE);
4033  /* Other valid target relkinds must provide wholerow */
4034  resultRelInfo->ri_RowIdAttNo =
4036  "wholerow");
4037  if (!AttributeNumberIsValid(resultRelInfo->ri_RowIdAttNo))
4038  elog(ERROR, "could not find junk wholerow column");
4039  }
4040  }
4041  }
4042 
4043  /*
4044  * If this is an inherited update/delete/merge, there will be a junk
4045  * attribute named "tableoid" present in the subplan's targetlist. It
4046  * will be used to identify the result relation for a given tuple to be
4047  * updated/deleted/merged.
4048  */
4049  mtstate->mt_resultOidAttno =
4050  ExecFindJunkAttributeInTlist(subplan->targetlist, "tableoid");
4051  Assert(AttributeNumberIsValid(mtstate->mt_resultOidAttno) || nrels == 1);
4052  mtstate->mt_lastResultOid = InvalidOid; /* force lookup at first tuple */
4053  mtstate->mt_lastResultIndex = 0; /* must be zero if no such attr */
4054 
4055  /* Get the root target relation */
4056  rel = mtstate->rootResultRelInfo->ri_RelationDesc;
4057 
4058  /*
4059  * Build state for tuple routing if it's a partitioned INSERT. An UPDATE
4060  * or MERGE might need this too, but only if it actually moves tuples
4061  * between partitions; in that case setup is done by
4062  * ExecCrossPartitionUpdate.
4063  */
4064  if (rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE &&
4065  operation == CMD_INSERT)
4066  mtstate->mt_partition_tuple_routing =
4067  ExecSetupPartitionTupleRouting(estate, rel);
4068 
4069  /*
4070  * Initialize any WITH CHECK OPTION constraints if needed.
4071  */
4072  resultRelInfo = mtstate->resultRelInfo;
4073  foreach(l, node->withCheckOptionLists)
4074  {
4075  List *wcoList = (List *) lfirst(l);
4076  List *wcoExprs = NIL;
4077  ListCell *ll;
4078 
4079  foreach(ll, wcoList)
4080  {
4081  WithCheckOption *wco = (WithCheckOption *) lfirst(ll);
4082  ExprState *wcoExpr = ExecInitQual((List *) wco->qual,
4083  &mtstate->ps);
4084 
4085  wcoExprs = lappend(wcoExprs, wcoExpr);
4086  }
4087 
4088  resultRelInfo->ri_WithCheckOptions = wcoList;
4089  resultRelInfo->ri_WithCheckOptionExprs = wcoExprs;
4090  resultRelInfo++;
4091  }
4092 
4093  /*
4094  * Initialize RETURNING projections if needed.
4095  */
4096  if (node->returningLists)
4097  {
4098  TupleTableSlot *slot;
4099  ExprContext *econtext;
4100 
4101  /*
4102  * Initialize result tuple slot and assign its rowtype using the first
4103  * RETURNING list. We assume the rest will look the same.
4104  */
4105  mtstate->ps.plan->targetlist = (List *) linitial(node->returningLists);
4106 
4107  /* Set up a slot for the output of the RETURNING projection(s) */
4109  slot = mtstate->ps.ps_ResultTupleSlot;
4110 
4111  /* Need an econtext too */
4112  if (mtstate->ps.ps_ExprContext == NULL)
4113  ExecAssignExprContext(estate, &mtstate->ps);
4114  econtext = mtstate->ps.ps_ExprContext;
4115 
4116  /*
4117  * Build a projection for each result rel.
4118  */
4119  resultRelInfo = mtstate->resultRelInfo;
4120  foreach(l, node->returningLists)
4121  {
4122  List *rlist = (List *) lfirst(l);
4123 
4124  resultRelInfo->ri_returningList = rlist;
4125  resultRelInfo->ri_projectReturning =
4126  ExecBuildProjectionInfo(rlist, econtext, slot, &mtstate->ps,
4127  resultRelInfo->ri_RelationDesc->rd_att);
4128  resultRelInfo++;
4129  }
4130  }
4131  else
4132  {
4133  /*
4134  * We still must construct a dummy result tuple type, because InitPlan
4135  * expects one (maybe should change that?).
4136  */
4137  mtstate->ps.plan->targetlist = NIL;
4138  ExecInitResultTypeTL(&mtstate->ps);
4139 
4140  mtstate->ps.ps_ExprContext = NULL;
4141  }
4142 
4143  /* Set the list of arbiter indexes if needed for ON CONFLICT */
4144  resultRelInfo = mtstate->resultRelInfo;
4145  if (node->onConflictAction != ONCONFLICT_NONE)
4146  {
4147  /* insert may only have one relation, inheritance is not expanded */
4148  Assert(nrels == 1);
4149  resultRelInfo->ri_onConflictArbiterIndexes = node->arbiterIndexes;
4150  }
4151 
4152  /*
4153  * If needed, Initialize target list, projection and qual for ON CONFLICT
4154  * DO UPDATE.
4155  */
4156  if (node->onConflictAction == ONCONFLICT_UPDATE)
4157  {
4159  ExprContext *econtext;
4160  TupleDesc relationDesc;
4161 
4162  /* already exists if created by RETURNING processing above */
4163  if (mtstate->ps.ps_ExprContext == NULL)
4164  ExecAssignExprContext(estate, &mtstate->ps);
4165 
4166  econtext = mtstate->ps.ps_ExprContext;
4167  relationDesc = resultRelInfo->ri_RelationDesc->rd_att;
4168 
4169  /* create state for DO UPDATE SET operation */
4170  resultRelInfo->ri_onConflict = onconfl;
4171 
4172  /* initialize slot for the existing tuple */
4173  onconfl->oc_Existing =
4174  table_slot_create(resultRelInfo->ri_RelationDesc,
4175  &mtstate->ps.state->es_tupleTable);
4176 
4177  /*
4178  * Create the tuple slot for the UPDATE SET projection. We want a slot
4179  * of the table's type here, because the slot will be used to insert
4180  * into the table, and for RETURNING processing - which may access
4181  * system attributes.
4182  */
4183  onconfl->oc_ProjSlot =
4184  table_slot_create(resultRelInfo->ri_RelationDesc,
4185  &mtstate->ps.state->es_tupleTable);
4186 
4187  /* build UPDATE SET projection state */
4188  onconfl->oc_ProjInfo =
4190  true,
4191  node->onConflictCols,
4192  relationDesc,
4193  econtext,
4194  onconfl->oc_ProjSlot,
4195  &mtstate->ps);
4196 
4197  /* initialize state to evaluate the WHERE clause, if any */
4198  if (node->onConflictWhere)
4199  {
4200  ExprState *qualexpr;
4201 
4202  qualexpr = ExecInitQual((List *) node->onConflictWhere,
4203  &mtstate->ps);
4204  onconfl->oc_WhereClause = qualexpr;
4205  }
4206  }
4207 
4208  /*
4209  * If we have any secondary relations in an UPDATE or DELETE, they need to
4210  * be treated like non-locked relations in SELECT FOR UPDATE, ie, the
4211  * EvalPlanQual mechanism needs to be told about them. Locate the
4212  * relevant ExecRowMarks.
4213  */
4214  arowmarks = NIL;
4215  foreach(l, node->rowMarks)
4216  {
4218  ExecRowMark *erm;
4219  ExecAuxRowMark *aerm;
4220 
4221  /* ignore "parent" rowmarks; they are irrelevant at runtime */
4222  if (rc->isParent)
4223  continue;
4224 
4225  /* Find ExecRowMark and build ExecAuxRowMark */
4226  erm = ExecFindRowMark(estate, rc->rti, false);
4227  aerm = ExecBuildAuxRowMark(erm, subplan->targetlist);
4228  arowmarks = lappend(arowmarks, aerm);
4229  }
4230 
4231  /* For a MERGE command, initialize its state */
4232  if (mtstate->operation == CMD_MERGE)
4233  ExecInitMerge(mtstate, estate);
4234 
4235  EvalPlanQualSetPlan(&mtstate->mt_epqstate, subplan, arowmarks);
4236 
4237  /*
4238  * If there are a lot of result relations, use a hash table to speed the
4239  * lookups. If there are not a lot, a simple linear search is faster.
4240  *
4241  * It's not clear where the threshold is, but try 64 for starters. In a
4242  * debugging build, use a small threshold so that we get some test
4243  * coverage of both code paths.
4244  */
4245 #ifdef USE_ASSERT_CHECKING
4246 #define MT_NRELS_HASH 4
4247 #else
4248 #define MT_NRELS_HASH 64
4249 #endif
4250  if (nrels >= MT_NRELS_HASH)
4251  {
4252  HASHCTL hash_ctl;
4253 
4254  hash_ctl.keysize = sizeof(Oid);
4255  hash_ctl.entrysize = sizeof(MTTargetRelLookup);
4256  hash_ctl.hcxt = CurrentMemoryContext;
4257  mtstate->mt_resultOidHash =
4258  hash_create("ModifyTable target hash",
4259  nrels, &hash_ctl,
4261  for (i = 0; i < nrels; i++)
4262  {
4263  Oid hashkey;
4264  MTTargetRelLookup *mtlookup;
4265  bool found;
4266 
4267  resultRelInfo = &mtstate->resultRelInfo[i];
4268  hashkey = RelationGetRelid(resultRelInfo->ri_RelationDesc);
4269  mtlookup = (MTTargetRelLookup *)
4270  hash_search(mtstate->mt_resultOidHash, &hashkey,
4271  HASH_ENTER, &found);
4272  Assert(!found);
4273  mtlookup->relationIndex = i;
4274  }
4275  }
4276  else
4277  mtstate->mt_resultOidHash = NULL;
4278 
4279  /*
4280  * Determine if the FDW supports batch insert and determine the batch size
4281  * (a FDW may support batching, but it may be disabled for the
4282  * server/table).
4283  *
4284  * We only do this for INSERT, so that for UPDATE/DELETE the batch size
4285  * remains set to 0.
4286  */
4287  if (operation == CMD_INSERT)
4288  {
4289  /* insert may only have one relation, inheritance is not expanded */
4290  Assert(nrels == 1);
4291  resultRelInfo = mtstate->resultRelInfo;
4292  if (!resultRelInfo->ri_usesFdwDirectModify &&
4293  resultRelInfo->ri_FdwRoutine != NULL &&
4294  resultRelInfo->ri_FdwRoutine->GetForeignModifyBatchSize &&
4295  resultRelInfo->ri_FdwRoutine->ExecForeignBatchInsert)
4296  {
4297  resultRelInfo->ri_BatchSize =
4298  resultRelInfo->ri_FdwRoutine->GetForeignModifyBatchSize(resultRelInfo);
4299  Assert(resultRelInfo->ri_BatchSize >= 1);
4300  }
4301  else
4302  resultRelInfo->ri_BatchSize = 1;
4303  }
4304 
4305  /*
4306  * Lastly, if this is not the primary (canSetTag) ModifyTable node, add it
4307  * to estate->es_auxmodifytables so that it will be run to completion by
4308  * ExecPostprocessPlan. (It'd actually work fine to add the primary
4309  * ModifyTable node too, but there's no need.) Note the use of lcons not
4310  * lappend: we need later-initialized ModifyTable nodes to be shut down
4311  * before earlier ones. This ensures that we don't throw away RETURNING
4312  * rows that need to be seen by a later CTE subplan.
4313  */
4314  if (!mtstate->canSetTag)
4315  estate->es_auxmodifytables = lcons(mtstate,
4316  estate->es_auxmodifytables);
4317 
4318  return mtstate;
4319 }
4320 
4321 /* ----------------------------------------------------------------
4322  * ExecEndModifyTable
4323  *
4324  * Shuts down the plan.
4325  *
4326  * Returns nothing of interest.
4327  * ----------------------------------------------------------------
4328  */
4329 void
4331 {
4332  int i;
4333 
4334  /*
4335  * Allow any FDWs to shut down
4336  */
4337  for (i = 0; i < node->mt_nrels; i++)
4338  {
4339  int j;
4340  ResultRelInfo *resultRelInfo = node->resultRelInfo + i;
4341 
4342  if (!resultRelInfo->ri_usesFdwDirectModify &&
4343  resultRelInfo->ri_FdwRoutine != NULL &&
4344  resultRelInfo->ri_FdwRoutine->EndForeignModify != NULL)
4345  resultRelInfo->ri_FdwRoutine->EndForeignModify(node->ps.state,
4346  resultRelInfo);
4347 
4348  /*
4349  * Cleanup the initialized batch slots. This only matters for FDWs
4350  * with batching, but the other cases will have ri_NumSlotsInitialized
4351  * == 0.
4352  */
4353  for (j = 0; j < resultRelInfo->ri_NumSlotsInitialized; j++)
4354  {
4355  ExecDropSingleTupleTableSlot(resultRelInfo->ri_Slots[j]);
4356  ExecDropSingleTupleTableSlot(resultRelInfo->ri_PlanSlots[j]);
4357  }
4358  }
4359 
4360  /*
4361  * Close all the partitioned tables, leaf partitions, and their indices
4362  * and release the slot used for tuple routing, if set.
4363  */
4364  if (node->mt_partition_tuple_routing)
4365  {
4367 
4368  if (node->mt_root_tuple_slot)
4370  }
4371 
4372  /*
4373  * Free the exprcontext
4374  */
4375  ExecFreeExprContext(&node->ps);
4376 
4377  /*
4378  * clean out the tuple table
4379  */
4380  if (node->ps.ps_ResultTupleSlot)
4382 
4383  /*
4384  * Terminate EPQ execution if active
4385  */
4386  EvalPlanQualEnd(&node->mt_epqstate);
4387 
4388  /*
4389  * shut down subplan
4390  */
4391  ExecEndNode(outerPlanState(node));
4392 }
4393 
4394 void
4396 {
4397  /*
4398  * Currently, we don't need to support rescan on ModifyTable nodes. The
4399  * semantics of that would be a bit debatable anyway.
4400  */
4401  elog(ERROR, "ExecReScanModifyTable is not implemented");
4402 }
#define AttributeNumberIsValid(attributeNumber)
Definition: attnum.h:34
bool bms_is_member(int x, const Bitmapset *a)
Definition: bitmapset.c:427
static Datum values[MAXATTR]
Definition: bootstrap.c:156
unsigned int uint32
Definition: c.h:452
#define unlikely(x)
Definition: c.h:284
unsigned int Index
Definition: c.h:560
uint32 TransactionId
Definition: c.h:598
Datum datumCopy(Datum value, bool typByVal, int typLen)
Definition: datum.c:132
void * hash_search(HTAB *hashp, const void *keyPtr, HASHACTION action, bool *foundPtr)
Definition: dynahash.c:954
HTAB * hash_create(const char *tabname, long nelem, const HASHCTL *info, int flags)
Definition: dynahash.c:349
int errdetail(const char *fmt,...)
Definition: elog.c:1037
int errhint(const char *fmt,...)
Definition: elog.c:1151
int errcode(int sqlerrcode)
Definition: elog.c:693
int errmsg(const char *fmt,...)
Definition: elog.c:904
#define ERROR
Definition: elog.h:33
#define elog(elevel,...)
Definition: elog.h:218
#define ereport(elevel,...)
Definition: elog.h:143
ExprState * ExecPrepareExpr(Expr *node, EState *estate)
Definition: execExpr.c:746
ProjectionInfo * ExecBuildUpdateProjection(List *targetList, bool evalTargetList, List *targetColnos, TupleDesc relDesc, ExprContext *econtext, TupleTableSlot *slot, PlanState *parent)
Definition: execExpr.c:513
ExprState * ExecInitQual(List *qual, PlanState *parent)
Definition: execExpr.c:209
ProjectionInfo * ExecBuildProjectionInfo(List *targetList, ExprContext *econtext, TupleTableSlot *slot, PlanState *parent, TupleDesc inputDesc)
Definition: execExpr.c:353
bool ExecCheckIndexConstraints(ResultRelInfo *resultRelInfo, TupleTableSlot *slot, EState *estate, ItemPointer conflictTid, List *arbiterIndexes)
Definition: execIndexing.c:505
List * ExecInsertIndexTuples(ResultRelInfo *resultRelInfo, TupleTableSlot *slot, EState *estate, bool update, bool noDupErr, bool *specConflict, List *arbiterIndexes)
Definition: execIndexing.c:284
void ExecOpenIndices(ResultRelInfo *resultRelInfo, bool speculative)
Definition: execIndexing.c:156
AttrNumber ExecFindJunkAttributeInTlist(List *targetlist, const char *attrName)
Definition: execJunk.c:222
LockTupleMode ExecUpdateLockMode(EState *estate, ResultRelInfo *relinfo)
Definition: execMain.c:2338
void EvalPlanQualBegin(EPQState *epqstate)
Definition: execMain.c:2720
TupleTableSlot * EvalPlanQual(EPQState *epqstate, Relation relation, Index rti, TupleTableSlot *inputslot)
Definition: execMain.c:2457
bool ExecPartitionCheck(ResultRelInfo *resultRelInfo, TupleTableSlot *slot, EState *estate, bool emitError)
Definition: execMain.c:1782
void ExecWithCheckOptions(WCOKind kind, ResultRelInfo *resultRelInfo, TupleTableSlot *slot, EState *estate)
Definition: execMain.c:2039
ExecAuxRowMark * ExecBuildAuxRowMark(ExecRowMark *erm, List *targetlist)
Definition: execMain.c:2387
void EvalPlanQualEnd(EPQState *epqstate)
Definition: execMain.c:2932
void EvalPlanQualSetPlan(EPQState *epqstate, Plan *subplan, List *auxrowmarks)
Definition: execMain.c:2550
void EvalPlanQualInit(EPQState *epqstate, EState *parentestate, Plan *subplan, List *auxrowmarks, int epqParam)
Definition: execMain.c:2511
ExecRowMark * ExecFindRowMark(EState *estate, Index rti, bool missing_ok)
Definition: execMain.c:2364
List * ExecGetAncestorResultRels(EState *estate, ResultRelInfo *resultRelInfo)
Definition: execMain.c:1362
TupleTableSlot * EvalPlanQualSlot(EPQState *epqstate, Relation relation, Index rti)
Definition: execMain.c:2567
void ExecPartitionCheckEmitError(ResultRelInfo *resultRelInfo, TupleTableSlot *slot, EState *estate)
Definition: execMain.c:1835
void ExecConstraints(ResultRelInfo *resultRelInfo, TupleTableSlot *slot, EState *estate)
Definition: execMain.c:1906
void CheckValidResultRel(ResultRelInfo *resultRelInfo, CmdType operation)
Definition: execMain.c:994
ResultRelInfo * ExecFindPartition(ModifyTableState *mtstate, ResultRelInfo *rootResultRelInfo, PartitionTupleRouting *proute, TupleTableSlot *slot, EState *estate)
PartitionTupleRouting * ExecSetupPartitionTupleRouting(EState *estate, Relation rel)
void ExecCleanupTupleRouting(ModifyTableState *mtstate, PartitionTupleRouting *proute)
void ExecEndNode(PlanState *node)
Definition: execProcnode.c:556
PlanState * ExecInitNode(Plan *node, EState *estate, int eflags)
Definition: execProcnode.c:141
const TupleTableSlotOps TTSOpsVirtual
Definition: execTuples.c:83
TupleTableSlot * ExecStoreVirtualTuple(TupleTableSlot *slot)
Definition: execTuples.c:1552
void ExecDropSingleTupleTableSlot(TupleTableSlot *slot)
Definition: execTuples.c:1254
TupleTableSlot * ExecStoreAllNullTuple(TupleTableSlot *slot)
Definition: execTuples.c:1576
void ExecInitResultTypeTL(PlanState *planstate)
Definition: execTuples.c:1755
void ExecInitResultTupleSlotTL(PlanState *planstate, const TupleTableSlotOps *tts_ops)
Definition: execTuples.c:1799
TupleTableSlot * MakeSingleTupleTableSlot(TupleDesc tupdesc, const TupleTableSlotOps *tts_ops)
Definition: execTuples.c:1238
void ExecForceStoreHeapTuple(HeapTuple tuple, TupleTableSlot *slot, bool shouldFree)
Definition: execTuples.c:1469
TupleTableSlot * ExecGetReturningSlot(EState *estate, ResultRelInfo *relInfo)
Definition: execUtils.c:1210
void ExecInitResultRelation(EState *estate, ResultRelInfo *resultRelInfo, Index rti)
Definition: execUtils.c:834
void ExecAssignExprContext(EState *estate, PlanState *planstate)
Definition: execUtils.c:480
TupleConversionMap * ExecGetChildToRootMap(ResultRelInfo *resultRelInfo)
Definition: execUtils.c:1234
Bitmapset * ExecGetExtraUpdatedCols(ResultRelInfo *relinfo, EState *estate)
Definition: execUtils.c:1321
void ExecFreeExprContext(PlanState *planstate)
Definition: execUtils.c:650
#define MERGE_UPDATE
Definition: execnodes.h:1216
#define InstrCountFiltered1(node, delta)
Definition: execnodes.h:1102
#define outerPlanState(node)
Definition: execnodes.h:1094
#define InstrCountTuples2(node, delta)
Definition: execnodes.h:1097
#define MERGE_INSERT
Definition: execnodes.h:1215
#define MERGE_DELETE
Definition: execnodes.h:1217
#define EXEC_FLAG_BACKWARD
Definition: executor.h:58
#define ResetPerTupleExprContext(estate)
Definition: executor.h:546
#define GetPerTupleExprContext(estate)
Definition: executor.h:537
static TupleTableSlot * ExecProject(ProjectionInfo *projInfo)
Definition: executor.h:363
#define ResetExprContext(econtext)
Definition: executor.h:531
#define GetPerTupleMemoryContext(estate)
Definition: executor.h:542
static bool ExecQual(ExprState *state, ExprContext *econtext)
Definition: executor.h:400
#define EvalPlanQualSetSlot(epqstate, slot)
Definition: executor.h:229
static Datum ExecEvalExpr(ExprState *state, ExprContext *econtext, bool *isNull)
Definition: executor.h:320
#define EXEC_FLAG_EXPLAIN_ONLY
Definition: executor.h:56
static Datum ExecGetJunkAttribute(TupleTableSlot *slot, AttrNumber attno, bool *isNull)
Definition: executor.h:178
#define EXEC_FLAG_MARK
Definition: executor.h:59
static TupleTableSlot * ExecProcNode(PlanState *node)
Definition: executor.h:254
#define DatumGetHeapTupleHeader(X)
Definition: fmgr.h:295
char * format_type_be(Oid type_oid)
Definition: format_type.c:343
@ HASH_FIND
Definition: hsearch.h:113
@ HASH_ENTER
Definition: hsearch.h:114
#define HASH_CONTEXT
Definition: hsearch.h:102
#define HASH_ELEM
Definition: hsearch.h:95
#define HASH_BLOBS
Definition: hsearch.h:97
#define HeapTupleHeaderGetDatumLength(tup)
Definition: htup_details.h:446
long val
Definition: informix.c:664
int j
Definition: isn.c:74
int i
Definition: isn.c:73
#define ItemPointerCopy(fromPointer, toPointer)
Definition: itemptr.h:161
#define ItemPointerIndicatesMovedPartitions(pointer)
Definition: itemptr.h:184
ItemPointerData * ItemPointer
Definition: itemptr.h:49
#define ItemPointerSetInvalid(pointer)
Definition: itemptr.h:172
Assert(fmt[strlen(fmt) - 1] !='\n')
List * lappend(List *list, void *datum)
Definition: list.c:336
void list_free(List *list)
Definition: list.c:1505
List * lcons(void *datum, List *list)
Definition: list.c:474
uint32 SpeculativeInsertionLockAcquire(TransactionId xid)
Definition: lmgr.c:783
void SpeculativeInsertionLockRelease(TransactionId xid)
Definition: lmgr.c:809
@ LockWaitBlock
Definition: lockoptions.h:39
LockTupleMode
Definition: lockoptions.h:50
@ LockTupleExclusive
Definition: lockoptions.h:58
MemoryContext CurrentMemoryContext
Definition: mcxt.c:42
void * palloc(Size size)
Definition: mcxt.c:1068
#define IsBootstrapProcessingMode()
Definition: miscadmin.h:406
#define CHECK_FOR_INTERRUPTS()
Definition: miscadmin.h:121
Oid exprType(const Node *expr)
Definition: nodeFuncs.c:41
static void ExecInitInsertProjection(ModifyTableState *mtstate, ResultRelInfo *resultRelInfo)
static void ExecSetupTransitionCaptureState(ModifyTableState *mtstate, EState *estate)
void ExecInitMergeTupleSlots(ModifyTableState *mtstate, ResultRelInfo *resultRelInfo)
static bool ExecDeletePrologue(ModifyTableContext *context, ResultRelInfo *resultRelInfo, ItemPointer tupleid, HeapTuple oldtuple, TupleTableSlot **epqreturnslot)
static TupleTableSlot * ExecMerge(ModifyTableContext *context, ResultRelInfo *resultRelInfo, ItemPointer tupleid, bool canSetTag)
struct ModifyTableContext ModifyTableContext
static void ExecUpdatePrepareSlot(ResultRelInfo *resultRelInfo, TupleTableSlot *slot, EState *estate)
static TupleTableSlot * mergeGetUpdateNewTuple(ResultRelInfo *relinfo, TupleTableSlot *planSlot, TupleTableSlot *oldSlot, MergeActionState *relaction)
static TupleTableSlot * ExecInsert(ModifyTableContext *context, ResultRelInfo *resultRelInfo, TupleTableSlot *slot, bool canSetTag, TupleTableSlot **inserted_tuple, ResultRelInfo **insert_destrel)
static void ExecMergeNotMatched(ModifyTableContext *context, ResultRelInfo *resultRelInfo, bool canSetTag)
static void ExecCheckPlanOutput(Relation resultRel, List *targetList)
static TupleTableSlot * ExecModifyTable(PlanState *pstate)
static void ExecCrossPartitionUpdateForeignKey(ModifyTableContext *context, ResultRelInfo *sourcePartInfo, ResultRelInfo *destPartInfo, ItemPointer tupleid, TupleTableSlot *oldslot, TupleTableSlot *newslot)
TupleTableSlot * ExecGetUpdateNewTuple(ResultRelInfo *relinfo, TupleTableSlot *planSlot, TupleTableSlot *oldSlot)
static void ExecInitUpdateProjection(ModifyTableState *mtstate, ResultRelInfo *resultRelInfo)
static bool ExecCrossPartitionUpdate(ModifyTableContext *context, ResultRelInfo *resultRelInfo, ItemPointer tupleid, HeapTuple oldtuple, TupleTableSlot *slot, bool canSetTag, UpdateContext *updateCxt, TupleTableSlot **inserted_tuple, ResultRelInfo **insert_destrel)
static void ExecCheckTIDVisible(EState *estate, ResultRelInfo *relinfo, ItemPointer tid, TupleTableSlot *tempSlot)
static TM_Result ExecDeleteAct(ModifyTableContext *context, ResultRelInfo *resultRelInfo, ItemPointer tupleid, bool changingPart)
static void ExecCheckTupleVisible(EState *estate, Relation rel, TupleTableSlot *slot)
static TupleTableSlot * ExecGetInsertNewTuple(ResultRelInfo *relinfo, TupleTableSlot *planSlot)
void ExecComputeStoredGenerated(ResultRelInfo *resultRelInfo, EState *estate, TupleTableSlot *slot, CmdType cmdtype)
static TupleTableSlot * ExecPrepareTupleRouting(ModifyTableState *mtstate, EState *estate, PartitionTupleRouting *proute, ResultRelInfo *targetRelInfo, TupleTableSlot *slot, ResultRelInfo **partRelInfo)
static void ExecUpdateEpilogue(ModifyTableContext *context, UpdateContext *updateCxt, ResultRelInfo *resultRelInfo, ItemPointer tupleid, HeapTuple oldtuple, TupleTableSlot *slot, List *recheckIndexes)
struct MTTargetRelLookup MTTargetRelLookup
static TupleTableSlot * ExecUpdate(ModifyTableContext *context, ResultRelInfo *resultRelInfo, ItemPointer tupleid, HeapTuple oldtuple, TupleTableSlot *slot, bool canSetTag)
ResultRelInfo * ExecLookupResultRelByOid(ModifyTableState *node, Oid resultoid, bool missing_ok, bool update_cache)
struct UpdateContext UpdateContext
#define MT_NRELS_HASH
static TM_Result ExecUpdateAct(ModifyTableContext *context, ResultRelInfo *resultRelInfo, ItemPointer tupleid, HeapTuple oldtuple, TupleTableSlot *slot, bool canSetTag, UpdateContext *updateCxt)
static TupleTableSlot * internalGetUpdateNewTuple(ResultRelInfo *relinfo, TupleTableSlot *planSlot, TupleTableSlot *oldSlot, MergeActionState *relaction)
static void fireBSTriggers(ModifyTableState *node)
static TupleTableSlot * ExecProcessReturning(ResultRelInfo *resultRelInfo, TupleTableSlot *tupleSlot, TupleTableSlot *planSlot)
void ExecReScanModifyTable(ModifyTableState *node)
void ExecEndModifyTable(ModifyTableState *node)
ModifyTableState * ExecInitModifyTable(ModifyTable *node, EState *estate, int eflags)
static void fireASTriggers(ModifyTableState *node)
static bool ExecOnConflictUpdate(ModifyTableContext *context, ResultRelInfo *resultRelInfo, ItemPointer conflictTid, TupleTableSlot *excludedSlot, bool canSetTag, TupleTableSlot **returning)
static void ExecBatchInsert(ModifyTableState *mtstate, ResultRelInfo *resultRelInfo, TupleTableSlot **slots, TupleTableSlot **planSlots, int numSlots, EState *estate, bool canSetTag)
static bool ExecUpdatePrologue(ModifyTableContext *context, ResultRelInfo *resultRelInfo, ItemPointer tupleid, HeapTuple oldtuple, TupleTableSlot *slot)
static void ExecDeleteEpilogue(ModifyTableContext *context, ResultRelInfo *resultRelInfo, ItemPointer tupleid, HeapTuple oldtuple, bool changingPart)
static bool ExecMergeMatched(ModifyTableContext *context, ResultRelInfo *resultRelInfo, ItemPointer tupleid, bool canSetTag)
static void ExecInitMerge(ModifyTableState *mtstate, EState *estate)
static TupleTableSlot * ExecDelete(ModifyTableContext *context, ResultRelInfo *resultRelInfo, ItemPointer tupleid, HeapTuple oldtuple, bool processReturning, bool changingPart, bool canSetTag, bool *tupleDeleted, TupleTableSlot **epqreturnslot)
#define IsA(nodeptr, _type_)
Definition: nodes.h:624
OnConflictAction
Definition: nodes.h:870
@ ONCONFLICT_NONE
Definition: nodes.h:871
@ ONCONFLICT_UPDATE
Definition: nodes.h:873
@ ONCONFLICT_NOTHING
Definition: nodes.h:872
CmdType
Definition: nodes.h:719
@ CMD_MERGE
Definition: nodes.h:725
@ CMD_INSERT
Definition: nodes.h:723
@ CMD_DELETE
Definition: nodes.h:724
@ CMD_UPDATE
Definition: nodes.h:722
@ CMD_NOTHING
Definition: nodes.h:728
#define makeNode(_type_)
Definition: nodes.h:621
#define castNode(_type_, nodeptr)
Definition: nodes.h:642
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:109
WCOKind
Definition: parsenodes.h:1225
@ WCO_RLS_MERGE_UPDATE_CHECK
Definition: parsenodes.h:1230
@ WCO_RLS_CONFLICT_CHECK
Definition: parsenodes.h:1229
@ WCO_RLS_INSERT_CHECK
Definition: parsenodes.h:1227
@ WCO_VIEW_CHECK
Definition: parsenodes.h:1226
@ WCO_RLS_UPDATE_CHECK
Definition: parsenodes.h:1228
@ WCO_RLS_MERGE_DELETE_CHECK
Definition: parsenodes.h:1231
FormData_pg_attribute * Form_pg_attribute
Definition: pg_attribute.h:207
#define lfirst(lc)
Definition: pg_list.h:169
#define lfirst_node(type, lc)
Definition: pg_list.h:172
static int list_length(const List *l)
Definition: pg_list.h:149
#define NIL
Definition: pg_list.h:65
#define lfirst_int(lc)
Definition: pg_list.h:170
#define linitial_int(l)
Definition: pg_list.h:175
#define linitial(l)
Definition: pg_list.h:174
static void * list_nth(const List *list, int n)
Definition: pg_list.h:278
#define ERRCODE_T_R_SERIALIZATION_FAILURE
Definition: pgbench.c:79
#define outerPlan(node)
Definition: plannodes.h:172
#define DatumGetTransactionId(X)
Definition: postgres.h:558
#define DatumGetObjectId(X)
Definition: postgres.h:544
uintptr_t Datum
Definition: postgres.h:411
#define DatumGetPointer(X)
Definition: postgres.h:593
#define InvalidOid
Definition: postgres_ext.h:36
unsigned int Oid
Definition: postgres_ext.h:31
static void test(void)
#define RelationGetRelid(relation)
Definition: rel.h:488
#define RelationGetDescr(relation)
Definition: rel.h:514
#define RelationGetRelationName(relation)
Definition: rel.h:522
Node * build_column_default(Relation rel, int attrno)
int RI_FKey_trigger_type(Oid tgfoid)
Definition: ri_triggers.c:2998
#define SnapshotAny
Definition: snapmgr.h:67
uint64 es_processed
Definition: execnodes.h:636
List * es_tuple_routing_result_relations
Definition: execnodes.h:620
MemoryContext es_query_cxt
Definition: execnodes.h:632
List * es_tupleTable
Definition: execnodes.h:634
struct EPQState * es_epq_active
Definition: execnodes.h:661
List * es_opened_result_relations
Definition: execnodes.h:610
CommandId es_output_cid
Definition: execnodes.h:604
Snapshot es_snapshot
Definition: execnodes.h:590
List * es_auxmodifytables
Definition: execnodes.h:646
Snapshot es_crosscheck_snapshot
Definition: execnodes.h:591
TupleTableSlot * ecxt_innertuple
Definition: execnodes.h:234
TupleTableSlot * ecxt_scantuple
Definition: execnodes.h:232
TupleTableSlot * ecxt_outertuple
Definition: execnodes.h:236
BeginForeignModify_function BeginForeignModify
Definition: fdwapi.h:231
EndForeignModify_function EndForeignModify
Definition: fdwapi.h:237
ExecForeignInsert_function ExecForeignInsert
Definition: fdwapi.h:232
ExecForeignUpdate_function ExecForeignUpdate
Definition: fdwapi.h:235
ExecForeignBatchInsert_function ExecForeignBatchInsert
Definition: fdwapi.h:233
GetForeignModifyBatchSize_function GetForeignModifyBatchSize
Definition: fdwapi.h:234
ExecForeignDelete_function ExecForeignDelete
Definition: fdwapi.h:236
Size keysize
Definition: hsearch.h:75
Size entrysize
Definition: hsearch.h:76
MemoryContext hcxt
Definition: hsearch.h:86
ItemPointerData t_self
Definition: htup.h:65
uint32 t_len
Definition: htup.h:64
HeapTupleHeader t_data
Definition: htup.h:68
Oid t_tableOid
Definition: htup.h:66
Definition: pg_list.h:51
MergeAction * mas_action
Definition: execnodes.h:402
ProjectionInfo * mas_proj
Definition: execnodes.h:403
ExprState * mas_whenqual
Definition: execnodes.h:405
CmdType commandType
Definition: parsenodes.h:1574
MergeActionState * relaction
TM_FailureData tmfd
TupleTableSlot * planSlot
TupleTableSlot *(* GetUpdateNewTuple)(ResultRelInfo *resultRelInfo, TupleTableSlot *epqslot, TupleTableSlot *oldSlot, MergeActionState *relaction)
TupleTableSlot * cpUpdateReturningSlot
ModifyTableState * mtstate
TupleTableSlot * cpUpdateRetrySlot
CmdType operation
Definition: execnodes.h:1226
ResultRelInfo * resultRelInfo
Definition: execnodes.h:1230
double mt_merge_deleted
Definition: execnodes.h:1275
struct PartitionTupleRouting * mt_partition_tuple_routing
Definition: execnodes.h:1261
double mt_merge_inserted
Definition: execnodes.h:1273
TupleTableSlot * mt_root_tuple_slot
Definition: execnodes.h:1258
EPQState mt_epqstate
Definition: execnodes.h:1240
int mt_merge_subcommands
Definition: execnodes.h:1270
double mt_merge_updated
Definition: execnodes.h:1274
PlanState ps
Definition: execnodes.h:1225
HTAB * mt_resultOidHash
Definition: execnodes.h:1252
ResultRelInfo * rootResultRelInfo
Definition: execnodes.h:1238
struct TransitionCaptureState * mt_transition_capture
Definition: execnodes.h:1264
struct TransitionCaptureState * mt_oc_transition_capture
Definition: execnodes.h:1267
List * updateColnosLists
Definition: plannodes.h:227
List * arbiterIndexes
Definition: plannodes.h:235
List * onConflictCols
Definition: plannodes.h:237
CmdType operation
Definition: plannodes.h:221
int epqParam
Definition: plannodes.h:233
List * resultRelations
Definition: plannodes.h:226
Bitmapset * fdwDirectModifyPlans
Definition: plannodes.h:231
List * onConflictSet
Definition: plannodes.h:236
List * mergeActionLists
Definition: plannodes.h:241
bool canSetTag
Definition: plannodes.h:222
List * fdwPrivLists
Definition: plannodes.h:230
List * returningLists
Definition: plannodes.h:229
List * withCheckOptionLists
Definition: plannodes.h:228
Index rootRelation
Definition: plannodes.h:224
Node * onConflictWhere
Definition: plannodes.h:238
List * rowMarks
Definition: plannodes.h:232
OnConflictAction onConflictAction
Definition: plannodes.h:234
Definition: nodes.h:574
TupleTableSlot * oc_ProjSlot
Definition: execnodes.h:387
TupleTableSlot * oc_Existing
Definition: execnodes.h:386
ExprState * oc_WhereClause
Definition: execnodes.h:389
ProjectionInfo * oc_ProjInfo
Definition: execnodes.h:388
bool isParent
Definition: plannodes.h:1165
Plan * plan
Definition: execnodes.h:998
EState * state
Definition: execnodes.h:1000
ExprContext * ps_ExprContext
Definition: execnodes.h:1037
TupleTableSlot * ps_ResultTupleSlot
Definition: execnodes.h:1036
ExecProcNodeMtd ExecProcNode
Definition: execnodes.h:1004
List * targetlist
Definition: plannodes.h:142
ExprContext * pi_exprContext
Definition: execnodes.h:341
TriggerDesc * trigdesc
Definition: rel.h:115
TupleDesc rd_att
Definition: rel.h:110
Form_pg_class rd_rel
Definition: rel.h:109
List * ri_matchedMergeAction
Definition: execnodes.h:520
TupleTableSlot * ri_PartitionTupleSlot
Definition: execnodes.h:540
List * ri_notMatchedMergeAction
Definition: execnodes.h:521
bool ri_projectNewInfoValid
Definition: execnodes.h:457
OnConflictSetState * ri_onConflict
Definition: execnodes.h:517
int ri_NumIndices
Definition: execnodes.h:436
List * ri_onConflictArbiterIndexes
Definition: execnodes.h:514
struct ResultRelInfo * ri_RootResultRelInfo
Definition: execnodes.h:538
TupleTableSlot ** ri_Slots
Definition: execnodes.h:489
Relation ri_RelationDesc
Definition: execnodes.h:433
RelationPtr ri_IndexRelationDescs
Definition: execnodes.h:439
int ri_NumSlotsInitialized
Definition: execnodes.h:487
ExprState ** ri_GeneratedExprs
Definition: execnodes.h:502
List * ri_WithCheckOptions
Definition: execnodes.h:493
TupleTableSlot * ri_oldTupleSlot
Definition: execnodes.h:455
TriggerDesc * ri_TrigDesc
Definition: execnodes.h:460
Index ri_RangeTableIndex
Definition: execnodes.h:430
TupleTableSlot * ri_newTupleSlot
Definition: execnodes.h:453
List * ri_WithCheckOptionExprs
Definition: execnodes.h:496
ProjectionInfo * ri_projectNew
Definition: execnodes.h:451
ProjectionInfo * ri_projectReturning
Definition: execnodes.h:511
struct FdwRoutine * ri_FdwRoutine
Definition: execnodes.h:477
List * ri_returningList
Definition: execnodes.h:508
int ri_NumGeneratedNeeded
Definition: execnodes.h:505
TupleConversionMap * ri_RootToPartitionMap
Definition: execnodes.h:539
TupleTableSlot ** ri_PlanSlots
Definition: execnodes.h:490
bool ri_usesFdwDirectModify
Definition: execnodes.h:483
AttrNumber ri_RowIdAttNo
Definition: execnodes.h:448
int ri_BatchSize
Definition: execnodes.h:488
bool traversed
Definition: tableam.h:129
TransactionId xmax
Definition: tableam.h:127
CommandId cmax
Definition: tableam.h:128
ItemPointerData ctid
Definition: tableam.h:126
Expr * expr
Definition: primnodes.h:1716
bool resjunk
Definition: primnodes.h:1723
TupleTableSlot * tcs_original_insert_tuple
Definition: trigger.h:76
int numtriggers
Definition: reltrigger.h:50
bool trig_delete_before_row
Definition: reltrigger.h:66
bool trig_update_instead_row
Definition: reltrigger.h:63
Trigger * triggers
Definition: reltrigger.h:49
bool trig_delete_instead_row
Definition: reltrigger.h:68
bool trig_update_after_row
Definition: reltrigger.h:62
bool trig_insert_instead_row
Definition: reltrigger.h:58
bool trig_update_before_row
Definition: reltrigger.h:61
bool trig_insert_before_row
Definition: reltrigger.h:56
Oid tgfoid
Definition: reltrigger.h:28
bool tgisclone
Definition: reltrigger.h:32
bool has_generated_stored
Definition: tupdesc.h:45
AttrMap * attrMap
Definition: tupconvert.h:28
TupleConstr * constr
Definition: tupdesc.h:85
Oid tts_tableOid
Definition: tuptable.h:131
TupleDesc tts_tupleDescriptor
Definition: tuptable.h:124
const TupleTableSlotOps *const tts_ops
Definition: tuptable.h:122
bool * tts_isnull
Definition: tuptable.h:128
Datum * tts_values
Definition: tuptable.h:126
LockTupleMode lockmode
#define MinTransactionIdAttributeNumber
Definition: sysattr.h:22
#define FirstLowInvalidHeapAttributeNumber
Definition: sysattr.h:27
TupleTableSlot * table_slot_create(Relation relation, List **reglist)
Definition: tableam.c:91
TM_Result
Definition: tableam.h:72
@ TM_Ok
Definition: tableam.h:77
@ TM_BeingModified
Definition: tableam.h:99
@ TM_Deleted
Definition: tableam.h:92
@ TM_WouldBlock
Definition: tableam.h:102
@ TM_Updated
Definition: tableam.h:89
@ TM_SelfModified
Definition: tableam.h:83
@ TM_Invisible
Definition: tableam.h:80
static TM_Result table_tuple_lock(Relation rel, ItemPointer tid, Snapshot snapshot, TupleTableSlot *slot, CommandId cid, LockTupleMode mode, LockWaitPolicy wait_policy, uint8 flags, TM_FailureData *tmfd)
Definition: tableam.h:1551
static void table_tuple_complete_speculative(Relation rel, TupleTableSlot *slot, uint32 specToken, bool succeeded)
Definition: tableam.h:1406
static TM_Result table_tuple_delete(Relation rel, ItemPointer tid, CommandId cid, Snapshot snapshot, Snapshot crosscheck, bool wait, TM_FailureData *tmfd, bool changingPart)
Definition: tableam.h:1462
#define TUPLE_LOCK_FLAG_FIND_LAST_VERSION
Definition: tableam.h:244
static void table_tuple_insert(Relation rel, TupleTableSlot *slot, CommandId cid, int options, struct BulkInsertStateData *bistate)
Definition: tableam.h:1373
static TM_Result table_tuple_update(Relation rel, ItemPointer otid, TupleTableSlot *slot, CommandId cid, Snapshot snapshot, Snapshot crosscheck, bool wait, TM_FailureData *tmfd, LockTupleMode *lockmode, bool *update_indexes)
Definition: tableam.h:1506
static void table_tuple_insert_speculative(Relation rel, TupleTableSlot *slot, CommandId cid, int options, struct BulkInsertStateData *bistate, uint32 specToken)
Definition: tableam.h:1392
static bool table_tuple_satisfies_snapshot(Relation rel, TupleTableSlot *slot, Snapshot snapshot)
Definition: tableam.h:1306
static bool table_tuple_fetch_row_version(Relation rel, ItemPointer tid, Snapshot snapshot, TupleTableSlot *slot)
Definition: tableam.h:1259
void ExecARDeleteTriggers(EState *estate, ResultRelInfo *relinfo, ItemPointer tupleid, HeapTuple fdw_trigtuple, TransitionCaptureState *transition_capture, bool is_crosspart_update)
Definition: trigger.c:2786
void ExecBSInsertTriggers(EState *estate, ResultRelInfo *relinfo)
Definition: trigger.c:2408
bool ExecBRInsertTriggers(EState *estate, ResultRelInfo *relinfo, TupleTableSlot *slot)
Definition: trigger.c:2472
bool ExecIRDeleteTriggers(EState *estate, ResultRelInfo *relinfo, HeapTuple trigtuple)
Definition: trigger.c:2822
void ExecBSDeleteTriggers(EState *estate, ResultRelInfo *relinfo)
Definition: trigger.c:2626
bool ExecIRInsertTriggers(EState *estate, ResultRelInfo *relinfo, TupleTableSlot *slot)
Definition: trigger.c:2565
void ExecARUpdateTriggers(EState *estate, ResultRelInfo *relinfo, ResultRelInfo *src_partinfo, ResultRelInfo *dst_partinfo, ItemPointer tupleid, HeapTuple fdw_trigtuple, TupleTableSlot *newslot, List *recheckIndexes, TransitionCaptureState *transition_capture, bool is_crosspart_update)
Definition: trigger.c:3089
bool ExecBRUpdateTriggers(EState *estate, EPQState *epqstate, ResultRelInfo *relinfo, ItemPointer tupleid, HeapTuple fdw_trigtuple, TupleTableSlot *newslot, TM_FailureData *tmfd)
Definition: trigger.c:2945
void ExecASUpdateTriggers(EState *estate, ResultRelInfo *relinfo, TransitionCaptureState *transition_capture)
Definition: trigger.c:2927
void ExecASDeleteTriggers(EState *estate, ResultRelInfo *relinfo, TransitionCaptureState *transition_capture)
Definition: trigger.c:2677
void ExecARInsertTriggers(EState *estate, ResultRelInfo *relinfo, TupleTableSlot *slot, List *recheckIndexes, TransitionCaptureState *transition_capture)
Definition: trigger.c:2548
TransitionCaptureState * MakeTransitionCaptureState(TriggerDesc *trigdesc, Oid relid, CmdType cmdType)
Definition: trigger.c:4825
void ExecASInsertTriggers(EState *estate, ResultRelInfo *relinfo, TransitionCaptureState *transition_capture)
Definition: trigger.c:2459
bool ExecIRUpdateTriggers(EState *estate, ResultRelInfo *relinfo, HeapTuple trigtuple, TupleTableSlot *newslot)
Definition: trigger.c:3147
bool ExecBRDeleteTriggers(EState *estate, EPQState *epqstate, ResultRelInfo *relinfo, ItemPointer tupleid, HeapTuple fdw_trigtuple, TupleTableSlot **epqslot)
Definition: trigger.c:2697
void ExecBSUpdateTriggers(EState *estate, ResultRelInfo *relinfo)
Definition: trigger.c:2869
#define RI_TRIGGER_PK
Definition: trigger.h:278
TupleTableSlot * execute_attr_map_slot(AttrMap *attrMap, TupleTableSlot *in_slot, TupleTableSlot *out_slot)
Definition: tupconvert.c:177
TupleDesc CreateTupleDescCopy(TupleDesc tupdesc)
Definition: tupdesc.c:111
#define TupleDescAttr(tupdesc, i)
Definition: tupdesc.h:92
static TupleTableSlot * ExecClearTuple(TupleTableSlot *slot)
Definition: tuptable.h:425
#define TTS_EMPTY(slot)
Definition: tuptable.h:97
static TupleTableSlot * ExecCopySlot(TupleTableSlot *dstslot, TupleTableSlot *srcslot)
Definition: tuptable.h:475
static Datum slot_getsysattr(TupleTableSlot *slot, int attnum, bool *isnull)
Definition: tuptable.h:402
#define TupIsNull(slot)
Definition: tuptable.h:292
static void slot_getallattrs(TupleTableSlot *slot)
Definition: tuptable.h:354
static void ExecMaterializeSlot(TupleTableSlot *slot)
Definition: tuptable.h:443
bool TransactionIdIsCurrentTransactionId(TransactionId xid)
Definition: xact.c:922
TransactionId GetCurrentTransactionId(void)
Definition: xact.c:441
#define IsolationUsesXactSnapshot()
Definition: xact.h:51