]> granicus.if.org Git - postgresql/blob - src/backend/executor/nodeModifyTable.c
Update copyright for 2015
[postgresql] / src / backend / executor / nodeModifyTable.c
1 /*-------------------------------------------------------------------------
2  *
3  * nodeModifyTable.c
4  *        routines to handle ModifyTable nodes.
5  *
6  * Portions Copyright (c) 1996-2015, 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"
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"
53
54
55 /*
56  * Verify that the tuples to be produced by INSERT or UPDATE match the
57  * target relation's rowtype
58  *
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.
63  *
64  * The plan output is represented by its targetlist, because that makes
65  * handling the dropped-column case easier.
66  */
67 static void
68 ExecCheckPlanOutput(Relation resultRel, List *targetList)
69 {
70         TupleDesc       resultDesc = RelationGetDescr(resultRel);
71         int                     attno = 0;
72         ListCell   *lc;
73
74         foreach(lc, targetList)
75         {
76                 TargetEntry *tle = (TargetEntry *) lfirst(lc);
77                 Form_pg_attribute attr;
78
79                 if (tle->resjunk)
80                         continue;                       /* ignore junk tlist items */
81
82                 if (attno >= resultDesc->natts)
83                         ereport(ERROR,
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++];
88
89                 if (!attr->attisdropped)
90                 {
91                         /* Normal case: demand type match */
92                         if (exprType((Node *) tle->expr) != attr->atttypid)
93                                 ereport(ERROR,
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),
98                                                                    attno,
99                                                          format_type_be(exprType((Node *) tle->expr)))));
100                 }
101                 else
102                 {
103                         /*
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.
107                          */
108                         if (!IsA(tle->expr, Const) ||
109                                 !((Const *) tle->expr)->constisnull)
110                                 ereport(ERROR,
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.",
114                                                                    attno)));
115                 }
116         }
117         if (attno != resultDesc->natts)
118                 ereport(ERROR,
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.")));
122 }
123
124 /*
125  * ExecProcessReturning --- evaluate a RETURNING list
126  *
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
130  *
131  * Returns a slot holding the result tuple
132  */
133 static TupleTableSlot *
134 ExecProcessReturning(ProjectionInfo *projectReturning,
135                                          TupleTableSlot *tupleSlot,
136                                          TupleTableSlot *planSlot)
137 {
138         ExprContext *econtext = projectReturning->pi_exprContext;
139
140         /*
141          * Reset per-tuple memory context to free any expression evaluation
142          * storage allocated in the previous cycle.
143          */
144         ResetExprContext(econtext);
145
146         /* Make tuple and any needed join variables available to ExecProject */
147         econtext->ecxt_scantuple = tupleSlot;
148         econtext->ecxt_outertuple = planSlot;
149
150         /* Compute the RETURNING expressions */
151         return ExecProject(projectReturning, NULL);
152 }
153
154 /* ----------------------------------------------------------------
155  *              ExecInsert
156  *
157  *              For INSERT, we have to insert the tuple into the target relation
158  *              and insert appropriate tuples into the index relations.
159  *
160  *              Returns RETURNING result if any, otherwise NULL.
161  * ----------------------------------------------------------------
162  */
163 static TupleTableSlot *
164 ExecInsert(TupleTableSlot *slot,
165                    TupleTableSlot *planSlot,
166                    EState *estate,
167                    bool canSetTag)
168 {
169         HeapTuple       tuple;
170         ResultRelInfo *resultRelInfo;
171         Relation        resultRelationDesc;
172         Oid                     newId;
173         List       *recheckIndexes = NIL;
174
175         /*
176          * get the heap tuple out of the tuple table slot, making sure we have a
177          * writable copy
178          */
179         tuple = ExecMaterializeSlot(slot);
180
181         /*
182          * get information on the (current) result relation
183          */
184         resultRelInfo = estate->es_result_relation_info;
185         resultRelationDesc = resultRelInfo->ri_RelationDesc;
186
187         /*
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
192          * rowtype.
193          *
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.
198          */
199         if (resultRelationDesc->rd_rel->relhasoids)
200                 HeapTupleSetOid(tuple, InvalidOid);
201
202         /* BEFORE ROW INSERT Triggers */
203         if (resultRelInfo->ri_TrigDesc &&
204                 resultRelInfo->ri_TrigDesc->trig_insert_before_row)
205         {
206                 slot = ExecBRInsertTriggers(estate, resultRelInfo, slot);
207
208                 if (slot == NULL)               /* "do nothing" */
209                         return NULL;
210
211                 /* trigger might have changed tuple */
212                 tuple = ExecMaterializeSlot(slot);
213         }
214
215         /* INSTEAD OF ROW INSERT Triggers */
216         if (resultRelInfo->ri_TrigDesc &&
217                 resultRelInfo->ri_TrigDesc->trig_insert_instead_row)
218         {
219                 slot = ExecIRInsertTriggers(estate, resultRelInfo, slot);
220
221                 if (slot == NULL)               /* "do nothing" */
222                         return NULL;
223
224                 /* trigger might have changed tuple */
225                 tuple = ExecMaterializeSlot(slot);
226
227                 newId = InvalidOid;
228         }
229         else if (resultRelInfo->ri_FdwRoutine)
230         {
231                 /*
232                  * insert into foreign table: let the FDW do it
233                  */
234                 slot = resultRelInfo->ri_FdwRoutine->ExecForeignInsert(estate,
235                                                                                                                            resultRelInfo,
236                                                                                                                            slot,
237                                                                                                                            planSlot);
238
239                 if (slot == NULL)               /* "do nothing" */
240                         return NULL;
241
242                 /* FDW might have changed tuple */
243                 tuple = ExecMaterializeSlot(slot);
244
245                 newId = InvalidOid;
246         }
247         else
248         {
249                 /*
250                  * Constraints might reference the tableoid column, so initialize
251                  * t_tableOid before evaluating them.
252                  */
253                 tuple->t_tableOid = RelationGetRelid(resultRelationDesc);
254
255                 /*
256                  * Check the constraints of the tuple
257                  */
258                 if (resultRelationDesc->rd_att->constr)
259                         ExecConstraints(resultRelInfo, slot, estate);
260
261                 /*
262                  * insert the tuple
263                  *
264                  * Note: heap_insert returns the tid (location) of the new tuple in
265                  * the t_self field.
266                  */
267                 newId = heap_insert(resultRelationDesc, tuple,
268                                                         estate->es_output_cid, 0, NULL);
269
270                 /*
271                  * insert index entries for tuple
272                  */
273                 if (resultRelInfo->ri_NumIndices > 0)
274                         recheckIndexes = ExecInsertIndexTuples(slot, &(tuple->t_self),
275                                                                                                    estate);
276         }
277
278         if (canSetTag)
279         {
280                 (estate->es_processed)++;
281                 estate->es_lastoid = newId;
282                 setLastTid(&(tuple->t_self));
283         }
284
285         /* AFTER ROW INSERT Triggers */
286         ExecARInsertTriggers(estate, resultRelInfo, tuple, recheckIndexes);
287
288         list_free(recheckIndexes);
289
290         /* Check any WITH CHECK OPTION constraints */
291         if (resultRelInfo->ri_WithCheckOptions != NIL)
292                 ExecWithCheckOptions(resultRelInfo, slot, estate);
293
294         /* Process RETURNING if present */
295         if (resultRelInfo->ri_projectReturning)
296                 return ExecProcessReturning(resultRelInfo->ri_projectReturning,
297                                                                         slot, planSlot);
298
299         return NULL;
300 }
301
302 /* ----------------------------------------------------------------
303  *              ExecDelete
304  *
305  *              DELETE is like UPDATE, except that we delete the tuple and no
306  *              index modifications are needed.
307  *
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.
316  *
317  *              Returns RETURNING result if any, otherwise NULL.
318  * ----------------------------------------------------------------
319  */
320 static TupleTableSlot *
321 ExecDelete(ItemPointer tupleid,
322                    HeapTuple oldtuple,
323                    TupleTableSlot *planSlot,
324                    EPQState *epqstate,
325                    EState *estate,
326                    bool canSetTag)
327 {
328         ResultRelInfo *resultRelInfo;
329         Relation        resultRelationDesc;
330         HTSU_Result result;
331         HeapUpdateFailureData hufd;
332         TupleTableSlot *slot = NULL;
333
334         /*
335          * get information on the (current) result relation
336          */
337         resultRelInfo = estate->es_result_relation_info;
338         resultRelationDesc = resultRelInfo->ri_RelationDesc;
339
340         /* BEFORE ROW DELETE Triggers */
341         if (resultRelInfo->ri_TrigDesc &&
342                 resultRelInfo->ri_TrigDesc->trig_delete_before_row)
343         {
344                 bool            dodelete;
345
346                 dodelete = ExecBRDeleteTriggers(estate, epqstate, resultRelInfo,
347                                                                                 tupleid, oldtuple);
348
349                 if (!dodelete)                  /* "do nothing" */
350                         return NULL;
351         }
352
353         /* INSTEAD OF ROW DELETE Triggers */
354         if (resultRelInfo->ri_TrigDesc &&
355                 resultRelInfo->ri_TrigDesc->trig_delete_instead_row)
356         {
357                 bool            dodelete;
358
359                 Assert(oldtuple != NULL);
360                 dodelete = ExecIRDeleteTriggers(estate, resultRelInfo, oldtuple);
361
362                 if (!dodelete)                  /* "do nothing" */
363                         return NULL;
364         }
365         else if (resultRelInfo->ri_FdwRoutine)
366         {
367                 /*
368                  * delete from foreign table: let the FDW do it
369                  *
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.
373                  */
374                 slot = estate->es_trig_tuple_slot;
375                 if (slot->tts_tupleDescriptor != RelationGetDescr(resultRelationDesc))
376                         ExecSetSlotDescriptor(slot, RelationGetDescr(resultRelationDesc));
377
378                 slot = resultRelInfo->ri_FdwRoutine->ExecForeignDelete(estate,
379                                                                                                                            resultRelInfo,
380                                                                                                                            slot,
381                                                                                                                            planSlot);
382
383                 if (slot == NULL)               /* "do nothing" */
384                         return NULL;
385         }
386         else
387         {
388                 /*
389                  * delete the tuple
390                  *
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
395                  * mode transactions.
396                  */
397 ldelete:;
398                 result = heap_delete(resultRelationDesc, tupleid,
399                                                          estate->es_output_cid,
400                                                          estate->es_crosscheck_snapshot,
401                                                          true /* wait for commit */ ,
402                                                          &hufd);
403                 switch (result)
404                 {
405                         case HeapTupleSelfUpdated:
406
407                                 /*
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.
414                                  *
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
425                                  * course.
426                                  *
427                                  * If a trigger actually intends this type of interaction, it
428                                  * can re-execute the DELETE and then return NULL to cancel
429                                  * the outer delete.
430                                  */
431                                 if (hufd.cmax != estate->es_output_cid)
432                                         ereport(ERROR,
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.")));
436
437                                 /* Else, already deleted by self; nothing to do */
438                                 return NULL;
439
440                         case HeapTupleMayBeUpdated:
441                                 break;
442
443                         case HeapTupleUpdated:
444                                 if (IsolationUsesXactSnapshot())
445                                         ereport(ERROR,
446                                                         (errcode(ERRCODE_T_R_SERIALIZATION_FAILURE),
447                                                          errmsg("could not serialize access due to concurrent update")));
448                                 if (!ItemPointerEquals(tupleid, &hufd.ctid))
449                                 {
450                                         TupleTableSlot *epqslot;
451
452                                         epqslot = EvalPlanQual(estate,
453                                                                                    epqstate,
454                                                                                    resultRelationDesc,
455                                                                                    resultRelInfo->ri_RangeTableIndex,
456                                                                                    LockTupleExclusive,
457                                                                                    &hufd.ctid,
458                                                                                    hufd.xmax);
459                                         if (!TupIsNull(epqslot))
460                                         {
461                                                 *tupleid = hufd.ctid;
462                                                 goto ldelete;
463                                         }
464                                 }
465                                 /* tuple already deleted; nothing to do */
466                                 return NULL;
467
468                         default:
469                                 elog(ERROR, "unrecognized heap_delete status: %u", result);
470                                 return NULL;
471                 }
472
473                 /*
474                  * Note: Normally one would think that we have to delete index tuples
475                  * associated with the heap tuple now...
476                  *
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.
480                  */
481         }
482
483         if (canSetTag)
484                 (estate->es_processed)++;
485
486         /* AFTER ROW DELETE Triggers */
487         ExecARDeleteTriggers(estate, resultRelInfo, tupleid, oldtuple);
488
489         /* Process RETURNING if present */
490         if (resultRelInfo->ri_projectReturning)
491         {
492                 /*
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.
495                  */
496                 TupleTableSlot *rslot;
497                 HeapTupleData deltuple;
498                 Buffer          delbuffer;
499
500                 if (resultRelInfo->ri_FdwRoutine)
501                 {
502                         /* FDW must have provided a slot containing the deleted row */
503                         Assert(!TupIsNull(slot));
504                         delbuffer = InvalidBuffer;
505                 }
506                 else
507                 {
508                         slot = estate->es_trig_tuple_slot;
509                         if (oldtuple != NULL)
510                         {
511                                 deltuple = *oldtuple;
512                                 delbuffer = InvalidBuffer;
513                         }
514                         else
515                         {
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");
520                         }
521
522                         if (slot->tts_tupleDescriptor != RelationGetDescr(resultRelationDesc))
523                                 ExecSetSlotDescriptor(slot, RelationGetDescr(resultRelationDesc));
524                         ExecStoreTuple(&deltuple, slot, InvalidBuffer, false);
525                 }
526
527                 rslot = ExecProcessReturning(resultRelInfo->ri_projectReturning,
528                                                                          slot, planSlot);
529
530                 /*
531                  * Before releasing the target tuple again, make sure rslot has a
532                  * local copy of any pass-by-reference values.
533                  */
534                 ExecMaterializeSlot(rslot);
535
536                 ExecClearTuple(slot);
537                 if (BufferIsValid(delbuffer))
538                         ReleaseBuffer(delbuffer);
539
540                 return rslot;
541         }
542
543         return NULL;
544 }
545
546 /* ----------------------------------------------------------------
547  *              ExecUpdate
548  *
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..
555  *
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.
564  *
565  *              Returns RETURNING result if any, otherwise NULL.
566  * ----------------------------------------------------------------
567  */
568 static TupleTableSlot *
569 ExecUpdate(ItemPointer tupleid,
570                    HeapTuple oldtuple,
571                    TupleTableSlot *slot,
572                    TupleTableSlot *planSlot,
573                    EPQState *epqstate,
574                    EState *estate,
575                    bool canSetTag)
576 {
577         HeapTuple       tuple;
578         ResultRelInfo *resultRelInfo;
579         Relation        resultRelationDesc;
580         HTSU_Result result;
581         HeapUpdateFailureData hufd;
582         List       *recheckIndexes = NIL;
583
584         /*
585          * abort the operation if not running transactions
586          */
587         if (IsBootstrapProcessingMode())
588                 elog(ERROR, "cannot UPDATE during bootstrap");
589
590         /*
591          * get the heap tuple out of the tuple table slot, making sure we have a
592          * writable copy
593          */
594         tuple = ExecMaterializeSlot(slot);
595
596         /*
597          * get information on the (current) result relation
598          */
599         resultRelInfo = estate->es_result_relation_info;
600         resultRelationDesc = resultRelInfo->ri_RelationDesc;
601
602         /* BEFORE ROW UPDATE Triggers */
603         if (resultRelInfo->ri_TrigDesc &&
604                 resultRelInfo->ri_TrigDesc->trig_update_before_row)
605         {
606                 slot = ExecBRUpdateTriggers(estate, epqstate, resultRelInfo,
607                                                                         tupleid, oldtuple, slot);
608
609                 if (slot == NULL)               /* "do nothing" */
610                         return NULL;
611
612                 /* trigger might have changed tuple */
613                 tuple = ExecMaterializeSlot(slot);
614         }
615
616         /* INSTEAD OF ROW UPDATE Triggers */
617         if (resultRelInfo->ri_TrigDesc &&
618                 resultRelInfo->ri_TrigDesc->trig_update_instead_row)
619         {
620                 slot = ExecIRUpdateTriggers(estate, resultRelInfo,
621                                                                         oldtuple, slot);
622
623                 if (slot == NULL)               /* "do nothing" */
624                         return NULL;
625
626                 /* trigger might have changed tuple */
627                 tuple = ExecMaterializeSlot(slot);
628         }
629         else if (resultRelInfo->ri_FdwRoutine)
630         {
631                 /*
632                  * update in foreign table: let the FDW do it
633                  */
634                 slot = resultRelInfo->ri_FdwRoutine->ExecForeignUpdate(estate,
635                                                                                                                            resultRelInfo,
636                                                                                                                            slot,
637                                                                                                                            planSlot);
638
639                 if (slot == NULL)               /* "do nothing" */
640                         return NULL;
641
642                 /* FDW might have changed tuple */
643                 tuple = ExecMaterializeSlot(slot);
644         }
645         else
646         {
647                 LockTupleMode lockmode;
648
649                 /*
650                  * Constraints might reference the tableoid column, so initialize
651                  * t_tableOid before evaluating them.
652                  */
653                 tuple->t_tableOid = RelationGetRelid(resultRelationDesc);
654
655                 /*
656                  * Check the constraints of the tuple
657                  *
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.)
663                  */
664 lreplace:;
665                 if (resultRelationDesc->rd_att->constr)
666                         ExecConstraints(resultRelInfo, slot, estate);
667
668                 /*
669                  * replace the heap tuple
670                  *
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
675                  * mode transactions.
676                  */
677                 result = heap_update(resultRelationDesc, tupleid, tuple,
678                                                          estate->es_output_cid,
679                                                          estate->es_crosscheck_snapshot,
680                                                          true /* wait for commit */ ,
681                                                          &hufd, &lockmode);
682                 switch (result)
683                 {
684                         case HeapTupleSelfUpdated:
685
686                                 /*
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.
694                                  *
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
703                                  * course.
704                                  *
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.
708                                  */
709                                 if (hufd.cmax != estate->es_output_cid)
710                                         ereport(ERROR,
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.")));
714
715                                 /* Else, already updated by self; nothing to do */
716                                 return NULL;
717
718                         case HeapTupleMayBeUpdated:
719                                 break;
720
721                         case HeapTupleUpdated:
722                                 if (IsolationUsesXactSnapshot())
723                                         ereport(ERROR,
724                                                         (errcode(ERRCODE_T_R_SERIALIZATION_FAILURE),
725                                                          errmsg("could not serialize access due to concurrent update")));
726                                 if (!ItemPointerEquals(tupleid, &hufd.ctid))
727                                 {
728                                         TupleTableSlot *epqslot;
729
730                                         epqslot = EvalPlanQual(estate,
731                                                                                    epqstate,
732                                                                                    resultRelationDesc,
733                                                                                    resultRelInfo->ri_RangeTableIndex,
734                                                                                    lockmode,
735                                                                                    &hufd.ctid,
736                                                                                    hufd.xmax);
737                                         if (!TupIsNull(epqslot))
738                                         {
739                                                 *tupleid = hufd.ctid;
740                                                 slot = ExecFilterJunk(resultRelInfo->ri_junkFilter, epqslot);
741                                                 tuple = ExecMaterializeSlot(slot);
742                                                 goto lreplace;
743                                         }
744                                 }
745                                 /* tuple already deleted; nothing to do */
746                                 return NULL;
747
748                         default:
749                                 elog(ERROR, "unrecognized heap_update status: %u", result);
750                                 return NULL;
751                 }
752
753                 /*
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
759                  */
760
761                 /*
762                  * insert index entries for tuple
763                  *
764                  * Note: heap_update returns the tid (location) of the new tuple in
765                  * the t_self field.
766                  *
767                  * If it's a HOT update, we mustn't insert new index entries.
768                  */
769                 if (resultRelInfo->ri_NumIndices > 0 && !HeapTupleIsHeapOnly(tuple))
770                         recheckIndexes = ExecInsertIndexTuples(slot, &(tuple->t_self),
771                                                                                                    estate);
772         }
773
774         if (canSetTag)
775                 (estate->es_processed)++;
776
777         /* AFTER ROW UPDATE Triggers */
778         ExecARUpdateTriggers(estate, resultRelInfo, tupleid, oldtuple, tuple,
779                                                  recheckIndexes);
780
781         list_free(recheckIndexes);
782
783         /* Check any WITH CHECK OPTION constraints */
784         if (resultRelInfo->ri_WithCheckOptions != NIL)
785                 ExecWithCheckOptions(resultRelInfo, slot, estate);
786
787         /* Process RETURNING if present */
788         if (resultRelInfo->ri_projectReturning)
789                 return ExecProcessReturning(resultRelInfo->ri_projectReturning,
790                                                                         slot, planSlot);
791
792         return NULL;
793 }
794
795
796 /*
797  * Process BEFORE EACH STATEMENT triggers
798  */
799 static void
800 fireBSTriggers(ModifyTableState *node)
801 {
802         switch (node->operation)
803         {
804                 case CMD_INSERT:
805                         ExecBSInsertTriggers(node->ps.state, node->resultRelInfo);
806                         break;
807                 case CMD_UPDATE:
808                         ExecBSUpdateTriggers(node->ps.state, node->resultRelInfo);
809                         break;
810                 case CMD_DELETE:
811                         ExecBSDeleteTriggers(node->ps.state, node->resultRelInfo);
812                         break;
813                 default:
814                         elog(ERROR, "unknown operation");
815                         break;
816         }
817 }
818
819 /*
820  * Process AFTER EACH STATEMENT triggers
821  */
822 static void
823 fireASTriggers(ModifyTableState *node)
824 {
825         switch (node->operation)
826         {
827                 case CMD_INSERT:
828                         ExecASInsertTriggers(node->ps.state, node->resultRelInfo);
829                         break;
830                 case CMD_UPDATE:
831                         ExecASUpdateTriggers(node->ps.state, node->resultRelInfo);
832                         break;
833                 case CMD_DELETE:
834                         ExecASDeleteTriggers(node->ps.state, node->resultRelInfo);
835                         break;
836                 default:
837                         elog(ERROR, "unknown operation");
838                         break;
839         }
840 }
841
842
843 /* ----------------------------------------------------------------
844  *         ExecModifyTable
845  *
846  *              Perform table modifications as required, and return RETURNING results
847  *              if needed.
848  * ----------------------------------------------------------------
849  */
850 TupleTableSlot *
851 ExecModifyTable(ModifyTableState *node)
852 {
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;
864         HeapTuple       oldtuple;
865
866         /*
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.)
874          */
875         if (estate->es_epqTuple != NULL)
876                 elog(ERROR, "ModifyTable should not be called during EvalPlanQual");
877
878         /*
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
882          * extra times.
883          */
884         if (node->mt_done)
885                 return NULL;
886
887         /*
888          * On first call, fire BEFORE STATEMENT triggers before proceeding.
889          */
890         if (node->fireBSTriggers)
891         {
892                 fireBSTriggers(node);
893                 node->fireBSTriggers = false;
894         }
895
896         /* Preload local variables */
897         resultRelInfo = node->resultRelInfo + node->mt_whichplan;
898         subplanstate = node->mt_plans[node->mt_whichplan];
899         junkfilter = resultRelInfo->ri_junkFilter;
900
901         /*
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.
907          */
908         saved_resultRelInfo = estate->es_result_relation_info;
909
910         estate->es_result_relation_info = resultRelInfo;
911
912         /*
913          * Fetch rows from subplan(s), and execute the required table modification
914          * for each row.
915          */
916         for (;;)
917         {
918                 /*
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.
923                  */
924                 ResetPerTupleExprContext(estate);
925
926                 planSlot = ExecProcNode(subplanstate);
927
928                 if (TupIsNull(planSlot))
929                 {
930                         /* advance to next subplan if any */
931                         node->mt_whichplan++;
932                         if (node->mt_whichplan < node->mt_nplans)
933                         {
934                                 resultRelInfo++;
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]);
940                                 continue;
941                         }
942                         else
943                                 break;
944                 }
945
946                 EvalPlanQualSetSlot(&node->mt_epqstate, planSlot);
947                 slot = planSlot;
948
949                 oldtuple = NULL;
950                 if (junkfilter != NULL)
951                 {
952                         /*
953                          * extract the 'ctid' or 'wholerow' junk attribute.
954                          */
955                         if (operation == CMD_UPDATE || operation == CMD_DELETE)
956                         {
957                                 char            relkind;
958                                 Datum           datum;
959                                 bool            isNull;
960
961                                 relkind = resultRelInfo->ri_RelationDesc->rd_rel->relkind;
962                                 if (relkind == RELKIND_RELATION || relkind == RELKIND_MATVIEW)
963                                 {
964                                         datum = ExecGetJunkAttribute(slot,
965                                                                                                  junkfilter->jf_junkAttNo,
966                                                                                                  &isNull);
967                                         /* shouldn't ever get a null result... */
968                                         if (isNull)
969                                                 elog(ERROR, "ctid is NULL");
970
971                                         tupleid = (ItemPointer) DatumGetPointer(datum);
972                                         tuple_ctid = *tupleid;          /* be sure we don't free
973                                                                                                  * ctid!! */
974                                         tupleid = &tuple_ctid;
975                                 }
976
977                                 /*
978                                  * Use the wholerow attribute, when available, to reconstruct
979                                  * the old relation tuple.
980                                  *
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.
987                                  *
988                                  * Other relevant relkinds, currently limited to views, always
989                                  * have a wholerow attribute.
990                                  */
991                                 else if (AttributeNumberIsValid(junkfilter->jf_junkAttNo))
992                                 {
993                                         datum = ExecGetJunkAttribute(slot,
994                                                                                                  junkfilter->jf_junkAttNo,
995                                                                                                  &isNull);
996                                         /* shouldn't ever get a null result... */
997                                         if (isNull)
998                                                 elog(ERROR, "wholerow is NULL");
999
1000                                         oldtupdata.t_data = DatumGetHeapTupleHeader(datum);
1001                                         oldtupdata.t_len =
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);
1008
1009                                         oldtuple = &oldtupdata;
1010                                 }
1011                                 else
1012                                         Assert(relkind == RELKIND_FOREIGN_TABLE);
1013                         }
1014
1015                         /*
1016                          * apply the junkfilter if needed.
1017                          */
1018                         if (operation != CMD_DELETE)
1019                                 slot = ExecFilterJunk(junkfilter, slot);
1020                 }
1021
1022                 switch (operation)
1023                 {
1024                         case CMD_INSERT:
1025                                 slot = ExecInsert(slot, planSlot, estate, node->canSetTag);
1026                                 break;
1027                         case CMD_UPDATE:
1028                                 slot = ExecUpdate(tupleid, oldtuple, slot, planSlot,
1029                                                                 &node->mt_epqstate, estate, node->canSetTag);
1030                                 break;
1031                         case CMD_DELETE:
1032                                 slot = ExecDelete(tupleid, oldtuple, planSlot,
1033                                                                 &node->mt_epqstate, estate, node->canSetTag);
1034                                 break;
1035                         default:
1036                                 elog(ERROR, "unknown operation");
1037                                 break;
1038                 }
1039
1040                 /*
1041                  * If we got a RETURNING result, return it to caller.  We'll continue
1042                  * the work on next call.
1043                  */
1044                 if (slot)
1045                 {
1046                         estate->es_result_relation_info = saved_resultRelInfo;
1047                         return slot;
1048                 }
1049         }
1050
1051         /* Restore es_result_relation_info before exiting */
1052         estate->es_result_relation_info = saved_resultRelInfo;
1053
1054         /*
1055          * We're done, but fire AFTER STATEMENT triggers before exiting.
1056          */
1057         fireASTriggers(node);
1058
1059         node->mt_done = true;
1060
1061         return NULL;
1062 }
1063
1064 /* ----------------------------------------------------------------
1065  *              ExecInitModifyTable
1066  * ----------------------------------------------------------------
1067  */
1068 ModifyTableState *
1069 ExecInitModifyTable(ModifyTable *node, EState *estate, int eflags)
1070 {
1071         ModifyTableState *mtstate;
1072         CmdType         operation = node->operation;
1073         int                     nplans = list_length(node->plans);
1074         ResultRelInfo *saved_resultRelInfo;
1075         ResultRelInfo *resultRelInfo;
1076         TupleDesc       tupDesc;
1077         Plan       *subplan;
1078         ListCell   *l;
1079         int                     i;
1080
1081         /* check for unsupported flags */
1082         Assert(!(eflags & (EXEC_FLAG_BACKWARD | EXEC_FLAG_MARK)));
1083
1084         /*
1085          * create state structure
1086          */
1087         mtstate = makeNode(ModifyTableState);
1088         mtstate->ps.plan = (Plan *) node;
1089         mtstate->ps.state = estate;
1090         mtstate->ps.targetlist = NIL;           /* not actually used */
1091
1092         mtstate->operation = operation;
1093         mtstate->canSetTag = node->canSetTag;
1094         mtstate->mt_done = false;
1095
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;
1100
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;
1104
1105         /*
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!
1112          */
1113         saved_resultRelInfo = estate->es_result_relation_info;
1114
1115         resultRelInfo = mtstate->resultRelInfo;
1116         i = 0;
1117         foreach(l, node->plans)
1118         {
1119                 subplan = (Plan *) lfirst(l);
1120
1121                 /*
1122                  * Verify result relation is a valid target for the current operation
1123                  */
1124                 CheckValidResultRel(resultRelInfo->ri_RelationDesc, operation);
1125
1126                 /*
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
1133                  * query.
1134                  */
1135                 if (resultRelInfo->ri_RelationDesc->rd_rel->relhasindex &&
1136                         operation != CMD_DELETE &&
1137                         resultRelInfo->ri_IndexRelationDescs == NULL)
1138                         ExecOpenIndices(resultRelInfo);
1139
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);
1143
1144                 /* Also let FDWs init themselves for foreign-table result rels */
1145                 if (resultRelInfo->ri_FdwRoutine != NULL &&
1146                         resultRelInfo->ri_FdwRoutine->BeginForeignModify != NULL)
1147                 {
1148                         List       *fdw_private = (List *) list_nth(node->fdwPrivLists, i);
1149
1150                         resultRelInfo->ri_FdwRoutine->BeginForeignModify(mtstate,
1151                                                                                                                          resultRelInfo,
1152                                                                                                                          fdw_private,
1153                                                                                                                          i,
1154                                                                                                                          eflags);
1155                 }
1156
1157                 resultRelInfo++;
1158                 i++;
1159         }
1160
1161         estate->es_result_relation_info = saved_resultRelInfo;
1162
1163         /*
1164          * Initialize any WITH CHECK OPTION constraints if needed.
1165          */
1166         resultRelInfo = mtstate->resultRelInfo;
1167         i = 0;
1168         foreach(l, node->withCheckOptionLists)
1169         {
1170                 List       *wcoList = (List *) lfirst(l);
1171                 List       *wcoExprs = NIL;
1172                 ListCell   *ll;
1173
1174                 foreach(ll, wcoList)
1175                 {
1176                         WithCheckOption *wco = (WithCheckOption *) lfirst(ll);
1177                         ExprState  *wcoExpr = ExecInitExpr((Expr *) wco->qual,
1178                                                                                            mtstate->mt_plans[i]);
1179
1180                         wcoExprs = lappend(wcoExprs, wcoExpr);
1181                 }
1182
1183                 resultRelInfo->ri_WithCheckOptions = wcoList;
1184                 resultRelInfo->ri_WithCheckOptionExprs = wcoExprs;
1185                 resultRelInfo++;
1186                 i++;
1187         }
1188
1189         /*
1190          * Initialize RETURNING projections if needed.
1191          */
1192         if (node->returningLists)
1193         {
1194                 TupleTableSlot *slot;
1195                 ExprContext *econtext;
1196
1197                 /*
1198                  * Initialize result tuple slot and assign its rowtype using the first
1199                  * RETURNING list.  We assume the rest will look the same.
1200                  */
1201                 tupDesc = ExecTypeFromTL((List *) linitial(node->returningLists),
1202                                                                  false);
1203
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;
1208
1209                 /* Need an econtext too */
1210                 econtext = CreateExprContext(estate);
1211                 mtstate->ps.ps_ExprContext = econtext;
1212
1213                 /*
1214                  * Build a projection for each result rel.
1215                  */
1216                 resultRelInfo = mtstate->resultRelInfo;
1217                 foreach(l, node->returningLists)
1218                 {
1219                         List       *rlist = (List *) lfirst(l);
1220                         List       *rliststate;
1221
1222                         rliststate = (List *) ExecInitExpr((Expr *) rlist, &mtstate->ps);
1223                         resultRelInfo->ri_projectReturning =
1224                                 ExecBuildProjectionInfo(rliststate, econtext, slot,
1225                                                                          resultRelInfo->ri_RelationDesc->rd_att);
1226                         resultRelInfo++;
1227                 }
1228         }
1229         else
1230         {
1231                 /*
1232                  * We still must construct a dummy result tuple type, because InitPlan
1233                  * expects one (maybe should change that?).
1234                  */
1235                 tupDesc = ExecTypeFromTL(NIL, false);
1236                 ExecInitResultTupleSlot(estate, &mtstate->ps);
1237                 ExecAssignResultType(&mtstate->ps, tupDesc);
1238
1239                 mtstate->ps.ps_ExprContext = NULL;
1240         }
1241
1242         /*
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.
1247          */
1248         foreach(l, node->rowMarks)
1249         {
1250                 PlanRowMark *rc = (PlanRowMark *) lfirst(l);
1251                 ExecRowMark *erm;
1252
1253                 Assert(IsA(rc, PlanRowMark));
1254
1255                 /* ignore "parent" rowmarks; they are irrelevant at runtime */
1256                 if (rc->isParent)
1257                         continue;
1258
1259                 /* find ExecRowMark (same for all subplans) */
1260                 erm = ExecFindRowMark(estate, rc->rti);
1261
1262                 /* build ExecAuxRowMark for each subplan */
1263                 for (i = 0; i < nplans; i++)
1264                 {
1265                         ExecAuxRowMark *aerm;
1266
1267                         subplan = mtstate->mt_plans[i]->plan;
1268                         aerm = ExecBuildAuxRowMark(erm, subplan->targetlist);
1269                         mtstate->mt_arowmarks[i] = lappend(mtstate->mt_arowmarks[i], aerm);
1270                 }
1271         }
1272
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]);
1278
1279         /*
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.
1284          *
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.
1288          *
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).
1291          */
1292         {
1293                 bool            junk_filter_needed = false;
1294
1295                 switch (operation)
1296                 {
1297                         case CMD_INSERT:
1298                                 foreach(l, subplan->targetlist)
1299                                 {
1300                                         TargetEntry *tle = (TargetEntry *) lfirst(l);
1301
1302                                         if (tle->resjunk)
1303                                         {
1304                                                 junk_filter_needed = true;
1305                                                 break;
1306                                         }
1307                                 }
1308                                 break;
1309                         case CMD_UPDATE:
1310                         case CMD_DELETE:
1311                                 junk_filter_needed = true;
1312                                 break;
1313                         default:
1314                                 elog(ERROR, "unknown operation");
1315                                 break;
1316                 }
1317
1318                 if (junk_filter_needed)
1319                 {
1320                         resultRelInfo = mtstate->resultRelInfo;
1321                         for (i = 0; i < nplans; i++)
1322                         {
1323                                 JunkFilter *j;
1324
1325                                 subplan = mtstate->mt_plans[i]->plan;
1326                                 if (operation == CMD_INSERT || operation == CMD_UPDATE)
1327                                         ExecCheckPlanOutput(resultRelInfo->ri_RelationDesc,
1328                                                                                 subplan->targetlist);
1329
1330                                 j = ExecInitJunkFilter(subplan->targetlist,
1331                                                         resultRelInfo->ri_RelationDesc->rd_att->tdhasoid,
1332                                                                            ExecInitExtraTupleSlot(estate));
1333
1334                                 if (operation == CMD_UPDATE || operation == CMD_DELETE)
1335                                 {
1336                                         /* For UPDATE/DELETE, find the appropriate junk attr now */
1337                                         char            relkind;
1338
1339                                         relkind = resultRelInfo->ri_RelationDesc->rd_rel->relkind;
1340                                         if (relkind == RELKIND_RELATION ||
1341                                                 relkind == RELKIND_MATVIEW)
1342                                         {
1343                                                 j->jf_junkAttNo = ExecFindJunkAttribute(j, "ctid");
1344                                                 if (!AttributeNumberIsValid(j->jf_junkAttNo))
1345                                                         elog(ERROR, "could not find junk ctid column");
1346                                         }
1347                                         else if (relkind == RELKIND_FOREIGN_TABLE)
1348                                         {
1349                                                 /*
1350                                                  * When there is an AFTER trigger, there should be a
1351                                                  * wholerow attribute.
1352                                                  */
1353                                                 j->jf_junkAttNo = ExecFindJunkAttribute(j, "wholerow");
1354                                         }
1355                                         else
1356                                         {
1357                                                 j->jf_junkAttNo = ExecFindJunkAttribute(j, "wholerow");
1358                                                 if (!AttributeNumberIsValid(j->jf_junkAttNo))
1359                                                         elog(ERROR, "could not find junk wholerow column");
1360                                         }
1361                                 }
1362
1363                                 resultRelInfo->ri_junkFilter = j;
1364                                 resultRelInfo++;
1365                         }
1366                 }
1367                 else
1368                 {
1369                         if (operation == CMD_INSERT)
1370                                 ExecCheckPlanOutput(mtstate->resultRelInfo->ri_RelationDesc,
1371                                                                         subplan->targetlist);
1372                 }
1373         }
1374
1375         /*
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.
1379          */
1380         if (estate->es_trig_tuple_slot == NULL)
1381                 estate->es_trig_tuple_slot = ExecInitExtraTupleSlot(estate);
1382
1383         /*
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.
1391          */
1392         if (!mtstate->canSetTag)
1393                 estate->es_auxmodifytables = lcons(mtstate,
1394                                                                                    estate->es_auxmodifytables);
1395
1396         return mtstate;
1397 }
1398
1399 /* ----------------------------------------------------------------
1400  *              ExecEndModifyTable
1401  *
1402  *              Shuts down the plan.
1403  *
1404  *              Returns nothing of interest.
1405  * ----------------------------------------------------------------
1406  */
1407 void
1408 ExecEndModifyTable(ModifyTableState *node)
1409 {
1410         int                     i;
1411
1412         /*
1413          * Allow any FDWs to shut down
1414          */
1415         for (i = 0; i < node->mt_nplans; i++)
1416         {
1417                 ResultRelInfo *resultRelInfo = node->resultRelInfo + i;
1418
1419                 if (resultRelInfo->ri_FdwRoutine != NULL &&
1420                         resultRelInfo->ri_FdwRoutine->EndForeignModify != NULL)
1421                         resultRelInfo->ri_FdwRoutine->EndForeignModify(node->ps.state,
1422                                                                                                                    resultRelInfo);
1423         }
1424
1425         /*
1426          * Free the exprcontext
1427          */
1428         ExecFreeExprContext(&node->ps);
1429
1430         /*
1431          * clean out the tuple table
1432          */
1433         ExecClearTuple(node->ps.ps_ResultTupleSlot);
1434
1435         /*
1436          * Terminate EPQ execution if active
1437          */
1438         EvalPlanQualEnd(&node->mt_epqstate);
1439
1440         /*
1441          * shut down subplans
1442          */
1443         for (i = 0; i < node->mt_nplans; i++)
1444                 ExecEndNode(node->mt_plans[i]);
1445 }
1446
1447 void
1448 ExecReScanModifyTable(ModifyTableState *node)
1449 {
1450         /*
1451          * Currently, we don't need to support rescan on ModifyTable nodes. The
1452          * semantics of that would be a bit debatable anyway.
1453          */
1454         elog(ERROR, "ExecReScanModifyTable is not implemented");
1455 }