1 /*-------------------------------------------------------------------------
4 * routines to handle ModifyTable nodes.
6 * Portions Copyright (c) 1996-2011, 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/xact.h"
41 #include "commands/trigger.h"
42 #include "executor/executor.h"
43 #include "executor/nodeModifyTable.h"
44 #include "miscadmin.h"
45 #include "nodes/nodeFuncs.h"
46 #include "storage/bufmgr.h"
47 #include "utils/builtins.h"
48 #include "utils/memutils.h"
49 #include "utils/tqual.h"
53 * Verify that the tuples to be produced by INSERT or UPDATE match the
54 * target relation's rowtype
56 * We do this to guard against stale plans. If plan invalidation is
57 * functioning properly then we should never get a failure here, but better
58 * safe than sorry. Note that this is called after we have obtained lock
59 * on the target rel, so the rowtype can't change underneath us.
61 * The plan output is represented by its targetlist, because that makes
62 * handling the dropped-column case easier.
65 ExecCheckPlanOutput(Relation resultRel, List *targetList)
67 TupleDesc resultDesc = RelationGetDescr(resultRel);
71 foreach(lc, targetList)
73 TargetEntry *tle = (TargetEntry *) lfirst(lc);
74 Form_pg_attribute attr;
77 continue; /* ignore junk tlist items */
79 if (attno >= resultDesc->natts)
81 (errcode(ERRCODE_DATATYPE_MISMATCH),
82 errmsg("table row type and query-specified row type do not match"),
83 errdetail("Query has too many columns.")));
84 attr = resultDesc->attrs[attno++];
86 if (!attr->attisdropped)
88 /* Normal case: demand type match */
89 if (exprType((Node *) tle->expr) != attr->atttypid)
91 (errcode(ERRCODE_DATATYPE_MISMATCH),
92 errmsg("table row type and query-specified row type do not match"),
93 errdetail("Table has type %s at ordinal position %d, but query expects %s.",
94 format_type_be(attr->atttypid),
96 format_type_be(exprType((Node *) tle->expr)))));
101 * For a dropped column, we can't check atttypid (it's likely 0).
102 * In any case the planner has most likely inserted an INT4 null.
103 * What we insist on is just *some* NULL constant.
105 if (!IsA(tle->expr, Const) ||
106 !((Const *) tle->expr)->constisnull)
108 (errcode(ERRCODE_DATATYPE_MISMATCH),
109 errmsg("table row type and query-specified row type do not match"),
110 errdetail("Query provides a value for a dropped column at ordinal position %d.",
114 if (attno != resultDesc->natts)
116 (errcode(ERRCODE_DATATYPE_MISMATCH),
117 errmsg("table row type and query-specified row type do not match"),
118 errdetail("Query has too few columns.")));
122 * ExecProcessReturning --- evaluate a RETURNING list
124 * projectReturning: RETURNING projection info for current result rel
125 * tupleSlot: slot holding tuple actually inserted/updated/deleted
126 * planSlot: slot holding tuple returned by top subplan node
128 * Returns a slot holding the result tuple
130 static TupleTableSlot *
131 ExecProcessReturning(ProjectionInfo *projectReturning,
132 TupleTableSlot *tupleSlot,
133 TupleTableSlot *planSlot)
135 ExprContext *econtext = projectReturning->pi_exprContext;
138 * Reset per-tuple memory context to free any expression evaluation
139 * storage allocated in the previous cycle.
141 ResetExprContext(econtext);
143 /* Make tuple and any needed join variables available to ExecProject */
144 econtext->ecxt_scantuple = tupleSlot;
145 econtext->ecxt_outertuple = planSlot;
147 /* Compute the RETURNING expressions */
148 return ExecProject(projectReturning, NULL);
151 /* ----------------------------------------------------------------
154 * For INSERT, we have to insert the tuple into the target relation
155 * and insert appropriate tuples into the index relations.
157 * Returns RETURNING result if any, otherwise NULL.
158 * ----------------------------------------------------------------
160 static TupleTableSlot *
161 ExecInsert(TupleTableSlot *slot,
162 TupleTableSlot *planSlot,
167 ResultRelInfo *resultRelInfo;
168 Relation resultRelationDesc;
170 List *recheckIndexes = NIL;
173 * get the heap tuple out of the tuple table slot, making sure we have a
176 tuple = ExecMaterializeSlot(slot);
179 * get information on the (current) result relation
181 resultRelInfo = estate->es_result_relation_info;
182 resultRelationDesc = resultRelInfo->ri_RelationDesc;
185 * If the result relation has OIDs, force the tuple's OID to zero so that
186 * heap_insert will assign a fresh OID. Usually the OID already will be
187 * zero at this point, but there are corner cases where the plan tree can
188 * return a tuple extracted literally from some table with the same
191 * XXX if we ever wanted to allow users to assign their own OIDs to new
192 * rows, this'd be the place to do it. For the moment, we make a point of
193 * doing this before calling triggers, so that a user-supplied trigger
194 * could hack the OID if desired.
196 if (resultRelationDesc->rd_rel->relhasoids)
197 HeapTupleSetOid(tuple, InvalidOid);
199 /* BEFORE ROW INSERT Triggers */
200 if (resultRelInfo->ri_TrigDesc &&
201 resultRelInfo->ri_TrigDesc->trig_insert_before_row)
203 slot = ExecBRInsertTriggers(estate, resultRelInfo, slot);
205 if (slot == NULL) /* "do nothing" */
208 /* trigger might have changed tuple */
209 tuple = ExecMaterializeSlot(slot);
212 /* INSTEAD OF ROW INSERT Triggers */
213 if (resultRelInfo->ri_TrigDesc &&
214 resultRelInfo->ri_TrigDesc->trig_insert_instead_row)
216 slot = ExecIRInsertTriggers(estate, resultRelInfo, slot);
218 if (slot == NULL) /* "do nothing" */
221 /* trigger might have changed tuple */
222 tuple = ExecMaterializeSlot(slot);
229 * Check the constraints of the tuple
231 if (resultRelationDesc->rd_att->constr)
232 ExecConstraints(resultRelInfo, slot, estate);
237 * Note: heap_insert returns the tid (location) of the new tuple in
240 newId = heap_insert(resultRelationDesc, tuple,
241 estate->es_output_cid, 0, NULL);
244 * insert index entries for tuple
246 if (resultRelInfo->ri_NumIndices > 0)
247 recheckIndexes = ExecInsertIndexTuples(slot, &(tuple->t_self),
253 (estate->es_processed)++;
254 estate->es_lastoid = newId;
255 setLastTid(&(tuple->t_self));
258 /* AFTER ROW INSERT Triggers */
259 ExecARInsertTriggers(estate, resultRelInfo, tuple, recheckIndexes);
261 list_free(recheckIndexes);
263 /* Process RETURNING if present */
264 if (resultRelInfo->ri_projectReturning)
265 return ExecProcessReturning(resultRelInfo->ri_projectReturning,
271 /* ----------------------------------------------------------------
274 * DELETE is like UPDATE, except that we delete the tuple and no
275 * index modifications are needed.
277 * When deleting from a table, tupleid identifies the tuple to
278 * delete and oldtuple is NULL. When deleting from a view,
279 * oldtuple is passed to the INSTEAD OF triggers and identifies
280 * what to delete, and tupleid is invalid.
282 * Returns RETURNING result if any, otherwise NULL.
283 * ----------------------------------------------------------------
285 static TupleTableSlot *
286 ExecDelete(ItemPointer tupleid,
287 HeapTupleHeader oldtuple,
288 TupleTableSlot *planSlot,
293 ResultRelInfo *resultRelInfo;
294 Relation resultRelationDesc;
296 ItemPointerData update_ctid;
297 TransactionId update_xmax;
300 * get information on the (current) result relation
302 resultRelInfo = estate->es_result_relation_info;
303 resultRelationDesc = resultRelInfo->ri_RelationDesc;
305 /* BEFORE ROW DELETE Triggers */
306 if (resultRelInfo->ri_TrigDesc &&
307 resultRelInfo->ri_TrigDesc->trig_delete_before_row)
311 dodelete = ExecBRDeleteTriggers(estate, epqstate, resultRelInfo,
314 if (!dodelete) /* "do nothing" */
318 /* INSTEAD OF ROW DELETE Triggers */
319 if (resultRelInfo->ri_TrigDesc &&
320 resultRelInfo->ri_TrigDesc->trig_delete_instead_row)
325 Assert(oldtuple != NULL);
326 tuple.t_data = oldtuple;
327 tuple.t_len = HeapTupleHeaderGetDatumLength(oldtuple);
328 ItemPointerSetInvalid(&(tuple.t_self));
329 tuple.t_tableOid = InvalidOid;
331 dodelete = ExecIRDeleteTriggers(estate, resultRelInfo, &tuple);
333 if (!dodelete) /* "do nothing" */
341 * Note: if es_crosscheck_snapshot isn't InvalidSnapshot, we check
342 * that the row to be deleted is visible to that snapshot, and throw a
343 * can't-serialize error if not. This is a special-case behavior
344 * needed for referential integrity updates in transaction-snapshot
348 result = heap_delete(resultRelationDesc, tupleid,
349 &update_ctid, &update_xmax,
350 estate->es_output_cid,
351 estate->es_crosscheck_snapshot,
352 true /* wait for commit */ );
355 case HeapTupleSelfUpdated:
356 /* already deleted by self; nothing to do */
359 case HeapTupleMayBeUpdated:
362 case HeapTupleUpdated:
363 if (IsolationUsesXactSnapshot())
365 (errcode(ERRCODE_T_R_SERIALIZATION_FAILURE),
366 errmsg("could not serialize access due to concurrent update")));
367 if (!ItemPointerEquals(tupleid, &update_ctid))
369 TupleTableSlot *epqslot;
371 epqslot = EvalPlanQual(estate,
374 resultRelInfo->ri_RangeTableIndex,
377 if (!TupIsNull(epqslot))
379 *tupleid = update_ctid;
383 /* tuple already deleted; nothing to do */
387 elog(ERROR, "unrecognized heap_delete status: %u", result);
392 * Note: Normally one would think that we have to delete index tuples
393 * associated with the heap tuple now...
395 * ... but in POSTGRES, we have no need to do this because VACUUM will
396 * take care of it later. We can't delete index tuples immediately
397 * anyway, since the tuple is still visible to other transactions.
402 (estate->es_processed)++;
404 /* AFTER ROW DELETE Triggers */
405 ExecARDeleteTriggers(estate, resultRelInfo, tupleid);
407 /* Process RETURNING if present */
408 if (resultRelInfo->ri_projectReturning)
411 * We have to put the target tuple into a slot, which means first we
412 * gotta fetch it. We can use the trigger tuple slot.
414 TupleTableSlot *slot = estate->es_trig_tuple_slot;
415 TupleTableSlot *rslot;
416 HeapTupleData deltuple;
419 if (oldtuple != NULL)
421 deltuple.t_data = oldtuple;
422 deltuple.t_len = HeapTupleHeaderGetDatumLength(oldtuple);
423 ItemPointerSetInvalid(&(deltuple.t_self));
424 deltuple.t_tableOid = InvalidOid;
425 delbuffer = InvalidBuffer;
429 deltuple.t_self = *tupleid;
430 if (!heap_fetch(resultRelationDesc, SnapshotAny,
431 &deltuple, &delbuffer, false, NULL))
432 elog(ERROR, "failed to fetch deleted tuple for DELETE RETURNING");
435 if (slot->tts_tupleDescriptor != RelationGetDescr(resultRelationDesc))
436 ExecSetSlotDescriptor(slot, RelationGetDescr(resultRelationDesc));
437 ExecStoreTuple(&deltuple, slot, InvalidBuffer, false);
439 rslot = ExecProcessReturning(resultRelInfo->ri_projectReturning,
442 ExecClearTuple(slot);
443 if (BufferIsValid(delbuffer))
444 ReleaseBuffer(delbuffer);
452 /* ----------------------------------------------------------------
455 * note: we can't run UPDATE queries with transactions
456 * off because UPDATEs are actually INSERTs and our
457 * scan will mistakenly loop forever, updating the tuple
458 * it just inserted.. This should be fixed but until it
459 * is, we don't want to get stuck in an infinite loop
460 * which corrupts your database..
462 * When updating a table, tupleid identifies the tuple to
463 * update and oldtuple is NULL. When updating a view, oldtuple
464 * is passed to the INSTEAD OF triggers and identifies what to
465 * update, and tupleid is invalid.
467 * Returns RETURNING result if any, otherwise NULL.
468 * ----------------------------------------------------------------
470 static TupleTableSlot *
471 ExecUpdate(ItemPointer tupleid,
472 HeapTupleHeader oldtuple,
473 TupleTableSlot *slot,
474 TupleTableSlot *planSlot,
480 ResultRelInfo *resultRelInfo;
481 Relation resultRelationDesc;
483 ItemPointerData update_ctid;
484 TransactionId update_xmax;
485 List *recheckIndexes = NIL;
488 * abort the operation if not running transactions
490 if (IsBootstrapProcessingMode())
491 elog(ERROR, "cannot UPDATE during bootstrap");
494 * get the heap tuple out of the tuple table slot, making sure we have a
497 tuple = ExecMaterializeSlot(slot);
500 * get information on the (current) result relation
502 resultRelInfo = estate->es_result_relation_info;
503 resultRelationDesc = resultRelInfo->ri_RelationDesc;
505 /* BEFORE ROW UPDATE Triggers */
506 if (resultRelInfo->ri_TrigDesc &&
507 resultRelInfo->ri_TrigDesc->trig_update_before_row)
509 slot = ExecBRUpdateTriggers(estate, epqstate, resultRelInfo,
512 if (slot == NULL) /* "do nothing" */
515 /* trigger might have changed tuple */
516 tuple = ExecMaterializeSlot(slot);
519 /* INSTEAD OF ROW UPDATE Triggers */
520 if (resultRelInfo->ri_TrigDesc &&
521 resultRelInfo->ri_TrigDesc->trig_update_instead_row)
523 HeapTupleData oldtup;
525 Assert(oldtuple != NULL);
526 oldtup.t_data = oldtuple;
527 oldtup.t_len = HeapTupleHeaderGetDatumLength(oldtuple);
528 ItemPointerSetInvalid(&(oldtup.t_self));
529 oldtup.t_tableOid = InvalidOid;
531 slot = ExecIRUpdateTriggers(estate, resultRelInfo,
534 if (slot == NULL) /* "do nothing" */
537 /* trigger might have changed tuple */
538 tuple = ExecMaterializeSlot(slot);
543 * Check the constraints of the tuple
545 * If we generate a new candidate tuple after EvalPlanQual testing, we
546 * must loop back here and recheck constraints. (We don't need to
547 * redo triggers, however. If there are any BEFORE triggers then
548 * trigger.c will have done heap_lock_tuple to lock the correct tuple,
549 * so there's no need to do them again.)
552 if (resultRelationDesc->rd_att->constr)
553 ExecConstraints(resultRelInfo, slot, estate);
556 * replace the heap tuple
558 * Note: if es_crosscheck_snapshot isn't InvalidSnapshot, we check
559 * that the row to be updated is visible to that snapshot, and throw a
560 * can't-serialize error if not. This is a special-case behavior
561 * needed for referential integrity updates in transaction-snapshot
564 result = heap_update(resultRelationDesc, tupleid, tuple,
565 &update_ctid, &update_xmax,
566 estate->es_output_cid,
567 estate->es_crosscheck_snapshot,
568 true /* wait for commit */ );
571 case HeapTupleSelfUpdated:
572 /* already deleted by self; nothing to do */
575 case HeapTupleMayBeUpdated:
578 case HeapTupleUpdated:
579 if (IsolationUsesXactSnapshot())
581 (errcode(ERRCODE_T_R_SERIALIZATION_FAILURE),
582 errmsg("could not serialize access due to concurrent update")));
583 if (!ItemPointerEquals(tupleid, &update_ctid))
585 TupleTableSlot *epqslot;
587 epqslot = EvalPlanQual(estate,
590 resultRelInfo->ri_RangeTableIndex,
593 if (!TupIsNull(epqslot))
595 *tupleid = update_ctid;
596 slot = ExecFilterJunk(resultRelInfo->ri_junkFilter, epqslot);
597 tuple = ExecMaterializeSlot(slot);
601 /* tuple already deleted; nothing to do */
605 elog(ERROR, "unrecognized heap_update status: %u", result);
610 * Note: instead of having to update the old index tuples associated
611 * with the heap tuple, all we do is form and insert new index tuples.
612 * This is because UPDATEs are actually DELETEs and INSERTs, and index
613 * tuple deletion is done later by VACUUM (see notes in ExecDelete).
614 * All we do here is insert new index tuples. -cim 9/27/89
618 * insert index entries for tuple
620 * Note: heap_update returns the tid (location) of the new tuple in
623 * If it's a HOT update, we mustn't insert new index entries.
625 if (resultRelInfo->ri_NumIndices > 0 && !HeapTupleIsHeapOnly(tuple))
626 recheckIndexes = ExecInsertIndexTuples(slot, &(tuple->t_self),
631 (estate->es_processed)++;
633 /* AFTER ROW UPDATE Triggers */
634 ExecARUpdateTriggers(estate, resultRelInfo, tupleid, tuple,
637 list_free(recheckIndexes);
639 /* Process RETURNING if present */
640 if (resultRelInfo->ri_projectReturning)
641 return ExecProcessReturning(resultRelInfo->ri_projectReturning,
649 * Process BEFORE EACH STATEMENT triggers
652 fireBSTriggers(ModifyTableState *node)
654 switch (node->operation)
657 ExecBSInsertTriggers(node->ps.state, node->resultRelInfo);
660 ExecBSUpdateTriggers(node->ps.state, node->resultRelInfo);
663 ExecBSDeleteTriggers(node->ps.state, node->resultRelInfo);
666 elog(ERROR, "unknown operation");
672 * Process AFTER EACH STATEMENT triggers
675 fireASTriggers(ModifyTableState *node)
677 switch (node->operation)
680 ExecASInsertTriggers(node->ps.state, node->resultRelInfo);
683 ExecASUpdateTriggers(node->ps.state, node->resultRelInfo);
686 ExecASDeleteTriggers(node->ps.state, node->resultRelInfo);
689 elog(ERROR, "unknown operation");
695 /* ----------------------------------------------------------------
698 * Perform table modifications as required, and return RETURNING results
700 * ----------------------------------------------------------------
703 ExecModifyTable(ModifyTableState *node)
705 EState *estate = node->ps.state;
706 CmdType operation = node->operation;
707 ResultRelInfo *saved_resultRelInfo;
708 ResultRelInfo *resultRelInfo;
709 PlanState *subplanstate;
710 JunkFilter *junkfilter;
711 TupleTableSlot *slot;
712 TupleTableSlot *planSlot;
713 ItemPointer tupleid = NULL;
714 ItemPointerData tuple_ctid;
715 HeapTupleHeader oldtuple = NULL;
718 * If we've already completed processing, don't try to do more. We need
719 * this test because ExecPostprocessPlan might call us an extra time, and
720 * our subplan's nodes aren't necessarily robust against being called
727 * On first call, fire BEFORE STATEMENT triggers before proceeding.
729 if (node->fireBSTriggers)
731 fireBSTriggers(node);
732 node->fireBSTriggers = false;
735 /* Preload local variables */
736 resultRelInfo = node->resultRelInfo + node->mt_whichplan;
737 subplanstate = node->mt_plans[node->mt_whichplan];
738 junkfilter = resultRelInfo->ri_junkFilter;
741 * es_result_relation_info must point to the currently active result
742 * relation while we are within this ModifyTable node. Even though
743 * ModifyTable nodes can't be nested statically, they can be nested
744 * dynamically (since our subplan could include a reference to a modifying
745 * CTE). So we have to save and restore the caller's value.
747 saved_resultRelInfo = estate->es_result_relation_info;
749 estate->es_result_relation_info = resultRelInfo;
752 * Fetch rows from subplan(s), and execute the required table modification
758 * Reset the per-output-tuple exprcontext. This is needed because
759 * triggers expect to use that context as workspace. It's a bit ugly
760 * to do this below the top level of the plan, however. We might need
761 * to rethink this later.
763 ResetPerTupleExprContext(estate);
765 planSlot = ExecProcNode(subplanstate);
767 if (TupIsNull(planSlot))
769 /* advance to next subplan if any */
770 node->mt_whichplan++;
771 if (node->mt_whichplan < node->mt_nplans)
774 subplanstate = node->mt_plans[node->mt_whichplan];
775 junkfilter = resultRelInfo->ri_junkFilter;
776 estate->es_result_relation_info = resultRelInfo;
777 EvalPlanQualSetPlan(&node->mt_epqstate, subplanstate->plan,
778 node->mt_arowmarks[node->mt_whichplan]);
785 EvalPlanQualSetSlot(&node->mt_epqstate, planSlot);
788 if (junkfilter != NULL)
791 * extract the 'ctid' or 'wholerow' junk attribute.
793 if (operation == CMD_UPDATE || operation == CMD_DELETE)
798 if (resultRelInfo->ri_RelationDesc->rd_rel->relkind == RELKIND_RELATION)
800 datum = ExecGetJunkAttribute(slot,
801 junkfilter->jf_junkAttNo,
803 /* shouldn't ever get a null result... */
805 elog(ERROR, "ctid is NULL");
807 tupleid = (ItemPointer) DatumGetPointer(datum);
808 tuple_ctid = *tupleid; /* be sure we don't free
810 tupleid = &tuple_ctid;
814 datum = ExecGetJunkAttribute(slot,
815 junkfilter->jf_junkAttNo,
817 /* shouldn't ever get a null result... */
819 elog(ERROR, "wholerow is NULL");
821 oldtuple = DatumGetHeapTupleHeader(datum);
826 * apply the junkfilter if needed.
828 if (operation != CMD_DELETE)
829 slot = ExecFilterJunk(junkfilter, slot);
835 slot = ExecInsert(slot, planSlot, estate, node->canSetTag);
838 slot = ExecUpdate(tupleid, oldtuple, slot, planSlot,
839 &node->mt_epqstate, estate, node->canSetTag);
842 slot = ExecDelete(tupleid, oldtuple, planSlot,
843 &node->mt_epqstate, estate, node->canSetTag);
846 elog(ERROR, "unknown operation");
851 * If we got a RETURNING result, return it to caller. We'll continue
852 * the work on next call.
856 estate->es_result_relation_info = saved_resultRelInfo;
861 /* Restore es_result_relation_info before exiting */
862 estate->es_result_relation_info = saved_resultRelInfo;
865 * We're done, but fire AFTER STATEMENT triggers before exiting.
867 fireASTriggers(node);
869 node->mt_done = true;
874 /* ----------------------------------------------------------------
875 * ExecInitModifyTable
876 * ----------------------------------------------------------------
879 ExecInitModifyTable(ModifyTable *node, EState *estate, int eflags)
881 ModifyTableState *mtstate;
882 CmdType operation = node->operation;
883 int nplans = list_length(node->plans);
884 ResultRelInfo *saved_resultRelInfo;
885 ResultRelInfo *resultRelInfo;
891 /* check for unsupported flags */
892 Assert(!(eflags & (EXEC_FLAG_BACKWARD | EXEC_FLAG_MARK)));
895 * This should NOT get called during EvalPlanQual; we should have passed a
896 * subplan tree to EvalPlanQual, instead. Use a runtime test not just
897 * Assert because this condition is easy to miss in testing ...
899 if (estate->es_epqTuple != NULL)
900 elog(ERROR, "ModifyTable should not be called during EvalPlanQual");
903 * create state structure
905 mtstate = makeNode(ModifyTableState);
906 mtstate->ps.plan = (Plan *) node;
907 mtstate->ps.state = estate;
908 mtstate->ps.targetlist = NIL; /* not actually used */
910 mtstate->operation = operation;
911 mtstate->canSetTag = node->canSetTag;
912 mtstate->mt_done = false;
914 mtstate->mt_plans = (PlanState **) palloc0(sizeof(PlanState *) * nplans);
915 mtstate->resultRelInfo = estate->es_result_relations + node->resultRelIndex;
916 mtstate->mt_arowmarks = (List **) palloc0(sizeof(List *) * nplans);
917 mtstate->mt_nplans = nplans;
919 /* set up epqstate with dummy subplan data for the moment */
920 EvalPlanQualInit(&mtstate->mt_epqstate, estate, NULL, NIL, node->epqParam);
921 mtstate->fireBSTriggers = true;
924 * call ExecInitNode on each of the plans to be executed and save the
925 * results into the array "mt_plans". This is also a convenient place to
926 * verify that the proposed target relations are valid and open their
927 * indexes for insertion of new index entries. Note we *must* set
928 * estate->es_result_relation_info correctly while we initialize each
929 * sub-plan; ExecContextForcesOids depends on that!
931 saved_resultRelInfo = estate->es_result_relation_info;
933 resultRelInfo = mtstate->resultRelInfo;
935 foreach(l, node->plans)
937 subplan = (Plan *) lfirst(l);
940 * Verify result relation is a valid target for the current operation
942 CheckValidResultRel(resultRelInfo->ri_RelationDesc, operation);
945 * If there are indices on the result relation, open them and save
946 * descriptors in the result relation info, so that we can add new
947 * index entries for the tuples we add/update. We need not do this
948 * for a DELETE, however, since deletion doesn't affect indexes.
950 if (resultRelInfo->ri_RelationDesc->rd_rel->relhasindex &&
951 operation != CMD_DELETE)
952 ExecOpenIndices(resultRelInfo);
954 /* Now init the plan for this result rel */
955 estate->es_result_relation_info = resultRelInfo;
956 mtstate->mt_plans[i] = ExecInitNode(subplan, estate, eflags);
962 estate->es_result_relation_info = saved_resultRelInfo;
965 * Initialize RETURNING projections if needed.
967 if (node->returningLists)
969 TupleTableSlot *slot;
970 ExprContext *econtext;
973 * Initialize result tuple slot and assign its rowtype using the first
974 * RETURNING list. We assume the rest will look the same.
976 tupDesc = ExecTypeFromTL((List *) linitial(node->returningLists),
979 /* Set up a slot for the output of the RETURNING projection(s) */
980 ExecInitResultTupleSlot(estate, &mtstate->ps);
981 ExecAssignResultType(&mtstate->ps, tupDesc);
982 slot = mtstate->ps.ps_ResultTupleSlot;
984 /* Need an econtext too */
985 econtext = CreateExprContext(estate);
986 mtstate->ps.ps_ExprContext = econtext;
989 * Build a projection for each result rel.
991 resultRelInfo = mtstate->resultRelInfo;
992 foreach(l, node->returningLists)
994 List *rlist = (List *) lfirst(l);
997 rliststate = (List *) ExecInitExpr((Expr *) rlist, &mtstate->ps);
998 resultRelInfo->ri_projectReturning =
999 ExecBuildProjectionInfo(rliststate, econtext, slot,
1000 resultRelInfo->ri_RelationDesc->rd_att);
1007 * We still must construct a dummy result tuple type, because InitPlan
1008 * expects one (maybe should change that?).
1010 tupDesc = ExecTypeFromTL(NIL, false);
1011 ExecInitResultTupleSlot(estate, &mtstate->ps);
1012 ExecAssignResultType(&mtstate->ps, tupDesc);
1014 mtstate->ps.ps_ExprContext = NULL;
1018 * If we have any secondary relations in an UPDATE or DELETE, they need to
1019 * be treated like non-locked relations in SELECT FOR UPDATE, ie, the
1020 * EvalPlanQual mechanism needs to be told about them. Locate the
1021 * relevant ExecRowMarks.
1023 foreach(l, node->rowMarks)
1025 PlanRowMark *rc = (PlanRowMark *) lfirst(l);
1028 Assert(IsA(rc, PlanRowMark));
1030 /* ignore "parent" rowmarks; they are irrelevant at runtime */
1034 /* find ExecRowMark (same for all subplans) */
1035 erm = ExecFindRowMark(estate, rc->rti);
1037 /* build ExecAuxRowMark for each subplan */
1038 for (i = 0; i < nplans; i++)
1040 ExecAuxRowMark *aerm;
1042 subplan = mtstate->mt_plans[i]->plan;
1043 aerm = ExecBuildAuxRowMark(erm, subplan->targetlist);
1044 mtstate->mt_arowmarks[i] = lappend(mtstate->mt_arowmarks[i], aerm);
1048 /* select first subplan */
1049 mtstate->mt_whichplan = 0;
1050 subplan = (Plan *) linitial(node->plans);
1051 EvalPlanQualSetPlan(&mtstate->mt_epqstate, subplan,
1052 mtstate->mt_arowmarks[0]);
1055 * Initialize the junk filter(s) if needed. INSERT queries need a filter
1056 * if there are any junk attrs in the tlist. UPDATE and DELETE always
1057 * need a filter, since there's always a junk 'ctid' or 'wholerow'
1058 * attribute present --- no need to look first.
1060 * If there are multiple result relations, each one needs its own junk
1061 * filter. Note multiple rels are only possible for UPDATE/DELETE, so we
1062 * can't be fooled by some needing a filter and some not.
1064 * This section of code is also a convenient place to verify that the
1065 * output of an INSERT or UPDATE matches the target table(s).
1068 bool junk_filter_needed = false;
1073 foreach(l, subplan->targetlist)
1075 TargetEntry *tle = (TargetEntry *) lfirst(l);
1079 junk_filter_needed = true;
1086 junk_filter_needed = true;
1089 elog(ERROR, "unknown operation");
1093 if (junk_filter_needed)
1095 resultRelInfo = mtstate->resultRelInfo;
1096 for (i = 0; i < nplans; i++)
1100 subplan = mtstate->mt_plans[i]->plan;
1101 if (operation == CMD_INSERT || operation == CMD_UPDATE)
1102 ExecCheckPlanOutput(resultRelInfo->ri_RelationDesc,
1103 subplan->targetlist);
1105 j = ExecInitJunkFilter(subplan->targetlist,
1106 resultRelInfo->ri_RelationDesc->rd_att->tdhasoid,
1107 ExecInitExtraTupleSlot(estate));
1109 if (operation == CMD_UPDATE || operation == CMD_DELETE)
1111 /* For UPDATE/DELETE, find the appropriate junk attr now */
1112 if (resultRelInfo->ri_RelationDesc->rd_rel->relkind == RELKIND_RELATION)
1114 j->jf_junkAttNo = ExecFindJunkAttribute(j, "ctid");
1115 if (!AttributeNumberIsValid(j->jf_junkAttNo))
1116 elog(ERROR, "could not find junk ctid column");
1120 j->jf_junkAttNo = ExecFindJunkAttribute(j, "wholerow");
1121 if (!AttributeNumberIsValid(j->jf_junkAttNo))
1122 elog(ERROR, "could not find junk wholerow column");
1126 resultRelInfo->ri_junkFilter = j;
1132 if (operation == CMD_INSERT)
1133 ExecCheckPlanOutput(mtstate->resultRelInfo->ri_RelationDesc,
1134 subplan->targetlist);
1139 * Set up a tuple table slot for use for trigger output tuples. In a plan
1140 * containing multiple ModifyTable nodes, all can share one such slot, so
1141 * we keep it in the estate.
1143 if (estate->es_trig_tuple_slot == NULL)
1144 estate->es_trig_tuple_slot = ExecInitExtraTupleSlot(estate);
1147 * Lastly, if this is not the primary (canSetTag) ModifyTable node, add it
1148 * to estate->es_auxmodifytables so that it will be run to completion by
1149 * ExecPostprocessPlan. (It'd actually work fine to add the primary
1150 * ModifyTable node too, but there's no need.) Note the use of lcons not
1151 * lappend: we need later-initialized ModifyTable nodes to be shut down
1152 * before earlier ones. This ensures that we don't throw away RETURNING
1153 * rows that need to be seen by a later CTE subplan.
1155 if (!mtstate->canSetTag)
1156 estate->es_auxmodifytables = lcons(mtstate,
1157 estate->es_auxmodifytables);
1162 /* ----------------------------------------------------------------
1163 * ExecEndModifyTable
1165 * Shuts down the plan.
1167 * Returns nothing of interest.
1168 * ----------------------------------------------------------------
1171 ExecEndModifyTable(ModifyTableState *node)
1176 * Free the exprcontext
1178 ExecFreeExprContext(&node->ps);
1181 * clean out the tuple table
1183 ExecClearTuple(node->ps.ps_ResultTupleSlot);
1186 * Terminate EPQ execution if active
1188 EvalPlanQualEnd(&node->mt_epqstate);
1191 * shut down subplans
1193 for (i = 0; i < node->mt_nplans; i++)
1194 ExecEndNode(node->mt_plans[i]);
1198 ExecReScanModifyTable(ModifyTableState *node)
1201 * Currently, we don't need to support rescan on ModifyTable nodes. The
1202 * semantics of that would be a bit debatable anyway.
1204 elog(ERROR, "ExecReScanModifyTable is not implemented");