PostgreSQL Source Code  git master
 All Data Structures Namespaces Files Functions Variables Typedefs Enumerations Enumerator Macros
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-2017, 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  * Each ModifyTable node contains a list of one or more subplans,
23  * much like an Append node. There is one subplan per result relation.
24  * The key reason for this is that in an inherited UPDATE command, each
25  * result relation could have a different schema (more or different
26  * columns) requiring a different plan tree to produce it. In an
27  * inherited DELETE, all the subplans should produce the same output
28  * rowtype, but we might still find that different plans are appropriate
29  * for different child relations.
30  *
31  * If the query specifies RETURNING, then the ModifyTable returns a
32  * RETURNING tuple after completing each row insert, update, or delete.
33  * It must be called again to continue the operation. Without RETURNING,
34  * we just loop within the node until all the work is done, then
35  * return NULL. This avoids useless call/return overhead.
36  */
37 
38 #include "postgres.h"
39 
40 #include "access/htup_details.h"
41 #include "access/xact.h"
42 #include "commands/trigger.h"
43 #include "executor/executor.h"
45 #include "foreign/fdwapi.h"
46 #include "miscadmin.h"
47 #include "nodes/nodeFuncs.h"
48 #include "parser/parsetree.h"
49 #include "storage/bufmgr.h"
50 #include "storage/lmgr.h"
51 #include "utils/builtins.h"
52 #include "utils/memutils.h"
53 #include "utils/rel.h"
54 #include "utils/tqual.h"
55 
56 
57 static bool ExecOnConflictUpdate(ModifyTableState *mtstate,
58  ResultRelInfo *resultRelInfo,
59  ItemPointer conflictTid,
60  TupleTableSlot *planSlot,
61  TupleTableSlot *excludedSlot,
62  EState *estate,
63  bool canSetTag,
64  TupleTableSlot **returning);
65 
66 /*
67  * Verify that the tuples to be produced by INSERT or UPDATE match the
68  * target relation's rowtype
69  *
70  * We do this to guard against stale plans. If plan invalidation is
71  * functioning properly then we should never get a failure here, but better
72  * safe than sorry. Note that this is called after we have obtained lock
73  * on the target rel, so the rowtype can't change underneath us.
74  *
75  * The plan output is represented by its targetlist, because that makes
76  * handling the dropped-column case easier.
77  */
78 static void
79 ExecCheckPlanOutput(Relation resultRel, List *targetList)
80 {
81  TupleDesc resultDesc = RelationGetDescr(resultRel);
82  int attno = 0;
83  ListCell *lc;
84 
85  foreach(lc, targetList)
86  {
87  TargetEntry *tle = (TargetEntry *) lfirst(lc);
88  Form_pg_attribute attr;
89 
90  if (tle->resjunk)
91  continue; /* ignore junk tlist items */
92 
93  if (attno >= resultDesc->natts)
94  ereport(ERROR,
95  (errcode(ERRCODE_DATATYPE_MISMATCH),
96  errmsg("table row type and query-specified row type do not match"),
97  errdetail("Query has too many columns.")));
98  attr = TupleDescAttr(resultDesc, attno);
99  attno++;
100 
101  if (!attr->attisdropped)
102  {
103  /* Normal case: demand type match */
104  if (exprType((Node *) tle->expr) != attr->atttypid)
105  ereport(ERROR,
106  (errcode(ERRCODE_DATATYPE_MISMATCH),
107  errmsg("table row type and query-specified row type do not match"),
108  errdetail("Table has type %s at ordinal position %d, but query expects %s.",
109  format_type_be(attr->atttypid),
110  attno,
111  format_type_be(exprType((Node *) tle->expr)))));
112  }
113  else
114  {
115  /*
116  * For a dropped column, we can't check atttypid (it's likely 0).
117  * In any case the planner has most likely inserted an INT4 null.
118  * What we insist on is just *some* NULL constant.
119  */
120  if (!IsA(tle->expr, Const) ||
121  !((Const *) tle->expr)->constisnull)
122  ereport(ERROR,
123  (errcode(ERRCODE_DATATYPE_MISMATCH),
124  errmsg("table row type and query-specified row type do not match"),
125  errdetail("Query provides a value for a dropped column at ordinal position %d.",
126  attno)));
127  }
128  }
129  if (attno != resultDesc->natts)
130  ereport(ERROR,
131  (errcode(ERRCODE_DATATYPE_MISMATCH),
132  errmsg("table row type and query-specified row type do not match"),
133  errdetail("Query has too few columns.")));
134 }
135 
136 /*
137  * ExecProcessReturning --- evaluate a RETURNING list
138  *
139  * projectReturning: RETURNING projection info for current result rel
140  * tupleSlot: slot holding tuple actually inserted/updated/deleted
141  * planSlot: slot holding tuple returned by top subplan node
142  *
143  * Note: If tupleSlot is NULL, the FDW should have already provided econtext's
144  * scan tuple.
145  *
146  * Returns a slot holding the result tuple
147  */
148 static TupleTableSlot *
150  TupleTableSlot *tupleSlot,
151  TupleTableSlot *planSlot)
152 {
153  ProjectionInfo *projectReturning = resultRelInfo->ri_projectReturning;
154  ExprContext *econtext = projectReturning->pi_exprContext;
155 
156  /*
157  * Reset per-tuple memory context to free any expression evaluation
158  * storage allocated in the previous cycle.
159  */
160  ResetExprContext(econtext);
161 
162  /* Make tuple and any needed join variables available to ExecProject */
163  if (tupleSlot)
164  econtext->ecxt_scantuple = tupleSlot;
165  else
166  {
167  HeapTuple tuple;
168 
169  /*
170  * RETURNING expressions might reference the tableoid column, so
171  * initialize t_tableOid before evaluating them.
172  */
173  Assert(!TupIsNull(econtext->ecxt_scantuple));
174  tuple = ExecMaterializeSlot(econtext->ecxt_scantuple);
175  tuple->t_tableOid = RelationGetRelid(resultRelInfo->ri_RelationDesc);
176  }
177  econtext->ecxt_outertuple = planSlot;
178 
179  /* Compute the RETURNING expressions */
180  return ExecProject(projectReturning);
181 }
182 
183 /*
184  * ExecCheckHeapTupleVisible -- verify heap tuple is visible
185  *
186  * It would not be consistent with guarantees of the higher isolation levels to
187  * proceed with avoiding insertion (taking speculative insertion's alternative
188  * path) on the basis of another tuple that is not visible to MVCC snapshot.
189  * Check for the need to raise a serialization failure, and do so as necessary.
190  */
191 static void
193  HeapTuple tuple,
194  Buffer buffer)
195 {
197  return;
198 
199  /*
200  * We need buffer pin and lock to call HeapTupleSatisfiesVisibility.
201  * Caller should be holding pin, but not lock.
202  */
203  LockBuffer(buffer, BUFFER_LOCK_SHARE);
204  if (!HeapTupleSatisfiesVisibility(tuple, estate->es_snapshot, buffer))
205  {
206  /*
207  * We should not raise a serialization failure if the conflict is
208  * against a tuple inserted by our own transaction, even if it's not
209  * visible to our snapshot. (This would happen, for example, if
210  * conflicting keys are proposed for insertion in a single command.)
211  */
213  ereport(ERROR,
214  (errcode(ERRCODE_T_R_SERIALIZATION_FAILURE),
215  errmsg("could not serialize access due to concurrent update")));
216  }
218 }
219 
220 /*
221  * ExecCheckTIDVisible -- convenience variant of ExecCheckHeapTupleVisible()
222  */
223 static void
225  ResultRelInfo *relinfo,
226  ItemPointer tid)
227 {
228  Relation rel = relinfo->ri_RelationDesc;
229  Buffer buffer;
230  HeapTupleData tuple;
231 
232  /* Redundantly check isolation level */
234  return;
235 
236  tuple.t_self = *tid;
237  if (!heap_fetch(rel, SnapshotAny, &tuple, &buffer, false, NULL))
238  elog(ERROR, "failed to fetch conflicting tuple for ON CONFLICT");
239  ExecCheckHeapTupleVisible(estate, &tuple, buffer);
240  ReleaseBuffer(buffer);
241 }
242 
243 /* ----------------------------------------------------------------
244  * ExecInsert
245  *
246  * For INSERT, we have to insert the tuple into the target relation
247  * and insert appropriate tuples into the index relations.
248  *
249  * Returns RETURNING result if any, otherwise NULL.
250  * ----------------------------------------------------------------
251  */
252 static TupleTableSlot *
254  TupleTableSlot *slot,
255  TupleTableSlot *planSlot,
256  List *arbiterIndexes,
257  OnConflictAction onconflict,
258  EState *estate,
259  bool canSetTag)
260 {
261  HeapTuple tuple;
262  ResultRelInfo *resultRelInfo;
263  ResultRelInfo *saved_resultRelInfo = NULL;
264  Relation resultRelationDesc;
265  Oid newId;
266  List *recheckIndexes = NIL;
267  TupleTableSlot *result = NULL;
268 
269  /*
270  * get the heap tuple out of the tuple table slot, making sure we have a
271  * writable copy
272  */
273  tuple = ExecMaterializeSlot(slot);
274 
275  /*
276  * get information on the (current) result relation
277  */
278  resultRelInfo = estate->es_result_relation_info;
279 
280  /* Determine the partition to heap_insert the tuple into */
281  if (mtstate->mt_partition_dispatch_info)
282  {
283  int leaf_part_index;
284  TupleConversionMap *map;
285 
286  /*
287  * Away we go ... If we end up not finding a partition after all,
288  * ExecFindPartition() does not return and errors out instead.
289  * Otherwise, the returned value is to be used as an index into arrays
290  * mt_partitions[] and mt_partition_tupconv_maps[] that will get us
291  * the ResultRelInfo and TupleConversionMap for the partition,
292  * respectively.
293  */
294  leaf_part_index = ExecFindPartition(resultRelInfo,
296  slot,
297  estate);
298  Assert(leaf_part_index >= 0 &&
299  leaf_part_index < mtstate->mt_num_partitions);
300 
301  /*
302  * Save the old ResultRelInfo and switch to the one corresponding to
303  * the selected partition.
304  */
305  saved_resultRelInfo = resultRelInfo;
306  resultRelInfo = mtstate->mt_partitions[leaf_part_index];
307 
308  /* We do not yet have a way to insert into a foreign partition */
309  if (resultRelInfo->ri_FdwRoutine)
310  ereport(ERROR,
311  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
312  errmsg("cannot route inserted tuples to a foreign table")));
313 
314  /* For ExecInsertIndexTuples() to work on the partition's indexes */
315  estate->es_result_relation_info = resultRelInfo;
316 
317  /*
318  * If we're capturing transition tuples, we might need to convert from
319  * the partition rowtype to parent rowtype.
320  */
321  if (mtstate->mt_transition_capture != NULL)
322  {
323  if (resultRelInfo->ri_TrigDesc &&
324  (resultRelInfo->ri_TrigDesc->trig_insert_before_row ||
325  resultRelInfo->ri_TrigDesc->trig_insert_instead_row))
326  {
327  /*
328  * If there are any BEFORE or INSTEAD triggers on the
329  * partition, we'll have to be ready to convert their result
330  * back to tuplestore format.
331  */
333  mtstate->mt_transition_capture->tcs_map =
334  mtstate->mt_transition_tupconv_maps[leaf_part_index];
335  }
336  else
337  {
338  /*
339  * Otherwise, just remember the original unconverted tuple, to
340  * avoid a needless round trip conversion.
341  */
343  mtstate->mt_transition_capture->tcs_map = NULL;
344  }
345  }
346  if (mtstate->mt_oc_transition_capture != NULL)
348  mtstate->mt_transition_tupconv_maps[leaf_part_index];
349 
350  /*
351  * We might need to convert from the parent rowtype to the partition
352  * rowtype.
353  */
354  map = mtstate->mt_partition_tupconv_maps[leaf_part_index];
355  if (map)
356  {
357  Relation partrel = resultRelInfo->ri_RelationDesc;
358 
359  tuple = do_convert_tuple(tuple, map);
360 
361  /*
362  * We must use the partition's tuple descriptor from this point
363  * on, until we're finished dealing with the partition. Use the
364  * dedicated slot for that.
365  */
366  slot = mtstate->mt_partition_tuple_slot;
367  Assert(slot != NULL);
368  ExecSetSlotDescriptor(slot, RelationGetDescr(partrel));
369  ExecStoreTuple(tuple, slot, InvalidBuffer, true);
370  }
371  }
372 
373  resultRelationDesc = resultRelInfo->ri_RelationDesc;
374 
375  /*
376  * If the result relation has OIDs, force the tuple's OID to zero so that
377  * heap_insert will assign a fresh OID. Usually the OID already will be
378  * zero at this point, but there are corner cases where the plan tree can
379  * return a tuple extracted literally from some table with the same
380  * rowtype.
381  *
382  * XXX if we ever wanted to allow users to assign their own OIDs to new
383  * rows, this'd be the place to do it. For the moment, we make a point of
384  * doing this before calling triggers, so that a user-supplied trigger
385  * could hack the OID if desired.
386  */
387  if (resultRelationDesc->rd_rel->relhasoids)
388  HeapTupleSetOid(tuple, InvalidOid);
389 
390  /*
391  * BEFORE ROW INSERT Triggers.
392  *
393  * Note: We fire BEFORE ROW TRIGGERS for every attempted insertion in an
394  * INSERT ... ON CONFLICT statement. We cannot check for constraint
395  * violations before firing these triggers, because they can change the
396  * values to insert. Also, they can run arbitrary user-defined code with
397  * side-effects that we can't cancel by just not inserting the tuple.
398  */
399  if (resultRelInfo->ri_TrigDesc &&
400  resultRelInfo->ri_TrigDesc->trig_insert_before_row)
401  {
402  slot = ExecBRInsertTriggers(estate, resultRelInfo, slot);
403 
404  if (slot == NULL) /* "do nothing" */
405  return NULL;
406 
407  /* trigger might have changed tuple */
408  tuple = ExecMaterializeSlot(slot);
409  }
410 
411  /* INSTEAD OF ROW INSERT Triggers */
412  if (resultRelInfo->ri_TrigDesc &&
413  resultRelInfo->ri_TrigDesc->trig_insert_instead_row)
414  {
415  slot = ExecIRInsertTriggers(estate, resultRelInfo, slot);
416 
417  if (slot == NULL) /* "do nothing" */
418  return NULL;
419 
420  /* trigger might have changed tuple */
421  tuple = ExecMaterializeSlot(slot);
422 
423  newId = InvalidOid;
424  }
425  else if (resultRelInfo->ri_FdwRoutine)
426  {
427  /*
428  * insert into foreign table: let the FDW do it
429  */
430  slot = resultRelInfo->ri_FdwRoutine->ExecForeignInsert(estate,
431  resultRelInfo,
432  slot,
433  planSlot);
434 
435  if (slot == NULL) /* "do nothing" */
436  return NULL;
437 
438  /* FDW might have changed tuple */
439  tuple = ExecMaterializeSlot(slot);
440 
441  /*
442  * AFTER ROW Triggers or RETURNING expressions might reference the
443  * tableoid column, so initialize t_tableOid before evaluating them.
444  */
445  tuple->t_tableOid = RelationGetRelid(resultRelationDesc);
446 
447  newId = InvalidOid;
448  }
449  else
450  {
451  /*
452  * We always check the partition constraint, including when the tuple
453  * got here via tuple-routing. However we don't need to in the latter
454  * case if no BR trigger is defined on the partition. Note that a BR
455  * trigger might modify the tuple such that the partition constraint
456  * is no longer satisfied, so we need to check in that case.
457  */
458  bool check_partition_constr =
459  (resultRelInfo->ri_PartitionCheck != NIL);
460 
461  /*
462  * Constraints might reference the tableoid column, so initialize
463  * t_tableOid before evaluating them.
464  */
465  tuple->t_tableOid = RelationGetRelid(resultRelationDesc);
466 
467  /*
468  * Check any RLS INSERT WITH CHECK policies
469  *
470  * ExecWithCheckOptions() will skip any WCOs which are not of the kind
471  * we are looking for at this point.
472  */
473  if (resultRelInfo->ri_WithCheckOptions != NIL)
475  resultRelInfo, slot, estate);
476 
477  /*
478  * No need though if the tuple has been routed, and a BR trigger
479  * doesn't exist.
480  */
481  if (saved_resultRelInfo != NULL &&
482  !(resultRelInfo->ri_TrigDesc &&
483  resultRelInfo->ri_TrigDesc->trig_insert_before_row))
484  check_partition_constr = false;
485 
486  /* Check the constraints of the tuple */
487  if (resultRelationDesc->rd_att->constr || check_partition_constr)
488  ExecConstraints(resultRelInfo, slot, estate);
489 
490  if (onconflict != ONCONFLICT_NONE && resultRelInfo->ri_NumIndices > 0)
491  {
492  /* Perform a speculative insertion. */
493  uint32 specToken;
494  ItemPointerData conflictTid;
495  bool specConflict;
496 
497  /*
498  * Do a non-conclusive check for conflicts first.
499  *
500  * We're not holding any locks yet, so this doesn't guarantee that
501  * the later insert won't conflict. But it avoids leaving behind
502  * a lot of canceled speculative insertions, if you run a lot of
503  * INSERT ON CONFLICT statements that do conflict.
504  *
505  * We loop back here if we find a conflict below, either during
506  * the pre-check, or when we re-check after inserting the tuple
507  * speculatively.
508  */
509  vlock:
510  specConflict = false;
511  if (!ExecCheckIndexConstraints(slot, estate, &conflictTid,
512  arbiterIndexes))
513  {
514  /* committed conflict tuple found */
515  if (onconflict == ONCONFLICT_UPDATE)
516  {
517  /*
518  * In case of ON CONFLICT DO UPDATE, execute the UPDATE
519  * part. Be prepared to retry if the UPDATE fails because
520  * of another concurrent UPDATE/DELETE to the conflict
521  * tuple.
522  */
523  TupleTableSlot *returning = NULL;
524 
525  if (ExecOnConflictUpdate(mtstate, resultRelInfo,
526  &conflictTid, planSlot, slot,
527  estate, canSetTag, &returning))
528  {
529  InstrCountFiltered2(&mtstate->ps, 1);
530  return returning;
531  }
532  else
533  goto vlock;
534  }
535  else
536  {
537  /*
538  * In case of ON CONFLICT DO NOTHING, do nothing. However,
539  * verify that the tuple is visible to the executor's MVCC
540  * snapshot at higher isolation levels.
541  */
542  Assert(onconflict == ONCONFLICT_NOTHING);
543  ExecCheckTIDVisible(estate, resultRelInfo, &conflictTid);
544  InstrCountFiltered2(&mtstate->ps, 1);
545  return NULL;
546  }
547  }
548 
549  /*
550  * Before we start insertion proper, acquire our "speculative
551  * insertion lock". Others can use that to wait for us to decide
552  * if we're going to go ahead with the insertion, instead of
553  * waiting for the whole transaction to complete.
554  */
556  HeapTupleHeaderSetSpeculativeToken(tuple->t_data, specToken);
557 
558  /* insert the tuple, with the speculative token */
559  newId = heap_insert(resultRelationDesc, tuple,
560  estate->es_output_cid,
562  NULL);
563 
564  /* insert index entries for tuple */
565  recheckIndexes = ExecInsertIndexTuples(slot, &(tuple->t_self),
566  estate, true, &specConflict,
567  arbiterIndexes);
568 
569  /* adjust the tuple's state accordingly */
570  if (!specConflict)
571  heap_finish_speculative(resultRelationDesc, tuple);
572  else
573  heap_abort_speculative(resultRelationDesc, tuple);
574 
575  /*
576  * Wake up anyone waiting for our decision. They will re-check
577  * the tuple, see that it's no longer speculative, and wait on our
578  * XID as if this was a regularly inserted tuple all along. Or if
579  * we killed the tuple, they will see it's dead, and proceed as if
580  * the tuple never existed.
581  */
583 
584  /*
585  * If there was a conflict, start from the beginning. We'll do
586  * the pre-check again, which will now find the conflicting tuple
587  * (unless it aborts before we get there).
588  */
589  if (specConflict)
590  {
591  list_free(recheckIndexes);
592  goto vlock;
593  }
594 
595  /* Since there was no insertion conflict, we're done */
596  }
597  else
598  {
599  /*
600  * insert the tuple normally.
601  *
602  * Note: heap_insert returns the tid (location) of the new tuple
603  * in the t_self field.
604  */
605  newId = heap_insert(resultRelationDesc, tuple,
606  estate->es_output_cid,
607  0, NULL);
608 
609  /* insert index entries for tuple */
610  if (resultRelInfo->ri_NumIndices > 0)
611  recheckIndexes = ExecInsertIndexTuples(slot, &(tuple->t_self),
612  estate, false, NULL,
613  arbiterIndexes);
614  }
615  }
616 
617  if (canSetTag)
618  {
619  (estate->es_processed)++;
620  estate->es_lastoid = newId;
621  setLastTid(&(tuple->t_self));
622  }
623 
624  /* AFTER ROW INSERT Triggers */
625  ExecARInsertTriggers(estate, resultRelInfo, tuple, recheckIndexes,
626  mtstate->mt_transition_capture);
627 
628  list_free(recheckIndexes);
629 
630  /*
631  * Check any WITH CHECK OPTION constraints from parent views. We are
632  * required to do this after testing all constraints and uniqueness
633  * violations per the SQL spec, so we do it after actually inserting the
634  * record into the heap and all indexes.
635  *
636  * ExecWithCheckOptions will elog(ERROR) if a violation is found, so the
637  * tuple will never be seen, if it violates the WITH CHECK OPTION.
638  *
639  * ExecWithCheckOptions() will skip any WCOs which are not of the kind we
640  * are looking for at this point.
641  */
642  if (resultRelInfo->ri_WithCheckOptions != NIL)
643  ExecWithCheckOptions(WCO_VIEW_CHECK, resultRelInfo, slot, estate);
644 
645  /* Process RETURNING if present */
646  if (resultRelInfo->ri_projectReturning)
647  result = ExecProcessReturning(resultRelInfo, slot, planSlot);
648 
649  if (saved_resultRelInfo)
650  estate->es_result_relation_info = saved_resultRelInfo;
651 
652  return result;
653 }
654 
655 /* ----------------------------------------------------------------
656  * ExecDelete
657  *
658  * DELETE is like UPDATE, except that we delete the tuple and no
659  * index modifications are needed.
660  *
661  * When deleting from a table, tupleid identifies the tuple to
662  * delete and oldtuple is NULL. When deleting from a view,
663  * oldtuple is passed to the INSTEAD OF triggers and identifies
664  * what to delete, and tupleid is invalid. When deleting from a
665  * foreign table, tupleid is invalid; the FDW has to figure out
666  * which row to delete using data from the planSlot. oldtuple is
667  * passed to foreign table triggers; it is NULL when the foreign
668  * table has no relevant triggers.
669  *
670  * Returns RETURNING result if any, otherwise NULL.
671  * ----------------------------------------------------------------
672  */
673 static TupleTableSlot *
675  ItemPointer tupleid,
676  HeapTuple oldtuple,
677  TupleTableSlot *planSlot,
678  EPQState *epqstate,
679  EState *estate,
680  bool canSetTag)
681 {
682  ResultRelInfo *resultRelInfo;
683  Relation resultRelationDesc;
684  HTSU_Result result;
686  TupleTableSlot *slot = NULL;
687 
688  /*
689  * get information on the (current) result relation
690  */
691  resultRelInfo = estate->es_result_relation_info;
692  resultRelationDesc = resultRelInfo->ri_RelationDesc;
693 
694  /* BEFORE ROW DELETE Triggers */
695  if (resultRelInfo->ri_TrigDesc &&
696  resultRelInfo->ri_TrigDesc->trig_delete_before_row)
697  {
698  bool dodelete;
699 
700  dodelete = ExecBRDeleteTriggers(estate, epqstate, resultRelInfo,
701  tupleid, oldtuple);
702 
703  if (!dodelete) /* "do nothing" */
704  return NULL;
705  }
706 
707  /* INSTEAD OF ROW DELETE Triggers */
708  if (resultRelInfo->ri_TrigDesc &&
709  resultRelInfo->ri_TrigDesc->trig_delete_instead_row)
710  {
711  bool dodelete;
712 
713  Assert(oldtuple != NULL);
714  dodelete = ExecIRDeleteTriggers(estate, resultRelInfo, oldtuple);
715 
716  if (!dodelete) /* "do nothing" */
717  return NULL;
718  }
719  else if (resultRelInfo->ri_FdwRoutine)
720  {
721  HeapTuple tuple;
722 
723  /*
724  * delete from foreign table: let the FDW do it
725  *
726  * We offer the trigger tuple slot as a place to store RETURNING data,
727  * although the FDW can return some other slot if it wants. Set up
728  * the slot's tupdesc so the FDW doesn't need to do that for itself.
729  */
730  slot = estate->es_trig_tuple_slot;
731  if (slot->tts_tupleDescriptor != RelationGetDescr(resultRelationDesc))
732  ExecSetSlotDescriptor(slot, RelationGetDescr(resultRelationDesc));
733 
734  slot = resultRelInfo->ri_FdwRoutine->ExecForeignDelete(estate,
735  resultRelInfo,
736  slot,
737  planSlot);
738 
739  if (slot == NULL) /* "do nothing" */
740  return NULL;
741 
742  /*
743  * RETURNING expressions might reference the tableoid column, so
744  * initialize t_tableOid before evaluating them.
745  */
746  if (slot->tts_isempty)
747  ExecStoreAllNullTuple(slot);
748  tuple = ExecMaterializeSlot(slot);
749  tuple->t_tableOid = RelationGetRelid(resultRelationDesc);
750  }
751  else
752  {
753  /*
754  * delete the tuple
755  *
756  * Note: if es_crosscheck_snapshot isn't InvalidSnapshot, we check
757  * that the row to be deleted is visible to that snapshot, and throw a
758  * can't-serialize error if not. This is a special-case behavior
759  * needed for referential integrity updates in transaction-snapshot
760  * mode transactions.
761  */
762 ldelete:;
763  result = heap_delete(resultRelationDesc, tupleid,
764  estate->es_output_cid,
765  estate->es_crosscheck_snapshot,
766  true /* wait for commit */ ,
767  &hufd);
768  switch (result)
769  {
771 
772  /*
773  * The target tuple was already updated or deleted by the
774  * current command, or by a later command in the current
775  * transaction. The former case is possible in a join DELETE
776  * where multiple tuples join to the same target tuple. This
777  * is somewhat questionable, but Postgres has always allowed
778  * it: we just ignore additional deletion attempts.
779  *
780  * The latter case arises if the tuple is modified by a
781  * command in a BEFORE trigger, or perhaps by a command in a
782  * volatile function used in the query. In such situations we
783  * should not ignore the deletion, but it is equally unsafe to
784  * proceed. We don't want to discard the original DELETE
785  * while keeping the triggered actions based on its deletion;
786  * and it would be no better to allow the original DELETE
787  * while discarding updates that it triggered. The row update
788  * carries some information that might be important according
789  * to business rules; so throwing an error is the only safe
790  * course.
791  *
792  * If a trigger actually intends this type of interaction, it
793  * can re-execute the DELETE and then return NULL to cancel
794  * the outer delete.
795  */
796  if (hufd.cmax != estate->es_output_cid)
797  ereport(ERROR,
798  (errcode(ERRCODE_TRIGGERED_DATA_CHANGE_VIOLATION),
799  errmsg("tuple to be updated was already modified by an operation triggered by the current command"),
800  errhint("Consider using an AFTER trigger instead of a BEFORE trigger to propagate changes to other rows.")));
801 
802  /* Else, already deleted by self; nothing to do */
803  return NULL;
804 
806  break;
807 
808  case HeapTupleUpdated:
810  ereport(ERROR,
811  (errcode(ERRCODE_T_R_SERIALIZATION_FAILURE),
812  errmsg("could not serialize access due to concurrent update")));
813  if (!ItemPointerEquals(tupleid, &hufd.ctid))
814  {
815  TupleTableSlot *epqslot;
816 
817  epqslot = EvalPlanQual(estate,
818  epqstate,
819  resultRelationDesc,
820  resultRelInfo->ri_RangeTableIndex,
822  &hufd.ctid,
823  hufd.xmax);
824  if (!TupIsNull(epqslot))
825  {
826  *tupleid = hufd.ctid;
827  goto ldelete;
828  }
829  }
830  /* tuple already deleted; nothing to do */
831  return NULL;
832 
833  default:
834  elog(ERROR, "unrecognized heap_delete status: %u", result);
835  return NULL;
836  }
837 
838  /*
839  * Note: Normally one would think that we have to delete index tuples
840  * associated with the heap tuple now...
841  *
842  * ... but in POSTGRES, we have no need to do this because VACUUM will
843  * take care of it later. We can't delete index tuples immediately
844  * anyway, since the tuple is still visible to other transactions.
845  */
846  }
847 
848  if (canSetTag)
849  (estate->es_processed)++;
850 
851  /* AFTER ROW DELETE Triggers */
852  ExecARDeleteTriggers(estate, resultRelInfo, tupleid, oldtuple,
853  mtstate->mt_transition_capture);
854 
855  /* Process RETURNING if present */
856  if (resultRelInfo->ri_projectReturning)
857  {
858  /*
859  * We have to put the target tuple into a slot, which means first we
860  * gotta fetch it. We can use the trigger tuple slot.
861  */
862  TupleTableSlot *rslot;
863  HeapTupleData deltuple;
864  Buffer delbuffer;
865 
866  if (resultRelInfo->ri_FdwRoutine)
867  {
868  /* FDW must have provided a slot containing the deleted row */
869  Assert(!TupIsNull(slot));
870  delbuffer = InvalidBuffer;
871  }
872  else
873  {
874  slot = estate->es_trig_tuple_slot;
875  if (oldtuple != NULL)
876  {
877  deltuple = *oldtuple;
878  delbuffer = InvalidBuffer;
879  }
880  else
881  {
882  deltuple.t_self = *tupleid;
883  if (!heap_fetch(resultRelationDesc, SnapshotAny,
884  &deltuple, &delbuffer, false, NULL))
885  elog(ERROR, "failed to fetch deleted tuple for DELETE RETURNING");
886  }
887 
888  if (slot->tts_tupleDescriptor != RelationGetDescr(resultRelationDesc))
889  ExecSetSlotDescriptor(slot, RelationGetDescr(resultRelationDesc));
890  ExecStoreTuple(&deltuple, slot, InvalidBuffer, false);
891  }
892 
893  rslot = ExecProcessReturning(resultRelInfo, slot, planSlot);
894 
895  /*
896  * Before releasing the target tuple again, make sure rslot has a
897  * local copy of any pass-by-reference values.
898  */
899  ExecMaterializeSlot(rslot);
900 
901  ExecClearTuple(slot);
902  if (BufferIsValid(delbuffer))
903  ReleaseBuffer(delbuffer);
904 
905  return rslot;
906  }
907 
908  return NULL;
909 }
910 
911 /* ----------------------------------------------------------------
912  * ExecUpdate
913  *
914  * note: we can't run UPDATE queries with transactions
915  * off because UPDATEs are actually INSERTs and our
916  * scan will mistakenly loop forever, updating the tuple
917  * it just inserted.. This should be fixed but until it
918  * is, we don't want to get stuck in an infinite loop
919  * which corrupts your database..
920  *
921  * When updating a table, tupleid identifies the tuple to
922  * update and oldtuple is NULL. When updating a view, oldtuple
923  * is passed to the INSTEAD OF triggers and identifies what to
924  * update, and tupleid is invalid. When updating a foreign table,
925  * tupleid is invalid; the FDW has to figure out which row to
926  * update using data from the planSlot. oldtuple is passed to
927  * foreign table triggers; it is NULL when the foreign table has
928  * no relevant triggers.
929  *
930  * Returns RETURNING result if any, otherwise NULL.
931  * ----------------------------------------------------------------
932  */
933 static TupleTableSlot *
935  ItemPointer tupleid,
936  HeapTuple oldtuple,
937  TupleTableSlot *slot,
938  TupleTableSlot *planSlot,
939  EPQState *epqstate,
940  EState *estate,
941  bool canSetTag)
942 {
943  HeapTuple tuple;
944  ResultRelInfo *resultRelInfo;
945  Relation resultRelationDesc;
946  HTSU_Result result;
948  List *recheckIndexes = NIL;
949 
950  /*
951  * abort the operation if not running transactions
952  */
954  elog(ERROR, "cannot UPDATE during bootstrap");
955 
956  /*
957  * get the heap tuple out of the tuple table slot, making sure we have a
958  * writable copy
959  */
960  tuple = ExecMaterializeSlot(slot);
961 
962  /*
963  * get information on the (current) result relation
964  */
965  resultRelInfo = estate->es_result_relation_info;
966  resultRelationDesc = resultRelInfo->ri_RelationDesc;
967 
968  /* BEFORE ROW UPDATE Triggers */
969  if (resultRelInfo->ri_TrigDesc &&
970  resultRelInfo->ri_TrigDesc->trig_update_before_row)
971  {
972  slot = ExecBRUpdateTriggers(estate, epqstate, resultRelInfo,
973  tupleid, oldtuple, slot);
974 
975  if (slot == NULL) /* "do nothing" */
976  return NULL;
977 
978  /* trigger might have changed tuple */
979  tuple = ExecMaterializeSlot(slot);
980  }
981 
982  /* INSTEAD OF ROW UPDATE Triggers */
983  if (resultRelInfo->ri_TrigDesc &&
984  resultRelInfo->ri_TrigDesc->trig_update_instead_row)
985  {
986  slot = ExecIRUpdateTriggers(estate, resultRelInfo,
987  oldtuple, slot);
988 
989  if (slot == NULL) /* "do nothing" */
990  return NULL;
991 
992  /* trigger might have changed tuple */
993  tuple = ExecMaterializeSlot(slot);
994  }
995  else if (resultRelInfo->ri_FdwRoutine)
996  {
997  /*
998  * update in foreign table: let the FDW do it
999  */
1000  slot = resultRelInfo->ri_FdwRoutine->ExecForeignUpdate(estate,
1001  resultRelInfo,
1002  slot,
1003  planSlot);
1004 
1005  if (slot == NULL) /* "do nothing" */
1006  return NULL;
1007 
1008  /* FDW might have changed tuple */
1009  tuple = ExecMaterializeSlot(slot);
1010 
1011  /*
1012  * AFTER ROW Triggers or RETURNING expressions might reference the
1013  * tableoid column, so initialize t_tableOid before evaluating them.
1014  */
1015  tuple->t_tableOid = RelationGetRelid(resultRelationDesc);
1016  }
1017  else
1018  {
1019  LockTupleMode lockmode;
1020 
1021  /*
1022  * Constraints might reference the tableoid column, so initialize
1023  * t_tableOid before evaluating them.
1024  */
1025  tuple->t_tableOid = RelationGetRelid(resultRelationDesc);
1026 
1027  /*
1028  * Check any RLS UPDATE WITH CHECK policies
1029  *
1030  * If we generate a new candidate tuple after EvalPlanQual testing, we
1031  * must loop back here and recheck any RLS policies and constraints.
1032  * (We don't need to redo triggers, however. If there are any BEFORE
1033  * triggers then trigger.c will have done heap_lock_tuple to lock the
1034  * correct tuple, so there's no need to do them again.)
1035  *
1036  * ExecWithCheckOptions() will skip any WCOs which are not of the kind
1037  * we are looking for at this point.
1038  */
1039 lreplace:;
1040  if (resultRelInfo->ri_WithCheckOptions != NIL)
1042  resultRelInfo, slot, estate);
1043 
1044  /*
1045  * Check the constraints of the tuple. Note that we pass the same
1046  * slot for the orig_slot argument, because unlike ExecInsert(), no
1047  * tuple-routing is performed here, hence the slot remains unchanged.
1048  */
1049  if (resultRelationDesc->rd_att->constr || resultRelInfo->ri_PartitionCheck)
1050  ExecConstraints(resultRelInfo, slot, estate);
1051 
1052  /*
1053  * replace the heap tuple
1054  *
1055  * Note: if es_crosscheck_snapshot isn't InvalidSnapshot, we check
1056  * that the row to be updated is visible to that snapshot, and throw a
1057  * can't-serialize error if not. This is a special-case behavior
1058  * needed for referential integrity updates in transaction-snapshot
1059  * mode transactions.
1060  */
1061  result = heap_update(resultRelationDesc, tupleid, tuple,
1062  estate->es_output_cid,
1063  estate->es_crosscheck_snapshot,
1064  true /* wait for commit */ ,
1065  &hufd, &lockmode);
1066  switch (result)
1067  {
1068  case HeapTupleSelfUpdated:
1069 
1070  /*
1071  * The target tuple was already updated or deleted by the
1072  * current command, or by a later command in the current
1073  * transaction. The former case is possible in a join UPDATE
1074  * where multiple tuples join to the same target tuple. This
1075  * is pretty questionable, but Postgres has always allowed it:
1076  * we just execute the first update action and ignore
1077  * additional update attempts.
1078  *
1079  * The latter case arises if the tuple is modified by a
1080  * command in a BEFORE trigger, or perhaps by a command in a
1081  * volatile function used in the query. In such situations we
1082  * should not ignore the update, but it is equally unsafe to
1083  * proceed. We don't want to discard the original UPDATE
1084  * while keeping the triggered actions based on it; and we
1085  * have no principled way to merge this update with the
1086  * previous ones. So throwing an error is the only safe
1087  * course.
1088  *
1089  * If a trigger actually intends this type of interaction, it
1090  * can re-execute the UPDATE (assuming it can figure out how)
1091  * and then return NULL to cancel the outer update.
1092  */
1093  if (hufd.cmax != estate->es_output_cid)
1094  ereport(ERROR,
1095  (errcode(ERRCODE_TRIGGERED_DATA_CHANGE_VIOLATION),
1096  errmsg("tuple to be updated was already modified by an operation triggered by the current command"),
1097  errhint("Consider using an AFTER trigger instead of a BEFORE trigger to propagate changes to other rows.")));
1098 
1099  /* Else, already updated by self; nothing to do */
1100  return NULL;
1101 
1102  case HeapTupleMayBeUpdated:
1103  break;
1104 
1105  case HeapTupleUpdated:
1107  ereport(ERROR,
1108  (errcode(ERRCODE_T_R_SERIALIZATION_FAILURE),
1109  errmsg("could not serialize access due to concurrent update")));
1110  if (!ItemPointerEquals(tupleid, &hufd.ctid))
1111  {
1112  TupleTableSlot *epqslot;
1113 
1114  epqslot = EvalPlanQual(estate,
1115  epqstate,
1116  resultRelationDesc,
1117  resultRelInfo->ri_RangeTableIndex,
1118  lockmode,
1119  &hufd.ctid,
1120  hufd.xmax);
1121  if (!TupIsNull(epqslot))
1122  {
1123  *tupleid = hufd.ctid;
1124  slot = ExecFilterJunk(resultRelInfo->ri_junkFilter, epqslot);
1125  tuple = ExecMaterializeSlot(slot);
1126  goto lreplace;
1127  }
1128  }
1129  /* tuple already deleted; nothing to do */
1130  return NULL;
1131 
1132  default:
1133  elog(ERROR, "unrecognized heap_update status: %u", result);
1134  return NULL;
1135  }
1136 
1137  /*
1138  * Note: instead of having to update the old index tuples associated
1139  * with the heap tuple, all we do is form and insert new index tuples.
1140  * This is because UPDATEs are actually DELETEs and INSERTs, and index
1141  * tuple deletion is done later by VACUUM (see notes in ExecDelete).
1142  * All we do here is insert new index tuples. -cim 9/27/89
1143  */
1144 
1145  /*
1146  * insert index entries for tuple
1147  *
1148  * Note: heap_update returns the tid (location) of the new tuple in
1149  * the t_self field.
1150  *
1151  * If it's a HOT update, we mustn't insert new index entries.
1152  */
1153  if (resultRelInfo->ri_NumIndices > 0 && !HeapTupleIsHeapOnly(tuple))
1154  recheckIndexes = ExecInsertIndexTuples(slot, &(tuple->t_self),
1155  estate, false, NULL, NIL);
1156  }
1157 
1158  if (canSetTag)
1159  (estate->es_processed)++;
1160 
1161  /* AFTER ROW UPDATE Triggers */
1162  ExecARUpdateTriggers(estate, resultRelInfo, tupleid, oldtuple, tuple,
1163  recheckIndexes,
1164  mtstate->operation == CMD_INSERT ?
1165  mtstate->mt_oc_transition_capture :
1166  mtstate->mt_transition_capture);
1167 
1168  list_free(recheckIndexes);
1169 
1170  /*
1171  * Check any WITH CHECK OPTION constraints from parent views. We are
1172  * required to do this after testing all constraints and uniqueness
1173  * violations per the SQL spec, so we do it after actually updating the
1174  * record in the heap and all indexes.
1175  *
1176  * ExecWithCheckOptions() will skip any WCOs which are not of the kind we
1177  * are looking for at this point.
1178  */
1179  if (resultRelInfo->ri_WithCheckOptions != NIL)
1180  ExecWithCheckOptions(WCO_VIEW_CHECK, resultRelInfo, slot, estate);
1181 
1182  /* Process RETURNING if present */
1183  if (resultRelInfo->ri_projectReturning)
1184  return ExecProcessReturning(resultRelInfo, slot, planSlot);
1185 
1186  return NULL;
1187 }
1188 
1189 /*
1190  * ExecOnConflictUpdate --- execute UPDATE of INSERT ON CONFLICT DO UPDATE
1191  *
1192  * Try to lock tuple for update as part of speculative insertion. If
1193  * a qual originating from ON CONFLICT DO UPDATE is satisfied, update
1194  * (but still lock row, even though it may not satisfy estate's
1195  * snapshot).
1196  *
1197  * Returns true if if we're done (with or without an update), or false if
1198  * the caller must retry the INSERT from scratch.
1199  */
1200 static bool
1202  ResultRelInfo *resultRelInfo,
1203  ItemPointer conflictTid,
1204  TupleTableSlot *planSlot,
1205  TupleTableSlot *excludedSlot,
1206  EState *estate,
1207  bool canSetTag,
1208  TupleTableSlot **returning)
1209 {
1210  ExprContext *econtext = mtstate->ps.ps_ExprContext;
1211  Relation relation = resultRelInfo->ri_RelationDesc;
1212  ExprState *onConflictSetWhere = resultRelInfo->ri_onConflictSetWhere;
1213  HeapTupleData tuple;
1214  HeapUpdateFailureData hufd;
1215  LockTupleMode lockmode;
1216  HTSU_Result test;
1217  Buffer buffer;
1218 
1219  /* Determine lock mode to use */
1220  lockmode = ExecUpdateLockMode(estate, resultRelInfo);
1221 
1222  /*
1223  * Lock tuple for update. Don't follow updates when tuple cannot be
1224  * locked without doing so. A row locking conflict here means our
1225  * previous conclusion that the tuple is conclusively committed is not
1226  * true anymore.
1227  */
1228  tuple.t_self = *conflictTid;
1229  test = heap_lock_tuple(relation, &tuple, estate->es_output_cid,
1230  lockmode, LockWaitBlock, false, &buffer,
1231  &hufd);
1232  switch (test)
1233  {
1234  case HeapTupleMayBeUpdated:
1235  /* success! */
1236  break;
1237 
1238  case HeapTupleInvisible:
1239 
1240  /*
1241  * This can occur when a just inserted tuple is updated again in
1242  * the same command. E.g. because multiple rows with the same
1243  * conflicting key values are inserted.
1244  *
1245  * This is somewhat similar to the ExecUpdate()
1246  * HeapTupleSelfUpdated case. We do not want to proceed because
1247  * it would lead to the same row being updated a second time in
1248  * some unspecified order, and in contrast to plain UPDATEs
1249  * there's no historical behavior to break.
1250  *
1251  * It is the user's responsibility to prevent this situation from
1252  * occurring. These problems are why SQL-2003 similarly specifies
1253  * that for SQL MERGE, an exception must be raised in the event of
1254  * an attempt to update the same row twice.
1255  */
1257  ereport(ERROR,
1258  (errcode(ERRCODE_CARDINALITY_VIOLATION),
1259  errmsg("ON CONFLICT DO UPDATE command cannot affect row a second time"),
1260  errhint("Ensure that no rows proposed for insertion within the same command have duplicate constrained values.")));
1261 
1262  /* This shouldn't happen */
1263  elog(ERROR, "attempted to lock invisible tuple");
1264 
1265  case HeapTupleSelfUpdated:
1266 
1267  /*
1268  * This state should never be reached. As a dirty snapshot is used
1269  * to find conflicting tuples, speculative insertion wouldn't have
1270  * seen this row to conflict with.
1271  */
1272  elog(ERROR, "unexpected self-updated tuple");
1273 
1274  case HeapTupleUpdated:
1276  ereport(ERROR,
1277  (errcode(ERRCODE_T_R_SERIALIZATION_FAILURE),
1278  errmsg("could not serialize access due to concurrent update")));
1279 
1280  /*
1281  * Tell caller to try again from the very start.
1282  *
1283  * It does not make sense to use the usual EvalPlanQual() style
1284  * loop here, as the new version of the row might not conflict
1285  * anymore, or the conflicting tuple has actually been deleted.
1286  */
1287  ReleaseBuffer(buffer);
1288  return false;
1289 
1290  default:
1291  elog(ERROR, "unrecognized heap_lock_tuple status: %u", test);
1292  }
1293 
1294  /*
1295  * Success, the tuple is locked.
1296  *
1297  * Reset per-tuple memory context to free any expression evaluation
1298  * storage allocated in the previous cycle.
1299  */
1300  ResetExprContext(econtext);
1301 
1302  /*
1303  * Verify that the tuple is visible to our MVCC snapshot if the current
1304  * isolation level mandates that.
1305  *
1306  * It's not sufficient to rely on the check within ExecUpdate() as e.g.
1307  * CONFLICT ... WHERE clause may prevent us from reaching that.
1308  *
1309  * This means we only ever continue when a new command in the current
1310  * transaction could see the row, even though in READ COMMITTED mode the
1311  * tuple will not be visible according to the current statement's
1312  * snapshot. This is in line with the way UPDATE deals with newer tuple
1313  * versions.
1314  */
1315  ExecCheckHeapTupleVisible(estate, &tuple, buffer);
1316 
1317  /* Store target's existing tuple in the state's dedicated slot */
1318  ExecStoreTuple(&tuple, mtstate->mt_existing, buffer, false);
1319 
1320  /*
1321  * Make tuple and any needed join variables available to ExecQual and
1322  * ExecProject. The EXCLUDED tuple is installed in ecxt_innertuple, while
1323  * the target's existing tuple is installed in the scantuple. EXCLUDED
1324  * has been made to reference INNER_VAR in setrefs.c, but there is no
1325  * other redirection.
1326  */
1327  econtext->ecxt_scantuple = mtstate->mt_existing;
1328  econtext->ecxt_innertuple = excludedSlot;
1329  econtext->ecxt_outertuple = NULL;
1330 
1331  if (!ExecQual(onConflictSetWhere, econtext))
1332  {
1333  ReleaseBuffer(buffer);
1334  InstrCountFiltered1(&mtstate->ps, 1);
1335  return true; /* done with the tuple */
1336  }
1337 
1338  if (resultRelInfo->ri_WithCheckOptions != NIL)
1339  {
1340  /*
1341  * Check target's existing tuple against UPDATE-applicable USING
1342  * security barrier quals (if any), enforced here as RLS checks/WCOs.
1343  *
1344  * The rewriter creates UPDATE RLS checks/WCOs for UPDATE security
1345  * quals, and stores them as WCOs of "kind" WCO_RLS_CONFLICT_CHECK,
1346  * but that's almost the extent of its special handling for ON
1347  * CONFLICT DO UPDATE.
1348  *
1349  * The rewriter will also have associated UPDATE applicable straight
1350  * RLS checks/WCOs for the benefit of the ExecUpdate() call that
1351  * follows. INSERTs and UPDATEs naturally have mutually exclusive WCO
1352  * kinds, so there is no danger of spurious over-enforcement in the
1353  * INSERT or UPDATE path.
1354  */
1356  mtstate->mt_existing,
1357  mtstate->ps.state);
1358  }
1359 
1360  /* Project the new tuple version */
1361  ExecProject(resultRelInfo->ri_onConflictSetProj);
1362 
1363  /*
1364  * Note that it is possible that the target tuple has been modified in
1365  * this session, after the above heap_lock_tuple. We choose to not error
1366  * out in that case, in line with ExecUpdate's treatment of similar cases.
1367  * This can happen if an UPDATE is triggered from within ExecQual(),
1368  * ExecWithCheckOptions() or ExecProject() above, e.g. by selecting from a
1369  * wCTE in the ON CONFLICT's SET.
1370  */
1371 
1372  /* Execute UPDATE with projection */
1373  *returning = ExecUpdate(mtstate, &tuple.t_self, NULL,
1374  mtstate->mt_conflproj, planSlot,
1375  &mtstate->mt_epqstate, mtstate->ps.state,
1376  canSetTag);
1377 
1378  ReleaseBuffer(buffer);
1379  return true;
1380 }
1381 
1382 
1383 /*
1384  * Process BEFORE EACH STATEMENT triggers
1385  */
1386 static void
1388 {
1389  ResultRelInfo *resultRelInfo = node->resultRelInfo;
1390 
1391  /*
1392  * If the node modifies a partitioned table, we must fire its triggers.
1393  * Note that in that case, node->resultRelInfo points to the first leaf
1394  * partition, not the root table.
1395  */
1396  if (node->rootResultRelInfo != NULL)
1397  resultRelInfo = node->rootResultRelInfo;
1398 
1399  switch (node->operation)
1400  {
1401  case CMD_INSERT:
1402  ExecBSInsertTriggers(node->ps.state, resultRelInfo);
1403  if (node->mt_onconflict == ONCONFLICT_UPDATE)
1405  resultRelInfo);
1406  break;
1407  case CMD_UPDATE:
1408  ExecBSUpdateTriggers(node->ps.state, resultRelInfo);
1409  break;
1410  case CMD_DELETE:
1411  ExecBSDeleteTriggers(node->ps.state, resultRelInfo);
1412  break;
1413  default:
1414  elog(ERROR, "unknown operation");
1415  break;
1416  }
1417 }
1418 
1419 /*
1420  * Return the ResultRelInfo for which we will fire AFTER STATEMENT triggers.
1421  * This is also the relation into whose tuple format all captured transition
1422  * tuples must be converted.
1423  */
1424 static ResultRelInfo *
1426 {
1427  /*
1428  * If the node modifies a partitioned table, we must fire its triggers.
1429  * Note that in that case, node->resultRelInfo points to the first leaf
1430  * partition, not the root table.
1431  */
1432  if (node->rootResultRelInfo != NULL)
1433  return node->rootResultRelInfo;
1434  else
1435  return node->resultRelInfo;
1436 }
1437 
1438 /*
1439  * Process AFTER EACH STATEMENT triggers
1440  */
1441 static void
1443 {
1444  ResultRelInfo *resultRelInfo = getASTriggerResultRelInfo(node);
1445 
1446  switch (node->operation)
1447  {
1448  case CMD_INSERT:
1449  if (node->mt_onconflict == ONCONFLICT_UPDATE)
1451  resultRelInfo,
1452  node->mt_oc_transition_capture);
1453  ExecASInsertTriggers(node->ps.state, resultRelInfo,
1454  node->mt_transition_capture);
1455  break;
1456  case CMD_UPDATE:
1457  ExecASUpdateTriggers(node->ps.state, resultRelInfo,
1458  node->mt_transition_capture);
1459  break;
1460  case CMD_DELETE:
1461  ExecASDeleteTriggers(node->ps.state, resultRelInfo,
1462  node->mt_transition_capture);
1463  break;
1464  default:
1465  elog(ERROR, "unknown operation");
1466  break;
1467  }
1468 }
1469 
1470 /*
1471  * Set up the state needed for collecting transition tuples for AFTER
1472  * triggers.
1473  */
1474 static void
1476 {
1477  ResultRelInfo *targetRelInfo = getASTriggerResultRelInfo(mtstate);
1478  int i;
1479 
1480  /* Check for transition tables on the directly targeted relation. */
1481  mtstate->mt_transition_capture =
1482  MakeTransitionCaptureState(targetRelInfo->ri_TrigDesc,
1483  RelationGetRelid(targetRelInfo->ri_RelationDesc),
1484  mtstate->operation);
1485  if (mtstate->operation == CMD_INSERT &&
1486  mtstate->mt_onconflict == ONCONFLICT_UPDATE)
1487  mtstate->mt_oc_transition_capture =
1488  MakeTransitionCaptureState(targetRelInfo->ri_TrigDesc,
1489  RelationGetRelid(targetRelInfo->ri_RelationDesc),
1490  CMD_UPDATE);
1491 
1492  /*
1493  * If we found that we need to collect transition tuples then we may also
1494  * need tuple conversion maps for any children that have TupleDescs that
1495  * aren't compatible with the tuplestores. (We can share these maps
1496  * between the regular and ON CONFLICT cases.)
1497  */
1498  if (mtstate->mt_transition_capture != NULL ||
1499  mtstate->mt_oc_transition_capture != NULL)
1500  {
1501  int numResultRelInfos;
1502 
1503  numResultRelInfos = (mtstate->mt_partition_tuple_slot != NULL ?
1504  mtstate->mt_num_partitions :
1505  mtstate->mt_nplans);
1506 
1507  /*
1508  * Build array of conversion maps from each child's TupleDesc to the
1509  * one used in the tuplestore. The map pointers may be NULL when no
1510  * conversion is necessary, which is hopefully a common case for
1511  * partitions.
1512  */
1514  palloc0(sizeof(TupleConversionMap *) * numResultRelInfos);
1515 
1516  /* Choose the right set of partitions */
1517  if (mtstate->mt_partition_dispatch_info != NULL)
1518  {
1519  /*
1520  * For tuple routing among partitions, we need TupleDescs based
1521  * on the partition routing table.
1522  */
1523  ResultRelInfo **resultRelInfos = mtstate->mt_partitions;
1524 
1525  for (i = 0; i < numResultRelInfos; ++i)
1526  {
1527  mtstate->mt_transition_tupconv_maps[i] =
1528  convert_tuples_by_name(RelationGetDescr(resultRelInfos[i]->ri_RelationDesc),
1529  RelationGetDescr(targetRelInfo->ri_RelationDesc),
1530  gettext_noop("could not convert row type"));
1531  }
1532  }
1533  else
1534  {
1535  /* Otherwise we need the ResultRelInfo for each subplan. */
1536  ResultRelInfo *resultRelInfos = mtstate->resultRelInfo;
1537 
1538  for (i = 0; i < numResultRelInfos; ++i)
1539  {
1540  mtstate->mt_transition_tupconv_maps[i] =
1541  convert_tuples_by_name(RelationGetDescr(resultRelInfos[i].ri_RelationDesc),
1542  RelationGetDescr(targetRelInfo->ri_RelationDesc),
1543  gettext_noop("could not convert row type"));
1544  }
1545  }
1546 
1547  /*
1548  * Install the conversion map for the first plan for UPDATE and DELETE
1549  * operations. It will be advanced each time we switch to the next
1550  * plan. (INSERT operations set it every time, so we need not update
1551  * mtstate->mt_oc_transition_capture here.)
1552  */
1553  if (mtstate->mt_transition_capture)
1554  mtstate->mt_transition_capture->tcs_map =
1555  mtstate->mt_transition_tupconv_maps[0];
1556  }
1557 }
1558 
1559 /* ----------------------------------------------------------------
1560  * ExecModifyTable
1561  *
1562  * Perform table modifications as required, and return RETURNING results
1563  * if needed.
1564  * ----------------------------------------------------------------
1565  */
1566 static TupleTableSlot *
1568 {
1569  ModifyTableState *node = castNode(ModifyTableState, pstate);
1570  EState *estate = node->ps.state;
1571  CmdType operation = node->operation;
1572  ResultRelInfo *saved_resultRelInfo;
1573  ResultRelInfo *resultRelInfo;
1574  PlanState *subplanstate;
1575  JunkFilter *junkfilter;
1576  TupleTableSlot *slot;
1577  TupleTableSlot *planSlot;
1578  ItemPointer tupleid = NULL;
1579  ItemPointerData tuple_ctid;
1580  HeapTupleData oldtupdata;
1581  HeapTuple oldtuple;
1582 
1584 
1585  /*
1586  * This should NOT get called during EvalPlanQual; we should have passed a
1587  * subplan tree to EvalPlanQual, instead. Use a runtime test not just
1588  * Assert because this condition is easy to miss in testing. (Note:
1589  * although ModifyTable should not get executed within an EvalPlanQual
1590  * operation, we do have to allow it to be initialized and shut down in
1591  * case it is within a CTE subplan. Hence this test must be here, not in
1592  * ExecInitModifyTable.)
1593  */
1594  if (estate->es_epqTuple != NULL)
1595  elog(ERROR, "ModifyTable should not be called during EvalPlanQual");
1596 
1597  /*
1598  * If we've already completed processing, don't try to do more. We need
1599  * this test because ExecPostprocessPlan might call us an extra time, and
1600  * our subplan's nodes aren't necessarily robust against being called
1601  * extra times.
1602  */
1603  if (node->mt_done)
1604  return NULL;
1605 
1606  /*
1607  * On first call, fire BEFORE STATEMENT triggers before proceeding.
1608  */
1609  if (node->fireBSTriggers)
1610  {
1611  fireBSTriggers(node);
1612  node->fireBSTriggers = false;
1613  }
1614 
1615  /* Preload local variables */
1616  resultRelInfo = node->resultRelInfo + node->mt_whichplan;
1617  subplanstate = node->mt_plans[node->mt_whichplan];
1618  junkfilter = resultRelInfo->ri_junkFilter;
1619 
1620  /*
1621  * es_result_relation_info must point to the currently active result
1622  * relation while we are within this ModifyTable node. Even though
1623  * ModifyTable nodes can't be nested statically, they can be nested
1624  * dynamically (since our subplan could include a reference to a modifying
1625  * CTE). So we have to save and restore the caller's value.
1626  */
1627  saved_resultRelInfo = estate->es_result_relation_info;
1628 
1629  estate->es_result_relation_info = resultRelInfo;
1630 
1631  /*
1632  * Fetch rows from subplan(s), and execute the required table modification
1633  * for each row.
1634  */
1635  for (;;)
1636  {
1637  /*
1638  * Reset the per-output-tuple exprcontext. This is needed because
1639  * triggers expect to use that context as workspace. It's a bit ugly
1640  * to do this below the top level of the plan, however. We might need
1641  * to rethink this later.
1642  */
1643  ResetPerTupleExprContext(estate);
1644 
1645  planSlot = ExecProcNode(subplanstate);
1646 
1647  if (TupIsNull(planSlot))
1648  {
1649  /* advance to next subplan if any */
1650  node->mt_whichplan++;
1651  if (node->mt_whichplan < node->mt_nplans)
1652  {
1653  resultRelInfo++;
1654  subplanstate = node->mt_plans[node->mt_whichplan];
1655  junkfilter = resultRelInfo->ri_junkFilter;
1656  estate->es_result_relation_info = resultRelInfo;
1657  EvalPlanQualSetPlan(&node->mt_epqstate, subplanstate->plan,
1658  node->mt_arowmarks[node->mt_whichplan]);
1659  /* Prepare to convert transition tuples from this child. */
1660  if (node->mt_transition_capture != NULL)
1661  {
1662  Assert(node->mt_transition_tupconv_maps != NULL);
1665  }
1666  if (node->mt_oc_transition_capture != NULL)
1667  {
1668  Assert(node->mt_transition_tupconv_maps != NULL);
1671  }
1672  continue;
1673  }
1674  else
1675  break;
1676  }
1677 
1678  /*
1679  * If resultRelInfo->ri_usesFdwDirectModify is true, all we need to do
1680  * here is compute the RETURNING expressions.
1681  */
1682  if (resultRelInfo->ri_usesFdwDirectModify)
1683  {
1684  Assert(resultRelInfo->ri_projectReturning);
1685 
1686  /*
1687  * A scan slot containing the data that was actually inserted,
1688  * updated or deleted has already been made available to
1689  * ExecProcessReturning by IterateDirectModify, so no need to
1690  * provide it here.
1691  */
1692  slot = ExecProcessReturning(resultRelInfo, NULL, planSlot);
1693 
1694  estate->es_result_relation_info = saved_resultRelInfo;
1695  return slot;
1696  }
1697 
1698  EvalPlanQualSetSlot(&node->mt_epqstate, planSlot);
1699  slot = planSlot;
1700 
1701  oldtuple = NULL;
1702  if (junkfilter != NULL)
1703  {
1704  /*
1705  * extract the 'ctid' or 'wholerow' junk attribute.
1706  */
1707  if (operation == CMD_UPDATE || operation == CMD_DELETE)
1708  {
1709  char relkind;
1710  Datum datum;
1711  bool isNull;
1712 
1713  relkind = resultRelInfo->ri_RelationDesc->rd_rel->relkind;
1714  if (relkind == RELKIND_RELATION || relkind == RELKIND_MATVIEW)
1715  {
1716  datum = ExecGetJunkAttribute(slot,
1717  junkfilter->jf_junkAttNo,
1718  &isNull);
1719  /* shouldn't ever get a null result... */
1720  if (isNull)
1721  elog(ERROR, "ctid is NULL");
1722 
1723  tupleid = (ItemPointer) DatumGetPointer(datum);
1724  tuple_ctid = *tupleid; /* be sure we don't free ctid!! */
1725  tupleid = &tuple_ctid;
1726  }
1727 
1728  /*
1729  * Use the wholerow attribute, when available, to reconstruct
1730  * the old relation tuple.
1731  *
1732  * Foreign table updates have a wholerow attribute when the
1733  * relation has a row-level trigger. Note that the wholerow
1734  * attribute does not carry system columns. Foreign table
1735  * triggers miss seeing those, except that we know enough here
1736  * to set t_tableOid. Quite separately from this, the FDW may
1737  * fetch its own junk attrs to identify the row.
1738  *
1739  * Other relevant relkinds, currently limited to views, always
1740  * have a wholerow attribute.
1741  */
1742  else if (AttributeNumberIsValid(junkfilter->jf_junkAttNo))
1743  {
1744  datum = ExecGetJunkAttribute(slot,
1745  junkfilter->jf_junkAttNo,
1746  &isNull);
1747  /* shouldn't ever get a null result... */
1748  if (isNull)
1749  elog(ERROR, "wholerow is NULL");
1750 
1751  oldtupdata.t_data = DatumGetHeapTupleHeader(datum);
1752  oldtupdata.t_len =
1754  ItemPointerSetInvalid(&(oldtupdata.t_self));
1755  /* Historically, view triggers see invalid t_tableOid. */
1756  oldtupdata.t_tableOid =
1757  (relkind == RELKIND_VIEW) ? InvalidOid :
1758  RelationGetRelid(resultRelInfo->ri_RelationDesc);
1759 
1760  oldtuple = &oldtupdata;
1761  }
1762  else
1763  Assert(relkind == RELKIND_FOREIGN_TABLE);
1764  }
1765 
1766  /*
1767  * apply the junkfilter if needed.
1768  */
1769  if (operation != CMD_DELETE)
1770  slot = ExecFilterJunk(junkfilter, slot);
1771  }
1772 
1773  switch (operation)
1774  {
1775  case CMD_INSERT:
1776  slot = ExecInsert(node, slot, planSlot,
1777  node->mt_arbiterindexes, node->mt_onconflict,
1778  estate, node->canSetTag);
1779  break;
1780  case CMD_UPDATE:
1781  slot = ExecUpdate(node, tupleid, oldtuple, slot, planSlot,
1782  &node->mt_epqstate, estate, node->canSetTag);
1783  break;
1784  case CMD_DELETE:
1785  slot = ExecDelete(node, tupleid, oldtuple, planSlot,
1786  &node->mt_epqstate, estate, node->canSetTag);
1787  break;
1788  default:
1789  elog(ERROR, "unknown operation");
1790  break;
1791  }
1792 
1793  /*
1794  * If we got a RETURNING result, return it to caller. We'll continue
1795  * the work on next call.
1796  */
1797  if (slot)
1798  {
1799  estate->es_result_relation_info = saved_resultRelInfo;
1800  return slot;
1801  }
1802  }
1803 
1804  /* Restore es_result_relation_info before exiting */
1805  estate->es_result_relation_info = saved_resultRelInfo;
1806 
1807  /*
1808  * We're done, but fire AFTER STATEMENT triggers before exiting.
1809  */
1810  fireASTriggers(node);
1811 
1812  node->mt_done = true;
1813 
1814  return NULL;
1815 }
1816 
1817 /* ----------------------------------------------------------------
1818  * ExecInitModifyTable
1819  * ----------------------------------------------------------------
1820  */
1822 ExecInitModifyTable(ModifyTable *node, EState *estate, int eflags)
1823 {
1824  ModifyTableState *mtstate;
1825  CmdType operation = node->operation;
1826  int nplans = list_length(node->plans);
1827  ResultRelInfo *saved_resultRelInfo;
1828  ResultRelInfo *resultRelInfo;
1829  TupleDesc tupDesc;
1830  Plan *subplan;
1831  ListCell *l;
1832  int i;
1833  Relation rel;
1834 
1835  /* check for unsupported flags */
1836  Assert(!(eflags & (EXEC_FLAG_BACKWARD | EXEC_FLAG_MARK)));
1837 
1838  /*
1839  * create state structure
1840  */
1841  mtstate = makeNode(ModifyTableState);
1842  mtstate->ps.plan = (Plan *) node;
1843  mtstate->ps.state = estate;
1844  mtstate->ps.ExecProcNode = ExecModifyTable;
1845 
1846  mtstate->operation = operation;
1847  mtstate->canSetTag = node->canSetTag;
1848  mtstate->mt_done = false;
1849 
1850  mtstate->mt_plans = (PlanState **) palloc0(sizeof(PlanState *) * nplans);
1851  mtstate->resultRelInfo = estate->es_result_relations + node->resultRelIndex;
1852 
1853  /* If modifying a partitioned table, initialize the root table info */
1854  if (node->rootResultRelIndex >= 0)
1855  mtstate->rootResultRelInfo = estate->es_root_result_relations +
1856  node->rootResultRelIndex;
1857 
1858  mtstate->mt_arowmarks = (List **) palloc0(sizeof(List *) * nplans);
1859  mtstate->mt_nplans = nplans;
1860  mtstate->mt_onconflict = node->onConflictAction;
1861  mtstate->mt_arbiterindexes = node->arbiterIndexes;
1862 
1863  /* set up epqstate with dummy subplan data for the moment */
1864  EvalPlanQualInit(&mtstate->mt_epqstate, estate, NULL, NIL, node->epqParam);
1865  mtstate->fireBSTriggers = true;
1866 
1867  /*
1868  * call ExecInitNode on each of the plans to be executed and save the
1869  * results into the array "mt_plans". This is also a convenient place to
1870  * verify that the proposed target relations are valid and open their
1871  * indexes for insertion of new index entries. Note we *must* set
1872  * estate->es_result_relation_info correctly while we initialize each
1873  * sub-plan; ExecContextForcesOids depends on that!
1874  */
1875  saved_resultRelInfo = estate->es_result_relation_info;
1876 
1877  resultRelInfo = mtstate->resultRelInfo;
1878  i = 0;
1879  foreach(l, node->plans)
1880  {
1881  subplan = (Plan *) lfirst(l);
1882 
1883  /* Initialize the usesFdwDirectModify flag */
1884  resultRelInfo->ri_usesFdwDirectModify = bms_is_member(i,
1885  node->fdwDirectModifyPlans);
1886 
1887  /*
1888  * Verify result relation is a valid target for the current operation
1889  */
1890  CheckValidResultRel(resultRelInfo, operation);
1891 
1892  /*
1893  * If there are indices on the result relation, open them and save
1894  * descriptors in the result relation info, so that we can add new
1895  * index entries for the tuples we add/update. We need not do this
1896  * for a DELETE, however, since deletion doesn't affect indexes. Also,
1897  * inside an EvalPlanQual operation, the indexes might be open
1898  * already, since we share the resultrel state with the original
1899  * query.
1900  */
1901  if (resultRelInfo->ri_RelationDesc->rd_rel->relhasindex &&
1902  operation != CMD_DELETE &&
1903  resultRelInfo->ri_IndexRelationDescs == NULL)
1904  ExecOpenIndices(resultRelInfo, mtstate->mt_onconflict != ONCONFLICT_NONE);
1905 
1906  /* Now init the plan for this result rel */
1907  estate->es_result_relation_info = resultRelInfo;
1908  mtstate->mt_plans[i] = ExecInitNode(subplan, estate, eflags);
1909 
1910  /* Also let FDWs init themselves for foreign-table result rels */
1911  if (!resultRelInfo->ri_usesFdwDirectModify &&
1912  resultRelInfo->ri_FdwRoutine != NULL &&
1913  resultRelInfo->ri_FdwRoutine->BeginForeignModify != NULL)
1914  {
1915  List *fdw_private = (List *) list_nth(node->fdwPrivLists, i);
1916 
1917  resultRelInfo->ri_FdwRoutine->BeginForeignModify(mtstate,
1918  resultRelInfo,
1919  fdw_private,
1920  i,
1921  eflags);
1922  }
1923 
1924  resultRelInfo++;
1925  i++;
1926  }
1927 
1928  estate->es_result_relation_info = saved_resultRelInfo;
1929 
1930  /* The root table RT index is at the head of the partitioned_rels list */
1931  if (node->partitioned_rels)
1932  {
1933  Index root_rti;
1934  Oid root_oid;
1935 
1936  root_rti = linitial_int(node->partitioned_rels);
1937  root_oid = getrelid(root_rti, estate->es_range_table);
1938  rel = heap_open(root_oid, NoLock); /* locked by InitPlan */
1939  }
1940  else
1941  rel = mtstate->resultRelInfo->ri_RelationDesc;
1942 
1943  /* Build state for INSERT tuple routing */
1944  if (operation == CMD_INSERT &&
1945  rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE)
1946  {
1947  PartitionDispatch *partition_dispatch_info;
1948  ResultRelInfo **partitions;
1949  TupleConversionMap **partition_tupconv_maps;
1950  TupleTableSlot *partition_tuple_slot;
1951  int num_parted,
1952  num_partitions;
1953 
1955  node->nominalRelation,
1956  estate,
1957  &partition_dispatch_info,
1958  &partitions,
1959  &partition_tupconv_maps,
1960  &partition_tuple_slot,
1961  &num_parted, &num_partitions);
1962  mtstate->mt_partition_dispatch_info = partition_dispatch_info;
1963  mtstate->mt_num_dispatch = num_parted;
1964  mtstate->mt_partitions = partitions;
1965  mtstate->mt_num_partitions = num_partitions;
1966  mtstate->mt_partition_tupconv_maps = partition_tupconv_maps;
1967  mtstate->mt_partition_tuple_slot = partition_tuple_slot;
1968  }
1969 
1970  /*
1971  * Build state for collecting transition tuples. This requires having a
1972  * valid trigger query context, so skip it in explain-only mode.
1973  */
1974  if (!(eflags & EXEC_FLAG_EXPLAIN_ONLY))
1975  ExecSetupTransitionCaptureState(mtstate, estate);
1976 
1977  /*
1978  * Initialize any WITH CHECK OPTION constraints if needed.
1979  */
1980  resultRelInfo = mtstate->resultRelInfo;
1981  i = 0;
1982  foreach(l, node->withCheckOptionLists)
1983  {
1984  List *wcoList = (List *) lfirst(l);
1985  List *wcoExprs = NIL;
1986  ListCell *ll;
1987 
1988  foreach(ll, wcoList)
1989  {
1990  WithCheckOption *wco = (WithCheckOption *) lfirst(ll);
1991  ExprState *wcoExpr = ExecInitQual((List *) wco->qual,
1992  mtstate->mt_plans[i]);
1993 
1994  wcoExprs = lappend(wcoExprs, wcoExpr);
1995  }
1996 
1997  resultRelInfo->ri_WithCheckOptions = wcoList;
1998  resultRelInfo->ri_WithCheckOptionExprs = wcoExprs;
1999  resultRelInfo++;
2000  i++;
2001  }
2002 
2003  /*
2004  * Build WITH CHECK OPTION constraints for each leaf partition rel. Note
2005  * that we didn't build the withCheckOptionList for each partition within
2006  * the planner, but simple translation of the varattnos for each partition
2007  * will suffice. This only occurs for the INSERT case; UPDATE/DELETE
2008  * cases are handled above.
2009  */
2010  if (node->withCheckOptionLists != NIL && mtstate->mt_num_partitions > 0)
2011  {
2012  List *wcoList;
2013  PlanState *plan;
2014 
2015  /*
2016  * In case of INSERT on partitioned tables, there is only one plan.
2017  * Likewise, there is only one WITH CHECK OPTIONS list, not one per
2018  * partition. We make a copy of the WCO qual for each partition; note
2019  * that, if there are SubPlans in there, they all end up attached to
2020  * the one parent Plan node.
2021  */
2022  Assert(operation == CMD_INSERT &&
2023  list_length(node->withCheckOptionLists) == 1 &&
2024  mtstate->mt_nplans == 1);
2025  wcoList = linitial(node->withCheckOptionLists);
2026  plan = mtstate->mt_plans[0];
2027  for (i = 0; i < mtstate->mt_num_partitions; i++)
2028  {
2029  Relation partrel;
2030  List *mapped_wcoList;
2031  List *wcoExprs = NIL;
2032  ListCell *ll;
2033 
2034  resultRelInfo = mtstate->mt_partitions[i];
2035  partrel = resultRelInfo->ri_RelationDesc;
2036 
2037  /* varno = node->nominalRelation */
2038  mapped_wcoList = map_partition_varattnos(wcoList,
2039  node->nominalRelation,
2040  partrel, rel, NULL);
2041  foreach(ll, mapped_wcoList)
2042  {
2044  ExprState *wcoExpr = ExecInitQual(castNode(List, wco->qual),
2045  plan);
2046 
2047  wcoExprs = lappend(wcoExprs, wcoExpr);
2048  }
2049 
2050  resultRelInfo->ri_WithCheckOptions = mapped_wcoList;
2051  resultRelInfo->ri_WithCheckOptionExprs = wcoExprs;
2052  }
2053  }
2054 
2055  /*
2056  * Initialize RETURNING projections if needed.
2057  */
2058  if (node->returningLists)
2059  {
2060  TupleTableSlot *slot;
2061  ExprContext *econtext;
2062  List *returningList;
2063 
2064  /*
2065  * Initialize result tuple slot and assign its rowtype using the first
2066  * RETURNING list. We assume the rest will look the same.
2067  */
2068  tupDesc = ExecTypeFromTL((List *) linitial(node->returningLists),
2069  false);
2070 
2071  /* Set up a slot for the output of the RETURNING projection(s) */
2072  ExecInitResultTupleSlot(estate, &mtstate->ps);
2073  ExecAssignResultType(&mtstate->ps, tupDesc);
2074  slot = mtstate->ps.ps_ResultTupleSlot;
2075 
2076  /* Need an econtext too */
2077  if (mtstate->ps.ps_ExprContext == NULL)
2078  ExecAssignExprContext(estate, &mtstate->ps);
2079  econtext = mtstate->ps.ps_ExprContext;
2080 
2081  /*
2082  * Build a projection for each result rel.
2083  */
2084  resultRelInfo = mtstate->resultRelInfo;
2085  foreach(l, node->returningLists)
2086  {
2087  List *rlist = (List *) lfirst(l);
2088 
2089  resultRelInfo->ri_projectReturning =
2090  ExecBuildProjectionInfo(rlist, econtext, slot, &mtstate->ps,
2091  resultRelInfo->ri_RelationDesc->rd_att);
2092  resultRelInfo++;
2093  }
2094 
2095  /*
2096  * Build a projection for each leaf partition rel. Note that we
2097  * didn't build the returningList for each partition within the
2098  * planner, but simple translation of the varattnos for each partition
2099  * will suffice. This only occurs for the INSERT case; UPDATE/DELETE
2100  * are handled above.
2101  */
2102  returningList = linitial(node->returningLists);
2103  for (i = 0; i < mtstate->mt_num_partitions; i++)
2104  {
2105  Relation partrel;
2106  List *rlist;
2107 
2108  resultRelInfo = mtstate->mt_partitions[i];
2109  partrel = resultRelInfo->ri_RelationDesc;
2110 
2111  /* varno = node->nominalRelation */
2112  rlist = map_partition_varattnos(returningList,
2113  node->nominalRelation,
2114  partrel, rel, NULL);
2115  resultRelInfo->ri_projectReturning =
2116  ExecBuildProjectionInfo(rlist, econtext, slot, &mtstate->ps,
2117  resultRelInfo->ri_RelationDesc->rd_att);
2118  }
2119  }
2120  else
2121  {
2122  /*
2123  * We still must construct a dummy result tuple type, because InitPlan
2124  * expects one (maybe should change that?).
2125  */
2126  tupDesc = ExecTypeFromTL(NIL, false);
2127  ExecInitResultTupleSlot(estate, &mtstate->ps);
2128  ExecAssignResultType(&mtstate->ps, tupDesc);
2129 
2130  mtstate->ps.ps_ExprContext = NULL;
2131  }
2132 
2133  /* Close the root partitioned rel if we opened it above. */
2134  if (rel != mtstate->resultRelInfo->ri_RelationDesc)
2135  heap_close(rel, NoLock);
2136 
2137  /*
2138  * If needed, Initialize target list, projection and qual for ON CONFLICT
2139  * DO UPDATE.
2140  */
2141  resultRelInfo = mtstate->resultRelInfo;
2142  if (node->onConflictAction == ONCONFLICT_UPDATE)
2143  {
2144  ExprContext *econtext;
2145  TupleDesc tupDesc;
2146 
2147  /* insert may only have one plan, inheritance is not expanded */
2148  Assert(nplans == 1);
2149 
2150  /* already exists if created by RETURNING processing above */
2151  if (mtstate->ps.ps_ExprContext == NULL)
2152  ExecAssignExprContext(estate, &mtstate->ps);
2153 
2154  econtext = mtstate->ps.ps_ExprContext;
2155 
2156  /* initialize slot for the existing tuple */
2157  mtstate->mt_existing = ExecInitExtraTupleSlot(mtstate->ps.state);
2159  resultRelInfo->ri_RelationDesc->rd_att);
2160 
2161  /* carried forward solely for the benefit of explain */
2162  mtstate->mt_excludedtlist = node->exclRelTlist;
2163 
2164  /* create target slot for UPDATE SET projection */
2165  tupDesc = ExecTypeFromTL((List *) node->onConflictSet,
2166  resultRelInfo->ri_RelationDesc->rd_rel->relhasoids);
2167  mtstate->mt_conflproj = ExecInitExtraTupleSlot(mtstate->ps.state);
2168  ExecSetSlotDescriptor(mtstate->mt_conflproj, tupDesc);
2169 
2170  /* build UPDATE SET projection state */
2171  resultRelInfo->ri_onConflictSetProj =
2172  ExecBuildProjectionInfo(node->onConflictSet, econtext,
2173  mtstate->mt_conflproj, &mtstate->ps,
2174  resultRelInfo->ri_RelationDesc->rd_att);
2175 
2176  /* build DO UPDATE WHERE clause expression */
2177  if (node->onConflictWhere)
2178  {
2179  ExprState *qualexpr;
2180 
2181  qualexpr = ExecInitQual((List *) node->onConflictWhere,
2182  &mtstate->ps);
2183 
2184  resultRelInfo->ri_onConflictSetWhere = qualexpr;
2185  }
2186  }
2187 
2188  /*
2189  * If we have any secondary relations in an UPDATE or DELETE, they need to
2190  * be treated like non-locked relations in SELECT FOR UPDATE, ie, the
2191  * EvalPlanQual mechanism needs to be told about them. Locate the
2192  * relevant ExecRowMarks.
2193  */
2194  foreach(l, node->rowMarks)
2195  {
2197  ExecRowMark *erm;
2198 
2199  /* ignore "parent" rowmarks; they are irrelevant at runtime */
2200  if (rc->isParent)
2201  continue;
2202 
2203  /* find ExecRowMark (same for all subplans) */
2204  erm = ExecFindRowMark(estate, rc->rti, false);
2205 
2206  /* build ExecAuxRowMark for each subplan */
2207  for (i = 0; i < nplans; i++)
2208  {
2209  ExecAuxRowMark *aerm;
2210 
2211  subplan = mtstate->mt_plans[i]->plan;
2212  aerm = ExecBuildAuxRowMark(erm, subplan->targetlist);
2213  mtstate->mt_arowmarks[i] = lappend(mtstate->mt_arowmarks[i], aerm);
2214  }
2215  }
2216 
2217  /* select first subplan */
2218  mtstate->mt_whichplan = 0;
2219  subplan = (Plan *) linitial(node->plans);
2220  EvalPlanQualSetPlan(&mtstate->mt_epqstate, subplan,
2221  mtstate->mt_arowmarks[0]);
2222 
2223  /*
2224  * Initialize the junk filter(s) if needed. INSERT queries need a filter
2225  * if there are any junk attrs in the tlist. UPDATE and DELETE always
2226  * need a filter, since there's always at least one junk attribute present
2227  * --- no need to look first. Typically, this will be a 'ctid' or
2228  * 'wholerow' attribute, but in the case of a foreign data wrapper it
2229  * might be a set of junk attributes sufficient to identify the remote
2230  * row.
2231  *
2232  * If there are multiple result relations, each one needs its own junk
2233  * filter. Note multiple rels are only possible for UPDATE/DELETE, so we
2234  * can't be fooled by some needing a filter and some not.
2235  *
2236  * This section of code is also a convenient place to verify that the
2237  * output of an INSERT or UPDATE matches the target table(s).
2238  */
2239  {
2240  bool junk_filter_needed = false;
2241 
2242  switch (operation)
2243  {
2244  case CMD_INSERT:
2245  foreach(l, subplan->targetlist)
2246  {
2247  TargetEntry *tle = (TargetEntry *) lfirst(l);
2248 
2249  if (tle->resjunk)
2250  {
2251  junk_filter_needed = true;
2252  break;
2253  }
2254  }
2255  break;
2256  case CMD_UPDATE:
2257  case CMD_DELETE:
2258  junk_filter_needed = true;
2259  break;
2260  default:
2261  elog(ERROR, "unknown operation");
2262  break;
2263  }
2264 
2265  if (junk_filter_needed)
2266  {
2267  resultRelInfo = mtstate->resultRelInfo;
2268  for (i = 0; i < nplans; i++)
2269  {
2270  JunkFilter *j;
2271 
2272  subplan = mtstate->mt_plans[i]->plan;
2273  if (operation == CMD_INSERT || operation == CMD_UPDATE)
2274  ExecCheckPlanOutput(resultRelInfo->ri_RelationDesc,
2275  subplan->targetlist);
2276 
2277  j = ExecInitJunkFilter(subplan->targetlist,
2278  resultRelInfo->ri_RelationDesc->rd_att->tdhasoid,
2279  ExecInitExtraTupleSlot(estate));
2280 
2281  if (operation == CMD_UPDATE || operation == CMD_DELETE)
2282  {
2283  /* For UPDATE/DELETE, find the appropriate junk attr now */
2284  char relkind;
2285 
2286  relkind = resultRelInfo->ri_RelationDesc->rd_rel->relkind;
2287  if (relkind == RELKIND_RELATION ||
2288  relkind == RELKIND_MATVIEW ||
2289  relkind == RELKIND_PARTITIONED_TABLE)
2290  {
2291  j->jf_junkAttNo = ExecFindJunkAttribute(j, "ctid");
2293  elog(ERROR, "could not find junk ctid column");
2294  }
2295  else if (relkind == RELKIND_FOREIGN_TABLE)
2296  {
2297  /*
2298  * When there is a row-level trigger, there should be
2299  * a wholerow attribute.
2300  */
2301  j->jf_junkAttNo = ExecFindJunkAttribute(j, "wholerow");
2302  }
2303  else
2304  {
2305  j->jf_junkAttNo = ExecFindJunkAttribute(j, "wholerow");
2307  elog(ERROR, "could not find junk wholerow column");
2308  }
2309  }
2310 
2311  resultRelInfo->ri_junkFilter = j;
2312  resultRelInfo++;
2313  }
2314  }
2315  else
2316  {
2317  if (operation == CMD_INSERT)
2319  subplan->targetlist);
2320  }
2321  }
2322 
2323  /*
2324  * Set up a tuple table slot for use for trigger output tuples. In a plan
2325  * containing multiple ModifyTable nodes, all can share one such slot, so
2326  * we keep it in the estate.
2327  */
2328  if (estate->es_trig_tuple_slot == NULL)
2329  estate->es_trig_tuple_slot = ExecInitExtraTupleSlot(estate);
2330 
2331  /*
2332  * Lastly, if this is not the primary (canSetTag) ModifyTable node, add it
2333  * to estate->es_auxmodifytables so that it will be run to completion by
2334  * ExecPostprocessPlan. (It'd actually work fine to add the primary
2335  * ModifyTable node too, but there's no need.) Note the use of lcons not
2336  * lappend: we need later-initialized ModifyTable nodes to be shut down
2337  * before earlier ones. This ensures that we don't throw away RETURNING
2338  * rows that need to be seen by a later CTE subplan.
2339  */
2340  if (!mtstate->canSetTag)
2341  estate->es_auxmodifytables = lcons(mtstate,
2342  estate->es_auxmodifytables);
2343 
2344  return mtstate;
2345 }
2346 
2347 /* ----------------------------------------------------------------
2348  * ExecEndModifyTable
2349  *
2350  * Shuts down the plan.
2351  *
2352  * Returns nothing of interest.
2353  * ----------------------------------------------------------------
2354  */
2355 void
2357 {
2358  int i;
2359 
2360  /*
2361  * Allow any FDWs to shut down
2362  */
2363  for (i = 0; i < node->mt_nplans; i++)
2364  {
2365  ResultRelInfo *resultRelInfo = node->resultRelInfo + i;
2366 
2367  if (!resultRelInfo->ri_usesFdwDirectModify &&
2368  resultRelInfo->ri_FdwRoutine != NULL &&
2369  resultRelInfo->ri_FdwRoutine->EndForeignModify != NULL)
2370  resultRelInfo->ri_FdwRoutine->EndForeignModify(node->ps.state,
2371  resultRelInfo);
2372  }
2373 
2374  /*
2375  * Close all the partitioned tables, leaf partitions, and their indices
2376  *
2377  * Remember node->mt_partition_dispatch_info[0] corresponds to the root
2378  * partitioned table, which we must not try to close, because it is the
2379  * main target table of the query that will be closed by ExecEndPlan().
2380  * Also, tupslot is NULL for the root partitioned table.
2381  */
2382  for (i = 1; i < node->mt_num_dispatch; i++)
2383  {
2385 
2386  heap_close(pd->reldesc, NoLock);
2388  }
2389  for (i = 0; i < node->mt_num_partitions; i++)
2390  {
2391  ResultRelInfo *resultRelInfo = node->mt_partitions[i];
2392 
2393  ExecCloseIndices(resultRelInfo);
2394  heap_close(resultRelInfo->ri_RelationDesc, NoLock);
2395  }
2396 
2397  /* Release the standalone partition tuple descriptor, if any */
2398  if (node->mt_partition_tuple_slot)
2400 
2401  /*
2402  * Free the exprcontext
2403  */
2404  ExecFreeExprContext(&node->ps);
2405 
2406  /*
2407  * clean out the tuple table
2408  */
2410 
2411  /*
2412  * Terminate EPQ execution if active
2413  */
2414  EvalPlanQualEnd(&node->mt_epqstate);
2415 
2416  /*
2417  * shut down subplans
2418  */
2419  for (i = 0; i < node->mt_nplans; i++)
2420  ExecEndNode(node->mt_plans[i]);
2421 }
2422 
2423 void
2425 {
2426  /*
2427  * Currently, we don't need to support rescan on ModifyTable nodes. The
2428  * semantics of that would be a bit debatable anyway.
2429  */
2430  elog(ERROR, "ExecReScanModifyTable is not implemented");
2431 }
AttrNumber jf_junkAttNo
Definition: execnodes.h:336
ExecForeignDelete_function ExecForeignDelete
Definition: fdwapi.h:205
int ri_NumIndices
Definition: execnodes.h:357
#define NIL
Definition: pg_list.h:69
TupleTableSlot * ExecStoreTuple(HeapTuple tuple, TupleTableSlot *slot, Buffer buffer, bool shouldFree)
Definition: execTuples.c:320
static ResultRelInfo * getASTriggerResultRelInfo(ModifyTableState *node)
#define BUFFER_LOCK_UNLOCK
Definition: bufmgr.h:87
JunkFilter * ri_junkFilter
Definition: execnodes.h:396
HeapTuple * es_epqTuple
Definition: execnodes.h:506
List * arbiterIndexes
Definition: plannodes.h:233
struct TransitionCaptureState * mt_oc_transition_capture
Definition: execnodes.h:988
Relation ri_RelationDesc
Definition: execnodes.h:354
bool tts_isempty
Definition: tuptable.h:116
bool ExecIRDeleteTriggers(EState *estate, ResultRelInfo *relinfo, HeapTuple trigtuple)
Definition: trigger.c:2604
#define IsA(nodeptr, _type_)
Definition: nodes.h:561
Bitmapset * fdwDirectModifyPlans
Definition: plannodes.h:229
void SpeculativeInsertionLockRelease(TransactionId xid)
Definition: lmgr.c:669
ExprState * ri_onConflictSetWhere
Definition: execnodes.h:405
TupleTableSlot * ExecInitExtraTupleSlot(EState *estate)
Definition: execTuples.c:852
static bool ExecOnConflictUpdate(ModifyTableState *mtstate, ResultRelInfo *resultRelInfo, ItemPointer conflictTid, TupleTableSlot *planSlot, TupleTableSlot *excludedSlot, EState *estate, bool canSetTag, TupleTableSlot **returning)
int errhint(const char *fmt,...)
Definition: elog.c:987
void ExecWithCheckOptions(WCOKind kind, ResultRelInfo *resultRelInfo, TupleTableSlot *slot, EState *estate)
Definition: execMain.c:2072
Index nominalRelation
Definition: plannodes.h:219
void ExecBSDeleteTriggers(EState *estate, ResultRelInfo *relinfo)
Definition: trigger.c:2435
void heap_abort_speculative(Relation relation, HeapTuple tuple)
Definition: heapam.c:6149
bool tdhasoid
Definition: tupdesc.h:76
CommandId es_output_cid
Definition: execnodes.h:438
ProjectionInfo * ri_onConflictSetProj
Definition: execnodes.h:402
static void test(void)
void ExecReScanModifyTable(ModifyTableState *node)
List * ExecInsertIndexTuples(TupleTableSlot *slot, ItemPointer tupleid, EState *estate, bool noDupErr, bool *specConflict, List *arbiterIndexes)
Definition: execIndexing.c:271
#define ResetPerTupleExprContext(estate)
Definition: executor.h:486
TupleTableSlot * ExecStoreAllNullTuple(TupleTableSlot *slot)
Definition: execTuples.c:512
#define RelationGetDescr(relation)
Definition: rel.h:428
bool TransactionIdIsCurrentTransactionId(TransactionId xid)
Definition: xact.c:766
Oid es_lastoid
Definition: execnodes.h:478
List * withCheckOptionLists
Definition: plannodes.h:226
HTSU_Result heap_lock_tuple(Relation relation, HeapTuple tuple, CommandId cid, LockTupleMode mode, LockWaitPolicy wait_policy, bool follow_updates, Buffer *buffer, HeapUpdateFailureData *hufd)
Definition: heapam.c:4603
#define castNode(_type_, nodeptr)
Definition: nodes.h:579
void ExecEndNode(PlanState *node)
Definition: execProcnode.c:523
int resultRelIndex
Definition: plannodes.h:223
ResultRelInfo * resultRelInfo
Definition: execnodes.h:965
static TupleTableSlot * ExecUpdate(ModifyTableState *mtstate, ItemPointer tupleid, HeapTuple oldtuple, TupleTableSlot *slot, TupleTableSlot *planSlot, EPQState *epqstate, EState *estate, bool canSetTag)
bool heap_fetch(Relation relation, Snapshot snapshot, HeapTuple tuple, Buffer *userbuf, bool keep_buf, Relation stats_relation)
Definition: heapam.c:1876
AttrNumber ExecFindJunkAttribute(JunkFilter *junkfilter, const char *attrName)
Definition: execJunk.c:209
#define TupleDescAttr(tupdesc, i)
Definition: tupdesc.h:84
ExecForeignInsert_function ExecForeignInsert
Definition: fdwapi.h:203
ExprContext * ps_ExprContext
Definition: execnodes.h:881
TupleTableSlot * EvalPlanQual(EState *estate, EPQState *epqstate, Relation relation, Index rti, int lockmode, ItemPointer tid, TransactionId priorXmax)
Definition: execMain.c:2477
static void fireBSTriggers(ModifyTableState *node)
TupleTableSlot * ExecBRUpdateTriggers(EState *estate, EPQState *epqstate, ResultRelInfo *relinfo, ItemPointer tupleid, HeapTuple fdw_trigtuple, TupleTableSlot *slot)
Definition: trigger.c:2724
TupleTableSlot * ExecIRInsertTriggers(EState *estate, ResultRelInfo *relinfo, TupleTableSlot *slot)
Definition: trigger.c:2369
TupleTableSlot * mt_conflproj
Definition: execnodes.h:976
TupleTableSlot * ExecClearTuple(TupleTableSlot *slot)
Definition: execTuples.c:439
#define RELKIND_MATVIEW
Definition: pg_class.h:165
void ExecConstraints(ResultRelInfo *resultRelInfo, TupleTableSlot *slot, EState *estate)
Definition: execMain.c:1940
#define IsolationUsesXactSnapshot()
Definition: xact.h:43
#define HeapTupleHeaderSetSpeculativeToken(tup, token)
Definition: htup_details.h:434
#define InvalidBuffer
Definition: buf.h:25
#define gettext_noop(x)
Definition: c.h:139
Definition: nodes.h:510
Snapshot es_crosscheck_snapshot
Definition: execnodes.h:430
int errcode(int sqlerrcode)
Definition: elog.c:575
uint32 SpeculativeInsertionLockAcquire(TransactionId xid)
Definition: lmgr.c:643
bool canSetTag
Definition: plannodes.h:218
char * format_type_be(Oid type_oid)
Definition: format_type.c:94
CmdType operation
Definition: execnodes.h:959
Snapshot es_snapshot
Definition: execnodes.h:429
ResultRelInfo * rootResultRelInfo
Definition: execnodes.h:966
void ExecARInsertTriggers(EState *estate, ResultRelInfo *relinfo, HeapTuple trigtuple, List *recheckIndexes, TransitionCaptureState *transition_capture)
Definition: trigger.c:2354
void ReleaseBuffer(Buffer buffer)
Definition: bufmgr.c:3309
void EvalPlanQualSetPlan(EPQState *epqstate, Plan *subplan, List *auxrowmarks)
Definition: execMain.c:2810
#define heap_close(r, l)
Definition: heapam.h:97
EState * state
Definition: execnodes.h:849
List * es_range_table
Definition: execnodes.h:431
Form_pg_class rd_rel
Definition: rel.h:114
unsigned int Oid
Definition: postgres_ext.h:31
static bool ExecQual(ExprState *state, ExprContext *econtext)
Definition: executor.h:366
#define DatumGetHeapTupleHeader(X)
Definition: fmgr.h:259
bool ExecCheckIndexConstraints(TupleTableSlot *slot, EState *estate, ItemPointer conflictTid, List *arbiterIndexes)
Definition: execIndexing.c:475
int natts
Definition: tupdesc.h:73
void ExecFreeExprContext(PlanState *planstate)
Definition: execUtils.c:521
List * plans
Definition: plannodes.h:225
void ExecAssignResultType(PlanState *planstate, TupleDesc tupDesc)
Definition: execUtils.c:433
HeapTuple tcs_original_insert_tuple
Definition: trigger.h:82
#define HEAP_INSERT_SPECULATIVE
Definition: heapam.h:31
ExprState * ExecInitQual(List *qual, PlanState *parent)
Definition: execExpr.c:160
List * map_partition_varattnos(List *expr, int target_varno, Relation partrel, Relation parent, bool *found_whole_row)
Definition: partition.c:1207
Index ri_RangeTableIndex
Definition: execnodes.h:351
void ExecASDeleteTriggers(EState *estate, ResultRelInfo *relinfo, TransitionCaptureState *transition_capture)
Definition: trigger.c:2492
#define HeapTupleSatisfiesVisibility(tuple, snapshot, buffer)
Definition: tqual.h:45
List * onConflictSet
Definition: plannodes.h:234
int rootResultRelIndex
Definition: plannodes.h:224
TupleTableSlot * ExecIRUpdateTriggers(EState *estate, ResultRelInfo *relinfo, HeapTuple trigtuple, TupleTableSlot *slot)
Definition: trigger.c:2878
void ExecOpenIndices(ResultRelInfo *resultRelInfo, bool speculative)
Definition: execIndexing.c:149
TupleTableSlot * mt_existing
Definition: execnodes.h:974
void EvalPlanQualEnd(EPQState *epqstate)
Definition: execMain.c:3202
ItemPointerData * ItemPointer
Definition: itemptr.h:49
HeapTupleHeader t_data
Definition: htup.h:67
List * ri_WithCheckOptionExprs
Definition: execnodes.h:390
#define HeapTupleSetOid(tuple, oid)
Definition: htup_details.h:698
#define linitial_int(l)
Definition: pg_list.h:112
void ExecARDeleteTriggers(EState *estate, ResultRelInfo *relinfo, ItemPointer tupleid, HeapTuple fdw_trigtuple, TransitionCaptureState *transition_capture)
Definition: trigger.c:2572
LockTupleMode
Definition: heapam.h:38
bool trig_insert_instead_row
Definition: reltrigger.h:57
OnConflictAction mt_onconflict
Definition: execnodes.h:971
TupleTableSlot * ps_ResultTupleSlot
Definition: execnodes.h:880
List * rowMarks
Definition: plannodes.h:230
bool resjunk
Definition: primnodes.h:1375
#define linitial(l)
Definition: pg_list.h:111
HTSU_Result heap_delete(Relation relation, ItemPointer tid, CommandId cid, Snapshot crosscheck, bool wait, HeapUpdateFailureData *hufd)
Definition: heapam.c:3073
#define ERROR
Definition: elog.h:43
PlanState ps
Definition: execnodes.h:958
static void ExecCheckTIDVisible(EState *estate, ResultRelInfo *relinfo, ItemPointer tid)
void ExecInitResultTupleSlot(EState *estate, PlanState *planstate)
Definition: execTuples.c:832
TupleConversionMap * tcs_map
Definition: trigger.h:73
ItemPointerData t_self
Definition: htup.h:65
bool ri_usesFdwDirectModify
Definition: execnodes.h:384
static void ExecSetupTransitionCaptureState(ModifyTableState *mtstate, EState *estate)
void CheckValidResultRel(ResultRelInfo *resultRelInfo, CmdType operation)
Definition: execMain.c:1100
#define EXEC_FLAG_BACKWARD
Definition: executor.h:60
#define lfirst_node(type, lc)
Definition: pg_list.h:109
TransactionId GetCurrentTransactionId(void)
Definition: xact.c:418
static void ExecCheckHeapTupleVisible(EState *estate, HeapTuple tuple, Buffer buffer)
uint32 t_len
Definition: htup.h:64
void ExecBSInsertTriggers(EState *estate, ResultRelInfo *relinfo)
Definition: trigger.c:2220
void * list_nth(const List *list, int n)
Definition: list.c:410
struct TransitionCaptureState * mt_transition_capture
Definition: execnodes.h:986
#define NoLock
Definition: lockdefs.h:34
void ExecDropSingleTupleTableSlot(TupleTableSlot *slot)
Definition: execTuples.c:216
ResultRelInfo * es_result_relations
Definition: execnodes.h:441
JunkFilter * ExecInitJunkFilter(List *targetList, bool hasoid, TupleTableSlot *slot)
Definition: execJunk.c:61
List * fdwPrivLists
Definition: plannodes.h:228
int errdetail(const char *fmt,...)
Definition: elog.c:873
EPQState mt_epqstate
Definition: execnodes.h:969
CommandId cmax
Definition: heapam.h:72
TupleTableSlot * ecxt_innertuple
Definition: execnodes.h:198
bool trig_update_before_row
Definition: reltrigger.h:60
HTSU_Result
Definition: snapshot.h:121
ResultRelInfo ** mt_partitions
Definition: execnodes.h:982
ProjectionInfo * ri_projectReturning
Definition: execnodes.h:399
#define TupIsNull(slot)
Definition: tuptable.h:138
FormData_pg_attribute * Form_pg_attribute
Definition: pg_attribute.h:187
struct FdwRoutine * ri_FdwRoutine
Definition: execnodes.h:378
unsigned int uint32
Definition: c.h:258
ModifyTableState * ExecInitModifyTable(ModifyTable *node, EState *estate, int eflags)
Oid t_tableOid
Definition: htup.h:66
#define RELKIND_FOREIGN_TABLE
Definition: pg_class.h:167
void setLastTid(const ItemPointer tid)
Definition: tid.c:252
List * partitioned_rels
Definition: plannodes.h:221
TupleTableSlot * es_trig_tuple_slot
Definition: execnodes.h:460
EndForeignModify_function EndForeignModify
Definition: fdwapi.h:206
#define InstrCountFiltered1(node, delta)
Definition: execnodes.h:896
#define ereport(elevel, rest)
Definition: elog.h:122
Oid heap_insert(Relation relation, HeapTuple tup, CommandId cid, int options, BulkInsertState bistate)
Definition: heapam.c:2456
TriggerDesc * ri_TrigDesc
Definition: execnodes.h:366
void ExecARUpdateTriggers(EState *estate, ResultRelInfo *relinfo, ItemPointer tupleid, HeapTuple fdw_trigtuple, HeapTuple newtuple, List *recheckIndexes, TransitionCaptureState *transition_capture)
Definition: trigger.c:2841
TupleDesc ExecTypeFromTL(List *targetList, bool hasoid)
Definition: execTuples.c:888
TupleConversionMap * convert_tuples_by_name(TupleDesc indesc, TupleDesc outdesc, const char *msg)
Definition: tupconvert.c:210
List * lappend(List *list, void *datum)
Definition: list.c:128
bool trig_update_instead_row
Definition: reltrigger.h:62
static TupleTableSlot * ExecProcessReturning(ResultRelInfo *resultRelInfo, TupleTableSlot *tupleSlot, TupleTableSlot *planSlot)
PlanState ** mt_plans
Definition: execnodes.h:962
TransactionId xmax
Definition: heapam.h:71
#define AttributeNumberIsValid(attributeNumber)
Definition: attnum.h:34
TupleDesc tts_tupleDescriptor
Definition: tuptable.h:121
static void fireASTriggers(ModifyTableState *node)
static TupleTableSlot * ExecModifyTable(PlanState *pstate)
#define RELKIND_PARTITIONED_TABLE
Definition: pg_class.h:168
bool trig_insert_before_row
Definition: reltrigger.h:55
bool trig_delete_instead_row
Definition: reltrigger.h:67
void ExecASUpdateTriggers(EState *estate, ResultRelInfo *relinfo, TransitionCaptureState *transition_capture)
Definition: trigger.c:2711
void * palloc0(Size size)
Definition: mcxt.c:877
List * es_auxmodifytables
Definition: execnodes.h:488
ExecProcNodeMtd ExecProcNode
Definition: execnodes.h:853
void ExecASInsertTriggers(EState *estate, ResultRelInfo *relinfo, TransitionCaptureState *transition_capture)
Definition: trigger.c:2277
static TupleTableSlot * ExecDelete(ModifyTableState *mtstate, ItemPointer tupleid, HeapTuple oldtuple, TupleTableSlot *planSlot, EPQState *epqstate, EState *estate, bool canSetTag)
uintptr_t Datum
Definition: postgres.h:372
TupleTableSlot * ExecFilterJunk(JunkFilter *junkfilter, TupleTableSlot *slot)
Definition: execJunk.c:262
TupleTableSlot * tupslot
Definition: partition.h:66
void ExecSetSlotDescriptor(TupleTableSlot *slot, TupleDesc tupdesc)
Definition: execTuples.c:247
#define SnapshotAny
Definition: tqual.h:28
static TupleTableSlot * ExecProcNode(PlanState *node)
Definition: executor.h:246
List * ri_WithCheckOptions
Definition: execnodes.h:387
int ExecFindPartition(ResultRelInfo *resultRelInfo, PartitionDispatch *pd, TupleTableSlot *slot, EState *estate)
Definition: execMain.c:3362
TupleTableSlot * mt_partition_tuple_slot
Definition: execnodes.h:985
void LockBuffer(Buffer buffer, int mode)
Definition: bufmgr.c:3546
TransitionCaptureState * MakeTransitionCaptureState(TriggerDesc *trigdesc, Oid relid, CmdType cmdType)
Definition: trigger.c:4404
Relation heap_open(Oid relationId, LOCKMODE lockmode)
Definition: heapam.c:1290
List * ri_PartitionCheck
Definition: execnodes.h:408
unsigned int Index
Definition: c.h:359
TupleDesc rd_att
Definition: rel.h:115
void EvalPlanQualInit(EPQState *epqstate, EState *estate, Plan *subplan, List *auxrowmarks, int epqParam)
Definition: execMain.c:2791
Plan * plan
Definition: execnodes.h:847
#define InvalidOid
Definition: postgres_ext.h:36
HTSU_Result heap_update(Relation relation, ItemPointer otid, HeapTuple newtup, CommandId cid, Snapshot crosscheck, bool wait, HeapUpdateFailureData *hufd, LockTupleMode *lockmode)
Definition: heapam.c:3524
ExecForeignUpdate_function ExecForeignUpdate
Definition: fdwapi.h:204
List * lcons(void *datum, List *list)
Definition: list.c:259
#define makeNode(_type_)
Definition: nodes.h:558
TupleTableSlot * ecxt_outertuple
Definition: execnodes.h:199
static void ExecCheckPlanOutput(Relation resultRel, List *targetList)
bool ExecBRDeleteTriggers(EState *estate, EPQState *epqstate, ResultRelInfo *relinfo, ItemPointer tupleid, HeapTuple fdw_trigtuple)
Definition: trigger.c:2503
#define HeapTupleIsHeapOnly(tuple)
Definition: htup_details.h:686
#define Assert(condition)
Definition: c.h:681
#define lfirst(lc)
Definition: pg_list.h:106
LockTupleMode ExecUpdateLockMode(EState *estate, ResultRelInfo *relinfo)
Definition: execMain.c:2356
#define EXEC_FLAG_MARK
Definition: executor.h:61
OnConflictAction onConflictAction
Definition: plannodes.h:232
Expr * expr
Definition: primnodes.h:1368
#define InstrCountFiltered2(node, delta)
Definition: execnodes.h:901
WalTimeSample buffer[LAG_TRACKER_BUFFER_SIZE]
Definition: walsender.c:214
void heap_finish_speculative(Relation relation, HeapTuple tuple)
Definition: heapam.c:6058
uint64 es_processed
Definition: execnodes.h:477
#define HeapTupleHeaderGetXmin(tup)
Definition: htup_details.h:307
TupleConstr * constr
Definition: tupdesc.h:78
void ExecAssignExprContext(EState *estate, PlanState *planstate)
Definition: execUtils.c:423
Oid exprType(const Node *expr)
Definition: nodeFuncs.c:42
static int list_length(const List *l)
Definition: pg_list.h:89
TupleTableSlot * ecxt_scantuple
Definition: execnodes.h:197
#define BufferIsValid(bufnum)
Definition: bufmgr.h:114
HeapTuple ExecMaterializeSlot(TupleTableSlot *slot)
Definition: execTuples.c:725
static TupleTableSlot * ExecInsert(ModifyTableState *mtstate, TupleTableSlot *slot, TupleTableSlot *planSlot, List *arbiterIndexes, OnConflictAction onconflict, EState *estate, bool canSetTag)
bool ItemPointerEquals(ItemPointer pointer1, ItemPointer pointer2)
Definition: itemptr.c:29
HeapTuple do_convert_tuple(HeapTuple tuple, TupleConversionMap *map)
Definition: tupconvert.c:354
List * targetlist
Definition: plannodes.h:144
#define DatumGetPointer(X)
Definition: postgres.h:555
TupleConversionMap ** mt_transition_tupconv_maps
Definition: execnodes.h:990
List * mt_arbiterindexes
Definition: execnodes.h:972
#define IsBootstrapProcessingMode()
Definition: miscadmin.h:367
List * mt_excludedtlist
Definition: execnodes.h:975
void ExecBSUpdateTriggers(EState *estate, ResultRelInfo *relinfo)
Definition: trigger.c:2651
#define ItemPointerSetInvalid(pointer)
Definition: itemptr.h:150
ProjectionInfo * ExecBuildProjectionInfo(List *targetList, ExprContext *econtext, TupleTableSlot *slot, PlanState *parent, TupleDesc inputDesc)
Definition: execExpr.c:301
int errmsg(const char *fmt,...)
Definition: elog.c:797
#define getrelid(rangeindex, rangetable)
Definition: parsetree.h:41
CmdType operation
Definition: plannodes.h:217
Datum ExecGetJunkAttribute(TupleTableSlot *slot, AttrNumber attno, bool *isNull)
Definition: execJunk.c:248
#define RELKIND_VIEW
Definition: pg_class.h:164
ResultRelInfo * es_root_result_relations
Definition: execnodes.h:452
void list_free(List *list)
Definition: list.c:1133
int i
struct PartitionDispatchData ** mt_partition_dispatch_info
Definition: execnodes.h:977
void ExecSetupPartitionTupleRouting(Relation rel, Index resultRTindex, EState *estate, PartitionDispatch **pd, ResultRelInfo ***partitions, TupleConversionMap ***tup_conv_maps, TupleTableSlot **partition_tuple_slot, int *num_parted, int *num_partitions)
Definition: execMain.c:3264
#define BUFFER_LOCK_SHARE
Definition: bufmgr.h:88
List * returningLists
Definition: plannodes.h:227
#define CHECK_FOR_INTERRUPTS()
Definition: miscadmin.h:98
bool isParent
Definition: plannodes.h:1020
TupleTableSlot * ExecBRInsertTriggers(EState *estate, ResultRelInfo *relinfo, TupleTableSlot *slot)
Definition: trigger.c:2288
ItemPointerData ctid
Definition: heapam.h:70
TupleConversionMap ** mt_partition_tupconv_maps
Definition: execnodes.h:983
#define elog
Definition: elog.h:219
ExprContext * pi_exprContext
Definition: execnodes.h:298
BeginForeignModify_function BeginForeignModify
Definition: fdwapi.h:202
#define RELKIND_RELATION
Definition: pg_class.h:160
PlanState * ExecInitNode(Plan *node, EState *estate, int eflags)
Definition: execProcnode.c:139
Definition: pg_list.h:45
int Buffer
Definition: buf.h:23
bool bms_is_member(int x, const Bitmapset *a)
Definition: bitmapset.c:420
OnConflictAction
Definition: nodes.h:800
#define EXEC_FLAG_EXPLAIN_ONLY
Definition: executor.h:58
#define RelationGetRelid(relation)
Definition: rel.h:416
CmdType
Definition: nodes.h:650
void ExecCloseIndices(ResultRelInfo *resultRelInfo)
Definition: execIndexing.c:224
void ExecEndModifyTable(ModifyTableState *node)
RelationPtr ri_IndexRelationDescs
Definition: execnodes.h:360
ExecAuxRowMark * ExecBuildAuxRowMark(ExecRowMark *erm, List *targetlist)
Definition: execMain.c:2406
List * exclRelTlist
Definition: plannodes.h:237
static TupleTableSlot * ExecProject(ProjectionInfo *projInfo)
Definition: executor.h:329
#define ResetExprContext(econtext)
Definition: executor.h:471
List ** mt_arowmarks
Definition: execnodes.h:968
#define EvalPlanQualSetSlot(epqstate, slot)
Definition: executor.h:222
int epqParam
Definition: plannodes.h:231
bool trig_delete_before_row
Definition: reltrigger.h:65
Node * onConflictWhere
Definition: plannodes.h:235
ExecRowMark * ExecFindRowMark(EState *estate, Index rti, bool missing_ok)
Definition: execMain.c:2382
#define HeapTupleHeaderGetDatumLength(tup)
Definition: htup_details.h:439
ResultRelInfo * es_result_relation_info
Definition: execnodes.h:443