OSDN Git Service

c0eab4bf0db894dce689bfcabbde4d7e281b7714
[pg-rex/syncrep.git] / src / backend / executor / nodeModifyTable.c
1 /*-------------------------------------------------------------------------
2  *
3  * nodeModifyTable.c
4  *        routines to handle ModifyTable nodes.
5  *
6  * Portions Copyright (c) 1996-2011, 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/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"
50
51
52 /*
53  * Verify that the tuples to be produced by INSERT or UPDATE match the
54  * target relation's rowtype
55  *
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.
60  *
61  * The plan output is represented by its targetlist, because that makes
62  * handling the dropped-column case easier.
63  */
64 static void
65 ExecCheckPlanOutput(Relation resultRel, List *targetList)
66 {
67         TupleDesc       resultDesc = RelationGetDescr(resultRel);
68         int                     attno = 0;
69         ListCell   *lc;
70
71         foreach(lc, targetList)
72         {
73                 TargetEntry *tle = (TargetEntry *) lfirst(lc);
74                 Form_pg_attribute attr;
75
76                 if (tle->resjunk)
77                         continue;                       /* ignore junk tlist items */
78
79                 if (attno >= resultDesc->natts)
80                         ereport(ERROR,
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++];
85
86                 if (!attr->attisdropped)
87                 {
88                         /* Normal case: demand type match */
89                         if (exprType((Node *) tle->expr) != attr->atttypid)
90                                 ereport(ERROR,
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),
95                                                                    attno,
96                                                          format_type_be(exprType((Node *) tle->expr)))));
97                 }
98                 else
99                 {
100                         /*
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.
104                          */
105                         if (!IsA(tle->expr, Const) ||
106                                 !((Const *) tle->expr)->constisnull)
107                                 ereport(ERROR,
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.",
111                                                                    attno)));
112                 }
113         }
114         if (attno != resultDesc->natts)
115                 ereport(ERROR,
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.")));
119 }
120
121 /*
122  * ExecProcessReturning --- evaluate a RETURNING list
123  *
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
127  *
128  * Returns a slot holding the result tuple
129  */
130 static TupleTableSlot *
131 ExecProcessReturning(ProjectionInfo *projectReturning,
132                                          TupleTableSlot *tupleSlot,
133                                          TupleTableSlot *planSlot)
134 {
135         ExprContext *econtext = projectReturning->pi_exprContext;
136
137         /*
138          * Reset per-tuple memory context to free any expression evaluation
139          * storage allocated in the previous cycle.
140          */
141         ResetExprContext(econtext);
142
143         /* Make tuple and any needed join variables available to ExecProject */
144         econtext->ecxt_scantuple = tupleSlot;
145         econtext->ecxt_outertuple = planSlot;
146
147         /* Compute the RETURNING expressions */
148         return ExecProject(projectReturning, NULL);
149 }
150
151 /* ----------------------------------------------------------------
152  *              ExecInsert
153  *
154  *              For INSERT, we have to insert the tuple into the target relation
155  *              and insert appropriate tuples into the index relations.
156  *
157  *              Returns RETURNING result if any, otherwise NULL.
158  * ----------------------------------------------------------------
159  */
160 static TupleTableSlot *
161 ExecInsert(TupleTableSlot *slot,
162                    TupleTableSlot *planSlot,
163                    EState *estate,
164                    bool canSetTag)
165 {
166         HeapTuple       tuple;
167         ResultRelInfo *resultRelInfo;
168         Relation        resultRelationDesc;
169         Oid                     newId;
170         List       *recheckIndexes = NIL;
171
172         /*
173          * get the heap tuple out of the tuple table slot, making sure we have a
174          * writable copy
175          */
176         tuple = ExecMaterializeSlot(slot);
177
178         /*
179          * get information on the (current) result relation
180          */
181         resultRelInfo = estate->es_result_relation_info;
182         resultRelationDesc = resultRelInfo->ri_RelationDesc;
183
184         /*
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
189          * rowtype.
190          *
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.
195          */
196         if (resultRelationDesc->rd_rel->relhasoids)
197                 HeapTupleSetOid(tuple, InvalidOid);
198
199         /* BEFORE ROW INSERT Triggers */
200         if (resultRelInfo->ri_TrigDesc &&
201                 resultRelInfo->ri_TrigDesc->trig_insert_before_row)
202         {
203                 slot = ExecBRInsertTriggers(estate, resultRelInfo, slot);
204
205                 if (slot == NULL)               /* "do nothing" */
206                         return NULL;
207
208                 /* trigger might have changed tuple */
209                 tuple = ExecMaterializeSlot(slot);
210         }
211
212         /* INSTEAD OF ROW INSERT Triggers */
213         if (resultRelInfo->ri_TrigDesc &&
214                 resultRelInfo->ri_TrigDesc->trig_insert_instead_row)
215         {
216                 slot = ExecIRInsertTriggers(estate, resultRelInfo, slot);
217
218                 if (slot == NULL)               /* "do nothing" */
219                         return NULL;
220
221                 /* trigger might have changed tuple */
222                 tuple = ExecMaterializeSlot(slot);
223
224                 newId = InvalidOid;
225         }
226         else
227         {
228                 /*
229                  * Check the constraints of the tuple
230                  */
231                 if (resultRelationDesc->rd_att->constr)
232                         ExecConstraints(resultRelInfo, slot, estate);
233
234                 /*
235                  * insert the tuple
236                  *
237                  * Note: heap_insert returns the tid (location) of the new tuple in
238                  * the t_self field.
239                  */
240                 newId = heap_insert(resultRelationDesc, tuple,
241                                                         estate->es_output_cid, 0, NULL);
242
243                 /*
244                  * insert index entries for tuple
245                  */
246                 if (resultRelInfo->ri_NumIndices > 0)
247                         recheckIndexes = ExecInsertIndexTuples(slot, &(tuple->t_self),
248                                                                                                    estate);
249         }
250
251         if (canSetTag)
252         {
253                 (estate->es_processed)++;
254                 estate->es_lastoid = newId;
255                 setLastTid(&(tuple->t_self));
256         }
257
258         /* AFTER ROW INSERT Triggers */
259         ExecARInsertTriggers(estate, resultRelInfo, tuple, recheckIndexes);
260
261         list_free(recheckIndexes);
262
263         /* Process RETURNING if present */
264         if (resultRelInfo->ri_projectReturning)
265                 return ExecProcessReturning(resultRelInfo->ri_projectReturning,
266                                                                         slot, planSlot);
267
268         return NULL;
269 }
270
271 /* ----------------------------------------------------------------
272  *              ExecDelete
273  *
274  *              DELETE is like UPDATE, except that we delete the tuple and no
275  *              index modifications are needed.
276  *
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.
281  *
282  *              Returns RETURNING result if any, otherwise NULL.
283  * ----------------------------------------------------------------
284  */
285 static TupleTableSlot *
286 ExecDelete(ItemPointer tupleid,
287                    HeapTupleHeader oldtuple,
288                    TupleTableSlot *planSlot,
289                    EPQState *epqstate,
290                    EState *estate,
291                    bool canSetTag)
292 {
293         ResultRelInfo *resultRelInfo;
294         Relation        resultRelationDesc;
295         HTSU_Result result;
296         ItemPointerData update_ctid;
297         TransactionId update_xmax;
298
299         /*
300          * get information on the (current) result relation
301          */
302         resultRelInfo = estate->es_result_relation_info;
303         resultRelationDesc = resultRelInfo->ri_RelationDesc;
304
305         /* BEFORE ROW DELETE Triggers */
306         if (resultRelInfo->ri_TrigDesc &&
307                 resultRelInfo->ri_TrigDesc->trig_delete_before_row)
308         {
309                 bool            dodelete;
310
311                 dodelete = ExecBRDeleteTriggers(estate, epqstate, resultRelInfo,
312                                                                                 tupleid);
313
314                 if (!dodelete)                  /* "do nothing" */
315                         return NULL;
316         }
317
318         /* INSTEAD OF ROW DELETE Triggers */
319         if (resultRelInfo->ri_TrigDesc &&
320                 resultRelInfo->ri_TrigDesc->trig_delete_instead_row)
321         {
322                 HeapTupleData tuple;
323                 bool            dodelete;
324
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;
330
331                 dodelete = ExecIRDeleteTriggers(estate, resultRelInfo, &tuple);
332
333                 if (!dodelete)                  /* "do nothing" */
334                         return NULL;
335         }
336         else
337         {
338                 /*
339                  * delete the tuple
340                  *
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
345                  * mode transactions.
346                  */
347 ldelete:;
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 */ );
353                 switch (result)
354                 {
355                         case HeapTupleSelfUpdated:
356                                 /* already deleted by self; nothing to do */
357                                 return NULL;
358
359                         case HeapTupleMayBeUpdated:
360                                 break;
361
362                         case HeapTupleUpdated:
363                                 if (IsolationUsesXactSnapshot())
364                                         ereport(ERROR,
365                                                         (errcode(ERRCODE_T_R_SERIALIZATION_FAILURE),
366                                                          errmsg("could not serialize access due to concurrent update")));
367                                 if (!ItemPointerEquals(tupleid, &update_ctid))
368                                 {
369                                         TupleTableSlot *epqslot;
370
371                                         epqslot = EvalPlanQual(estate,
372                                                                                    epqstate,
373                                                                                    resultRelationDesc,
374                                                                                    resultRelInfo->ri_RangeTableIndex,
375                                                                                    &update_ctid,
376                                                                                    update_xmax);
377                                         if (!TupIsNull(epqslot))
378                                         {
379                                                 *tupleid = update_ctid;
380                                                 goto ldelete;
381                                         }
382                                 }
383                                 /* tuple already deleted; nothing to do */
384                                 return NULL;
385
386                         default:
387                                 elog(ERROR, "unrecognized heap_delete status: %u", result);
388                                 return NULL;
389                 }
390
391                 /*
392                  * Note: Normally one would think that we have to delete index tuples
393                  * associated with the heap tuple now...
394                  *
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.
398                  */
399         }
400
401         if (canSetTag)
402                 (estate->es_processed)++;
403
404         /* AFTER ROW DELETE Triggers */
405         ExecARDeleteTriggers(estate, resultRelInfo, tupleid);
406
407         /* Process RETURNING if present */
408         if (resultRelInfo->ri_projectReturning)
409         {
410                 /*
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.
413                  */
414                 TupleTableSlot *slot = estate->es_trig_tuple_slot;
415                 TupleTableSlot *rslot;
416                 HeapTupleData deltuple;
417                 Buffer          delbuffer;
418
419                 if (oldtuple != NULL)
420                 {
421                         deltuple.t_data = oldtuple;
422                         deltuple.t_len = HeapTupleHeaderGetDatumLength(oldtuple);
423                         ItemPointerSetInvalid(&(deltuple.t_self));
424                         deltuple.t_tableOid = InvalidOid;
425                         delbuffer = InvalidBuffer;
426                 }
427                 else
428                 {
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");
433                 }
434
435                 if (slot->tts_tupleDescriptor != RelationGetDescr(resultRelationDesc))
436                         ExecSetSlotDescriptor(slot, RelationGetDescr(resultRelationDesc));
437                 ExecStoreTuple(&deltuple, slot, InvalidBuffer, false);
438
439                 rslot = ExecProcessReturning(resultRelInfo->ri_projectReturning,
440                                                                          slot, planSlot);
441
442                 ExecClearTuple(slot);
443                 if (BufferIsValid(delbuffer))
444                         ReleaseBuffer(delbuffer);
445
446                 return rslot;
447         }
448
449         return NULL;
450 }
451
452 /* ----------------------------------------------------------------
453  *              ExecUpdate
454  *
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..
461  *
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.
466  *
467  *              Returns RETURNING result if any, otherwise NULL.
468  * ----------------------------------------------------------------
469  */
470 static TupleTableSlot *
471 ExecUpdate(ItemPointer tupleid,
472                    HeapTupleHeader oldtuple,
473                    TupleTableSlot *slot,
474                    TupleTableSlot *planSlot,
475                    EPQState *epqstate,
476                    EState *estate,
477                    bool canSetTag)
478 {
479         HeapTuple       tuple;
480         ResultRelInfo *resultRelInfo;
481         Relation        resultRelationDesc;
482         HTSU_Result result;
483         ItemPointerData update_ctid;
484         TransactionId update_xmax;
485         List       *recheckIndexes = NIL;
486
487         /*
488          * abort the operation if not running transactions
489          */
490         if (IsBootstrapProcessingMode())
491                 elog(ERROR, "cannot UPDATE during bootstrap");
492
493         /*
494          * get the heap tuple out of the tuple table slot, making sure we have a
495          * writable copy
496          */
497         tuple = ExecMaterializeSlot(slot);
498
499         /*
500          * get information on the (current) result relation
501          */
502         resultRelInfo = estate->es_result_relation_info;
503         resultRelationDesc = resultRelInfo->ri_RelationDesc;
504
505         /* BEFORE ROW UPDATE Triggers */
506         if (resultRelInfo->ri_TrigDesc &&
507                 resultRelInfo->ri_TrigDesc->trig_update_before_row)
508         {
509                 slot = ExecBRUpdateTriggers(estate, epqstate, resultRelInfo,
510                                                                         tupleid, slot);
511
512                 if (slot == NULL)               /* "do nothing" */
513                         return NULL;
514
515                 /* trigger might have changed tuple */
516                 tuple = ExecMaterializeSlot(slot);
517         }
518
519         /* INSTEAD OF ROW UPDATE Triggers */
520         if (resultRelInfo->ri_TrigDesc &&
521                 resultRelInfo->ri_TrigDesc->trig_update_instead_row)
522         {
523                 HeapTupleData oldtup;
524
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;
530
531                 slot = ExecIRUpdateTriggers(estate, resultRelInfo,
532                                                                         &oldtup, slot);
533
534                 if (slot == NULL)               /* "do nothing" */
535                         return NULL;
536
537                 /* trigger might have changed tuple */
538                 tuple = ExecMaterializeSlot(slot);
539         }
540         else
541         {
542                 /*
543                  * Check the constraints of the tuple
544                  *
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.)
550                  */
551 lreplace:;
552                 if (resultRelationDesc->rd_att->constr)
553                         ExecConstraints(resultRelInfo, slot, estate);
554
555                 /*
556                  * replace the heap tuple
557                  *
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
562                  * mode transactions.
563                  */
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 */ );
569                 switch (result)
570                 {
571                         case HeapTupleSelfUpdated:
572                                 /* already deleted by self; nothing to do */
573                                 return NULL;
574
575                         case HeapTupleMayBeUpdated:
576                                 break;
577
578                         case HeapTupleUpdated:
579                                 if (IsolationUsesXactSnapshot())
580                                         ereport(ERROR,
581                                                         (errcode(ERRCODE_T_R_SERIALIZATION_FAILURE),
582                                                          errmsg("could not serialize access due to concurrent update")));
583                                 if (!ItemPointerEquals(tupleid, &update_ctid))
584                                 {
585                                         TupleTableSlot *epqslot;
586
587                                         epqslot = EvalPlanQual(estate,
588                                                                                    epqstate,
589                                                                                    resultRelationDesc,
590                                                                                    resultRelInfo->ri_RangeTableIndex,
591                                                                                    &update_ctid,
592                                                                                    update_xmax);
593                                         if (!TupIsNull(epqslot))
594                                         {
595                                                 *tupleid = update_ctid;
596                                                 slot = ExecFilterJunk(resultRelInfo->ri_junkFilter, epqslot);
597                                                 tuple = ExecMaterializeSlot(slot);
598                                                 goto lreplace;
599                                         }
600                                 }
601                                 /* tuple already deleted; nothing to do */
602                                 return NULL;
603
604                         default:
605                                 elog(ERROR, "unrecognized heap_update status: %u", result);
606                                 return NULL;
607                 }
608
609                 /*
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
615                  */
616
617                 /*
618                  * insert index entries for tuple
619                  *
620                  * Note: heap_update returns the tid (location) of the new tuple in
621                  * the t_self field.
622                  *
623                  * If it's a HOT update, we mustn't insert new index entries.
624                  */
625                 if (resultRelInfo->ri_NumIndices > 0 && !HeapTupleIsHeapOnly(tuple))
626                         recheckIndexes = ExecInsertIndexTuples(slot, &(tuple->t_self),
627                                                                                                    estate);
628         }
629
630         if (canSetTag)
631                 (estate->es_processed)++;
632
633         /* AFTER ROW UPDATE Triggers */
634         ExecARUpdateTriggers(estate, resultRelInfo, tupleid, tuple,
635                                                  recheckIndexes);
636
637         list_free(recheckIndexes);
638
639         /* Process RETURNING if present */
640         if (resultRelInfo->ri_projectReturning)
641                 return ExecProcessReturning(resultRelInfo->ri_projectReturning,
642                                                                         slot, planSlot);
643
644         return NULL;
645 }
646
647
648 /*
649  * Process BEFORE EACH STATEMENT triggers
650  */
651 static void
652 fireBSTriggers(ModifyTableState *node)
653 {
654         switch (node->operation)
655         {
656                 case CMD_INSERT:
657                         ExecBSInsertTriggers(node->ps.state, node->resultRelInfo);
658                         break;
659                 case CMD_UPDATE:
660                         ExecBSUpdateTriggers(node->ps.state, node->resultRelInfo);
661                         break;
662                 case CMD_DELETE:
663                         ExecBSDeleteTriggers(node->ps.state, node->resultRelInfo);
664                         break;
665                 default:
666                         elog(ERROR, "unknown operation");
667                         break;
668         }
669 }
670
671 /*
672  * Process AFTER EACH STATEMENT triggers
673  */
674 static void
675 fireASTriggers(ModifyTableState *node)
676 {
677         switch (node->operation)
678         {
679                 case CMD_INSERT:
680                         ExecASInsertTriggers(node->ps.state, node->resultRelInfo);
681                         break;
682                 case CMD_UPDATE:
683                         ExecASUpdateTriggers(node->ps.state, node->resultRelInfo);
684                         break;
685                 case CMD_DELETE:
686                         ExecASDeleteTriggers(node->ps.state, node->resultRelInfo);
687                         break;
688                 default:
689                         elog(ERROR, "unknown operation");
690                         break;
691         }
692 }
693
694
695 /* ----------------------------------------------------------------
696  *         ExecModifyTable
697  *
698  *              Perform table modifications as required, and return RETURNING results
699  *              if needed.
700  * ----------------------------------------------------------------
701  */
702 TupleTableSlot *
703 ExecModifyTable(ModifyTableState *node)
704 {
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;
716
717         /*
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
721          * extra times.
722          */
723         if (node->mt_done)
724                 return NULL;
725
726         /*
727          * On first call, fire BEFORE STATEMENT triggers before proceeding.
728          */
729         if (node->fireBSTriggers)
730         {
731                 fireBSTriggers(node);
732                 node->fireBSTriggers = false;
733         }
734
735         /* Preload local variables */
736         resultRelInfo = node->resultRelInfo + node->mt_whichplan;
737         subplanstate = node->mt_plans[node->mt_whichplan];
738         junkfilter = resultRelInfo->ri_junkFilter;
739
740         /*
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.
746          */
747         saved_resultRelInfo = estate->es_result_relation_info;
748
749         estate->es_result_relation_info = resultRelInfo;
750
751         /*
752          * Fetch rows from subplan(s), and execute the required table modification
753          * for each row.
754          */
755         for (;;)
756         {
757                 /*
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.
762                  */
763                 ResetPerTupleExprContext(estate);
764
765                 planSlot = ExecProcNode(subplanstate);
766
767                 if (TupIsNull(planSlot))
768                 {
769                         /* advance to next subplan if any */
770                         node->mt_whichplan++;
771                         if (node->mt_whichplan < node->mt_nplans)
772                         {
773                                 resultRelInfo++;
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]);
779                                 continue;
780                         }
781                         else
782                                 break;
783                 }
784
785                 EvalPlanQualSetSlot(&node->mt_epqstate, planSlot);
786                 slot = planSlot;
787
788                 if (junkfilter != NULL)
789                 {
790                         /*
791                          * extract the 'ctid' or 'wholerow' junk attribute.
792                          */
793                         if (operation == CMD_UPDATE || operation == CMD_DELETE)
794                         {
795                                 Datum           datum;
796                                 bool            isNull;
797
798                                 if (resultRelInfo->ri_RelationDesc->rd_rel->relkind == RELKIND_RELATION)
799                                 {
800                                         datum = ExecGetJunkAttribute(slot,
801                                                                                                  junkfilter->jf_junkAttNo,
802                                                                                                  &isNull);
803                                         /* shouldn't ever get a null result... */
804                                         if (isNull)
805                                                 elog(ERROR, "ctid is NULL");
806
807                                         tupleid = (ItemPointer) DatumGetPointer(datum);
808                                         tuple_ctid = *tupleid;          /* be sure we don't free
809                                                                                                  * ctid!! */
810                                         tupleid = &tuple_ctid;
811                                 }
812                                 else
813                                 {
814                                         datum = ExecGetJunkAttribute(slot,
815                                                                                                  junkfilter->jf_junkAttNo,
816                                                                                                  &isNull);
817                                         /* shouldn't ever get a null result... */
818                                         if (isNull)
819                                                 elog(ERROR, "wholerow is NULL");
820
821                                         oldtuple = DatumGetHeapTupleHeader(datum);
822                                 }
823                         }
824
825                         /*
826                          * apply the junkfilter if needed.
827                          */
828                         if (operation != CMD_DELETE)
829                                 slot = ExecFilterJunk(junkfilter, slot);
830                 }
831
832                 switch (operation)
833                 {
834                         case CMD_INSERT:
835                                 slot = ExecInsert(slot, planSlot, estate, node->canSetTag);
836                                 break;
837                         case CMD_UPDATE:
838                                 slot = ExecUpdate(tupleid, oldtuple, slot, planSlot,
839                                                                 &node->mt_epqstate, estate, node->canSetTag);
840                                 break;
841                         case CMD_DELETE:
842                                 slot = ExecDelete(tupleid, oldtuple, planSlot,
843                                                                 &node->mt_epqstate, estate, node->canSetTag);
844                                 break;
845                         default:
846                                 elog(ERROR, "unknown operation");
847                                 break;
848                 }
849
850                 /*
851                  * If we got a RETURNING result, return it to caller.  We'll continue
852                  * the work on next call.
853                  */
854                 if (slot)
855                 {
856                         estate->es_result_relation_info = saved_resultRelInfo;
857                         return slot;
858                 }
859         }
860
861         /* Restore es_result_relation_info before exiting */
862         estate->es_result_relation_info = saved_resultRelInfo;
863
864         /*
865          * We're done, but fire AFTER STATEMENT triggers before exiting.
866          */
867         fireASTriggers(node);
868
869         node->mt_done = true;
870
871         return NULL;
872 }
873
874 /* ----------------------------------------------------------------
875  *              ExecInitModifyTable
876  * ----------------------------------------------------------------
877  */
878 ModifyTableState *
879 ExecInitModifyTable(ModifyTable *node, EState *estate, int eflags)
880 {
881         ModifyTableState *mtstate;
882         CmdType         operation = node->operation;
883         int                     nplans = list_length(node->plans);
884         ResultRelInfo *saved_resultRelInfo;
885         ResultRelInfo *resultRelInfo;
886         TupleDesc       tupDesc;
887         Plan       *subplan;
888         ListCell   *l;
889         int                     i;
890
891         /* check for unsupported flags */
892         Assert(!(eflags & (EXEC_FLAG_BACKWARD | EXEC_FLAG_MARK)));
893
894         /*
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 ...
898          */
899         if (estate->es_epqTuple != NULL)
900                 elog(ERROR, "ModifyTable should not be called during EvalPlanQual");
901
902         /*
903          * create state structure
904          */
905         mtstate = makeNode(ModifyTableState);
906         mtstate->ps.plan = (Plan *) node;
907         mtstate->ps.state = estate;
908         mtstate->ps.targetlist = NIL;           /* not actually used */
909
910         mtstate->operation = operation;
911         mtstate->canSetTag = node->canSetTag;
912         mtstate->mt_done = false;
913
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;
918
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;
922
923         /*
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!
930          */
931         saved_resultRelInfo = estate->es_result_relation_info;
932
933         resultRelInfo = mtstate->resultRelInfo;
934         i = 0;
935         foreach(l, node->plans)
936         {
937                 subplan = (Plan *) lfirst(l);
938
939                 /*
940                  * Verify result relation is a valid target for the current operation
941                  */
942                 CheckValidResultRel(resultRelInfo->ri_RelationDesc, operation);
943
944                 /*
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.
949                  */
950                 if (resultRelInfo->ri_RelationDesc->rd_rel->relhasindex &&
951                         operation != CMD_DELETE)
952                         ExecOpenIndices(resultRelInfo);
953
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);
957
958                 resultRelInfo++;
959                 i++;
960         }
961
962         estate->es_result_relation_info = saved_resultRelInfo;
963
964         /*
965          * Initialize RETURNING projections if needed.
966          */
967         if (node->returningLists)
968         {
969                 TupleTableSlot *slot;
970                 ExprContext *econtext;
971
972                 /*
973                  * Initialize result tuple slot and assign its rowtype using the first
974                  * RETURNING list.      We assume the rest will look the same.
975                  */
976                 tupDesc = ExecTypeFromTL((List *) linitial(node->returningLists),
977                                                                  false);
978
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;
983
984                 /* Need an econtext too */
985                 econtext = CreateExprContext(estate);
986                 mtstate->ps.ps_ExprContext = econtext;
987
988                 /*
989                  * Build a projection for each result rel.
990                  */
991                 resultRelInfo = mtstate->resultRelInfo;
992                 foreach(l, node->returningLists)
993                 {
994                         List       *rlist = (List *) lfirst(l);
995                         List       *rliststate;
996
997                         rliststate = (List *) ExecInitExpr((Expr *) rlist, &mtstate->ps);
998                         resultRelInfo->ri_projectReturning =
999                                 ExecBuildProjectionInfo(rliststate, econtext, slot,
1000                                                                          resultRelInfo->ri_RelationDesc->rd_att);
1001                         resultRelInfo++;
1002                 }
1003         }
1004         else
1005         {
1006                 /*
1007                  * We still must construct a dummy result tuple type, because InitPlan
1008                  * expects one (maybe should change that?).
1009                  */
1010                 tupDesc = ExecTypeFromTL(NIL, false);
1011                 ExecInitResultTupleSlot(estate, &mtstate->ps);
1012                 ExecAssignResultType(&mtstate->ps, tupDesc);
1013
1014                 mtstate->ps.ps_ExprContext = NULL;
1015         }
1016
1017         /*
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.
1022          */
1023         foreach(l, node->rowMarks)
1024         {
1025                 PlanRowMark *rc = (PlanRowMark *) lfirst(l);
1026                 ExecRowMark *erm;
1027
1028                 Assert(IsA(rc, PlanRowMark));
1029
1030                 /* ignore "parent" rowmarks; they are irrelevant at runtime */
1031                 if (rc->isParent)
1032                         continue;
1033
1034                 /* find ExecRowMark (same for all subplans) */
1035                 erm = ExecFindRowMark(estate, rc->rti);
1036
1037                 /* build ExecAuxRowMark for each subplan */
1038                 for (i = 0; i < nplans; i++)
1039                 {
1040                         ExecAuxRowMark *aerm;
1041
1042                         subplan = mtstate->mt_plans[i]->plan;
1043                         aerm = ExecBuildAuxRowMark(erm, subplan->targetlist);
1044                         mtstate->mt_arowmarks[i] = lappend(mtstate->mt_arowmarks[i], aerm);
1045                 }
1046         }
1047
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]);
1053
1054         /*
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.
1059          *
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.
1063          *
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).
1066          */
1067         {
1068                 bool            junk_filter_needed = false;
1069
1070                 switch (operation)
1071                 {
1072                         case CMD_INSERT:
1073                                 foreach(l, subplan->targetlist)
1074                                 {
1075                                         TargetEntry *tle = (TargetEntry *) lfirst(l);
1076
1077                                         if (tle->resjunk)
1078                                         {
1079                                                 junk_filter_needed = true;
1080                                                 break;
1081                                         }
1082                                 }
1083                                 break;
1084                         case CMD_UPDATE:
1085                         case CMD_DELETE:
1086                                 junk_filter_needed = true;
1087                                 break;
1088                         default:
1089                                 elog(ERROR, "unknown operation");
1090                                 break;
1091                 }
1092
1093                 if (junk_filter_needed)
1094                 {
1095                         resultRelInfo = mtstate->resultRelInfo;
1096                         for (i = 0; i < nplans; i++)
1097                         {
1098                                 JunkFilter *j;
1099
1100                                 subplan = mtstate->mt_plans[i]->plan;
1101                                 if (operation == CMD_INSERT || operation == CMD_UPDATE)
1102                                         ExecCheckPlanOutput(resultRelInfo->ri_RelationDesc,
1103                                                                                 subplan->targetlist);
1104
1105                                 j = ExecInitJunkFilter(subplan->targetlist,
1106                                                         resultRelInfo->ri_RelationDesc->rd_att->tdhasoid,
1107                                                                            ExecInitExtraTupleSlot(estate));
1108
1109                                 if (operation == CMD_UPDATE || operation == CMD_DELETE)
1110                                 {
1111                                         /* For UPDATE/DELETE, find the appropriate junk attr now */
1112                                         if (resultRelInfo->ri_RelationDesc->rd_rel->relkind == RELKIND_RELATION)
1113                                         {
1114                                                 j->jf_junkAttNo = ExecFindJunkAttribute(j, "ctid");
1115                                                 if (!AttributeNumberIsValid(j->jf_junkAttNo))
1116                                                         elog(ERROR, "could not find junk ctid column");
1117                                         }
1118                                         else
1119                                         {
1120                                                 j->jf_junkAttNo = ExecFindJunkAttribute(j, "wholerow");
1121                                                 if (!AttributeNumberIsValid(j->jf_junkAttNo))
1122                                                         elog(ERROR, "could not find junk wholerow column");
1123                                         }
1124                                 }
1125
1126                                 resultRelInfo->ri_junkFilter = j;
1127                                 resultRelInfo++;
1128                         }
1129                 }
1130                 else
1131                 {
1132                         if (operation == CMD_INSERT)
1133                                 ExecCheckPlanOutput(mtstate->resultRelInfo->ri_RelationDesc,
1134                                                                         subplan->targetlist);
1135                 }
1136         }
1137
1138         /*
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.
1142          */
1143         if (estate->es_trig_tuple_slot == NULL)
1144                 estate->es_trig_tuple_slot = ExecInitExtraTupleSlot(estate);
1145
1146         /*
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.
1154          */
1155         if (!mtstate->canSetTag)
1156                 estate->es_auxmodifytables = lcons(mtstate,
1157                                                                                    estate->es_auxmodifytables);
1158
1159         return mtstate;
1160 }
1161
1162 /* ----------------------------------------------------------------
1163  *              ExecEndModifyTable
1164  *
1165  *              Shuts down the plan.
1166  *
1167  *              Returns nothing of interest.
1168  * ----------------------------------------------------------------
1169  */
1170 void
1171 ExecEndModifyTable(ModifyTableState *node)
1172 {
1173         int                     i;
1174
1175         /*
1176          * Free the exprcontext
1177          */
1178         ExecFreeExprContext(&node->ps);
1179
1180         /*
1181          * clean out the tuple table
1182          */
1183         ExecClearTuple(node->ps.ps_ResultTupleSlot);
1184
1185         /*
1186          * Terminate EPQ execution if active
1187          */
1188         EvalPlanQualEnd(&node->mt_epqstate);
1189
1190         /*
1191          * shut down subplans
1192          */
1193         for (i = 0; i < node->mt_nplans; i++)
1194                 ExecEndNode(node->mt_plans[i]);
1195 }
1196
1197 void
1198 ExecReScanModifyTable(ModifyTableState *node)
1199 {
1200         /*
1201          * Currently, we don't need to support rescan on ModifyTable nodes. The
1202          * semantics of that would be a bit debatable anyway.
1203          */
1204         elog(ERROR, "ExecReScanModifyTable is not implemented");
1205 }