1 /*-------------------------------------------------------------------------
4 * routines to handle ModifyTable nodes.
6 * Portions Copyright (c) 1996-2015, PostgreSQL Global Development Group
7 * Portions Copyright (c) 1994, Regents of the University of California
11 * src/backend/executor/nodeModifyTable.c
13 *-------------------------------------------------------------------------
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
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.
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.
40 #include "access/htup_details.h"
41 #include "access/xact.h"
42 #include "commands/trigger.h"
43 #include "executor/executor.h"
44 #include "executor/nodeModifyTable.h"
45 #include "foreign/fdwapi.h"
46 #include "miscadmin.h"
47 #include "nodes/nodeFuncs.h"
48 #include "storage/bufmgr.h"
49 #include "utils/builtins.h"
50 #include "utils/memutils.h"
51 #include "utils/rel.h"
52 #include "utils/tqual.h"
56 * Verify that the tuples to be produced by INSERT or UPDATE match the
57 * target relation's rowtype
59 * We do this to guard against stale plans. If plan invalidation is
60 * functioning properly then we should never get a failure here, but better
61 * safe than sorry. Note that this is called after we have obtained lock
62 * on the target rel, so the rowtype can't change underneath us.
64 * The plan output is represented by its targetlist, because that makes
65 * handling the dropped-column case easier.
68 ExecCheckPlanOutput(Relation resultRel, List *targetList)
70 TupleDesc resultDesc = RelationGetDescr(resultRel);
74 foreach(lc, targetList)
76 TargetEntry *tle = (TargetEntry *) lfirst(lc);
77 Form_pg_attribute attr;
80 continue; /* ignore junk tlist items */
82 if (attno >= resultDesc->natts)
84 (errcode(ERRCODE_DATATYPE_MISMATCH),
85 errmsg("table row type and query-specified row type do not match"),
86 errdetail("Query has too many columns.")));
87 attr = resultDesc->attrs[attno++];
89 if (!attr->attisdropped)
91 /* Normal case: demand type match */
92 if (exprType((Node *) tle->expr) != attr->atttypid)
94 (errcode(ERRCODE_DATATYPE_MISMATCH),
95 errmsg("table row type and query-specified row type do not match"),
96 errdetail("Table has type %s at ordinal position %d, but query expects %s.",
97 format_type_be(attr->atttypid),
99 format_type_be(exprType((Node *) tle->expr)))));
104 * For a dropped column, we can't check atttypid (it's likely 0).
105 * In any case the planner has most likely inserted an INT4 null.
106 * What we insist on is just *some* NULL constant.
108 if (!IsA(tle->expr, Const) ||
109 !((Const *) tle->expr)->constisnull)
111 (errcode(ERRCODE_DATATYPE_MISMATCH),
112 errmsg("table row type and query-specified row type do not match"),
113 errdetail("Query provides a value for a dropped column at ordinal position %d.",
117 if (attno != resultDesc->natts)
119 (errcode(ERRCODE_DATATYPE_MISMATCH),
120 errmsg("table row type and query-specified row type do not match"),
121 errdetail("Query has too few columns.")));
125 * ExecProcessReturning --- evaluate a RETURNING list
127 * projectReturning: RETURNING projection info for current result rel
128 * tupleSlot: slot holding tuple actually inserted/updated/deleted
129 * planSlot: slot holding tuple returned by top subplan node
131 * Returns a slot holding the result tuple
133 static TupleTableSlot *
134 ExecProcessReturning(ProjectionInfo *projectReturning,
135 TupleTableSlot *tupleSlot,
136 TupleTableSlot *planSlot)
138 ExprContext *econtext = projectReturning->pi_exprContext;
141 * Reset per-tuple memory context to free any expression evaluation
142 * storage allocated in the previous cycle.
144 ResetExprContext(econtext);
146 /* Make tuple and any needed join variables available to ExecProject */
147 econtext->ecxt_scantuple = tupleSlot;
148 econtext->ecxt_outertuple = planSlot;
150 /* Compute the RETURNING expressions */
151 return ExecProject(projectReturning, NULL);
154 /* ----------------------------------------------------------------
157 * For INSERT, we have to insert the tuple into the target relation
158 * and insert appropriate tuples into the index relations.
160 * Returns RETURNING result if any, otherwise NULL.
161 * ----------------------------------------------------------------
163 static TupleTableSlot *
164 ExecInsert(TupleTableSlot *slot,
165 TupleTableSlot *planSlot,
170 ResultRelInfo *resultRelInfo;
171 Relation resultRelationDesc;
173 List *recheckIndexes = NIL;
176 * get the heap tuple out of the tuple table slot, making sure we have a
179 tuple = ExecMaterializeSlot(slot);
182 * get information on the (current) result relation
184 resultRelInfo = estate->es_result_relation_info;
185 resultRelationDesc = resultRelInfo->ri_RelationDesc;
188 * If the result relation has OIDs, force the tuple's OID to zero so that
189 * heap_insert will assign a fresh OID. Usually the OID already will be
190 * zero at this point, but there are corner cases where the plan tree can
191 * return a tuple extracted literally from some table with the same
194 * XXX if we ever wanted to allow users to assign their own OIDs to new
195 * rows, this'd be the place to do it. For the moment, we make a point of
196 * doing this before calling triggers, so that a user-supplied trigger
197 * could hack the OID if desired.
199 if (resultRelationDesc->rd_rel->relhasoids)
200 HeapTupleSetOid(tuple, InvalidOid);
202 /* BEFORE ROW INSERT Triggers */
203 if (resultRelInfo->ri_TrigDesc &&
204 resultRelInfo->ri_TrigDesc->trig_insert_before_row)
206 slot = ExecBRInsertTriggers(estate, resultRelInfo, slot);
208 if (slot == NULL) /* "do nothing" */
211 /* trigger might have changed tuple */
212 tuple = ExecMaterializeSlot(slot);
215 /* INSTEAD OF ROW INSERT Triggers */
216 if (resultRelInfo->ri_TrigDesc &&
217 resultRelInfo->ri_TrigDesc->trig_insert_instead_row)
219 slot = ExecIRInsertTriggers(estate, resultRelInfo, slot);
221 if (slot == NULL) /* "do nothing" */
224 /* trigger might have changed tuple */
225 tuple = ExecMaterializeSlot(slot);
229 else if (resultRelInfo->ri_FdwRoutine)
232 * insert into foreign table: let the FDW do it
234 slot = resultRelInfo->ri_FdwRoutine->ExecForeignInsert(estate,
239 if (slot == NULL) /* "do nothing" */
242 /* FDW might have changed tuple */
243 tuple = ExecMaterializeSlot(slot);
250 * Constraints might reference the tableoid column, so initialize
251 * t_tableOid before evaluating them.
253 tuple->t_tableOid = RelationGetRelid(resultRelationDesc);
256 * Check the constraints of the tuple
258 if (resultRelationDesc->rd_att->constr)
259 ExecConstraints(resultRelInfo, slot, estate);
264 * Note: heap_insert returns the tid (location) of the new tuple in
267 newId = heap_insert(resultRelationDesc, tuple,
268 estate->es_output_cid, 0, NULL);
271 * insert index entries for tuple
273 if (resultRelInfo->ri_NumIndices > 0)
274 recheckIndexes = ExecInsertIndexTuples(slot, &(tuple->t_self),
280 (estate->es_processed)++;
281 estate->es_lastoid = newId;
282 setLastTid(&(tuple->t_self));
285 /* AFTER ROW INSERT Triggers */
286 ExecARInsertTriggers(estate, resultRelInfo, tuple, recheckIndexes);
288 list_free(recheckIndexes);
290 /* Check any WITH CHECK OPTION constraints */
291 if (resultRelInfo->ri_WithCheckOptions != NIL)
292 ExecWithCheckOptions(resultRelInfo, slot, estate);
294 /* Process RETURNING if present */
295 if (resultRelInfo->ri_projectReturning)
296 return ExecProcessReturning(resultRelInfo->ri_projectReturning,
302 /* ----------------------------------------------------------------
305 * DELETE is like UPDATE, except that we delete the tuple and no
306 * index modifications are needed.
308 * When deleting from a table, tupleid identifies the tuple to
309 * delete and oldtuple is NULL. When deleting from a view,
310 * oldtuple is passed to the INSTEAD OF triggers and identifies
311 * what to delete, and tupleid is invalid. When deleting from a
312 * foreign table, tupleid is invalid; the FDW has to figure out
313 * which row to delete using data from the planSlot. oldtuple is
314 * passed to foreign table triggers; it is NULL when the foreign
315 * table has no relevant triggers.
317 * Returns RETURNING result if any, otherwise NULL.
318 * ----------------------------------------------------------------
320 static TupleTableSlot *
321 ExecDelete(ItemPointer tupleid,
323 TupleTableSlot *planSlot,
328 ResultRelInfo *resultRelInfo;
329 Relation resultRelationDesc;
331 HeapUpdateFailureData hufd;
332 TupleTableSlot *slot = NULL;
335 * get information on the (current) result relation
337 resultRelInfo = estate->es_result_relation_info;
338 resultRelationDesc = resultRelInfo->ri_RelationDesc;
340 /* BEFORE ROW DELETE Triggers */
341 if (resultRelInfo->ri_TrigDesc &&
342 resultRelInfo->ri_TrigDesc->trig_delete_before_row)
346 dodelete = ExecBRDeleteTriggers(estate, epqstate, resultRelInfo,
349 if (!dodelete) /* "do nothing" */
353 /* INSTEAD OF ROW DELETE Triggers */
354 if (resultRelInfo->ri_TrigDesc &&
355 resultRelInfo->ri_TrigDesc->trig_delete_instead_row)
359 Assert(oldtuple != NULL);
360 dodelete = ExecIRDeleteTriggers(estate, resultRelInfo, oldtuple);
362 if (!dodelete) /* "do nothing" */
365 else if (resultRelInfo->ri_FdwRoutine)
368 * delete from foreign table: let the FDW do it
370 * We offer the trigger tuple slot as a place to store RETURNING data,
371 * although the FDW can return some other slot if it wants. Set up
372 * the slot's tupdesc so the FDW doesn't need to do that for itself.
374 slot = estate->es_trig_tuple_slot;
375 if (slot->tts_tupleDescriptor != RelationGetDescr(resultRelationDesc))
376 ExecSetSlotDescriptor(slot, RelationGetDescr(resultRelationDesc));
378 slot = resultRelInfo->ri_FdwRoutine->ExecForeignDelete(estate,
383 if (slot == NULL) /* "do nothing" */
391 * Note: if es_crosscheck_snapshot isn't InvalidSnapshot, we check
392 * that the row to be deleted is visible to that snapshot, and throw a
393 * can't-serialize error if not. This is a special-case behavior
394 * needed for referential integrity updates in transaction-snapshot
398 result = heap_delete(resultRelationDesc, tupleid,
399 estate->es_output_cid,
400 estate->es_crosscheck_snapshot,
401 true /* wait for commit */ ,
405 case HeapTupleSelfUpdated:
408 * The target tuple was already updated or deleted by the
409 * current command, or by a later command in the current
410 * transaction. The former case is possible in a join DELETE
411 * where multiple tuples join to the same target tuple. This
412 * is somewhat questionable, but Postgres has always allowed
413 * it: we just ignore additional deletion attempts.
415 * The latter case arises if the tuple is modified by a
416 * command in a BEFORE trigger, or perhaps by a command in a
417 * volatile function used in the query. In such situations we
418 * should not ignore the deletion, but it is equally unsafe to
419 * proceed. We don't want to discard the original DELETE
420 * while keeping the triggered actions based on its deletion;
421 * and it would be no better to allow the original DELETE
422 * while discarding updates that it triggered. The row update
423 * carries some information that might be important according
424 * to business rules; so throwing an error is the only safe
427 * If a trigger actually intends this type of interaction, it
428 * can re-execute the DELETE and then return NULL to cancel
431 if (hufd.cmax != estate->es_output_cid)
433 (errcode(ERRCODE_TRIGGERED_DATA_CHANGE_VIOLATION),
434 errmsg("tuple to be updated was already modified by an operation triggered by the current command"),
435 errhint("Consider using an AFTER trigger instead of a BEFORE trigger to propagate changes to other rows.")));
437 /* Else, already deleted by self; nothing to do */
440 case HeapTupleMayBeUpdated:
443 case HeapTupleUpdated:
444 if (IsolationUsesXactSnapshot())
446 (errcode(ERRCODE_T_R_SERIALIZATION_FAILURE),
447 errmsg("could not serialize access due to concurrent update")));
448 if (!ItemPointerEquals(tupleid, &hufd.ctid))
450 TupleTableSlot *epqslot;
452 epqslot = EvalPlanQual(estate,
455 resultRelInfo->ri_RangeTableIndex,
459 if (!TupIsNull(epqslot))
461 *tupleid = hufd.ctid;
465 /* tuple already deleted; nothing to do */
469 elog(ERROR, "unrecognized heap_delete status: %u", result);
474 * Note: Normally one would think that we have to delete index tuples
475 * associated with the heap tuple now...
477 * ... but in POSTGRES, we have no need to do this because VACUUM will
478 * take care of it later. We can't delete index tuples immediately
479 * anyway, since the tuple is still visible to other transactions.
484 (estate->es_processed)++;
486 /* AFTER ROW DELETE Triggers */
487 ExecARDeleteTriggers(estate, resultRelInfo, tupleid, oldtuple);
489 /* Process RETURNING if present */
490 if (resultRelInfo->ri_projectReturning)
493 * We have to put the target tuple into a slot, which means first we
494 * gotta fetch it. We can use the trigger tuple slot.
496 TupleTableSlot *rslot;
497 HeapTupleData deltuple;
500 if (resultRelInfo->ri_FdwRoutine)
502 /* FDW must have provided a slot containing the deleted row */
503 Assert(!TupIsNull(slot));
504 delbuffer = InvalidBuffer;
508 slot = estate->es_trig_tuple_slot;
509 if (oldtuple != NULL)
511 deltuple = *oldtuple;
512 delbuffer = InvalidBuffer;
516 deltuple.t_self = *tupleid;
517 if (!heap_fetch(resultRelationDesc, SnapshotAny,
518 &deltuple, &delbuffer, false, NULL))
519 elog(ERROR, "failed to fetch deleted tuple for DELETE RETURNING");
522 if (slot->tts_tupleDescriptor != RelationGetDescr(resultRelationDesc))
523 ExecSetSlotDescriptor(slot, RelationGetDescr(resultRelationDesc));
524 ExecStoreTuple(&deltuple, slot, InvalidBuffer, false);
527 rslot = ExecProcessReturning(resultRelInfo->ri_projectReturning,
531 * Before releasing the target tuple again, make sure rslot has a
532 * local copy of any pass-by-reference values.
534 ExecMaterializeSlot(rslot);
536 ExecClearTuple(slot);
537 if (BufferIsValid(delbuffer))
538 ReleaseBuffer(delbuffer);
546 /* ----------------------------------------------------------------
549 * note: we can't run UPDATE queries with transactions
550 * off because UPDATEs are actually INSERTs and our
551 * scan will mistakenly loop forever, updating the tuple
552 * it just inserted.. This should be fixed but until it
553 * is, we don't want to get stuck in an infinite loop
554 * which corrupts your database..
556 * When updating a table, tupleid identifies the tuple to
557 * update and oldtuple is NULL. When updating a view, oldtuple
558 * is passed to the INSTEAD OF triggers and identifies what to
559 * update, and tupleid is invalid. When updating a foreign table,
560 * tupleid is invalid; the FDW has to figure out which row to
561 * update using data from the planSlot. oldtuple is passed to
562 * foreign table triggers; it is NULL when the foreign table has
563 * no relevant triggers.
565 * Returns RETURNING result if any, otherwise NULL.
566 * ----------------------------------------------------------------
568 static TupleTableSlot *
569 ExecUpdate(ItemPointer tupleid,
571 TupleTableSlot *slot,
572 TupleTableSlot *planSlot,
578 ResultRelInfo *resultRelInfo;
579 Relation resultRelationDesc;
581 HeapUpdateFailureData hufd;
582 List *recheckIndexes = NIL;
585 * abort the operation if not running transactions
587 if (IsBootstrapProcessingMode())
588 elog(ERROR, "cannot UPDATE during bootstrap");
591 * get the heap tuple out of the tuple table slot, making sure we have a
594 tuple = ExecMaterializeSlot(slot);
597 * get information on the (current) result relation
599 resultRelInfo = estate->es_result_relation_info;
600 resultRelationDesc = resultRelInfo->ri_RelationDesc;
602 /* BEFORE ROW UPDATE Triggers */
603 if (resultRelInfo->ri_TrigDesc &&
604 resultRelInfo->ri_TrigDesc->trig_update_before_row)
606 slot = ExecBRUpdateTriggers(estate, epqstate, resultRelInfo,
607 tupleid, oldtuple, slot);
609 if (slot == NULL) /* "do nothing" */
612 /* trigger might have changed tuple */
613 tuple = ExecMaterializeSlot(slot);
616 /* INSTEAD OF ROW UPDATE Triggers */
617 if (resultRelInfo->ri_TrigDesc &&
618 resultRelInfo->ri_TrigDesc->trig_update_instead_row)
620 slot = ExecIRUpdateTriggers(estate, resultRelInfo,
623 if (slot == NULL) /* "do nothing" */
626 /* trigger might have changed tuple */
627 tuple = ExecMaterializeSlot(slot);
629 else if (resultRelInfo->ri_FdwRoutine)
632 * update in foreign table: let the FDW do it
634 slot = resultRelInfo->ri_FdwRoutine->ExecForeignUpdate(estate,
639 if (slot == NULL) /* "do nothing" */
642 /* FDW might have changed tuple */
643 tuple = ExecMaterializeSlot(slot);
647 LockTupleMode lockmode;
650 * Constraints might reference the tableoid column, so initialize
651 * t_tableOid before evaluating them.
653 tuple->t_tableOid = RelationGetRelid(resultRelationDesc);
656 * Check the constraints of the tuple
658 * If we generate a new candidate tuple after EvalPlanQual testing, we
659 * must loop back here and recheck constraints. (We don't need to
660 * redo triggers, however. If there are any BEFORE triggers then
661 * trigger.c will have done heap_lock_tuple to lock the correct tuple,
662 * so there's no need to do them again.)
665 if (resultRelationDesc->rd_att->constr)
666 ExecConstraints(resultRelInfo, slot, estate);
669 * replace the heap tuple
671 * Note: if es_crosscheck_snapshot isn't InvalidSnapshot, we check
672 * that the row to be updated is visible to that snapshot, and throw a
673 * can't-serialize error if not. This is a special-case behavior
674 * needed for referential integrity updates in transaction-snapshot
677 result = heap_update(resultRelationDesc, tupleid, tuple,
678 estate->es_output_cid,
679 estate->es_crosscheck_snapshot,
680 true /* wait for commit */ ,
684 case HeapTupleSelfUpdated:
687 * The target tuple was already updated or deleted by the
688 * current command, or by a later command in the current
689 * transaction. The former case is possible in a join UPDATE
690 * where multiple tuples join to the same target tuple. This
691 * is pretty questionable, but Postgres has always allowed it:
692 * we just execute the first update action and ignore
693 * additional update attempts.
695 * The latter case arises if the tuple is modified by a
696 * command in a BEFORE trigger, or perhaps by a command in a
697 * volatile function used in the query. In such situations we
698 * should not ignore the update, but it is equally unsafe to
699 * proceed. We don't want to discard the original UPDATE
700 * while keeping the triggered actions based on it; and we
701 * have no principled way to merge this update with the
702 * previous ones. So throwing an error is the only safe
705 * If a trigger actually intends this type of interaction, it
706 * can re-execute the UPDATE (assuming it can figure out how)
707 * and then return NULL to cancel the outer update.
709 if (hufd.cmax != estate->es_output_cid)
711 (errcode(ERRCODE_TRIGGERED_DATA_CHANGE_VIOLATION),
712 errmsg("tuple to be updated was already modified by an operation triggered by the current command"),
713 errhint("Consider using an AFTER trigger instead of a BEFORE trigger to propagate changes to other rows.")));
715 /* Else, already updated by self; nothing to do */
718 case HeapTupleMayBeUpdated:
721 case HeapTupleUpdated:
722 if (IsolationUsesXactSnapshot())
724 (errcode(ERRCODE_T_R_SERIALIZATION_FAILURE),
725 errmsg("could not serialize access due to concurrent update")));
726 if (!ItemPointerEquals(tupleid, &hufd.ctid))
728 TupleTableSlot *epqslot;
730 epqslot = EvalPlanQual(estate,
733 resultRelInfo->ri_RangeTableIndex,
737 if (!TupIsNull(epqslot))
739 *tupleid = hufd.ctid;
740 slot = ExecFilterJunk(resultRelInfo->ri_junkFilter, epqslot);
741 tuple = ExecMaterializeSlot(slot);
745 /* tuple already deleted; nothing to do */
749 elog(ERROR, "unrecognized heap_update status: %u", result);
754 * Note: instead of having to update the old index tuples associated
755 * with the heap tuple, all we do is form and insert new index tuples.
756 * This is because UPDATEs are actually DELETEs and INSERTs, and index
757 * tuple deletion is done later by VACUUM (see notes in ExecDelete).
758 * All we do here is insert new index tuples. -cim 9/27/89
762 * insert index entries for tuple
764 * Note: heap_update returns the tid (location) of the new tuple in
767 * If it's a HOT update, we mustn't insert new index entries.
769 if (resultRelInfo->ri_NumIndices > 0 && !HeapTupleIsHeapOnly(tuple))
770 recheckIndexes = ExecInsertIndexTuples(slot, &(tuple->t_self),
775 (estate->es_processed)++;
777 /* AFTER ROW UPDATE Triggers */
778 ExecARUpdateTriggers(estate, resultRelInfo, tupleid, oldtuple, tuple,
781 list_free(recheckIndexes);
783 /* Check any WITH CHECK OPTION constraints */
784 if (resultRelInfo->ri_WithCheckOptions != NIL)
785 ExecWithCheckOptions(resultRelInfo, slot, estate);
787 /* Process RETURNING if present */
788 if (resultRelInfo->ri_projectReturning)
789 return ExecProcessReturning(resultRelInfo->ri_projectReturning,
797 * Process BEFORE EACH STATEMENT triggers
800 fireBSTriggers(ModifyTableState *node)
802 switch (node->operation)
805 ExecBSInsertTriggers(node->ps.state, node->resultRelInfo);
808 ExecBSUpdateTriggers(node->ps.state, node->resultRelInfo);
811 ExecBSDeleteTriggers(node->ps.state, node->resultRelInfo);
814 elog(ERROR, "unknown operation");
820 * Process AFTER EACH STATEMENT triggers
823 fireASTriggers(ModifyTableState *node)
825 switch (node->operation)
828 ExecASInsertTriggers(node->ps.state, node->resultRelInfo);
831 ExecASUpdateTriggers(node->ps.state, node->resultRelInfo);
834 ExecASDeleteTriggers(node->ps.state, node->resultRelInfo);
837 elog(ERROR, "unknown operation");
843 /* ----------------------------------------------------------------
846 * Perform table modifications as required, and return RETURNING results
848 * ----------------------------------------------------------------
851 ExecModifyTable(ModifyTableState *node)
853 EState *estate = node->ps.state;
854 CmdType operation = node->operation;
855 ResultRelInfo *saved_resultRelInfo;
856 ResultRelInfo *resultRelInfo;
857 PlanState *subplanstate;
858 JunkFilter *junkfilter;
859 TupleTableSlot *slot;
860 TupleTableSlot *planSlot;
861 ItemPointer tupleid = NULL;
862 ItemPointerData tuple_ctid;
863 HeapTupleData oldtupdata;
867 * This should NOT get called during EvalPlanQual; we should have passed a
868 * subplan tree to EvalPlanQual, instead. Use a runtime test not just
869 * Assert because this condition is easy to miss in testing. (Note:
870 * although ModifyTable should not get executed within an EvalPlanQual
871 * operation, we do have to allow it to be initialized and shut down in
872 * case it is within a CTE subplan. Hence this test must be here, not in
873 * ExecInitModifyTable.)
875 if (estate->es_epqTuple != NULL)
876 elog(ERROR, "ModifyTable should not be called during EvalPlanQual");
879 * If we've already completed processing, don't try to do more. We need
880 * this test because ExecPostprocessPlan might call us an extra time, and
881 * our subplan's nodes aren't necessarily robust against being called
888 * On first call, fire BEFORE STATEMENT triggers before proceeding.
890 if (node->fireBSTriggers)
892 fireBSTriggers(node);
893 node->fireBSTriggers = false;
896 /* Preload local variables */
897 resultRelInfo = node->resultRelInfo + node->mt_whichplan;
898 subplanstate = node->mt_plans[node->mt_whichplan];
899 junkfilter = resultRelInfo->ri_junkFilter;
902 * es_result_relation_info must point to the currently active result
903 * relation while we are within this ModifyTable node. Even though
904 * ModifyTable nodes can't be nested statically, they can be nested
905 * dynamically (since our subplan could include a reference to a modifying
906 * CTE). So we have to save and restore the caller's value.
908 saved_resultRelInfo = estate->es_result_relation_info;
910 estate->es_result_relation_info = resultRelInfo;
913 * Fetch rows from subplan(s), and execute the required table modification
919 * Reset the per-output-tuple exprcontext. This is needed because
920 * triggers expect to use that context as workspace. It's a bit ugly
921 * to do this below the top level of the plan, however. We might need
922 * to rethink this later.
924 ResetPerTupleExprContext(estate);
926 planSlot = ExecProcNode(subplanstate);
928 if (TupIsNull(planSlot))
930 /* advance to next subplan if any */
931 node->mt_whichplan++;
932 if (node->mt_whichplan < node->mt_nplans)
935 subplanstate = node->mt_plans[node->mt_whichplan];
936 junkfilter = resultRelInfo->ri_junkFilter;
937 estate->es_result_relation_info = resultRelInfo;
938 EvalPlanQualSetPlan(&node->mt_epqstate, subplanstate->plan,
939 node->mt_arowmarks[node->mt_whichplan]);
946 EvalPlanQualSetSlot(&node->mt_epqstate, planSlot);
950 if (junkfilter != NULL)
953 * extract the 'ctid' or 'wholerow' junk attribute.
955 if (operation == CMD_UPDATE || operation == CMD_DELETE)
961 relkind = resultRelInfo->ri_RelationDesc->rd_rel->relkind;
962 if (relkind == RELKIND_RELATION || relkind == RELKIND_MATVIEW)
964 datum = ExecGetJunkAttribute(slot,
965 junkfilter->jf_junkAttNo,
967 /* shouldn't ever get a null result... */
969 elog(ERROR, "ctid is NULL");
971 tupleid = (ItemPointer) DatumGetPointer(datum);
972 tuple_ctid = *tupleid; /* be sure we don't free
974 tupleid = &tuple_ctid;
978 * Use the wholerow attribute, when available, to reconstruct
979 * the old relation tuple.
981 * Foreign table updates have a wholerow attribute when the
982 * relation has an AFTER ROW trigger. Note that the wholerow
983 * attribute does not carry system columns. Foreign table
984 * triggers miss seeing those, except that we know enough here
985 * to set t_tableOid. Quite separately from this, the FDW may
986 * fetch its own junk attrs to identify the row.
988 * Other relevant relkinds, currently limited to views, always
989 * have a wholerow attribute.
991 else if (AttributeNumberIsValid(junkfilter->jf_junkAttNo))
993 datum = ExecGetJunkAttribute(slot,
994 junkfilter->jf_junkAttNo,
996 /* shouldn't ever get a null result... */
998 elog(ERROR, "wholerow is NULL");
1000 oldtupdata.t_data = DatumGetHeapTupleHeader(datum);
1002 HeapTupleHeaderGetDatumLength(oldtupdata.t_data);
1003 ItemPointerSetInvalid(&(oldtupdata.t_self));
1004 /* Historically, view triggers see invalid t_tableOid. */
1005 oldtupdata.t_tableOid =
1006 (relkind == RELKIND_VIEW) ? InvalidOid :
1007 RelationGetRelid(resultRelInfo->ri_RelationDesc);
1009 oldtuple = &oldtupdata;
1012 Assert(relkind == RELKIND_FOREIGN_TABLE);
1016 * apply the junkfilter if needed.
1018 if (operation != CMD_DELETE)
1019 slot = ExecFilterJunk(junkfilter, slot);
1025 slot = ExecInsert(slot, planSlot, estate, node->canSetTag);
1028 slot = ExecUpdate(tupleid, oldtuple, slot, planSlot,
1029 &node->mt_epqstate, estate, node->canSetTag);
1032 slot = ExecDelete(tupleid, oldtuple, planSlot,
1033 &node->mt_epqstate, estate, node->canSetTag);
1036 elog(ERROR, "unknown operation");
1041 * If we got a RETURNING result, return it to caller. We'll continue
1042 * the work on next call.
1046 estate->es_result_relation_info = saved_resultRelInfo;
1051 /* Restore es_result_relation_info before exiting */
1052 estate->es_result_relation_info = saved_resultRelInfo;
1055 * We're done, but fire AFTER STATEMENT triggers before exiting.
1057 fireASTriggers(node);
1059 node->mt_done = true;
1064 /* ----------------------------------------------------------------
1065 * ExecInitModifyTable
1066 * ----------------------------------------------------------------
1069 ExecInitModifyTable(ModifyTable *node, EState *estate, int eflags)
1071 ModifyTableState *mtstate;
1072 CmdType operation = node->operation;
1073 int nplans = list_length(node->plans);
1074 ResultRelInfo *saved_resultRelInfo;
1075 ResultRelInfo *resultRelInfo;
1081 /* check for unsupported flags */
1082 Assert(!(eflags & (EXEC_FLAG_BACKWARD | EXEC_FLAG_MARK)));
1085 * create state structure
1087 mtstate = makeNode(ModifyTableState);
1088 mtstate->ps.plan = (Plan *) node;
1089 mtstate->ps.state = estate;
1090 mtstate->ps.targetlist = NIL; /* not actually used */
1092 mtstate->operation = operation;
1093 mtstate->canSetTag = node->canSetTag;
1094 mtstate->mt_done = false;
1096 mtstate->mt_plans = (PlanState **) palloc0(sizeof(PlanState *) * nplans);
1097 mtstate->resultRelInfo = estate->es_result_relations + node->resultRelIndex;
1098 mtstate->mt_arowmarks = (List **) palloc0(sizeof(List *) * nplans);
1099 mtstate->mt_nplans = nplans;
1101 /* set up epqstate with dummy subplan data for the moment */
1102 EvalPlanQualInit(&mtstate->mt_epqstate, estate, NULL, NIL, node->epqParam);
1103 mtstate->fireBSTriggers = true;
1106 * call ExecInitNode on each of the plans to be executed and save the
1107 * results into the array "mt_plans". This is also a convenient place to
1108 * verify that the proposed target relations are valid and open their
1109 * indexes for insertion of new index entries. Note we *must* set
1110 * estate->es_result_relation_info correctly while we initialize each
1111 * sub-plan; ExecContextForcesOids depends on that!
1113 saved_resultRelInfo = estate->es_result_relation_info;
1115 resultRelInfo = mtstate->resultRelInfo;
1117 foreach(l, node->plans)
1119 subplan = (Plan *) lfirst(l);
1122 * Verify result relation is a valid target for the current operation
1124 CheckValidResultRel(resultRelInfo->ri_RelationDesc, operation);
1127 * If there are indices on the result relation, open them and save
1128 * descriptors in the result relation info, so that we can add new
1129 * index entries for the tuples we add/update. We need not do this
1130 * for a DELETE, however, since deletion doesn't affect indexes. Also,
1131 * inside an EvalPlanQual operation, the indexes might be open
1132 * already, since we share the resultrel state with the original
1135 if (resultRelInfo->ri_RelationDesc->rd_rel->relhasindex &&
1136 operation != CMD_DELETE &&
1137 resultRelInfo->ri_IndexRelationDescs == NULL)
1138 ExecOpenIndices(resultRelInfo);
1140 /* Now init the plan for this result rel */
1141 estate->es_result_relation_info = resultRelInfo;
1142 mtstate->mt_plans[i] = ExecInitNode(subplan, estate, eflags);
1144 /* Also let FDWs init themselves for foreign-table result rels */
1145 if (resultRelInfo->ri_FdwRoutine != NULL &&
1146 resultRelInfo->ri_FdwRoutine->BeginForeignModify != NULL)
1148 List *fdw_private = (List *) list_nth(node->fdwPrivLists, i);
1150 resultRelInfo->ri_FdwRoutine->BeginForeignModify(mtstate,
1161 estate->es_result_relation_info = saved_resultRelInfo;
1164 * Initialize any WITH CHECK OPTION constraints if needed.
1166 resultRelInfo = mtstate->resultRelInfo;
1168 foreach(l, node->withCheckOptionLists)
1170 List *wcoList = (List *) lfirst(l);
1171 List *wcoExprs = NIL;
1174 foreach(ll, wcoList)
1176 WithCheckOption *wco = (WithCheckOption *) lfirst(ll);
1177 ExprState *wcoExpr = ExecInitExpr((Expr *) wco->qual,
1178 mtstate->mt_plans[i]);
1180 wcoExprs = lappend(wcoExprs, wcoExpr);
1183 resultRelInfo->ri_WithCheckOptions = wcoList;
1184 resultRelInfo->ri_WithCheckOptionExprs = wcoExprs;
1190 * Initialize RETURNING projections if needed.
1192 if (node->returningLists)
1194 TupleTableSlot *slot;
1195 ExprContext *econtext;
1198 * Initialize result tuple slot and assign its rowtype using the first
1199 * RETURNING list. We assume the rest will look the same.
1201 tupDesc = ExecTypeFromTL((List *) linitial(node->returningLists),
1204 /* Set up a slot for the output of the RETURNING projection(s) */
1205 ExecInitResultTupleSlot(estate, &mtstate->ps);
1206 ExecAssignResultType(&mtstate->ps, tupDesc);
1207 slot = mtstate->ps.ps_ResultTupleSlot;
1209 /* Need an econtext too */
1210 econtext = CreateExprContext(estate);
1211 mtstate->ps.ps_ExprContext = econtext;
1214 * Build a projection for each result rel.
1216 resultRelInfo = mtstate->resultRelInfo;
1217 foreach(l, node->returningLists)
1219 List *rlist = (List *) lfirst(l);
1222 rliststate = (List *) ExecInitExpr((Expr *) rlist, &mtstate->ps);
1223 resultRelInfo->ri_projectReturning =
1224 ExecBuildProjectionInfo(rliststate, econtext, slot,
1225 resultRelInfo->ri_RelationDesc->rd_att);
1232 * We still must construct a dummy result tuple type, because InitPlan
1233 * expects one (maybe should change that?).
1235 tupDesc = ExecTypeFromTL(NIL, false);
1236 ExecInitResultTupleSlot(estate, &mtstate->ps);
1237 ExecAssignResultType(&mtstate->ps, tupDesc);
1239 mtstate->ps.ps_ExprContext = NULL;
1243 * If we have any secondary relations in an UPDATE or DELETE, they need to
1244 * be treated like non-locked relations in SELECT FOR UPDATE, ie, the
1245 * EvalPlanQual mechanism needs to be told about them. Locate the
1246 * relevant ExecRowMarks.
1248 foreach(l, node->rowMarks)
1250 PlanRowMark *rc = (PlanRowMark *) lfirst(l);
1253 Assert(IsA(rc, PlanRowMark));
1255 /* ignore "parent" rowmarks; they are irrelevant at runtime */
1259 /* find ExecRowMark (same for all subplans) */
1260 erm = ExecFindRowMark(estate, rc->rti);
1262 /* build ExecAuxRowMark for each subplan */
1263 for (i = 0; i < nplans; i++)
1265 ExecAuxRowMark *aerm;
1267 subplan = mtstate->mt_plans[i]->plan;
1268 aerm = ExecBuildAuxRowMark(erm, subplan->targetlist);
1269 mtstate->mt_arowmarks[i] = lappend(mtstate->mt_arowmarks[i], aerm);
1273 /* select first subplan */
1274 mtstate->mt_whichplan = 0;
1275 subplan = (Plan *) linitial(node->plans);
1276 EvalPlanQualSetPlan(&mtstate->mt_epqstate, subplan,
1277 mtstate->mt_arowmarks[0]);
1280 * Initialize the junk filter(s) if needed. INSERT queries need a filter
1281 * if there are any junk attrs in the tlist. UPDATE and DELETE always
1282 * need a filter, since there's always a junk 'ctid' or 'wholerow'
1283 * attribute present --- no need to look first.
1285 * If there are multiple result relations, each one needs its own junk
1286 * filter. Note multiple rels are only possible for UPDATE/DELETE, so we
1287 * can't be fooled by some needing a filter and some not.
1289 * This section of code is also a convenient place to verify that the
1290 * output of an INSERT or UPDATE matches the target table(s).
1293 bool junk_filter_needed = false;
1298 foreach(l, subplan->targetlist)
1300 TargetEntry *tle = (TargetEntry *) lfirst(l);
1304 junk_filter_needed = true;
1311 junk_filter_needed = true;
1314 elog(ERROR, "unknown operation");
1318 if (junk_filter_needed)
1320 resultRelInfo = mtstate->resultRelInfo;
1321 for (i = 0; i < nplans; i++)
1325 subplan = mtstate->mt_plans[i]->plan;
1326 if (operation == CMD_INSERT || operation == CMD_UPDATE)
1327 ExecCheckPlanOutput(resultRelInfo->ri_RelationDesc,
1328 subplan->targetlist);
1330 j = ExecInitJunkFilter(subplan->targetlist,
1331 resultRelInfo->ri_RelationDesc->rd_att->tdhasoid,
1332 ExecInitExtraTupleSlot(estate));
1334 if (operation == CMD_UPDATE || operation == CMD_DELETE)
1336 /* For UPDATE/DELETE, find the appropriate junk attr now */
1339 relkind = resultRelInfo->ri_RelationDesc->rd_rel->relkind;
1340 if (relkind == RELKIND_RELATION ||
1341 relkind == RELKIND_MATVIEW)
1343 j->jf_junkAttNo = ExecFindJunkAttribute(j, "ctid");
1344 if (!AttributeNumberIsValid(j->jf_junkAttNo))
1345 elog(ERROR, "could not find junk ctid column");
1347 else if (relkind == RELKIND_FOREIGN_TABLE)
1350 * When there is an AFTER trigger, there should be a
1351 * wholerow attribute.
1353 j->jf_junkAttNo = ExecFindJunkAttribute(j, "wholerow");
1357 j->jf_junkAttNo = ExecFindJunkAttribute(j, "wholerow");
1358 if (!AttributeNumberIsValid(j->jf_junkAttNo))
1359 elog(ERROR, "could not find junk wholerow column");
1363 resultRelInfo->ri_junkFilter = j;
1369 if (operation == CMD_INSERT)
1370 ExecCheckPlanOutput(mtstate->resultRelInfo->ri_RelationDesc,
1371 subplan->targetlist);
1376 * Set up a tuple table slot for use for trigger output tuples. In a plan
1377 * containing multiple ModifyTable nodes, all can share one such slot, so
1378 * we keep it in the estate.
1380 if (estate->es_trig_tuple_slot == NULL)
1381 estate->es_trig_tuple_slot = ExecInitExtraTupleSlot(estate);
1384 * Lastly, if this is not the primary (canSetTag) ModifyTable node, add it
1385 * to estate->es_auxmodifytables so that it will be run to completion by
1386 * ExecPostprocessPlan. (It'd actually work fine to add the primary
1387 * ModifyTable node too, but there's no need.) Note the use of lcons not
1388 * lappend: we need later-initialized ModifyTable nodes to be shut down
1389 * before earlier ones. This ensures that we don't throw away RETURNING
1390 * rows that need to be seen by a later CTE subplan.
1392 if (!mtstate->canSetTag)
1393 estate->es_auxmodifytables = lcons(mtstate,
1394 estate->es_auxmodifytables);
1399 /* ----------------------------------------------------------------
1400 * ExecEndModifyTable
1402 * Shuts down the plan.
1404 * Returns nothing of interest.
1405 * ----------------------------------------------------------------
1408 ExecEndModifyTable(ModifyTableState *node)
1413 * Allow any FDWs to shut down
1415 for (i = 0; i < node->mt_nplans; i++)
1417 ResultRelInfo *resultRelInfo = node->resultRelInfo + i;
1419 if (resultRelInfo->ri_FdwRoutine != NULL &&
1420 resultRelInfo->ri_FdwRoutine->EndForeignModify != NULL)
1421 resultRelInfo->ri_FdwRoutine->EndForeignModify(node->ps.state,
1426 * Free the exprcontext
1428 ExecFreeExprContext(&node->ps);
1431 * clean out the tuple table
1433 ExecClearTuple(node->ps.ps_ResultTupleSlot);
1436 * Terminate EPQ execution if active
1438 EvalPlanQualEnd(&node->mt_epqstate);
1441 * shut down subplans
1443 for (i = 0; i < node->mt_nplans; i++)
1444 ExecEndNode(node->mt_plans[i]);
1448 ExecReScanModifyTable(ModifyTableState *node)
1451 * Currently, we don't need to support rescan on ModifyTable nodes. The
1452 * semantics of that would be a bit debatable anyway.
1454 elog(ERROR, "ExecReScanModifyTable is not implemented");