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