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