Debian Codegraph @

src/backend/executor/nodeModifyTable.c

raw
1 /*-------------------------------------------------------------------------
2 *
3 * nodeModifyTable.c
4 * routines to handle ModifyTable nodes.
5 *
6 * Portions Copyright (c) 1996-2025, 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 * The ModifyTable node receives input from its outerPlan, which is
23 * the data to insert for INSERT cases, the changed columns' new
24 * values plus row-locating info for UPDATE and MERGE cases, or just the
25 * row-locating info for DELETE cases.
26 *
27 * The relation to modify can be an ordinary table, a foreign table, or a
28 * view. If it's a view, either it has sufficient INSTEAD OF triggers or
29 * this node executes only MERGE ... DO NOTHING. If the original MERGE
30 * targeted a view not in one of those two categories, earlier processing
31 * already pointed the ModifyTable result relation to an underlying
32 * relation of that other view. This node does process
33 * ri_WithCheckOptions, which may have expressions from those other,
34 * automatically updatable views.
35 *
36 * MERGE runs a join between the source relation and the target table.
37 * If any WHEN NOT MATCHED [BY TARGET] clauses are present, then the join
38 * is an outer join that might output tuples without a matching target
39 * tuple. In this case, any unmatched target tuples will have NULL
40 * row-locating info, and only INSERT can be run. But for matched target
41 * tuples, the row-locating info is used to determine the tuple to UPDATE
42 * or DELETE. When all clauses are WHEN MATCHED or WHEN NOT MATCHED BY
43 * SOURCE, all tuples produced by the join will include a matching target
44 * tuple, so all tuples contain row-locating info.
45 *
46 * If the query specifies RETURNING, then the ModifyTable returns a
47 * RETURNING tuple after completing each row insert, update, or delete.
48 * It must be called again to continue the operation. Without RETURNING,
49 * we just loop within the node until all the work is done, then
50 * return NULL. This avoids useless call/return overhead.
51 */
52
53 #include "postgres.h"
54
55 #include "access/htup_details.h"
56 #include "access/tableam.h"
57 #include "access/xact.h"
58 #include "commands/trigger.h"
59 #include "executor/execPartition.h"
60 #include "executor/executor.h"
61 #include "executor/nodeModifyTable.h"
62 #include "foreign/fdwapi.h"
63 #include "miscadmin.h"
64 #include "nodes/nodeFuncs.h"
65 #include "optimizer/optimizer.h"
66 #include "rewrite/rewriteHandler.h"
67 #include "rewrite/rewriteManip.h"
68 #include "storage/lmgr.h"
69 #include "utils/builtins.h"
70 #include "utils/datum.h"
71 #include "utils/rel.h"
72 #include "utils/snapmgr.h"
73
74
75 typedef struct MTTargetRelLookup
76 {
77 Oid relationOid; /* hash key, must be first */
78 int relationIndex; /* rel's index in resultRelInfo[] array */
79 } MTTargetRelLookup;
80
81 /*
82 * Context struct for a ModifyTable operation, containing basic execution
83 * state and some output variables populated by ExecUpdateAct() and
84 * ExecDeleteAct() to report the result of their actions to callers.
85 */
86 typedef struct ModifyTableContext
87 {
88 /* Operation state */
89 ModifyTableState *mtstate;
90 EPQState *epqstate;
91 EState *estate;
92
93 /*
94 * Slot containing tuple obtained from ModifyTable's subplan. Used to
95 * access "junk" columns that are not going to be stored.
96 */
97 TupleTableSlot *planSlot;
98
99 /*
100 * Information about the changes that were made concurrently to a tuple
101 * being updated or deleted
102 */
103 TM_FailureData tmfd;
104
105 /*
106 * The tuple deleted when doing a cross-partition UPDATE with a RETURNING
107 * clause that refers to OLD columns (converted to the root's tuple
108 * descriptor).
109 */
110 TupleTableSlot *cpDeletedSlot;
111
112 /*
113 * The tuple projected by the INSERT's RETURNING clause, when doing a
114 * cross-partition UPDATE
115 */
116 TupleTableSlot *cpUpdateReturningSlot;
117 } ModifyTableContext;
118
119 /*
120 * Context struct containing output data specific to UPDATE operations.
121 */
122 typedef struct UpdateContext
123 {
124 bool crossPartUpdate; /* was it a cross-partition update? */
125 TU_UpdateIndexes updateIndexes; /* Which index updates are required? */
126
127 /*
128 * Lock mode to acquire on the latest tuple version before performing
129 * EvalPlanQual on it
130 */
131 LockTupleMode lockmode;
132 } UpdateContext;
133
134
135 static void ExecBatchInsert(ModifyTableState *mtstate,
136 ResultRelInfo *resultRelInfo,
137 TupleTableSlot **slots,
138 TupleTableSlot **planSlots,
139 int numSlots,
140 EState *estate,
141 bool canSetTag);
142 static void ExecPendingInserts(EState *estate);
143 static void ExecCrossPartitionUpdateForeignKey(ModifyTableContext *context,
144 ResultRelInfo *sourcePartInfo,
145 ResultRelInfo *destPartInfo,
146 ItemPointer tupleid,
147 TupleTableSlot *oldslot,
148 TupleTableSlot *newslot);
149 static bool ExecOnConflictUpdate(ModifyTableContext *context,
150 ResultRelInfo *resultRelInfo,
151 ItemPointer conflictTid,
152 TupleTableSlot *excludedSlot,
153 bool canSetTag,
154 TupleTableSlot **returning);
155 static TupleTableSlot *ExecPrepareTupleRouting(ModifyTableState *mtstate,
156 EState *estate,
157 PartitionTupleRouting *proute,
158 ResultRelInfo *targetRelInfo,
159 TupleTableSlot *slot,
160 ResultRelInfo **partRelInfo);
161
162 static TupleTableSlot *ExecMerge(ModifyTableContext *context,
163 ResultRelInfo *resultRelInfo,
164 ItemPointer tupleid,
165 HeapTuple oldtuple,
166 bool canSetTag);
167 static void ExecInitMerge(ModifyTableState *mtstate, EState *estate);
168 static TupleTableSlot *ExecMergeMatched(ModifyTableContext *context,
169 ResultRelInfo *resultRelInfo,
170 ItemPointer tupleid,
171 HeapTuple oldtuple,
172 bool canSetTag,
173 bool *matched);
174 static TupleTableSlot *ExecMergeNotMatched(ModifyTableContext *context,
175 ResultRelInfo *resultRelInfo,
176 bool canSetTag);
177
178
179 /*
180 * Verify that the tuples to be produced by INSERT match the
181 * target relation's rowtype
182 *
183 * We do this to guard against stale plans. If plan invalidation is
184 * functioning properly then we should never get a failure here, but better
185 * safe than sorry. Note that this is called after we have obtained lock
186 * on the target rel, so the rowtype can't change underneath us.
187 *
188 * The plan output is represented by its targetlist, because that makes
189 * handling the dropped-column case easier.
190 *
191 * We used to use this for UPDATE as well, but now the equivalent checks
192 * are done in ExecBuildUpdateProjection.
193 */
194 static void
195 ExecCheckPlanOutput(Relation resultRel, List *targetList)
196 {
197 TupleDesc resultDesc = RelationGetDescr(resultRel);
198 int attno = 0;
199 ListCell *lc;
200
201 foreach(lc, targetList)
202 {
203 TargetEntry *tle = (TargetEntry *) lfirst(lc);
204 Form_pg_attribute attr;
205
206 Assert(!tle->resjunk); /* caller removed junk items already */
207
208 if (attno >= resultDesc->natts)
209 ereport(ERROR,
210 (errcode(ERRCODE_DATATYPE_MISMATCH),
211 errmsg("table row type and query-specified row type do not match"),
212 errdetail("Query has too many columns.")));
213 attr = TupleDescAttr(resultDesc, attno);
214 attno++;
215
216 /*
217 * Special cases here should match planner's expand_insert_targetlist.
218 */
219 if (attr->attisdropped)
220 {
221 /*
222 * For a dropped column, we can't check atttypid (it's likely 0).
223 * In any case the planner has most likely inserted an INT4 null.
224 * What we insist on is just *some* NULL constant.
225 */
226 if (!IsA(tle->expr, Const) ||
227 !((Const *) tle->expr)->constisnull)
228 ereport(ERROR,
229 (errcode(ERRCODE_DATATYPE_MISMATCH),
230 errmsg("table row type and query-specified row type do not match"),
231 errdetail("Query provides a value for a dropped column at ordinal position %d.",
232 attno)));
233 }
234 else if (attr->attgenerated)
235 {
236 /*
237 * For a generated column, the planner will have inserted a null
238 * of the column's base type (to avoid possibly failing on domain
239 * not-null constraints). It doesn't seem worth insisting on that
240 * exact type though, since a null value is type-independent. As
241 * above, just insist on *some* NULL constant.
242 */
243 if (!IsA(tle->expr, Const) ||
244 !((Const *) tle->expr)->constisnull)
245 ereport(ERROR,
246 (errcode(ERRCODE_DATATYPE_MISMATCH),
247 errmsg("table row type and query-specified row type do not match"),
248 errdetail("Query provides a value for a generated column at ordinal position %d.",
249 attno)));
250 }
251 else
252 {
253 /* Normal case: demand type match */
254 if (exprType((Node *) tle->expr) != attr->atttypid)
255 ereport(ERROR,
256 (errcode(ERRCODE_DATATYPE_MISMATCH),
257 errmsg("table row type and query-specified row type do not match"),
258 errdetail("Table has type %s at ordinal position %d, but query expects %s.",
259 format_type_be(attr->atttypid),
260 attno,
261 format_type_be(exprType((Node *) tle->expr)))));
262 }
263 }
264 if (attno != resultDesc->natts)
265 ereport(ERROR,
266 (errcode(ERRCODE_DATATYPE_MISMATCH),
267 errmsg("table row type and query-specified row type do not match"),
268 errdetail("Query has too few columns.")));
269 }
270
271 /*
272 * ExecProcessReturning --- evaluate a RETURNING list
273 *
274 * context: context for the ModifyTable operation
275 * resultRelInfo: current result rel
276 * cmdType: operation/merge action performed (INSERT, UPDATE, or DELETE)
277 * oldSlot: slot holding old tuple deleted or updated
278 * newSlot: slot holding new tuple inserted or updated
279 * planSlot: slot holding tuple returned by top subplan node
280 *
281 * Note: If oldSlot and newSlot are NULL, the FDW should have already provided
282 * econtext's scan tuple and its old & new tuples are not needed (FDW direct-
283 * modify is disabled if the RETURNING list refers to any OLD/NEW values).
284 *
285 * Returns a slot holding the result tuple
286 */
287 static TupleTableSlot *
288 ExecProcessReturning(ModifyTableContext *context,
289 ResultRelInfo *resultRelInfo,
290 CmdType cmdType,
291 TupleTableSlot *oldSlot,
292 TupleTableSlot *newSlot,
293 TupleTableSlot *planSlot)
294 {
295 EState *estate = context->estate;
296 ProjectionInfo *projectReturning = resultRelInfo->ri_projectReturning;
297 ExprContext *econtext = projectReturning->pi_exprContext;
298
299 /* Make tuple and any needed join variables available to ExecProject */
300 switch (cmdType)
301 {
302 case CMD_INSERT:
303 case CMD_UPDATE:
304 /* return new tuple by default */
305 if (newSlot)
306 econtext->ecxt_scantuple = newSlot;
307 break;
308
309 case CMD_DELETE:
310 /* return old tuple by default */
311 if (oldSlot)
312 econtext->ecxt_scantuple = oldSlot;
313 break;
314
315 default:
316 elog(ERROR, "unrecognized commandType: %d", (int) cmdType);
317 }
318 econtext->ecxt_outertuple = planSlot;
319
320 /* Make old/new tuples available to ExecProject, if required */
321 if (oldSlot)
322 econtext->ecxt_oldtuple = oldSlot;
323 else if (projectReturning->pi_state.flags & EEO_FLAG_HAS_OLD)
324 econtext->ecxt_oldtuple = ExecGetAllNullSlot(estate, resultRelInfo);
325 else
326 econtext->ecxt_oldtuple = NULL; /* No references to OLD columns */
327
328 if (newSlot)
329 econtext->ecxt_newtuple = newSlot;
330 else if (projectReturning->pi_state.flags & EEO_FLAG_HAS_NEW)
331 econtext->ecxt_newtuple = ExecGetAllNullSlot(estate, resultRelInfo);
332 else
333 econtext->ecxt_newtuple = NULL; /* No references to NEW columns */
334
335 /*
336 * Tell ExecProject whether or not the OLD/NEW rows actually exist. This
337 * information is required to evaluate ReturningExpr nodes and also in
338 * ExecEvalSysVar() and ExecEvalWholeRowVar().
339 */
340 if (oldSlot == NULL)
341 projectReturning->pi_state.flags |= EEO_FLAG_OLD_IS_NULL;
342 else
343 projectReturning->pi_state.flags &= ~EEO_FLAG_OLD_IS_NULL;
344
345 if (newSlot == NULL)
346 projectReturning->pi_state.flags |= EEO_FLAG_NEW_IS_NULL;
347 else
348 projectReturning->pi_state.flags &= ~EEO_FLAG_NEW_IS_NULL;
349
350 /* Compute the RETURNING expressions */
351 return ExecProject(projectReturning);
352 }
353
354 /*
355 * ExecCheckTupleVisible -- verify tuple is visible
356 *
357 * It would not be consistent with guarantees of the higher isolation levels to
358 * proceed with avoiding insertion (taking speculative insertion's alternative
359 * path) on the basis of another tuple that is not visible to MVCC snapshot.
360 * Check for the need to raise a serialization failure, and do so as necessary.
361 */
362 static void
363 ExecCheckTupleVisible(EState *estate,
364 Relation rel,
365 TupleTableSlot *slot)
366 {
367 if (!IsolationUsesXactSnapshot())
368 return;
369
370 if (!table_tuple_satisfies_snapshot(rel, slot, estate->es_snapshot))
371 {
372 Datum xminDatum;
373 TransactionId xmin;
374 bool isnull;
375
376 xminDatum = slot_getsysattr(slot, MinTransactionIdAttributeNumber, &isnull);
377 Assert(!isnull);
378 xmin = DatumGetTransactionId(xminDatum);
379
380 /*
381 * We should not raise a serialization failure if the conflict is
382 * against a tuple inserted by our own transaction, even if it's not
383 * visible to our snapshot. (This would happen, for example, if
384 * conflicting keys are proposed for insertion in a single command.)
385 */
386 if (!TransactionIdIsCurrentTransactionId(xmin))
387 ereport(ERROR,
388 (errcode(ERRCODE_T_R_SERIALIZATION_FAILURE),
389 errmsg("could not serialize access due to concurrent update")));
390 }
391 }
392
393 /*
394 * ExecCheckTIDVisible -- convenience variant of ExecCheckTupleVisible()
395 */
396 static void
397 ExecCheckTIDVisible(EState *estate,
398 ResultRelInfo *relinfo,
399 ItemPointer tid,
400 TupleTableSlot *tempSlot)
401 {
402 Relation rel = relinfo->ri_RelationDesc;
403
404 /* Redundantly check isolation level */
405 if (!IsolationUsesXactSnapshot())
406 return;
407
408 if (!table_tuple_fetch_row_version(rel, tid, SnapshotAny, tempSlot))
409 elog(ERROR, "failed to fetch conflicting tuple for ON CONFLICT");
410 ExecCheckTupleVisible(estate, rel, tempSlot);
411 ExecClearTuple(tempSlot);
412 }
413
414 /*
415 * Initialize generated columns handling for a tuple
416 *
417 * This fills the resultRelInfo's ri_GeneratedExprsI/ri_NumGeneratedNeededI or
418 * ri_GeneratedExprsU/ri_NumGeneratedNeededU fields, depending on cmdtype.
419 * This is used only for stored generated columns.
420 *
421 * If cmdType == CMD_UPDATE, the ri_extraUpdatedCols field is filled too.
422 * This is used by both stored and virtual generated columns.
423 *
424 * Note: usually, a given query would need only one of ri_GeneratedExprsI and
425 * ri_GeneratedExprsU per result rel; but MERGE can need both, and so can
426 * cross-partition UPDATEs, since a partition might be the target of both
427 * UPDATE and INSERT actions.
428 */
429 void
430 ExecInitGenerated(ResultRelInfo *resultRelInfo,
431 EState *estate,
432 CmdType cmdtype)
433 {
434 Relation rel = resultRelInfo->ri_RelationDesc;
435 TupleDesc tupdesc = RelationGetDescr(rel);
436 int natts = tupdesc->natts;
437 ExprState **ri_GeneratedExprs;
438 int ri_NumGeneratedNeeded;
439 Bitmapset *updatedCols;
440 MemoryContext oldContext;
441
442 /* Nothing to do if no generated columns */
443 if (!(tupdesc->constr && (tupdesc->constr->has_generated_stored || tupdesc->constr->has_generated_virtual)))
444 return;
445
446 /*
447 * In an UPDATE, we can skip computing any generated columns that do not
448 * depend on any UPDATE target column. But if there is a BEFORE ROW
449 * UPDATE trigger, we cannot skip because the trigger might change more
450 * columns.
451 */
452 if (cmdtype == CMD_UPDATE &&
453 !(rel->trigdesc && rel->trigdesc->trig_update_before_row))
454 updatedCols = ExecGetUpdatedCols(resultRelInfo, estate);
455 else
456 updatedCols = NULL;
457
458 /*
459 * Make sure these data structures are built in the per-query memory
460 * context so they'll survive throughout the query.
461 */
462 oldContext = MemoryContextSwitchTo(estate->es_query_cxt);
463
464 ri_GeneratedExprs = (ExprState **) palloc0(natts * sizeof(ExprState *));
465 ri_NumGeneratedNeeded = 0;
466
467 for (int i = 0; i < natts; i++)
468 {
469 char attgenerated = TupleDescAttr(tupdesc, i)->attgenerated;
470
471 if (attgenerated)
472 {
473 Expr *expr;
474
475 /* Fetch the GENERATED AS expression tree */
476 expr = (Expr *) build_column_default(rel, i + 1);
477 if (expr == NULL)
478 elog(ERROR, "no generation expression found for column number %d of table \"%s\"",
479 i + 1, RelationGetRelationName(rel));
480
481 /*
482 * If it's an update with a known set of update target columns,
483 * see if we can skip the computation.
484 */
485 if (updatedCols)
486 {
487 Bitmapset *attrs_used = NULL;
488
489 pull_varattnos((Node *) expr, 1, &attrs_used);
490
491 if (!bms_overlap(updatedCols, attrs_used))
492 continue; /* need not update this column */
493 }
494
495 /* No luck, so prepare the expression for execution */
496 if (attgenerated == ATTRIBUTE_GENERATED_STORED)
497 {
498 ri_GeneratedExprs[i] = ExecPrepareExpr(expr, estate);
499 ri_NumGeneratedNeeded++;
500 }
501
502 /* If UPDATE, mark column in resultRelInfo->ri_extraUpdatedCols */
503 if (cmdtype == CMD_UPDATE)
504 resultRelInfo->ri_extraUpdatedCols =
505 bms_add_member(resultRelInfo->ri_extraUpdatedCols,
506 i + 1 - FirstLowInvalidHeapAttributeNumber);
507 }
508 }
509
510 if (ri_NumGeneratedNeeded == 0)
511 {
512 /* didn't need it after all */
513 pfree(ri_GeneratedExprs);
514 ri_GeneratedExprs = NULL;
515 }
516
517 /* Save in appropriate set of fields */
518 if (cmdtype == CMD_UPDATE)
519 {
520 /* Don't call twice */
521 Assert(resultRelInfo->ri_GeneratedExprsU == NULL);
522
523 resultRelInfo->ri_GeneratedExprsU = ri_GeneratedExprs;
524 resultRelInfo->ri_NumGeneratedNeededU = ri_NumGeneratedNeeded;
525
526 resultRelInfo->ri_extraUpdatedCols_valid = true;
527 }
528 else
529 {
530 /* Don't call twice */
531 Assert(resultRelInfo->ri_GeneratedExprsI == NULL);
532
533 resultRelInfo->ri_GeneratedExprsI = ri_GeneratedExprs;
534 resultRelInfo->ri_NumGeneratedNeededI = ri_NumGeneratedNeeded;
535 }
536
537 MemoryContextSwitchTo(oldContext);
538 }
539
540 /*
541 * Compute stored generated columns for a tuple
542 */
543 void
544 ExecComputeStoredGenerated(ResultRelInfo *resultRelInfo,
545 EState *estate, TupleTableSlot *slot,
546 CmdType cmdtype)
547 {
548 Relation rel = resultRelInfo->ri_RelationDesc;
549 TupleDesc tupdesc = RelationGetDescr(rel);
550 int natts = tupdesc->natts;
551 ExprContext *econtext = GetPerTupleExprContext(estate);
552 ExprState **ri_GeneratedExprs;
553 MemoryContext oldContext;
554 Datum *values;
555 bool *nulls;
556
557 /* We should not be called unless this is true */
558 Assert(tupdesc->constr && tupdesc->constr->has_generated_stored);
559
560 /*
561 * Initialize the expressions if we didn't already, and check whether we
562 * can exit early because nothing needs to be computed.
563 */
564 if (cmdtype == CMD_UPDATE)
565 {
566 if (resultRelInfo->ri_GeneratedExprsU == NULL)
567 ExecInitGenerated(resultRelInfo, estate, cmdtype);
568 if (resultRelInfo->ri_NumGeneratedNeededU == 0)
569 return;
570 ri_GeneratedExprs = resultRelInfo->ri_GeneratedExprsU;
571 }
572 else
573 {
574 if (resultRelInfo->ri_GeneratedExprsI == NULL)
575 ExecInitGenerated(resultRelInfo, estate, cmdtype);
576 /* Early exit is impossible given the prior Assert */
577 Assert(resultRelInfo->ri_NumGeneratedNeededI > 0);
578 ri_GeneratedExprs = resultRelInfo->ri_GeneratedExprsI;
579 }
580
581 oldContext = MemoryContextSwitchTo(GetPerTupleMemoryContext(estate));
582
583 values = palloc(sizeof(*values) * natts);
584 nulls = palloc(sizeof(*nulls) * natts);
585
586 slot_getallattrs(slot);
587 memcpy(nulls, slot->tts_isnull, sizeof(*nulls) * natts);
588
589 for (int i = 0; i < natts; i++)
590 {
591 CompactAttribute *attr = TupleDescCompactAttr(tupdesc, i);
592
593 if (ri_GeneratedExprs[i])
594 {
595 Datum val;
596 bool isnull;
597
598 Assert(TupleDescAttr(tupdesc, i)->attgenerated == ATTRIBUTE_GENERATED_STORED);
599
600 econtext->ecxt_scantuple = slot;
601
602 val = ExecEvalExpr(ri_GeneratedExprs[i], econtext, &isnull);
603
604 /*
605 * We must make a copy of val as we have no guarantees about where
606 * memory for a pass-by-reference Datum is located.
607 */
608 if (!isnull)
609 val = datumCopy(val, attr->attbyval, attr->attlen);
610
611 values[i] = val;
612 nulls[i] = isnull;
613 }
614 else
615 {
616 if (!nulls[i])
617 values[i] = datumCopy(slot->tts_values[i], attr->attbyval, attr->attlen);
618 }
619 }
620
621 ExecClearTuple(slot);
622 memcpy(slot->tts_values, values, sizeof(*values) * natts);
623 memcpy(slot->tts_isnull, nulls, sizeof(*nulls) * natts);
624 ExecStoreVirtualTuple(slot);
625 ExecMaterializeSlot(slot);
626
627 MemoryContextSwitchTo(oldContext);
628 }
629
630 /*
631 * ExecInitInsertProjection
632 * Do one-time initialization of projection data for INSERT tuples.
633 *
634 * INSERT queries may need a projection to filter out junk attrs in the tlist.
635 *
636 * This is also a convenient place to verify that the
637 * output of an INSERT matches the target table.
638 */
639 static void
640 ExecInitInsertProjection(ModifyTableState *mtstate,
641 ResultRelInfo *resultRelInfo)
642 {
643 ModifyTable *node = (ModifyTable *) mtstate->ps.plan;
644 Plan *subplan = outerPlan(node);
645 EState *estate = mtstate->ps.state;
646 List *insertTargetList = NIL;
647 bool need_projection = false;
648 ListCell *l;
649
650 /* Extract non-junk columns of the subplan's result tlist. */
651 foreach(l, subplan->targetlist)
652 {
653 TargetEntry *tle = (TargetEntry *) lfirst(l);
654
655 if (!tle->resjunk)
656 insertTargetList = lappend(insertTargetList, tle);
657 else
658 need_projection = true;
659 }
660
661 /*
662 * The junk-free list must produce a tuple suitable for the result
663 * relation.
664 */
665 ExecCheckPlanOutput(resultRelInfo->ri_RelationDesc, insertTargetList);
666
667 /* We'll need a slot matching the table's format. */
668 resultRelInfo->ri_newTupleSlot =
669 table_slot_create(resultRelInfo->ri_RelationDesc,
670 &estate->es_tupleTable);
671
672 /* Build ProjectionInfo if needed (it probably isn't). */
673 if (need_projection)
674 {
675 TupleDesc relDesc = RelationGetDescr(resultRelInfo->ri_RelationDesc);
676
677 /* need an expression context to do the projection */
678 if (mtstate->ps.ps_ExprContext == NULL)
679 ExecAssignExprContext(estate, &mtstate->ps);
680
681 resultRelInfo->ri_projectNew =
682 ExecBuildProjectionInfo(insertTargetList,
683 mtstate->ps.ps_ExprContext,
684 resultRelInfo->ri_newTupleSlot,
685 &mtstate->ps,
686 relDesc);
687 }
688
689 resultRelInfo->ri_projectNewInfoValid = true;
690 }
691
692 /*
693 * ExecInitUpdateProjection
694 * Do one-time initialization of projection data for UPDATE tuples.
695 *
696 * UPDATE always needs a projection, because (1) there's always some junk
697 * attrs, and (2) we may need to merge values of not-updated columns from
698 * the old tuple into the final tuple. In UPDATE, the tuple arriving from
699 * the subplan contains only new values for the changed columns, plus row
700 * identity info in the junk attrs.
701 *
702 * This is "one-time" for any given result rel, but we might touch more than
703 * one result rel in the course of an inherited UPDATE, and each one needs
704 * its own projection due to possible column order variation.
705 *
706 * This is also a convenient place to verify that the output of an UPDATE
707 * matches the target table (ExecBuildUpdateProjection does that).
708 */
709 static void
710 ExecInitUpdateProjection(ModifyTableState *mtstate,
711 ResultRelInfo *resultRelInfo)
712 {
713 ModifyTable *node = (ModifyTable *) mtstate->ps.plan;
714 Plan *subplan = outerPlan(node);
715 EState *estate = mtstate->ps.state;
716 TupleDesc relDesc = RelationGetDescr(resultRelInfo->ri_RelationDesc);
717 int whichrel;
718 List *updateColnos;
719
720 /*
721 * Usually, mt_lastResultIndex matches the target rel. If it happens not
722 * to, we can get the index the hard way with an integer division.
723 */
724 whichrel = mtstate->mt_lastResultIndex;
725 if (resultRelInfo != mtstate->resultRelInfo + whichrel)
726 {
727 whichrel = resultRelInfo - mtstate->resultRelInfo;
728 Assert(whichrel >= 0 && whichrel < mtstate->mt_nrels);
729 }
730
731 updateColnos = (List *) list_nth(mtstate->mt_updateColnosLists, whichrel);
732
733 /*
734 * For UPDATE, we use the old tuple to fill up missing values in the tuple
735 * produced by the subplan to get the new tuple. We need two slots, both
736 * matching the table's desired format.
737 */
738 resultRelInfo->ri_oldTupleSlot =
739 table_slot_create(resultRelInfo->ri_RelationDesc,
740 &estate->es_tupleTable);
741 resultRelInfo->ri_newTupleSlot =
742 table_slot_create(resultRelInfo->ri_RelationDesc,
743 &estate->es_tupleTable);
744
745 /* need an expression context to do the projection */
746 if (mtstate->ps.ps_ExprContext == NULL)
747 ExecAssignExprContext(estate, &mtstate->ps);
748
749 resultRelInfo->ri_projectNew =
750 ExecBuildUpdateProjection(subplan->targetlist,
751 false, /* subplan did the evaluation */
752 updateColnos,
753 relDesc,
754 mtstate->ps.ps_ExprContext,
755 resultRelInfo->ri_newTupleSlot,
756 &mtstate->ps);
757
758 resultRelInfo->ri_projectNewInfoValid = true;
759 }
760
761 /*
762 * ExecGetInsertNewTuple
763 * This prepares a "new" tuple ready to be inserted into given result
764 * relation, by removing any junk columns of the plan's output tuple
765 * and (if necessary) coercing the tuple to the right tuple format.
766 */
767 static TupleTableSlot *
768 ExecGetInsertNewTuple(ResultRelInfo *relinfo,
769 TupleTableSlot *planSlot)
770 {
771 ProjectionInfo *newProj = relinfo->ri_projectNew;
772 ExprContext *econtext;
773
774 /*
775 * If there's no projection to be done, just make sure the slot is of the
776 * right type for the target rel. If the planSlot is the right type we
777 * can use it as-is, else copy the data into ri_newTupleSlot.
778 */
779 if (newProj == NULL)
780 {
781 if (relinfo->ri_newTupleSlot->tts_ops != planSlot->tts_ops)
782 {
783 ExecCopySlot(relinfo->ri_newTupleSlot, planSlot);
784 return relinfo->ri_newTupleSlot;
785 }
786 else
787 return planSlot;
788 }
789
790 /*
791 * Else project; since the projection output slot is ri_newTupleSlot, this
792 * will also fix any slot-type problem.
793 *
794 * Note: currently, this is dead code, because INSERT cases don't receive
795 * any junk columns so there's never a projection to be done.
796 */
797 econtext = newProj->pi_exprContext;
798 econtext->ecxt_outertuple = planSlot;
799 return ExecProject(newProj);
800 }
801
802 /*
803 * ExecGetUpdateNewTuple
804 * This prepares a "new" tuple by combining an UPDATE subplan's output
805 * tuple (which contains values of changed columns) with unchanged
806 * columns taken from the old tuple.
807 *
808 * The subplan tuple might also contain junk columns, which are ignored.
809 * Note that the projection also ensures we have a slot of the right type.
810 */
811 TupleTableSlot *
812 ExecGetUpdateNewTuple(ResultRelInfo *relinfo,
813 TupleTableSlot *planSlot,
814 TupleTableSlot *oldSlot)
815 {
816 ProjectionInfo *newProj = relinfo->ri_projectNew;
817 ExprContext *econtext;
818
819 /* Use a few extra Asserts to protect against outside callers */
820 Assert(relinfo->ri_projectNewInfoValid);
821 Assert(planSlot != NULL && !TTS_EMPTY(planSlot));
822 Assert(oldSlot != NULL && !TTS_EMPTY(oldSlot));
823
824 econtext = newProj->pi_exprContext;
825 econtext->ecxt_outertuple = planSlot;
826 econtext->ecxt_scantuple = oldSlot;
827 return ExecProject(newProj);
828 }
829
830 /* ----------------------------------------------------------------
831 * ExecInsert
832 *
833 * For INSERT, we have to insert the tuple into the target relation
834 * (or partition thereof) and insert appropriate tuples into the index
835 * relations.
836 *
837 * slot contains the new tuple value to be stored.
838 *
839 * Returns RETURNING result if any, otherwise NULL.
840 * *inserted_tuple is the tuple that's effectively inserted;
841 * *insert_destrel is the relation where it was inserted.
842 * These are only set on success.
843 *
844 * This may change the currently active tuple conversion map in
845 * mtstate->mt_transition_capture, so the callers must take care to
846 * save the previous value to avoid losing track of it.
847 * ----------------------------------------------------------------
848 */
849 static TupleTableSlot *
850 ExecInsert(ModifyTableContext *context,
851 ResultRelInfo *resultRelInfo,
852 TupleTableSlot *slot,
853 bool canSetTag,
854 TupleTableSlot **inserted_tuple,
855 ResultRelInfo **insert_destrel)
856 {
857 ModifyTableState *mtstate = context->mtstate;
858 EState *estate = context->estate;
859 Relation resultRelationDesc;
860 List *recheckIndexes = NIL;
861 TupleTableSlot *planSlot = context->planSlot;
862 TupleTableSlot *result = NULL;
863 TransitionCaptureState *ar_insert_trig_tcs;
864 ModifyTable *node = (ModifyTable *) mtstate->ps.plan;
865 OnConflictAction onconflict = node->onConflictAction;
866 PartitionTupleRouting *proute = mtstate->mt_partition_tuple_routing;
867 MemoryContext oldContext;
868
869 /*
870 * If the input result relation is a partitioned table, find the leaf
871 * partition to insert the tuple into.
872 */
873 if (proute)
874 {
875 ResultRelInfo *partRelInfo;
876
877 slot = ExecPrepareTupleRouting(mtstate, estate, proute,
878 resultRelInfo, slot,
879 &partRelInfo);
880 resultRelInfo = partRelInfo;
881 }
882
883 ExecMaterializeSlot(slot);
884
885 resultRelationDesc = resultRelInfo->ri_RelationDesc;
886
887 /*
888 * Open the table's indexes, if we have not done so already, so that we
889 * can add new index entries for the inserted tuple.
890 */
891 if (resultRelationDesc->rd_rel->relhasindex &&
892 resultRelInfo->ri_IndexRelationDescs == NULL)
893 ExecOpenIndices(resultRelInfo, onconflict != ONCONFLICT_NONE);
894
895 /*
896 * BEFORE ROW INSERT Triggers.
897 *
898 * Note: We fire BEFORE ROW TRIGGERS for every attempted insertion in an
899 * INSERT ... ON CONFLICT statement. We cannot check for constraint
900 * violations before firing these triggers, because they can change the
901 * values to insert. Also, they can run arbitrary user-defined code with
902 * side-effects that we can't cancel by just not inserting the tuple.
903 */
904 if (resultRelInfo->ri_TrigDesc &&
905 resultRelInfo->ri_TrigDesc->trig_insert_before_row)
906 {
907 /* Flush any pending inserts, so rows are visible to the triggers */
908 if (estate->es_insert_pending_result_relations != NIL)
909 ExecPendingInserts(estate);
910
911 if (!ExecBRInsertTriggers(estate, resultRelInfo, slot))
912 return NULL; /* "do nothing" */
913 }
914
915 /* INSTEAD OF ROW INSERT Triggers */
916 if (resultRelInfo->ri_TrigDesc &&
917 resultRelInfo->ri_TrigDesc->trig_insert_instead_row)
918 {
919 if (!ExecIRInsertTriggers(estate, resultRelInfo, slot))
920 return NULL; /* "do nothing" */
921 }
922 else if (resultRelInfo->ri_FdwRoutine)
923 {
924 /*
925 * GENERATED expressions might reference the tableoid column, so
926 * (re-)initialize tts_tableOid before evaluating them.
927 */
928 slot->tts_tableOid = RelationGetRelid(resultRelInfo->ri_RelationDesc);
929
930 /*
931 * Compute stored generated columns
932 */
933 if (resultRelationDesc->rd_att->constr &&
934 resultRelationDesc->rd_att->constr->has_generated_stored)
935 ExecComputeStoredGenerated(resultRelInfo, estate, slot,
936 CMD_INSERT);
937
938 /*
939 * If the FDW supports batching, and batching is requested, accumulate
940 * rows and insert them in batches. Otherwise use the per-row inserts.
941 */
942 if (resultRelInfo->ri_BatchSize > 1)
943 {
944 bool flushed = false;
945
946 /*
947 * When we've reached the desired batch size, perform the
948 * insertion.
949 */
950 if (resultRelInfo->ri_NumSlots == resultRelInfo->ri_BatchSize)
951 {
952 ExecBatchInsert(mtstate, resultRelInfo,
953 resultRelInfo->ri_Slots,
954 resultRelInfo->ri_PlanSlots,
955 resultRelInfo->ri_NumSlots,
956 estate, canSetTag);
957 flushed = true;
958 }
959
960 oldContext = MemoryContextSwitchTo(estate->es_query_cxt);
961
962 if (resultRelInfo->ri_Slots == NULL)
963 {
964 resultRelInfo->ri_Slots = palloc(sizeof(TupleTableSlot *) *
965 resultRelInfo->ri_BatchSize);
966 resultRelInfo->ri_PlanSlots = palloc(sizeof(TupleTableSlot *) *
967 resultRelInfo->ri_BatchSize);
968 }
969
970 /*
971 * Initialize the batch slots. We don't know how many slots will
972 * be needed, so we initialize them as the batch grows, and we
973 * keep them across batches. To mitigate an inefficiency in how
974 * resource owner handles objects with many references (as with
975 * many slots all referencing the same tuple descriptor) we copy
976 * the appropriate tuple descriptor for each slot.
977 */
978 if (resultRelInfo->ri_NumSlots >= resultRelInfo->ri_NumSlotsInitialized)
979 {
980 TupleDesc tdesc = CreateTupleDescCopy(slot->tts_tupleDescriptor);
981 TupleDesc plan_tdesc =
982 CreateTupleDescCopy(planSlot->tts_tupleDescriptor);
983
984 resultRelInfo->ri_Slots[resultRelInfo->ri_NumSlots] =
985 MakeSingleTupleTableSlot(tdesc, slot->tts_ops);
986
987 resultRelInfo->ri_PlanSlots[resultRelInfo->ri_NumSlots] =
988 MakeSingleTupleTableSlot(plan_tdesc, planSlot->tts_ops);
989
990 /* remember how many batch slots we initialized */
991 resultRelInfo->ri_NumSlotsInitialized++;
992 }
993
994 ExecCopySlot(resultRelInfo->ri_Slots[resultRelInfo->ri_NumSlots],
995 slot);
996
997 ExecCopySlot(resultRelInfo->ri_PlanSlots[resultRelInfo->ri_NumSlots],
998 planSlot);
999
1000 /*
1001 * If these are the first tuples stored in the buffers, add the
1002 * target rel and the mtstate to the
1003 * es_insert_pending_result_relations and
1004 * es_insert_pending_modifytables lists respectively, except in
1005 * the case where flushing was done above, in which case they
1006 * would already have been added to the lists, so no need to do
1007 * this.
1008 */
1009 if (resultRelInfo->ri_NumSlots == 0 && !flushed)
1010 {
1011 Assert(!list_member_ptr(estate->es_insert_pending_result_relations,
1012 resultRelInfo));
1013 estate->es_insert_pending_result_relations =
1014 lappend(estate->es_insert_pending_result_relations,
1015 resultRelInfo);
1016 estate->es_insert_pending_modifytables =
1017 lappend(estate->es_insert_pending_modifytables, mtstate);
1018 }
1019 Assert(list_member_ptr(estate->es_insert_pending_result_relations,
1020 resultRelInfo));
1021
1022 resultRelInfo->ri_NumSlots++;
1023
1024 MemoryContextSwitchTo(oldContext);
1025
1026 return NULL;
1027 }
1028
1029 /*
1030 * insert into foreign table: let the FDW do it
1031 */
1032 slot = resultRelInfo->ri_FdwRoutine->ExecForeignInsert(estate,
1033 resultRelInfo,
1034 slot,
1035 planSlot);
1036
1037 if (slot == NULL) /* "do nothing" */
1038 return NULL;
1039
1040 /*
1041 * AFTER ROW Triggers or RETURNING expressions might reference the
1042 * tableoid column, so (re-)initialize tts_tableOid before evaluating
1043 * them. (This covers the case where the FDW replaced the slot.)
1044 */
1045 slot->tts_tableOid = RelationGetRelid(resultRelInfo->ri_RelationDesc);
1046 }
1047 else
1048 {
1049 WCOKind wco_kind;
1050
1051 /*
1052 * Constraints and GENERATED expressions might reference the tableoid
1053 * column, so (re-)initialize tts_tableOid before evaluating them.
1054 */
1055 slot->tts_tableOid = RelationGetRelid(resultRelationDesc);
1056
1057 /*
1058 * Compute stored generated columns
1059 */
1060 if (resultRelationDesc->rd_att->constr &&
1061 resultRelationDesc->rd_att->constr->has_generated_stored)
1062 ExecComputeStoredGenerated(resultRelInfo, estate, slot,
1063 CMD_INSERT);
1064
1065 /*
1066 * Check any RLS WITH CHECK policies.
1067 *
1068 * Normally we should check INSERT policies. But if the insert is the
1069 * result of a partition key update that moved the tuple to a new
1070 * partition, we should instead check UPDATE policies, because we are
1071 * executing policies defined on the target table, and not those
1072 * defined on the child partitions.
1073 *
1074 * If we're running MERGE, we refer to the action that we're executing
1075 * to know if we're doing an INSERT or UPDATE to a partition table.
1076 */
1077 if (mtstate->operation == CMD_UPDATE)
1078 wco_kind = WCO_RLS_UPDATE_CHECK;
1079 else if (mtstate->operation == CMD_MERGE)
1080 wco_kind = (mtstate->mt_merge_action->mas_action->commandType == CMD_UPDATE) ?
1081 WCO_RLS_UPDATE_CHECK : WCO_RLS_INSERT_CHECK;
1082 else
1083 wco_kind = WCO_RLS_INSERT_CHECK;
1084
1085 /*
1086 * ExecWithCheckOptions() will skip any WCOs which are not of the kind
1087 * we are looking for at this point.
1088 */
1089 if (resultRelInfo->ri_WithCheckOptions != NIL)
1090 ExecWithCheckOptions(wco_kind, resultRelInfo, slot, estate);
1091
1092 /*
1093 * Check the constraints of the tuple.
1094 */
1095 if (resultRelationDesc->rd_att->constr)
1096 ExecConstraints(resultRelInfo, slot, estate);
1097
1098 /*
1099 * Also check the tuple against the partition constraint, if there is
1100 * one; except that if we got here via tuple-routing, we don't need to
1101 * if there's no BR trigger defined on the partition.
1102 */
1103 if (resultRelationDesc->rd_rel->relispartition &&
1104 (resultRelInfo->ri_RootResultRelInfo == NULL ||
1105 (resultRelInfo->ri_TrigDesc &&
1106 resultRelInfo->ri_TrigDesc->trig_insert_before_row)))
1107 ExecPartitionCheck(resultRelInfo, slot, estate, true);
1108
1109 if (onconflict != ONCONFLICT_NONE && resultRelInfo->ri_NumIndices > 0)
1110 {
1111 /* Perform a speculative insertion. */
1112 uint32 specToken;
1113 ItemPointerData conflictTid;
1114 ItemPointerData invalidItemPtr;
1115 bool specConflict;
1116 List *arbiterIndexes;
1117
1118 ItemPointerSetInvalid(&invalidItemPtr);
1119 arbiterIndexes = resultRelInfo->ri_onConflictArbiterIndexes;
1120
1121 /*
1122 * Do a non-conclusive check for conflicts first.
1123 *
1124 * We're not holding any locks yet, so this doesn't guarantee that
1125 * the later insert won't conflict. But it avoids leaving behind
1126 * a lot of canceled speculative insertions, if you run a lot of
1127 * INSERT ON CONFLICT statements that do conflict.
1128 *
1129 * We loop back here if we find a conflict below, either during
1130 * the pre-check, or when we re-check after inserting the tuple
1131 * speculatively. Better allow interrupts in case some bug makes
1132 * this an infinite loop.
1133 */
1134 vlock:
1135 CHECK_FOR_INTERRUPTS();
1136 specConflict = false;
1137 if (!ExecCheckIndexConstraints(resultRelInfo, slot, estate,
1138 &conflictTid, &invalidItemPtr,
1139 arbiterIndexes))
1140 {
1141 /* committed conflict tuple found */
1142 if (onconflict == ONCONFLICT_UPDATE)
1143 {
1144 /*
1145 * In case of ON CONFLICT DO UPDATE, execute the UPDATE
1146 * part. Be prepared to retry if the UPDATE fails because
1147 * of another concurrent UPDATE/DELETE to the conflict
1148 * tuple.
1149 */
1150 TupleTableSlot *returning = NULL;
1151
1152 if (ExecOnConflictUpdate(context, resultRelInfo,
1153 &conflictTid, slot, canSetTag,
1154 &returning))
1155 {
1156 InstrCountTuples2(&mtstate->ps, 1);
1157 return returning;
1158 }
1159 else
1160 goto vlock;
1161 }
1162 else
1163 {
1164 /*
1165 * In case of ON CONFLICT DO NOTHING, do nothing. However,
1166 * verify that the tuple is visible to the executor's MVCC
1167 * snapshot at higher isolation levels.
1168 *
1169 * Using ExecGetReturningSlot() to store the tuple for the
1170 * recheck isn't that pretty, but we can't trivially use
1171 * the input slot, because it might not be of a compatible
1172 * type. As there's no conflicting usage of
1173 * ExecGetReturningSlot() in the DO NOTHING case...
1174 */
1175 Assert(onconflict == ONCONFLICT_NOTHING);
1176 ExecCheckTIDVisible(estate, resultRelInfo, &conflictTid,
1177 ExecGetReturningSlot(estate, resultRelInfo));
1178 InstrCountTuples2(&mtstate->ps, 1);
1179 return NULL;
1180 }
1181 }
1182
1183 /*
1184 * Before we start insertion proper, acquire our "speculative
1185 * insertion lock". Others can use that to wait for us to decide
1186 * if we're going to go ahead with the insertion, instead of
1187 * waiting for the whole transaction to complete.
1188 */
1189 specToken = SpeculativeInsertionLockAcquire(GetCurrentTransactionId());
1190
1191 /* insert the tuple, with the speculative token */
1192 table_tuple_insert_speculative(resultRelationDesc, slot,
1193 estate->es_output_cid,
1194 0,
1195 NULL,
1196 specToken);
1197
1198 /* insert index entries for tuple */
1199 recheckIndexes = ExecInsertIndexTuples(resultRelInfo,
1200 slot, estate, false, true,
1201 &specConflict,
1202 arbiterIndexes,
1203 false);
1204
1205 /* adjust the tuple's state accordingly */
1206 table_tuple_complete_speculative(resultRelationDesc, slot,
1207 specToken, !specConflict);
1208
1209 /*
1210 * Wake up anyone waiting for our decision. They will re-check
1211 * the tuple, see that it's no longer speculative, and wait on our
1212 * XID as if this was a regularly inserted tuple all along. Or if
1213 * we killed the tuple, they will see it's dead, and proceed as if
1214 * the tuple never existed.
1215 */
1216 SpeculativeInsertionLockRelease(GetCurrentTransactionId());
1217
1218 /*
1219 * If there was a conflict, start from the beginning. We'll do
1220 * the pre-check again, which will now find the conflicting tuple
1221 * (unless it aborts before we get there).
1222 */
1223 if (specConflict)
1224 {
1225 list_free(recheckIndexes);
1226 goto vlock;
1227 }
1228
1229 /* Since there was no insertion conflict, we're done */
1230 }
1231 else
1232 {
1233 /* insert the tuple normally */
1234 table_tuple_insert(resultRelationDesc, slot,
1235 estate->es_output_cid,
1236 0, NULL);
1237
1238 /* insert index entries for tuple */
1239 if (resultRelInfo->ri_NumIndices > 0)
1240 recheckIndexes = ExecInsertIndexTuples(resultRelInfo,
1241 slot, estate, false,
1242 false, NULL, NIL,
1243 false);
1244 }
1245 }
1246
1247 if (canSetTag)
1248 (estate->es_processed)++;
1249
1250 /*
1251 * If this insert is the result of a partition key update that moved the
1252 * tuple to a new partition, put this row into the transition NEW TABLE,
1253 * if there is one. We need to do this separately for DELETE and INSERT
1254 * because they happen on different tables.
1255 */
1256 ar_insert_trig_tcs = mtstate->mt_transition_capture;
1257 if (mtstate->operation == CMD_UPDATE && mtstate->mt_transition_capture
1258 && mtstate->mt_transition_capture->tcs_update_new_table)
1259 {
1260 ExecARUpdateTriggers(estate, resultRelInfo,
1261 NULL, NULL,
1262 NULL,
1263 NULL,
1264 slot,
1265 NULL,
1266 mtstate->mt_transition_capture,
1267 false);
1268
1269 /*
1270 * We've already captured the NEW TABLE row, so make sure any AR
1271 * INSERT trigger fired below doesn't capture it again.
1272 */
1273 ar_insert_trig_tcs = NULL;
1274 }
1275
1276 /* AFTER ROW INSERT Triggers */
1277 ExecARInsertTriggers(estate, resultRelInfo, slot, recheckIndexes,
1278 ar_insert_trig_tcs);
1279
1280 list_free(recheckIndexes);
1281
1282 /*
1283 * Check any WITH CHECK OPTION constraints from parent views. We are
1284 * required to do this after testing all constraints and uniqueness
1285 * violations per the SQL spec, so we do it after actually inserting the
1286 * record into the heap and all indexes.
1287 *
1288 * ExecWithCheckOptions will elog(ERROR) if a violation is found, so the
1289 * tuple will never be seen, if it violates the WITH CHECK OPTION.
1290 *
1291 * ExecWithCheckOptions() will skip any WCOs which are not of the kind we
1292 * are looking for at this point.
1293 */
1294 if (resultRelInfo->ri_WithCheckOptions != NIL)
1295 ExecWithCheckOptions(WCO_VIEW_CHECK, resultRelInfo, slot, estate);
1296
1297 /* Process RETURNING if present */
1298 if (resultRelInfo->ri_projectReturning)
1299 {
1300 TupleTableSlot *oldSlot = NULL;
1301
1302 /*
1303 * If this is part of a cross-partition UPDATE, and the RETURNING list
1304 * refers to any OLD columns, ExecDelete() will have saved the tuple
1305 * deleted from the original partition, which we must use here to
1306 * compute the OLD column values. Otherwise, all OLD column values
1307 * will be NULL.
1308 */
1309 if (context->cpDeletedSlot)
1310 {
1311 TupleConversionMap *tupconv_map;
1312
1313 /*
1314 * Convert the OLD tuple to the new partition's format/slot, if
1315 * needed. Note that ExecDelete() already converted it to the
1316 * root's partition's format/slot.
1317 */
1318 oldSlot = context->cpDeletedSlot;
1319 tupconv_map = ExecGetRootToChildMap(resultRelInfo, estate);
1320 if (tupconv_map != NULL)
1321 {
1322 oldSlot = execute_attr_map_slot(tupconv_map->attrMap,
1323 oldSlot,
1324 ExecGetReturningSlot(estate,
1325 resultRelInfo));
1326
1327 oldSlot->tts_tableOid = context->cpDeletedSlot->tts_tableOid;
1328 ItemPointerCopy(&context->cpDeletedSlot->tts_tid, &oldSlot->tts_tid);
1329 }
1330 }
1331
1332 result = ExecProcessReturning(context, resultRelInfo, CMD_INSERT,
1333 oldSlot, slot, planSlot);
1334
1335 /*
1336 * For a cross-partition UPDATE, release the old tuple, first making
1337 * sure that the result slot has a local copy of any pass-by-reference
1338 * values.
1339 */
1340 if (context->cpDeletedSlot)
1341 {
1342 ExecMaterializeSlot(result);
1343 ExecClearTuple(oldSlot);
1344 if (context->cpDeletedSlot != oldSlot)
1345 ExecClearTuple(context->cpDeletedSlot);
1346 context->cpDeletedSlot = NULL;
1347 }
1348 }
1349
1350 if (inserted_tuple)
1351 *inserted_tuple = slot;
1352 if (insert_destrel)
1353 *insert_destrel = resultRelInfo;
1354
1355 return result;
1356 }
1357
1358 /* ----------------------------------------------------------------
1359 * ExecBatchInsert
1360 *
1361 * Insert multiple tuples in an efficient way.
1362 * Currently, this handles inserting into a foreign table without
1363 * RETURNING clause.
1364 * ----------------------------------------------------------------
1365 */
1366 static void
1367 ExecBatchInsert(ModifyTableState *mtstate,
1368 ResultRelInfo *resultRelInfo,
1369 TupleTableSlot **slots,
1370 TupleTableSlot **planSlots,
1371 int numSlots,
1372 EState *estate,
1373 bool canSetTag)
1374 {
1375 int i;
1376 int numInserted = numSlots;
1377 TupleTableSlot *slot = NULL;
1378 TupleTableSlot **rslots;
1379
1380 /*
1381 * insert into foreign table: let the FDW do it
1382 */
1383 rslots = resultRelInfo->ri_FdwRoutine->ExecForeignBatchInsert(estate,
1384 resultRelInfo,
1385 slots,
1386 planSlots,
1387 &numInserted);
1388
1389 for (i = 0; i < numInserted; i++)
1390 {
1391 slot = rslots[i];
1392
1393 /*
1394 * AFTER ROW Triggers might reference the tableoid column, so
1395 * (re-)initialize tts_tableOid before evaluating them.
1396 */
1397 slot->tts_tableOid = RelationGetRelid(resultRelInfo->ri_RelationDesc);
1398
1399 /* AFTER ROW INSERT Triggers */
1400 ExecARInsertTriggers(estate, resultRelInfo, slot, NIL,
1401 mtstate->mt_transition_capture);
1402
1403 /*
1404 * Check any WITH CHECK OPTION constraints from parent views. See the
1405 * comment in ExecInsert.
1406 */
1407 if (resultRelInfo->ri_WithCheckOptions != NIL)
1408 ExecWithCheckOptions(WCO_VIEW_CHECK, resultRelInfo, slot, estate);
1409 }
1410
1411 if (canSetTag && numInserted > 0)
1412 estate->es_processed += numInserted;
1413
1414 /* Clean up all the slots, ready for the next batch */
1415 for (i = 0; i < numSlots; i++)
1416 {
1417 ExecClearTuple(slots[i]);
1418 ExecClearTuple(planSlots[i]);
1419 }
1420 resultRelInfo->ri_NumSlots = 0;
1421 }
1422
1423 /*
1424 * ExecPendingInserts -- flushes all pending inserts to the foreign tables
1425 */
1426 static void
1427 ExecPendingInserts(EState *estate)
1428 {
1429 ListCell *l1,
1430 *l2;
1431
1432 forboth(l1, estate->es_insert_pending_result_relations,
1433 l2, estate->es_insert_pending_modifytables)
1434 {
1435 ResultRelInfo *resultRelInfo = (ResultRelInfo *) lfirst(l1);
1436 ModifyTableState *mtstate = (ModifyTableState *) lfirst(l2);
1437
1438 Assert(mtstate);
1439 ExecBatchInsert(mtstate, resultRelInfo,
1440 resultRelInfo->ri_Slots,
1441 resultRelInfo->ri_PlanSlots,
1442 resultRelInfo->ri_NumSlots,
1443 estate, mtstate->canSetTag);
1444 }
1445
1446 list_free(estate->es_insert_pending_result_relations);
1447 list_free(estate->es_insert_pending_modifytables);
1448 estate->es_insert_pending_result_relations = NIL;
1449 estate->es_insert_pending_modifytables = NIL;
1450 }
1451
1452 /*
1453 * ExecDeletePrologue -- subroutine for ExecDelete
1454 *
1455 * Prepare executor state for DELETE. Actually, the only thing we have to do
1456 * here is execute BEFORE ROW triggers. We return false if one of them makes
1457 * the delete a no-op; otherwise, return true.
1458 */
1459 static bool
1460 ExecDeletePrologue(ModifyTableContext *context, ResultRelInfo *resultRelInfo,
1461 ItemPointer tupleid, HeapTuple oldtuple,
1462 TupleTableSlot **epqreturnslot, TM_Result *result)
1463 {
1464 if (result)
1465 *result = TM_Ok;
1466
1467 /* BEFORE ROW DELETE triggers */
1468 if (resultRelInfo->ri_TrigDesc &&
1469 resultRelInfo->ri_TrigDesc->trig_delete_before_row)
1470 {
1471 /* Flush any pending inserts, so rows are visible to the triggers */
1472 if (context->estate->es_insert_pending_result_relations != NIL)
1473 ExecPendingInserts(context->estate);
1474
1475 return ExecBRDeleteTriggers(context->estate, context->epqstate,
1476 resultRelInfo, tupleid, oldtuple,
1477 epqreturnslot, result, &context->tmfd,
1478 context->mtstate->operation == CMD_MERGE);
1479 }
1480
1481 return true;
1482 }
1483
1484 /*
1485 * ExecDeleteAct -- subroutine for ExecDelete
1486 *
1487 * Actually delete the tuple from a plain table.
1488 *
1489 * Caller is in charge of doing EvalPlanQual as necessary
1490 */
1491 static TM_Result
1492 ExecDeleteAct(ModifyTableContext *context, ResultRelInfo *resultRelInfo,
1493 ItemPointer tupleid, bool changingPart)
1494 {
1495 EState *estate = context->estate;
1496
1497 return table_tuple_delete(resultRelInfo->ri_RelationDesc, tupleid,
1498 estate->es_output_cid,
1499 estate->es_snapshot,
1500 estate->es_crosscheck_snapshot,
1501 true /* wait for commit */ ,
1502 &context->tmfd,
1503 changingPart);
1504 }
1505
1506 /*
1507 * ExecDeleteEpilogue -- subroutine for ExecDelete
1508 *
1509 * Closing steps of tuple deletion; this invokes AFTER FOR EACH ROW triggers,
1510 * including the UPDATE triggers if the deletion is being done as part of a
1511 * cross-partition tuple move.
1512 */
1513 static void
1514 ExecDeleteEpilogue(ModifyTableContext *context, ResultRelInfo *resultRelInfo,
1515 ItemPointer tupleid, HeapTuple oldtuple, bool changingPart)
1516 {
1517 ModifyTableState *mtstate = context->mtstate;
1518 EState *estate = context->estate;
1519 TransitionCaptureState *ar_delete_trig_tcs;
1520
1521 /*
1522 * If this delete is the result of a partition key update that moved the
1523 * tuple to a new partition, put this row into the transition OLD TABLE,
1524 * if there is one. We need to do this separately for DELETE and INSERT
1525 * because they happen on different tables.
1526 */
1527 ar_delete_trig_tcs = mtstate->mt_transition_capture;
1528 if (mtstate->operation == CMD_UPDATE && mtstate->mt_transition_capture &&
1529 mtstate->mt_transition_capture->tcs_update_old_table)
1530 {
1531 ExecARUpdateTriggers(estate, resultRelInfo,
1532 NULL, NULL,
1533 tupleid, oldtuple,
1534 NULL, NULL, mtstate->mt_transition_capture,
1535 false);
1536
1537 /*
1538 * We've already captured the OLD TABLE row, so make sure any AR
1539 * DELETE trigger fired below doesn't capture it again.
1540 */
1541 ar_delete_trig_tcs = NULL;
1542 }
1543
1544 /* AFTER ROW DELETE Triggers */
1545 ExecARDeleteTriggers(estate, resultRelInfo, tupleid, oldtuple,
1546 ar_delete_trig_tcs, changingPart);
1547 }
1548
1549 /* ----------------------------------------------------------------
1550 * ExecDelete
1551 *
1552 * DELETE is like UPDATE, except that we delete the tuple and no
1553 * index modifications are needed.
1554 *
1555 * When deleting from a table, tupleid identifies the tuple to delete and
1556 * oldtuple is NULL. When deleting through a view INSTEAD OF trigger,
1557 * oldtuple is passed to the triggers and identifies what to delete, and
1558 * tupleid is invalid. When deleting from a foreign table, tupleid is
1559 * invalid; the FDW has to figure out which row to delete using data from
1560 * the planSlot. oldtuple is passed to foreign table triggers; it is
1561 * NULL when the foreign table has no relevant triggers. We use
1562 * tupleDeleted to indicate whether the tuple is actually deleted,
1563 * callers can use it to decide whether to continue the operation. When
1564 * this DELETE is a part of an UPDATE of partition-key, then the slot
1565 * returned by EvalPlanQual() is passed back using output parameter
1566 * epqreturnslot.
1567 *
1568 * Returns RETURNING result if any, otherwise NULL.
1569 * ----------------------------------------------------------------
1570 */
1571 static TupleTableSlot *
1572 ExecDelete(ModifyTableContext *context,
1573 ResultRelInfo *resultRelInfo,
1574 ItemPointer tupleid,
1575 HeapTuple oldtuple,
1576 bool processReturning,
1577 bool changingPart,
1578 bool canSetTag,
1579 TM_Result *tmresult,
1580 bool *tupleDeleted,
1581 TupleTableSlot **epqreturnslot)
1582 {
1583 EState *estate = context->estate;
1584 Relation resultRelationDesc = resultRelInfo->ri_RelationDesc;
1585 TupleTableSlot *slot = NULL;
1586 TM_Result result;
1587 bool saveOld;
1588
1589 if (tupleDeleted)
1590 *tupleDeleted = false;
1591
1592 /*
1593 * Prepare for the delete. This includes BEFORE ROW triggers, so we're
1594 * done if it says we are.
1595 */
1596 if (!ExecDeletePrologue(context, resultRelInfo, tupleid, oldtuple,
1597 epqreturnslot, tmresult))
1598 return NULL;
1599
1600 /* INSTEAD OF ROW DELETE Triggers */
1601 if (resultRelInfo->ri_TrigDesc &&
1602 resultRelInfo->ri_TrigDesc->trig_delete_instead_row)
1603 {
1604 bool dodelete;
1605
1606 Assert(oldtuple != NULL);
1607 dodelete = ExecIRDeleteTriggers(estate, resultRelInfo, oldtuple);
1608
1609 if (!dodelete) /* "do nothing" */
1610 return NULL;
1611 }
1612 else if (resultRelInfo->ri_FdwRoutine)
1613 {
1614 /*
1615 * delete from foreign table: let the FDW do it
1616 *
1617 * We offer the returning slot as a place to store RETURNING data,
1618 * although the FDW can return some other slot if it wants.
1619 */
1620 slot = ExecGetReturningSlot(estate, resultRelInfo);
1621 slot = resultRelInfo->ri_FdwRoutine->ExecForeignDelete(estate,
1622 resultRelInfo,
1623 slot,
1624 context->planSlot);
1625
1626 if (slot == NULL) /* "do nothing" */
1627 return NULL;
1628
1629 /*
1630 * RETURNING expressions might reference the tableoid column, so
1631 * (re)initialize tts_tableOid before evaluating them.
1632 */
1633 if (TTS_EMPTY(slot))
1634 ExecStoreAllNullTuple(slot);
1635
1636 slot->tts_tableOid = RelationGetRelid(resultRelationDesc);
1637 }
1638 else
1639 {
1640 /*
1641 * delete the tuple
1642 *
1643 * Note: if context->estate->es_crosscheck_snapshot isn't
1644 * InvalidSnapshot, we check that the row to be deleted is visible to
1645 * that snapshot, and throw a can't-serialize error if not. This is a
1646 * special-case behavior needed for referential integrity updates in
1647 * transaction-snapshot mode transactions.
1648 */
1649 ldelete:
1650 result = ExecDeleteAct(context, resultRelInfo, tupleid, changingPart);
1651
1652 if (tmresult)
1653 *tmresult = result;
1654
1655 switch (result)
1656 {
1657 case TM_SelfModified:
1658
1659 /*
1660 * The target tuple was already updated or deleted by the
1661 * current command, or by a later command in the current
1662 * transaction. The former case is possible in a join DELETE
1663 * where multiple tuples join to the same target tuple. This
1664 * is somewhat questionable, but Postgres has always allowed
1665 * it: we just ignore additional deletion attempts.
1666 *
1667 * The latter case arises if the tuple is modified by a
1668 * command in a BEFORE trigger, or perhaps by a command in a
1669 * volatile function used in the query. In such situations we
1670 * should not ignore the deletion, but it is equally unsafe to
1671 * proceed. We don't want to discard the original DELETE
1672 * while keeping the triggered actions based on its deletion;
1673 * and it would be no better to allow the original DELETE
1674 * while discarding updates that it triggered. The row update
1675 * carries some information that might be important according
1676 * to business rules; so throwing an error is the only safe
1677 * course.
1678 *
1679 * If a trigger actually intends this type of interaction, it
1680 * can re-execute the DELETE and then return NULL to cancel
1681 * the outer delete.
1682 */
1683 if (context->tmfd.cmax != estate->es_output_cid)
1684 ereport(ERROR,
1685 (errcode(ERRCODE_TRIGGERED_DATA_CHANGE_VIOLATION),
1686 errmsg("tuple to be deleted was already modified by an operation triggered by the current command"),
1687 errhint("Consider using an AFTER trigger instead of a BEFORE trigger to propagate changes to other rows.")));
1688
1689 /* Else, already deleted by self; nothing to do */
1690 return NULL;
1691
1692 case TM_Ok:
1693 break;
1694
1695 case TM_Updated:
1696 {
1697 TupleTableSlot *inputslot;
1698 TupleTableSlot *epqslot;
1699
1700 if (IsolationUsesXactSnapshot())
1701 ereport(ERROR,
1702 (errcode(ERRCODE_T_R_SERIALIZATION_FAILURE),
1703 errmsg("could not serialize access due to concurrent update")));
1704
1705 /*
1706 * Already know that we're going to need to do EPQ, so
1707 * fetch tuple directly into the right slot.
1708 */
1709 EvalPlanQualBegin(context->epqstate);
1710 inputslot = EvalPlanQualSlot(context->epqstate, resultRelationDesc,
1711 resultRelInfo->ri_RangeTableIndex);
1712
1713 result = table_tuple_lock(resultRelationDesc, tupleid,
1714 estate->es_snapshot,
1715 inputslot, estate->es_output_cid,
1716 LockTupleExclusive, LockWaitBlock,
1717 TUPLE_LOCK_FLAG_FIND_LAST_VERSION,
1718 &context->tmfd);
1719
1720 switch (result)
1721 {
1722 case TM_Ok:
1723 Assert(context->tmfd.traversed);
1724 epqslot = EvalPlanQual(context->epqstate,
1725 resultRelationDesc,
1726 resultRelInfo->ri_RangeTableIndex,
1727 inputslot);
1728 if (TupIsNull(epqslot))
1729 /* Tuple not passing quals anymore, exiting... */
1730 return NULL;
1731
1732 /*
1733 * If requested, skip delete and pass back the
1734 * updated row.
1735 */
1736 if (epqreturnslot)
1737 {
1738 *epqreturnslot = epqslot;
1739 return NULL;
1740 }
1741 else
1742 goto ldelete;
1743
1744 case TM_SelfModified:
1745
1746 /*
1747 * This can be reached when following an update
1748 * chain from a tuple updated by another session,
1749 * reaching a tuple that was already updated in
1750 * this transaction. If previously updated by this
1751 * command, ignore the delete, otherwise error
1752 * out.
1753 *
1754 * See also TM_SelfModified response to
1755 * table_tuple_delete() above.
1756 */
1757 if (context->tmfd.cmax != estate->es_output_cid)
1758 ereport(ERROR,
1759 (errcode(ERRCODE_TRIGGERED_DATA_CHANGE_VIOLATION),
1760 errmsg("tuple to be deleted was already modified by an operation triggered by the current command"),
1761 errhint("Consider using an AFTER trigger instead of a BEFORE trigger to propagate changes to other rows.")));
1762 return NULL;
1763
1764 case TM_Deleted:
1765 /* tuple already deleted; nothing to do */
1766 return NULL;
1767
1768 default:
1769
1770 /*
1771 * TM_Invisible should be impossible because we're
1772 * waiting for updated row versions, and would
1773 * already have errored out if the first version
1774 * is invisible.
1775 *
1776 * TM_Updated should be impossible, because we're
1777 * locking the latest version via
1778 * TUPLE_LOCK_FLAG_FIND_LAST_VERSION.
1779 */
1780 elog(ERROR, "unexpected table_tuple_lock status: %u",
1781 result);
1782 return NULL;
1783 }
1784
1785 Assert(false);
1786 break;
1787 }
1788
1789 case TM_Deleted:
1790 if (IsolationUsesXactSnapshot())
1791 ereport(ERROR,
1792 (errcode(ERRCODE_T_R_SERIALIZATION_FAILURE),
1793 errmsg("could not serialize access due to concurrent delete")));
1794 /* tuple already deleted; nothing to do */
1795 return NULL;
1796
1797 default:
1798 elog(ERROR, "unrecognized table_tuple_delete status: %u",
1799 result);
1800 return NULL;
1801 }
1802
1803 /*
1804 * Note: Normally one would think that we have to delete index tuples
1805 * associated with the heap tuple now...
1806 *
1807 * ... but in POSTGRES, we have no need to do this because VACUUM will
1808 * take care of it later. We can't delete index tuples immediately
1809 * anyway, since the tuple is still visible to other transactions.
1810 */
1811 }
1812
1813 if (canSetTag)
1814 (estate->es_processed)++;
1815
1816 /* Tell caller that the delete actually happened. */
1817 if (tupleDeleted)
1818 *tupleDeleted = true;
1819
1820 ExecDeleteEpilogue(context, resultRelInfo, tupleid, oldtuple, changingPart);
1821
1822 /*
1823 * Process RETURNING if present and if requested.
1824 *
1825 * If this is part of a cross-partition UPDATE, and the RETURNING list
1826 * refers to any OLD column values, save the old tuple here for later
1827 * processing of the RETURNING list by ExecInsert().
1828 */
1829 saveOld = changingPart && resultRelInfo->ri_projectReturning &&
1830 resultRelInfo->ri_projectReturning->pi_state.flags & EEO_FLAG_HAS_OLD;
1831
1832 if (resultRelInfo->ri_projectReturning && (processReturning || saveOld))
1833 {
1834 /*
1835 * We have to put the target tuple into a slot, which means first we
1836 * gotta fetch it. We can use the trigger tuple slot.
1837 */
1838 TupleTableSlot *rslot;
1839
1840 if (resultRelInfo->ri_FdwRoutine)
1841 {
1842 /* FDW must have provided a slot containing the deleted row */
1843 Assert(!TupIsNull(slot));
1844 }
1845 else
1846 {
1847 slot = ExecGetReturningSlot(estate, resultRelInfo);
1848 if (oldtuple != NULL)
1849 {
1850 ExecForceStoreHeapTuple(oldtuple, slot, false);
1851 }
1852 else
1853 {
1854 if (!table_tuple_fetch_row_version(resultRelationDesc, tupleid,
1855 SnapshotAny, slot))
1856 elog(ERROR, "failed to fetch deleted tuple for DELETE RETURNING");
1857 }
1858 }
1859
1860 /*
1861 * If required, save the old tuple for later processing of the
1862 * RETURNING list by ExecInsert().
1863 */
1864 if (saveOld)
1865 {
1866 TupleConversionMap *tupconv_map;
1867
1868 /*
1869 * Convert the tuple into the root partition's format/slot, if
1870 * needed. ExecInsert() will then convert it to the new
1871 * partition's format/slot, if necessary.
1872 */
1873 tupconv_map = ExecGetChildToRootMap(resultRelInfo);
1874 if (tupconv_map != NULL)
1875 {
1876 ResultRelInfo *rootRelInfo = context->mtstate->rootResultRelInfo;
1877 TupleTableSlot *oldSlot = slot;
1878
1879 slot = execute_attr_map_slot(tupconv_map->attrMap,
1880 slot,
1881 ExecGetReturningSlot(estate,
1882 rootRelInfo));
1883
1884 slot->tts_tableOid = oldSlot->tts_tableOid;
1885 ItemPointerCopy(&oldSlot->tts_tid, &slot->tts_tid);
1886 }
1887
1888 context->cpDeletedSlot = slot;
1889
1890 return NULL;
1891 }
1892
1893 rslot = ExecProcessReturning(context, resultRelInfo, CMD_DELETE,
1894 slot, NULL, context->planSlot);
1895
1896 /*
1897 * Before releasing the target tuple again, make sure rslot has a
1898 * local copy of any pass-by-reference values.
1899 */
1900 ExecMaterializeSlot(rslot);
1901
1902 ExecClearTuple(slot);
1903
1904 return rslot;
1905 }
1906
1907 return NULL;
1908 }
1909
1910 /*
1911 * ExecCrossPartitionUpdate --- Move an updated tuple to another partition.
1912 *
1913 * This works by first deleting the old tuple from the current partition,
1914 * followed by inserting the new tuple into the root parent table, that is,
1915 * mtstate->rootResultRelInfo. It will be re-routed from there to the
1916 * correct partition.
1917 *
1918 * Returns true if the tuple has been successfully moved, or if it's found
1919 * that the tuple was concurrently deleted so there's nothing more to do
1920 * for the caller.
1921 *
1922 * False is returned if the tuple we're trying to move is found to have been
1923 * concurrently updated. In that case, the caller must check if the updated
1924 * tuple that's returned in *retry_slot still needs to be re-routed, and call
1925 * this function again or perform a regular update accordingly. For MERGE,
1926 * the updated tuple is not returned in *retry_slot; it has its own retry
1927 * logic.
1928 */
1929 static bool
1930 ExecCrossPartitionUpdate(ModifyTableContext *context,
1931 ResultRelInfo *resultRelInfo,
1932 ItemPointer tupleid, HeapTuple oldtuple,
1933 TupleTableSlot *slot,
1934 bool canSetTag,
1935 UpdateContext *updateCxt,
1936 TM_Result *tmresult,
1937 TupleTableSlot **retry_slot,
1938 TupleTableSlot **inserted_tuple,
1939 ResultRelInfo **insert_destrel)
1940 {
1941 ModifyTableState *mtstate = context->mtstate;
1942 EState *estate = mtstate->ps.state;
1943 TupleConversionMap *tupconv_map;
1944 bool tuple_deleted;
1945 TupleTableSlot *epqslot = NULL;
1946
1947 context->cpDeletedSlot = NULL;
1948 context->cpUpdateReturningSlot = NULL;
1949 *retry_slot = NULL;
1950
1951 /*
1952 * Disallow an INSERT ON CONFLICT DO UPDATE that causes the original row
1953 * to migrate to a different partition. Maybe this can be implemented
1954 * some day, but it seems a fringe feature with little redeeming value.
1955 */
1956 if (((ModifyTable *) mtstate->ps.plan)->onConflictAction == ONCONFLICT_UPDATE)
1957 ereport(ERROR,
1958 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1959 errmsg("invalid ON UPDATE specification"),
1960 errdetail("The result tuple would appear in a different partition than the original tuple.")));
1961
1962 /*
1963 * When an UPDATE is run directly on a leaf partition, simply fail with a
1964 * partition constraint violation error.
1965 */
1966 if (resultRelInfo == mtstate->rootResultRelInfo)
1967 ExecPartitionCheckEmitError(resultRelInfo, slot, estate);
1968
1969 /* Initialize tuple routing info if not already done. */
1970 if (mtstate->mt_partition_tuple_routing == NULL)
1971 {
1972 Relation rootRel = mtstate->rootResultRelInfo->ri_RelationDesc;
1973 MemoryContext oldcxt;
1974
1975 /* Things built here have to last for the query duration. */
1976 oldcxt = MemoryContextSwitchTo(estate->es_query_cxt);
1977
1978 mtstate->mt_partition_tuple_routing =
1979 ExecSetupPartitionTupleRouting(estate, rootRel);
1980
1981 /*
1982 * Before a partition's tuple can be re-routed, it must first be
1983 * converted to the root's format, so we'll need a slot for storing
1984 * such tuples.
1985 */
1986 Assert(mtstate->mt_root_tuple_slot == NULL);
1987 mtstate->mt_root_tuple_slot = table_slot_create(rootRel, NULL);
1988
1989 MemoryContextSwitchTo(oldcxt);
1990 }
1991
1992 /*
1993 * Row movement, part 1. Delete the tuple, but skip RETURNING processing.
1994 * We want to return rows from INSERT.
1995 */
1996 ExecDelete(context, resultRelInfo,
1997 tupleid, oldtuple,
1998 false, /* processReturning */
1999 true, /* changingPart */
2000 false, /* canSetTag */
2001 tmresult, &tuple_deleted, &epqslot);
2002
2003 /*
2004 * For some reason if DELETE didn't happen (e.g. trigger prevented it, or
2005 * it was already deleted by self, or it was concurrently deleted by
2006 * another transaction), then we should skip the insert as well;
2007 * otherwise, an UPDATE could cause an increase in the total number of
2008 * rows across all partitions, which is clearly wrong.
2009 *
2010 * For a normal UPDATE, the case where the tuple has been the subject of a
2011 * concurrent UPDATE or DELETE would be handled by the EvalPlanQual
2012 * machinery, but for an UPDATE that we've translated into a DELETE from
2013 * this partition and an INSERT into some other partition, that's not
2014 * available, because CTID chains can't span relation boundaries. We
2015 * mimic the semantics to a limited extent by skipping the INSERT if the
2016 * DELETE fails to find a tuple. This ensures that two concurrent
2017 * attempts to UPDATE the same tuple at the same time can't turn one tuple
2018 * into two, and that an UPDATE of a just-deleted tuple can't resurrect
2019 * it.
2020 */
2021 if (!tuple_deleted)
2022 {
2023 /*
2024 * epqslot will be typically NULL. But when ExecDelete() finds that
2025 * another transaction has concurrently updated the same row, it
2026 * re-fetches the row, skips the delete, and epqslot is set to the
2027 * re-fetched tuple slot. In that case, we need to do all the checks
2028 * again. For MERGE, we leave everything to the caller (it must do
2029 * additional rechecking, and might end up executing a different
2030 * action entirely).
2031 */
2032 if (mtstate->operation == CMD_MERGE)
2033 return *tmresult == TM_Ok;
2034 else if (TupIsNull(epqslot))
2035 return true;
2036 else
2037 {
2038 /* Fetch the most recent version of old tuple. */
2039 TupleTableSlot *oldSlot;
2040
2041 /* ... but first, make sure ri_oldTupleSlot is initialized. */
2042 if (unlikely(!resultRelInfo->ri_projectNewInfoValid))
2043 ExecInitUpdateProjection(mtstate, resultRelInfo);
2044 oldSlot = resultRelInfo->ri_oldTupleSlot;
2045 if (!table_tuple_fetch_row_version(resultRelInfo->ri_RelationDesc,
2046 tupleid,
2047 SnapshotAny,
2048 oldSlot))
2049 elog(ERROR, "failed to fetch tuple being updated");
2050 /* and project the new tuple to retry the UPDATE with */
2051 *retry_slot = ExecGetUpdateNewTuple(resultRelInfo, epqslot,
2052 oldSlot);
2053 return false;
2054 }
2055 }
2056
2057 /*
2058 * resultRelInfo is one of the per-relation resultRelInfos. So we should
2059 * convert the tuple into root's tuple descriptor if needed, since
2060 * ExecInsert() starts the search from root.
2061 */
2062 tupconv_map = ExecGetChildToRootMap(resultRelInfo);
2063 if (tupconv_map != NULL)
2064 slot = execute_attr_map_slot(tupconv_map->attrMap,
2065 slot,
2066 mtstate->mt_root_tuple_slot);
2067
2068 /* Tuple routing starts from the root table. */
2069 context->cpUpdateReturningSlot =
2070 ExecInsert(context, mtstate->rootResultRelInfo, slot, canSetTag,
2071 inserted_tuple, insert_destrel);
2072
2073 /*
2074 * Reset the transition state that may possibly have been written by
2075 * INSERT.
2076 */
2077 if (mtstate->mt_transition_capture)
2078 mtstate->mt_transition_capture->tcs_original_insert_tuple = NULL;
2079
2080 /* We're done moving. */
2081 return true;
2082 }
2083
2084 /*
2085 * ExecUpdatePrologue -- subroutine for ExecUpdate
2086 *
2087 * Prepare executor state for UPDATE. This includes running BEFORE ROW
2088 * triggers. We return false if one of them makes the update a no-op;
2089 * otherwise, return true.
2090 */
2091 static bool
2092 ExecUpdatePrologue(ModifyTableContext *context, ResultRelInfo *resultRelInfo,
2093 ItemPointer tupleid, HeapTuple oldtuple, TupleTableSlot *slot,
2094 TM_Result *result)
2095 {
2096 Relation resultRelationDesc = resultRelInfo->ri_RelationDesc;
2097
2098 if (result)
2099 *result = TM_Ok;
2100
2101 ExecMaterializeSlot(slot);
2102
2103 /*
2104 * Open the table's indexes, if we have not done so already, so that we
2105 * can add new index entries for the updated tuple.
2106 */
2107 if (resultRelationDesc->rd_rel->relhasindex &&
2108 resultRelInfo->ri_IndexRelationDescs == NULL)
2109 ExecOpenIndices(resultRelInfo, false);
2110
2111 /* BEFORE ROW UPDATE triggers */
2112 if (resultRelInfo->ri_TrigDesc &&
2113 resultRelInfo->ri_TrigDesc->trig_update_before_row)
2114 {
2115 /* Flush any pending inserts, so rows are visible to the triggers */
2116 if (context->estate->es_insert_pending_result_relations != NIL)
2117 ExecPendingInserts(context->estate);
2118
2119 return ExecBRUpdateTriggers(context->estate, context->epqstate,
2120 resultRelInfo, tupleid, oldtuple, slot,
2121 result, &context->tmfd,
2122 context->mtstate->operation == CMD_MERGE);
2123 }
2124
2125 return true;
2126 }
2127
2128 /*
2129 * ExecUpdatePrepareSlot -- subroutine for ExecUpdateAct
2130 *
2131 * Apply the final modifications to the tuple slot before the update.
2132 * (This is split out because we also need it in the foreign-table code path.)
2133 */
2134 static void
2135 ExecUpdatePrepareSlot(ResultRelInfo *resultRelInfo,
2136 TupleTableSlot *slot,
2137 EState *estate)
2138 {
2139 Relation resultRelationDesc = resultRelInfo->ri_RelationDesc;
2140
2141 /*
2142 * Constraints and GENERATED expressions might reference the tableoid
2143 * column, so (re-)initialize tts_tableOid before evaluating them.
2144 */
2145 slot->tts_tableOid = RelationGetRelid(resultRelationDesc);
2146
2147 /*
2148 * Compute stored generated columns
2149 */
2150 if (resultRelationDesc->rd_att->constr &&
2151 resultRelationDesc->rd_att->constr->has_generated_stored)
2152 ExecComputeStoredGenerated(resultRelInfo, estate, slot,
2153 CMD_UPDATE);
2154 }
2155
2156 /*
2157 * ExecUpdateAct -- subroutine for ExecUpdate
2158 *
2159 * Actually update the tuple, when operating on a plain table. If the
2160 * table is a partition, and the command was called referencing an ancestor
2161 * partitioned table, this routine migrates the resulting tuple to another
2162 * partition.
2163 *
2164 * The caller is in charge of keeping indexes current as necessary. The
2165 * caller is also in charge of doing EvalPlanQual if the tuple is found to
2166 * be concurrently updated. However, in case of a cross-partition update,
2167 * this routine does it.
2168 */
2169 static TM_Result
2170 ExecUpdateAct(ModifyTableContext *context, ResultRelInfo *resultRelInfo,
2171 ItemPointer tupleid, HeapTuple oldtuple, TupleTableSlot *slot,
2172 bool canSetTag, UpdateContext *updateCxt)
2173 {
2174 EState *estate = context->estate;
2175 Relation resultRelationDesc = resultRelInfo->ri_RelationDesc;
2176 bool partition_constraint_failed;
2177 TM_Result result;
2178
2179 updateCxt->crossPartUpdate = false;
2180
2181 /*
2182 * If we move the tuple to a new partition, we loop back here to recompute
2183 * GENERATED values (which are allowed to be different across partitions)
2184 * and recheck any RLS policies and constraints. We do not fire any
2185 * BEFORE triggers of the new partition, however.
2186 */
2187 lreplace:
2188 /* Fill in GENERATEd columns */
2189 ExecUpdatePrepareSlot(resultRelInfo, slot, estate);
2190
2191 /* ensure slot is independent, consider e.g. EPQ */
2192 ExecMaterializeSlot(slot);
2193
2194 /*
2195 * If partition constraint fails, this row might get moved to another
2196 * partition, in which case we should check the RLS CHECK policy just
2197 * before inserting into the new partition, rather than doing it here.
2198 * This is because a trigger on that partition might again change the row.
2199 * So skip the WCO checks if the partition constraint fails.
2200 */
2201 partition_constraint_failed =
2202 resultRelationDesc->rd_rel->relispartition &&
2203 !ExecPartitionCheck(resultRelInfo, slot, estate, false);
2204
2205 /* Check any RLS UPDATE WITH CHECK policies */
2206 if (!partition_constraint_failed &&
2207 resultRelInfo->ri_WithCheckOptions != NIL)
2208 {
2209 /*
2210 * ExecWithCheckOptions() will skip any WCOs which are not of the kind
2211 * we are looking for at this point.
2212 */
2213 ExecWithCheckOptions(WCO_RLS_UPDATE_CHECK,
2214 resultRelInfo, slot, estate);
2215 }
2216
2217 /*
2218 * If a partition check failed, try to move the row into the right
2219 * partition.
2220 */
2221 if (partition_constraint_failed)
2222 {
2223 TupleTableSlot *inserted_tuple,
2224 *retry_slot;
2225 ResultRelInfo *insert_destrel = NULL;
2226
2227 /*
2228 * ExecCrossPartitionUpdate will first DELETE the row from the
2229 * partition it's currently in and then insert it back into the root
2230 * table, which will re-route it to the correct partition. However,
2231 * if the tuple has been concurrently updated, a retry is needed.
2232 */
2233 if (ExecCrossPartitionUpdate(context, resultRelInfo,
2234 tupleid, oldtuple, slot,
2235 canSetTag, updateCxt,
2236 &result,
2237 &retry_slot,
2238 &inserted_tuple,
2239 &insert_destrel))
2240 {
2241 /* success! */
2242 updateCxt->crossPartUpdate = true;
2243
2244 /*
2245 * If the partitioned table being updated is referenced in foreign
2246 * keys, queue up trigger events to check that none of them were
2247 * violated. No special treatment is needed in
2248 * non-cross-partition update situations, because the leaf
2249 * partition's AR update triggers will take care of that. During
2250 * cross-partition updates implemented as delete on the source
2251 * partition followed by insert on the destination partition,
2252 * AR-UPDATE triggers of the root table (that is, the table
2253 * mentioned in the query) must be fired.
2254 *
2255 * NULL insert_destrel means that the move failed to occur, that
2256 * is, the update failed, so no need to anything in that case.
2257 */
2258 if (insert_destrel &&
2259 resultRelInfo->ri_TrigDesc &&
2260 resultRelInfo->ri_TrigDesc->trig_update_after_row)
2261 ExecCrossPartitionUpdateForeignKey(context,
2262 resultRelInfo,
2263 insert_destrel,
2264 tupleid, slot,
2265 inserted_tuple);
2266
2267 return TM_Ok;
2268 }
2269
2270 /*
2271 * No luck, a retry is needed. If running MERGE, we do not do so
2272 * here; instead let it handle that on its own rules.
2273 */
2274 if (context->mtstate->operation == CMD_MERGE)
2275 return result;
2276
2277 /*
2278 * ExecCrossPartitionUpdate installed an updated version of the new
2279 * tuple in the retry slot; start over.
2280 */
2281 slot = retry_slot;
2282 goto lreplace;
2283 }
2284
2285 /*
2286 * Check the constraints of the tuple. We've already checked the
2287 * partition constraint above; however, we must still ensure the tuple
2288 * passes all other constraints, so we will call ExecConstraints() and
2289 * have it validate all remaining checks.
2290 */
2291 if (resultRelationDesc->rd_att->constr)
2292 ExecConstraints(resultRelInfo, slot, estate);
2293
2294 /*
2295 * replace the heap tuple
2296 *
2297 * Note: if es_crosscheck_snapshot isn't InvalidSnapshot, we check that
2298 * the row to be updated is visible to that snapshot, and throw a
2299 * can't-serialize error if not. This is a special-case behavior needed
2300 * for referential integrity updates in transaction-snapshot mode
2301 * transactions.
2302 */
2303 result = table_tuple_update(resultRelationDesc, tupleid, slot,
2304 estate->es_output_cid,
2305 estate->es_snapshot,
2306 estate->es_crosscheck_snapshot,
2307 true /* wait for commit */ ,
2308 &context->tmfd, &updateCxt->lockmode,
2309 &updateCxt->updateIndexes);
2310
2311 return result;
2312 }
2313
2314 /*
2315 * ExecUpdateEpilogue -- subroutine for ExecUpdate
2316 *
2317 * Closing steps of updating a tuple. Must be called if ExecUpdateAct
2318 * returns indicating that the tuple was updated.
2319 */
2320 static void
2321 ExecUpdateEpilogue(ModifyTableContext *context, UpdateContext *updateCxt,
2322 ResultRelInfo *resultRelInfo, ItemPointer tupleid,
2323 HeapTuple oldtuple, TupleTableSlot *slot)
2324 {
2325 ModifyTableState *mtstate = context->mtstate;
2326 List *recheckIndexes = NIL;
2327
2328 /* insert index entries for tuple if necessary */
2329 if (resultRelInfo->ri_NumIndices > 0 && (updateCxt->updateIndexes != TU_None))
2330 recheckIndexes = ExecInsertIndexTuples(resultRelInfo,
2331 slot, context->estate,
2332 true, false,
2333 NULL, NIL,
2334 (updateCxt->updateIndexes == TU_Summarizing));
2335
2336 /* AFTER ROW UPDATE Triggers */
2337 ExecARUpdateTriggers(context->estate, resultRelInfo,
2338 NULL, NULL,
2339 tupleid, oldtuple, slot,
2340 recheckIndexes,
2341 mtstate->operation == CMD_INSERT ?
2342 mtstate->mt_oc_transition_capture :
2343 mtstate->mt_transition_capture,
2344 false);
2345
2346 list_free(recheckIndexes);
2347
2348 /*
2349 * Check any WITH CHECK OPTION constraints from parent views. We are
2350 * required to do this after testing all constraints and uniqueness
2351 * violations per the SQL spec, so we do it after actually updating the
2352 * record in the heap and all indexes.
2353 *
2354 * ExecWithCheckOptions() will skip any WCOs which are not of the kind we
2355 * are looking for at this point.
2356 */
2357 if (resultRelInfo->ri_WithCheckOptions != NIL)
2358 ExecWithCheckOptions(WCO_VIEW_CHECK, resultRelInfo,
2359 slot, context->estate);
2360 }
2361
2362 /*
2363 * Queues up an update event using the target root partitioned table's
2364 * trigger to check that a cross-partition update hasn't broken any foreign
2365 * keys pointing into it.
2366 */
2367 static void
2368 ExecCrossPartitionUpdateForeignKey(ModifyTableContext *context,
2369 ResultRelInfo *sourcePartInfo,
2370 ResultRelInfo *destPartInfo,
2371 ItemPointer tupleid,
2372 TupleTableSlot *oldslot,
2373 TupleTableSlot *newslot)
2374 {
2375 ListCell *lc;
2376 ResultRelInfo *rootRelInfo;
2377 List *ancestorRels;
2378
2379 rootRelInfo = sourcePartInfo->ri_RootResultRelInfo;
2380 ancestorRels = ExecGetAncestorResultRels(context->estate, sourcePartInfo);
2381
2382 /*
2383 * For any foreign keys that point directly into a non-root ancestors of
2384 * the source partition, we can in theory fire an update event to enforce
2385 * those constraints using their triggers, if we could tell that both the
2386 * source and the destination partitions are under the same ancestor. But
2387 * for now, we simply report an error that those cannot be enforced.
2388 */
2389 foreach(lc, ancestorRels)
2390 {
2391 ResultRelInfo *rInfo = lfirst(lc);
2392 TriggerDesc *trigdesc = rInfo->ri_TrigDesc;
2393 bool has_noncloned_fkey = false;
2394
2395 /* Root ancestor's triggers will be processed. */
2396 if (rInfo == rootRelInfo)
2397 continue;
2398
2399 if (trigdesc && trigdesc->trig_update_after_row)
2400 {
2401 for (int i = 0; i < trigdesc->numtriggers; i++)
2402 {
2403 Trigger *trig = &trigdesc->triggers[i];
2404
2405 if (!trig->tgisclone &&
2406 RI_FKey_trigger_type(trig->tgfoid) == RI_TRIGGER_PK)
2407 {
2408 has_noncloned_fkey = true;
2409 break;
2410 }
2411 }
2412 }
2413
2414 if (has_noncloned_fkey)
2415 ereport(ERROR,
2416 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2417 errmsg("cannot move tuple across partitions when a non-root ancestor of the source partition is directly referenced in a foreign key"),
2418 errdetail("A foreign key points to ancestor \"%s\" but not the root ancestor \"%s\".",
2419 RelationGetRelationName(rInfo->ri_RelationDesc),
2420 RelationGetRelationName(rootRelInfo->ri_RelationDesc)),
2421 errhint("Consider defining the foreign key on table \"%s\".",
2422 RelationGetRelationName(rootRelInfo->ri_RelationDesc))));
2423 }
2424
2425 /* Perform the root table's triggers. */
2426 ExecARUpdateTriggers(context->estate,
2427 rootRelInfo, sourcePartInfo, destPartInfo,
2428 tupleid, NULL, newslot, NIL, NULL, true);
2429 }
2430
2431 /* ----------------------------------------------------------------
2432 * ExecUpdate
2433 *
2434 * note: we can't run UPDATE queries with transactions
2435 * off because UPDATEs are actually INSERTs and our
2436 * scan will mistakenly loop forever, updating the tuple
2437 * it just inserted.. This should be fixed but until it
2438 * is, we don't want to get stuck in an infinite loop
2439 * which corrupts your database..
2440 *
2441 * When updating a table, tupleid identifies the tuple to update and
2442 * oldtuple is NULL. When updating through a view INSTEAD OF trigger,
2443 * oldtuple is passed to the triggers and identifies what to update, and
2444 * tupleid is invalid. When updating a foreign table, tupleid is
2445 * invalid; the FDW has to figure out which row to update using data from
2446 * the planSlot. oldtuple is passed to foreign table triggers; it is
2447 * NULL when the foreign table has no relevant triggers.
2448 *
2449 * oldSlot contains the old tuple value.
2450 * slot contains the new tuple value to be stored.
2451 * planSlot is the output of the ModifyTable's subplan; we use it
2452 * to access values from other input tables (for RETURNING),
2453 * row-ID junk columns, etc.
2454 *
2455 * Returns RETURNING result if any, otherwise NULL. On exit, if tupleid
2456 * had identified the tuple to update, it will identify the tuple
2457 * actually updated after EvalPlanQual.
2458 * ----------------------------------------------------------------
2459 */
2460 static TupleTableSlot *
2461 ExecUpdate(ModifyTableContext *context, ResultRelInfo *resultRelInfo,
2462 ItemPointer tupleid, HeapTuple oldtuple, TupleTableSlot *oldSlot,
2463 TupleTableSlot *slot, bool canSetTag)
2464 {
2465 EState *estate = context->estate;
2466 Relation resultRelationDesc = resultRelInfo->ri_RelationDesc;
2467 UpdateContext updateCxt = {0};
2468 TM_Result result;
2469
2470 /*
2471 * abort the operation if not running transactions
2472 */
2473 if (IsBootstrapProcessingMode())
2474 elog(ERROR, "cannot UPDATE during bootstrap");
2475
2476 /*
2477 * Prepare for the update. This includes BEFORE ROW triggers, so we're
2478 * done if it says we are.
2479 */
2480 context->tmfd.traversed = false;
2481 if (!ExecUpdatePrologue(context, resultRelInfo, tupleid, oldtuple, slot, NULL))
2482 return NULL;
2483
2484 /*
2485 * If the target tuple was concurrently updated, the trigger code will
2486 * have done EPQ and updated tupleid, following the update chain. In this
2487 * case, we must fetch the most recent version of old tuple for the
2488 * benefit of RETURNING. Technically, we could get away with not doing
2489 * this, if there is no RETURNING clause, or it doesn't refer to OLD, but
2490 * it seems preferable to always ensure that the contents of oldSlot are
2491 * correct.
2492 */
2493 if (context->tmfd.traversed)
2494 {
2495 if (!table_tuple_fetch_row_version(resultRelInfo->ri_RelationDesc,
2496 tupleid,
2497 SnapshotAny,
2498 oldSlot))
2499 elog(ERROR, "failed to re-fetch tuple updated during trigger execution");
2500 }
2501
2502 /* INSTEAD OF ROW UPDATE Triggers */
2503 if (resultRelInfo->ri_TrigDesc &&
2504 resultRelInfo->ri_TrigDesc->trig_update_instead_row)
2505 {
2506 if (!ExecIRUpdateTriggers(estate, resultRelInfo,
2507 oldtuple, slot))
2508 return NULL; /* "do nothing" */
2509 }
2510 else if (resultRelInfo->ri_FdwRoutine)
2511 {
2512 /* Fill in GENERATEd columns */
2513 ExecUpdatePrepareSlot(resultRelInfo, slot, estate);
2514
2515 /*
2516 * update in foreign table: let the FDW do it
2517 */
2518 slot = resultRelInfo->ri_FdwRoutine->ExecForeignUpdate(estate,
2519 resultRelInfo,
2520 slot,
2521 context->planSlot);
2522
2523 if (slot == NULL) /* "do nothing" */
2524 return NULL;
2525
2526 /*
2527 * AFTER ROW Triggers or RETURNING expressions might reference the
2528 * tableoid column, so (re-)initialize tts_tableOid before evaluating
2529 * them. (This covers the case where the FDW replaced the slot.)
2530 */
2531 slot->tts_tableOid = RelationGetRelid(resultRelationDesc);
2532 }
2533 else
2534 {
2535 ItemPointerData lockedtid;
2536
2537 /*
2538 * If we generate a new candidate tuple after EvalPlanQual testing, we
2539 * must loop back here to try again. (We don't need to redo triggers,
2540 * however. If there are any BEFORE triggers then trigger.c will have
2541 * done table_tuple_lock to lock the correct tuple, so there's no need
2542 * to do them again.)
2543 */
2544 redo_act:
2545 lockedtid = *tupleid;
2546 result = ExecUpdateAct(context, resultRelInfo, tupleid, oldtuple, slot,
2547 canSetTag, &updateCxt);
2548
2549 /*
2550 * If ExecUpdateAct reports that a cross-partition update was done,
2551 * then the RETURNING tuple (if any) has been projected and there's
2552 * nothing else for us to do.
2553 */
2554 if (updateCxt.crossPartUpdate)
2555 return context->cpUpdateReturningSlot;
2556
2557 switch (result)
2558 {
2559 case TM_SelfModified:
2560
2561 /*
2562 * The target tuple was already updated or deleted by the
2563 * current command, or by a later command in the current
2564 * transaction. The former case is possible in a join UPDATE
2565 * where multiple tuples join to the same target tuple. This
2566 * is pretty questionable, but Postgres has always allowed it:
2567 * we just execute the first update action and ignore
2568 * additional update attempts.
2569 *
2570 * The latter case arises if the tuple is modified by a
2571 * command in a BEFORE trigger, or perhaps by a command in a
2572 * volatile function used in the query. In such situations we
2573 * should not ignore the update, but it is equally unsafe to
2574 * proceed. We don't want to discard the original UPDATE
2575 * while keeping the triggered actions based on it; and we
2576 * have no principled way to merge this update with the
2577 * previous ones. So throwing an error is the only safe
2578 * course.
2579 *
2580 * If a trigger actually intends this type of interaction, it
2581 * can re-execute the UPDATE (assuming it can figure out how)
2582 * and then return NULL to cancel the outer update.
2583 */
2584 if (context->tmfd.cmax != estate->es_output_cid)
2585 ereport(ERROR,
2586 (errcode(ERRCODE_TRIGGERED_DATA_CHANGE_VIOLATION),
2587 errmsg("tuple to be updated was already modified by an operation triggered by the current command"),
2588 errhint("Consider using an AFTER trigger instead of a BEFORE trigger to propagate changes to other rows.")));
2589
2590 /* Else, already updated by self; nothing to do */
2591 return NULL;
2592
2593 case TM_Ok:
2594 break;
2595
2596 case TM_Updated:
2597 {
2598 TupleTableSlot *inputslot;
2599 TupleTableSlot *epqslot;
2600
2601 if (IsolationUsesXactSnapshot())
2602 ereport(ERROR,
2603 (errcode(ERRCODE_T_R_SERIALIZATION_FAILURE),
2604 errmsg("could not serialize access due to concurrent update")));
2605
2606 /*
2607 * Already know that we're going to need to do EPQ, so
2608 * fetch tuple directly into the right slot.
2609 */
2610 inputslot = EvalPlanQualSlot(context->epqstate, resultRelationDesc,
2611 resultRelInfo->ri_RangeTableIndex);
2612
2613 result = table_tuple_lock(resultRelationDesc, tupleid,
2614 estate->es_snapshot,
2615 inputslot, estate->es_output_cid,
2616 updateCxt.lockmode, LockWaitBlock,
2617 TUPLE_LOCK_FLAG_FIND_LAST_VERSION,
2618 &context->tmfd);
2619
2620 switch (result)
2621 {
2622 case TM_Ok:
2623 Assert(context->tmfd.traversed);
2624
2625 epqslot = EvalPlanQual(context->epqstate,
2626 resultRelationDesc,
2627 resultRelInfo->ri_RangeTableIndex,
2628 inputslot);
2629 if (TupIsNull(epqslot))
2630 /* Tuple not passing quals anymore, exiting... */
2631 return NULL;
2632
2633 /* Make sure ri_oldTupleSlot is initialized. */
2634 if (unlikely(!resultRelInfo->ri_projectNewInfoValid))
2635 ExecInitUpdateProjection(context->mtstate,
2636 resultRelInfo);
2637
2638 if (resultRelInfo->ri_needLockTagTuple)
2639 {
2640 UnlockTuple(resultRelationDesc,
2641 &lockedtid, InplaceUpdateTupleLock);
2642 LockTuple(resultRelationDesc,
2643 tupleid, InplaceUpdateTupleLock);
2644 }
2645
2646 /* Fetch the most recent version of old tuple. */
2647 oldSlot = resultRelInfo->ri_oldTupleSlot;
2648 if (!table_tuple_fetch_row_version(resultRelationDesc,
2649 tupleid,
2650 SnapshotAny,
2651 oldSlot))
2652 elog(ERROR, "failed to fetch tuple being updated");
2653 slot = ExecGetUpdateNewTuple(resultRelInfo,
2654 epqslot, oldSlot);
2655 goto redo_act;
2656
2657 case TM_Deleted:
2658 /* tuple already deleted; nothing to do */
2659 return NULL;
2660
2661 case TM_SelfModified:
2662
2663 /*
2664 * This can be reached when following an update
2665 * chain from a tuple updated by another session,
2666 * reaching a tuple that was already updated in
2667 * this transaction. If previously modified by
2668 * this command, ignore the redundant update,
2669 * otherwise error out.
2670 *
2671 * See also TM_SelfModified response to
2672 * table_tuple_update() above.
2673 */
2674 if (context->tmfd.cmax != estate->es_output_cid)
2675 ereport(ERROR,
2676 (errcode(ERRCODE_TRIGGERED_DATA_CHANGE_VIOLATION),
2677 errmsg("tuple to be updated was already modified by an operation triggered by the current command"),
2678 errhint("Consider using an AFTER trigger instead of a BEFORE trigger to propagate changes to other rows.")));
2679 return NULL;
2680
2681 default:
2682 /* see table_tuple_lock call in ExecDelete() */
2683 elog(ERROR, "unexpected table_tuple_lock status: %u",
2684 result);
2685 return NULL;
2686 }
2687 }
2688
2689 break;
2690
2691 case TM_Deleted:
2692 if (IsolationUsesXactSnapshot())
2693 ereport(ERROR,
2694 (errcode(ERRCODE_T_R_SERIALIZATION_FAILURE),
2695 errmsg("could not serialize access due to concurrent delete")));
2696 /* tuple already deleted; nothing to do */
2697 return NULL;
2698
2699 default:
2700 elog(ERROR, "unrecognized table_tuple_update status: %u",
2701 result);
2702 return NULL;
2703 }
2704 }
2705
2706 if (canSetTag)
2707 (estate->es_processed)++;
2708
2709 ExecUpdateEpilogue(context, &updateCxt, resultRelInfo, tupleid, oldtuple,
2710 slot);
2711
2712 /* Process RETURNING if present */
2713 if (resultRelInfo->ri_projectReturning)
2714 return ExecProcessReturning(context, resultRelInfo, CMD_UPDATE,
2715 oldSlot, slot, context->planSlot);
2716
2717 return NULL;
2718 }
2719
2720 /*
2721 * ExecOnConflictUpdate --- execute UPDATE of INSERT ON CONFLICT DO UPDATE
2722 *
2723 * Try to lock tuple for update as part of speculative insertion. If
2724 * a qual originating from ON CONFLICT DO UPDATE is satisfied, update
2725 * (but still lock row, even though it may not satisfy estate's
2726 * snapshot).
2727 *
2728 * Returns true if we're done (with or without an update), or false if
2729 * the caller must retry the INSERT from scratch.
2730 */
2731 static bool
2732 ExecOnConflictUpdate(ModifyTableContext *context,
2733 ResultRelInfo *resultRelInfo,
2734 ItemPointer conflictTid,
2735 TupleTableSlot *excludedSlot,
2736 bool canSetTag,
2737 TupleTableSlot **returning)
2738 {
2739 ModifyTableState *mtstate = context->mtstate;
2740 ExprContext *econtext = mtstate->ps.ps_ExprContext;
2741 Relation relation = resultRelInfo->ri_RelationDesc;
2742 ExprState *onConflictSetWhere = resultRelInfo->ri_onConflict->oc_WhereClause;
2743 TupleTableSlot *existing = resultRelInfo->ri_onConflict->oc_Existing;
2744 TM_FailureData tmfd;
2745 LockTupleMode lockmode;
2746 TM_Result test;
2747 Datum xminDatum;
2748 TransactionId xmin;
2749 bool isnull;
2750
2751 /*
2752 * Parse analysis should have blocked ON CONFLICT for all system
2753 * relations, which includes these. There's no fundamental obstacle to
2754 * supporting this; we'd just need to handle LOCKTAG_TUPLE like the other
2755 * ExecUpdate() caller.
2756 */
2757 Assert(!resultRelInfo->ri_needLockTagTuple);
2758
2759 /* Determine lock mode to use */
2760 lockmode = ExecUpdateLockMode(context->estate, resultRelInfo);
2761
2762 /*
2763 * Lock tuple for update. Don't follow updates when tuple cannot be
2764 * locked without doing so. A row locking conflict here means our
2765 * previous conclusion that the tuple is conclusively committed is not
2766 * true anymore.
2767 */
2768 test = table_tuple_lock(relation, conflictTid,
2769 context->estate->es_snapshot,
2770 existing, context->estate->es_output_cid,
2771 lockmode, LockWaitBlock, 0,
2772 &tmfd);
2773 switch (test)
2774 {
2775 case TM_Ok:
2776 /* success! */
2777 break;
2778
2779 case TM_Invisible:
2780
2781 /*
2782 * This can occur when a just inserted tuple is updated again in
2783 * the same command. E.g. because multiple rows with the same
2784 * conflicting key values are inserted.
2785 *
2786 * This is somewhat similar to the ExecUpdate() TM_SelfModified
2787 * case. We do not want to proceed because it would lead to the
2788 * same row being updated a second time in some unspecified order,
2789 * and in contrast to plain UPDATEs there's no historical behavior
2790 * to break.
2791 *
2792 * It is the user's responsibility to prevent this situation from
2793 * occurring. These problems are why the SQL standard similarly
2794 * specifies that for SQL MERGE, an exception must be raised in
2795 * the event of an attempt to update the same row twice.
2796 */
2797 xminDatum = slot_getsysattr(existing,
2798 MinTransactionIdAttributeNumber,
2799 &isnull);
2800 Assert(!isnull);
2801 xmin = DatumGetTransactionId(xminDatum);
2802
2803 if (TransactionIdIsCurrentTransactionId(xmin))
2804 ereport(ERROR,
2805 (errcode(ERRCODE_CARDINALITY_VIOLATION),
2806 /* translator: %s is a SQL command name */
2807 errmsg("%s command cannot affect row a second time",
2808 "ON CONFLICT DO UPDATE"),
2809 errhint("Ensure that no rows proposed for insertion within the same command have duplicate constrained values.")));
2810
2811 /* This shouldn't happen */
2812 elog(ERROR, "attempted to lock invisible tuple");
2813 break;
2814
2815 case TM_SelfModified:
2816
2817 /*
2818 * This state should never be reached. As a dirty snapshot is used
2819 * to find conflicting tuples, speculative insertion wouldn't have
2820 * seen this row to conflict with.
2821 */
2822 elog(ERROR, "unexpected self-updated tuple");
2823 break;
2824
2825 case TM_Updated:
2826 if (IsolationUsesXactSnapshot())
2827 ereport(ERROR,
2828 (errcode(ERRCODE_T_R_SERIALIZATION_FAILURE),
2829 errmsg("could not serialize access due to concurrent update")));
2830
2831 /*
2832 * Tell caller to try again from the very start.
2833 *
2834 * It does not make sense to use the usual EvalPlanQual() style
2835 * loop here, as the new version of the row might not conflict
2836 * anymore, or the conflicting tuple has actually been deleted.
2837 */
2838 ExecClearTuple(existing);
2839 return false;
2840
2841 case TM_Deleted:
2842 if (IsolationUsesXactSnapshot())
2843 ereport(ERROR,
2844 (errcode(ERRCODE_T_R_SERIALIZATION_FAILURE),
2845 errmsg("could not serialize access due to concurrent delete")));
2846
2847 /* see TM_Updated case */
2848 ExecClearTuple(existing);
2849 return false;
2850
2851 default:
2852 elog(ERROR, "unrecognized table_tuple_lock status: %u", test);
2853 }
2854
2855 /* Success, the tuple is locked. */
2856
2857 /*
2858 * Verify that the tuple is visible to our MVCC snapshot if the current
2859 * isolation level mandates that.
2860 *
2861 * It's not sufficient to rely on the check within ExecUpdate() as e.g.
2862 * CONFLICT ... WHERE clause may prevent us from reaching that.
2863 *
2864 * This means we only ever continue when a new command in the current
2865 * transaction could see the row, even though in READ COMMITTED mode the
2866 * tuple will not be visible according to the current statement's
2867 * snapshot. This is in line with the way UPDATE deals with newer tuple
2868 * versions.
2869 */
2870 ExecCheckTupleVisible(context->estate, relation, existing);
2871
2872 /*
2873 * Make tuple and any needed join variables available to ExecQual and
2874 * ExecProject. The EXCLUDED tuple is installed in ecxt_innertuple, while
2875 * the target's existing tuple is installed in the scantuple. EXCLUDED
2876 * has been made to reference INNER_VAR in setrefs.c, but there is no
2877 * other redirection.
2878 */
2879 econtext->ecxt_scantuple = existing;
2880 econtext->ecxt_innertuple = excludedSlot;
2881 econtext->ecxt_outertuple = NULL;
2882
2883 if (!ExecQual(onConflictSetWhere, econtext))
2884 {
2885 ExecClearTuple(existing); /* see return below */
2886 InstrCountFiltered1(&mtstate->ps, 1);
2887 return true; /* done with the tuple */
2888 }
2889
2890 if (resultRelInfo->ri_WithCheckOptions != NIL)
2891 {
2892 /*
2893 * Check target's existing tuple against UPDATE-applicable USING
2894 * security barrier quals (if any), enforced here as RLS checks/WCOs.
2895 *
2896 * The rewriter creates UPDATE RLS checks/WCOs for UPDATE security
2897 * quals, and stores them as WCOs of "kind" WCO_RLS_CONFLICT_CHECK,
2898 * but that's almost the extent of its special handling for ON
2899 * CONFLICT DO UPDATE.
2900 *
2901 * The rewriter will also have associated UPDATE applicable straight
2902 * RLS checks/WCOs for the benefit of the ExecUpdate() call that
2903 * follows. INSERTs and UPDATEs naturally have mutually exclusive WCO
2904 * kinds, so there is no danger of spurious over-enforcement in the
2905 * INSERT or UPDATE path.
2906 */
2907 ExecWithCheckOptions(WCO_RLS_CONFLICT_CHECK, resultRelInfo,
2908 existing,
2909 mtstate->ps.state);
2910 }
2911
2912 /* Project the new tuple version */
2913 ExecProject(resultRelInfo->ri_onConflict->oc_ProjInfo);
2914
2915 /*
2916 * Note that it is possible that the target tuple has been modified in
2917 * this session, after the above table_tuple_lock. We choose to not error
2918 * out in that case, in line with ExecUpdate's treatment of similar cases.
2919 * This can happen if an UPDATE is triggered from within ExecQual(),
2920 * ExecWithCheckOptions() or ExecProject() above, e.g. by selecting from a
2921 * wCTE in the ON CONFLICT's SET.
2922 */
2923
2924 /* Execute UPDATE with projection */
2925 *returning = ExecUpdate(context, resultRelInfo,
2926 conflictTid, NULL, existing,
2927 resultRelInfo->ri_onConflict->oc_ProjSlot,
2928 canSetTag);
2929
2930 /*
2931 * Clear out existing tuple, as there might not be another conflict among
2932 * the next input rows. Don't want to hold resources till the end of the
2933 * query. First though, make sure that the returning slot, if any, has a
2934 * local copy of any OLD pass-by-reference values, if it refers to any OLD
2935 * columns.
2936 */
2937 if (*returning != NULL &&
2938 resultRelInfo->ri_projectReturning->pi_state.flags & EEO_FLAG_HAS_OLD)
2939 ExecMaterializeSlot(*returning);
2940
2941 ExecClearTuple(existing);
2942
2943 return true;
2944 }
2945
2946 /*
2947 * Perform MERGE.
2948 */
2949 static TupleTableSlot *
2950 ExecMerge(ModifyTableContext *context, ResultRelInfo *resultRelInfo,
2951 ItemPointer tupleid, HeapTuple oldtuple, bool canSetTag)
2952 {
2953 TupleTableSlot *rslot = NULL;
2954 bool matched;
2955
2956 /*-----
2957 * If we are dealing with a WHEN MATCHED case, tupleid or oldtuple is
2958 * valid, depending on whether the result relation is a table or a view.
2959 * We execute the first action for which the additional WHEN MATCHED AND
2960 * quals pass. If an action without quals is found, that action is
2961 * executed.
2962 *
2963 * Similarly, in the WHEN NOT MATCHED BY SOURCE case, tupleid or oldtuple
2964 * is valid, and we look at the given WHEN NOT MATCHED BY SOURCE actions
2965 * in sequence until one passes. This is almost identical to the WHEN
2966 * MATCHED case, and both cases are handled by ExecMergeMatched().
2967 *
2968 * Finally, in the WHEN NOT MATCHED [BY TARGET] case, both tupleid and
2969 * oldtuple are invalid, and we look at the given WHEN NOT MATCHED [BY
2970 * TARGET] actions in sequence until one passes.
2971 *
2972 * Things get interesting in case of concurrent update/delete of the
2973 * target tuple. Such concurrent update/delete is detected while we are
2974 * executing a WHEN MATCHED or WHEN NOT MATCHED BY SOURCE action.
2975 *
2976 * A concurrent update can:
2977 *
2978 * 1. modify the target tuple so that the results from checking any
2979 * additional quals attached to WHEN MATCHED or WHEN NOT MATCHED BY
2980 * SOURCE actions potentially change, but the result from the join
2981 * quals does not change.
2982 *
2983 * In this case, we are still dealing with the same kind of match
2984 * (MATCHED or NOT MATCHED BY SOURCE). We recheck the same list of
2985 * actions from the start and choose the first one that satisfies the
2986 * new target tuple.
2987 *
2988 * 2. modify the target tuple in the WHEN MATCHED case so that the join
2989 * quals no longer pass and hence the source and target tuples no
2990 * longer match.
2991 *
2992 * In this case, we are now dealing with a NOT MATCHED case, and we
2993 * process both WHEN NOT MATCHED BY SOURCE and WHEN NOT MATCHED [BY
2994 * TARGET] actions. First ExecMergeMatched() processes the list of
2995 * WHEN NOT MATCHED BY SOURCE actions in sequence until one passes,
2996 * then ExecMergeNotMatched() processes any WHEN NOT MATCHED [BY
2997 * TARGET] actions in sequence until one passes. Thus we may execute
2998 * two actions; one of each kind.
2999 *
3000 * Thus we support concurrent updates that turn MATCHED candidate rows
3001 * into NOT MATCHED rows. However, we do not attempt to support cases
3002 * that would turn NOT MATCHED rows into MATCHED rows, or which would
3003 * cause a target row to match a different source row.
3004 *
3005 * A concurrent delete changes a WHEN MATCHED case to WHEN NOT MATCHED
3006 * [BY TARGET].
3007 *
3008 * ExecMergeMatched() takes care of following the update chain and
3009 * re-finding the qualifying WHEN MATCHED or WHEN NOT MATCHED BY SOURCE
3010 * action, as long as the target tuple still exists. If the target tuple
3011 * gets deleted or a concurrent update causes the join quals to fail, it
3012 * returns a matched status of false and we call ExecMergeNotMatched().
3013 * Given that ExecMergeMatched() always makes progress by following the
3014 * update chain and we never switch from ExecMergeNotMatched() to
3015 * ExecMergeMatched(), there is no risk of a livelock.
3016 */
3017 matched = tupleid != NULL || oldtuple != NULL;
3018 if (matched)
3019 rslot = ExecMergeMatched(context, resultRelInfo, tupleid, oldtuple,
3020 canSetTag, &matched);
3021
3022 /*
3023 * Deal with the NOT MATCHED case (either a NOT MATCHED tuple from the
3024 * join, or a previously MATCHED tuple for which ExecMergeMatched() set
3025 * "matched" to false, indicating that it no longer matches).
3026 */
3027 if (!matched)
3028 {
3029 /*
3030 * If a concurrent update turned a MATCHED case into a NOT MATCHED
3031 * case, and we have both WHEN NOT MATCHED BY SOURCE and WHEN NOT
3032 * MATCHED [BY TARGET] actions, and there is a RETURNING clause,
3033 * ExecMergeMatched() may have already executed a WHEN NOT MATCHED BY
3034 * SOURCE action, and computed the row to return. If so, we cannot
3035 * execute a WHEN NOT MATCHED [BY TARGET] action now, so mark it as
3036 * pending (to be processed on the next call to ExecModifyTable()).
3037 * Otherwise, just process the action now.
3038 */
3039 if (rslot == NULL)
3040 rslot = ExecMergeNotMatched(context, resultRelInfo, canSetTag);
3041 else
3042 context->mtstate->mt_merge_pending_not_matched = context->planSlot;
3043 }
3044
3045 return rslot;
3046 }
3047
3048 /*
3049 * Check and execute the first qualifying MATCHED or NOT MATCHED BY SOURCE
3050 * action, depending on whether the join quals are satisfied. If the target
3051 * relation is a table, the current target tuple is identified by tupleid.
3052 * Otherwise, if the target relation is a view, oldtuple is the current target
3053 * tuple from the view.
3054 *
3055 * We start from the first WHEN MATCHED or WHEN NOT MATCHED BY SOURCE action
3056 * and check if the WHEN quals pass, if any. If the WHEN quals for the first
3057 * action do not pass, we check the second, then the third and so on. If we
3058 * reach the end without finding a qualifying action, we return NULL.
3059 * Otherwise, we execute the qualifying action and return its RETURNING
3060 * result, if any, or NULL.
3061 *
3062 * On entry, "*matched" is assumed to be true. If a concurrent update or
3063 * delete is detected that causes the join quals to no longer pass, we set it
3064 * to false, indicating that the caller should process any NOT MATCHED [BY
3065 * TARGET] actions.
3066 *
3067 * After a concurrent update, we restart from the first action to look for a
3068 * new qualifying action to execute. If the join quals originally passed, and
3069 * the concurrent update caused them to no longer pass, then we switch from
3070 * the MATCHED to the NOT MATCHED BY SOURCE list of actions before restarting
3071 * (and setting "*matched" to false). As a result we may execute a WHEN NOT
3072 * MATCHED BY SOURCE action, and set "*matched" to false, causing the caller
3073 * to also execute a WHEN NOT MATCHED [BY TARGET] action.
3074 */
3075 static TupleTableSlot *
3076 ExecMergeMatched(ModifyTableContext *context, ResultRelInfo *resultRelInfo,
3077 ItemPointer tupleid, HeapTuple oldtuple, bool canSetTag,
3078 bool *matched)
3079 {
3080 ModifyTableState *mtstate = context->mtstate;
3081 List **mergeActions = resultRelInfo->ri_MergeActions;
3082 ItemPointerData lockedtid;
3083 List *actionStates;
3084 TupleTableSlot *newslot = NULL;
3085 TupleTableSlot *rslot = NULL;
3086 EState *estate = context->estate;
3087 ExprContext *econtext = mtstate->ps.ps_ExprContext;
3088 bool isNull;
3089 EPQState *epqstate = &mtstate->mt_epqstate;
3090 ListCell *l;
3091
3092 /* Expect matched to be true on entry */
3093 Assert(*matched);
3094
3095 /*
3096 * If there are no WHEN MATCHED or WHEN NOT MATCHED BY SOURCE actions, we
3097 * are done.
3098 */
3099 if (mergeActions[MERGE_WHEN_MATCHED] == NIL &&
3100 mergeActions[MERGE_WHEN_NOT_MATCHED_BY_SOURCE] == NIL)
3101 return NULL;
3102
3103 /*
3104 * Make tuple and any needed join variables available to ExecQual and
3105 * ExecProject. The target's existing tuple is installed in the scantuple.
3106 * This target relation's slot is required only in the case of a MATCHED
3107 * or NOT MATCHED BY SOURCE tuple and UPDATE/DELETE actions.
3108 */
3109 econtext->ecxt_scantuple = resultRelInfo->ri_oldTupleSlot;
3110 econtext->ecxt_innertuple = context->planSlot;
3111 econtext->ecxt_outertuple = NULL;
3112
3113 /*
3114 * This routine is only invoked for matched target rows, so we should
3115 * either have the tupleid of the target row, or an old tuple from the
3116 * target wholerow junk attr.
3117 */
3118 Assert(tupleid != NULL || oldtuple != NULL);
3119 ItemPointerSetInvalid(&lockedtid);
3120 if (oldtuple != NULL)
3121 {
3122 Assert(!resultRelInfo->ri_needLockTagTuple);
3123 ExecForceStoreHeapTuple(oldtuple, resultRelInfo->ri_oldTupleSlot,
3124 false);
3125 }
3126 else
3127 {
3128 if (resultRelInfo->ri_needLockTagTuple)
3129 {
3130 /*
3131 * This locks even for CMD_DELETE, for CMD_NOTHING, and for tuples
3132 * that don't match mas_whenqual. MERGE on system catalogs is a
3133 * minor use case, so don't bother optimizing those.
3134 */
3135 LockTuple(resultRelInfo->ri_RelationDesc, tupleid,
3136 InplaceUpdateTupleLock);
3137 lockedtid = *tupleid;
3138 }
3139 if (!table_tuple_fetch_row_version(resultRelInfo->ri_RelationDesc,
3140 tupleid,
3141 SnapshotAny,
3142 resultRelInfo->ri_oldTupleSlot))
3143 elog(ERROR, "failed to fetch the target tuple");
3144 }
3145
3146 /*
3147 * Test the join condition. If it's satisfied, perform a MATCHED action.
3148 * Otherwise, perform a NOT MATCHED BY SOURCE action.
3149 *
3150 * Note that this join condition will be NULL if there are no NOT MATCHED
3151 * BY SOURCE actions --- see transform_MERGE_to_join(). In that case, we
3152 * need only consider MATCHED actions here.
3153 */
3154 if (ExecQual(resultRelInfo->ri_MergeJoinCondition, econtext))
3155 actionStates = mergeActions[MERGE_WHEN_MATCHED];
3156 else
3157 actionStates = mergeActions[MERGE_WHEN_NOT_MATCHED_BY_SOURCE];
3158
3159 lmerge_matched:
3160
3161 foreach(l, actionStates)
3162 {
3163 MergeActionState *relaction = (MergeActionState *) lfirst(l);
3164 CmdType commandType = relaction->mas_action->commandType;
3165 TM_Result result;
3166 UpdateContext updateCxt = {0};
3167
3168 /*
3169 * Test condition, if any.
3170 *
3171 * In the absence of any condition, we perform the action
3172 * unconditionally (no need to check separately since ExecQual() will
3173 * return true if there are no conditions to evaluate).
3174 */
3175 if (!ExecQual(relaction->mas_whenqual, econtext))
3176 continue;
3177
3178 /*
3179 * Check if the existing target tuple meets the USING checks of
3180 * UPDATE/DELETE RLS policies. If those checks fail, we throw an
3181 * error.
3182 *
3183 * The WITH CHECK quals for UPDATE RLS policies are applied in
3184 * ExecUpdateAct() and hence we need not do anything special to handle
3185 * them.
3186 *
3187 * NOTE: We must do this after WHEN quals are evaluated, so that we
3188 * check policies only when they matter.
3189 */
3190 if (resultRelInfo->ri_WithCheckOptions && commandType != CMD_NOTHING)
3191 {
3192 ExecWithCheckOptions(commandType == CMD_UPDATE ?
3193 WCO_RLS_MERGE_UPDATE_CHECK : WCO_RLS_MERGE_DELETE_CHECK,
3194 resultRelInfo,
3195 resultRelInfo->ri_oldTupleSlot,
3196 context->mtstate->ps.state);
3197 }
3198
3199 /* Perform stated action */
3200 switch (commandType)
3201 {
3202 case CMD_UPDATE:
3203
3204 /*
3205 * Project the output tuple, and use that to update the table.
3206 * We don't need to filter out junk attributes, because the
3207 * UPDATE action's targetlist doesn't have any.
3208 */
3209 newslot = ExecProject(relaction->mas_proj);
3210
3211 mtstate->mt_merge_action = relaction;
3212 if (!ExecUpdatePrologue(context, resultRelInfo,
3213 tupleid, NULL, newslot, &result))
3214 {
3215 if (result == TM_Ok)
3216 goto out; /* "do nothing" */
3217
3218 break; /* concurrent update/delete */
3219 }
3220
3221 /* INSTEAD OF ROW UPDATE Triggers */
3222 if (resultRelInfo->ri_TrigDesc &&
3223 resultRelInfo->ri_TrigDesc->trig_update_instead_row)
3224 {
3225 if (!ExecIRUpdateTriggers(estate, resultRelInfo,
3226 oldtuple, newslot))
3227 goto out; /* "do nothing" */
3228 }
3229 else
3230 {
3231 /* checked ri_needLockTagTuple above */
3232 Assert(oldtuple == NULL);
3233
3234 result = ExecUpdateAct(context, resultRelInfo, tupleid,
3235 NULL, newslot, canSetTag,
3236 &updateCxt);
3237
3238 /*
3239 * As in ExecUpdate(), if ExecUpdateAct() reports that a
3240 * cross-partition update was done, then there's nothing
3241 * else for us to do --- the UPDATE has been turned into a
3242 * DELETE and an INSERT, and we must not perform any of
3243 * the usual post-update tasks. Also, the RETURNING tuple
3244 * (if any) has been projected, so we can just return
3245 * that.
3246 */
3247 if (updateCxt.crossPartUpdate)
3248 {
3249 mtstate->mt_merge_updated += 1;
3250 rslot = context->cpUpdateReturningSlot;
3251 goto out;
3252 }
3253 }
3254
3255 if (result == TM_Ok)
3256 {
3257 ExecUpdateEpilogue(context, &updateCxt, resultRelInfo,
3258 tupleid, NULL, newslot);
3259 mtstate->mt_merge_updated += 1;
3260 }
3261 break;
3262
3263 case CMD_DELETE:
3264 mtstate->mt_merge_action = relaction;
3265 if (!ExecDeletePrologue(context, resultRelInfo, tupleid,
3266 NULL, NULL, &result))
3267 {
3268 if (result == TM_Ok)
3269 goto out; /* "do nothing" */
3270
3271 break; /* concurrent update/delete */
3272 }
3273
3274 /* INSTEAD OF ROW DELETE Triggers */
3275 if (resultRelInfo->ri_TrigDesc &&
3276 resultRelInfo->ri_TrigDesc->trig_delete_instead_row)
3277 {
3278 if (!ExecIRDeleteTriggers(estate, resultRelInfo,
3279 oldtuple))
3280 goto out; /* "do nothing" */
3281 }
3282 else
3283 {
3284 /* checked ri_needLockTagTuple above */
3285 Assert(oldtuple == NULL);
3286
3287 result = ExecDeleteAct(context, resultRelInfo, tupleid,
3288 false);
3289 }
3290
3291 if (result == TM_Ok)
3292 {
3293 ExecDeleteEpilogue(context, resultRelInfo, tupleid, NULL,
3294 false);
3295 mtstate->mt_merge_deleted += 1;
3296 }
3297 break;
3298
3299 case CMD_NOTHING:
3300 /* Doing nothing is always OK */
3301 result = TM_Ok;
3302 break;
3303
3304 default:
3305 elog(ERROR, "unknown action in MERGE WHEN clause");
3306 }
3307
3308 switch (result)
3309 {
3310 case TM_Ok:
3311 /* all good; perform final actions */
3312 if (canSetTag && commandType != CMD_NOTHING)
3313 (estate->es_processed)++;
3314
3315 break;
3316
3317 case TM_SelfModified:
3318
3319 /*
3320 * The target tuple was already updated or deleted by the
3321 * current command, or by a later command in the current
3322 * transaction. The former case is explicitly disallowed by
3323 * the SQL standard for MERGE, which insists that the MERGE
3324 * join condition should not join a target row to more than
3325 * one source row.
3326 *
3327 * The latter case arises if the tuple is modified by a
3328 * command in a BEFORE trigger, or perhaps by a command in a
3329 * volatile function used in the query. In such situations we
3330 * should not ignore the MERGE action, but it is equally
3331 * unsafe to proceed. We don't want to discard the original
3332 * MERGE action while keeping the triggered actions based on
3333 * it; and it would be no better to allow the original MERGE
3334 * action while discarding the updates that it triggered. So
3335 * throwing an error is the only safe course.
3336 */
3337 if (context->tmfd.cmax != estate->es_output_cid)
3338 ereport(ERROR,
3339 (errcode(ERRCODE_TRIGGERED_DATA_CHANGE_VIOLATION),
3340 errmsg("tuple to be updated or deleted was already modified by an operation triggered by the current command"),
3341 errhint("Consider using an AFTER trigger instead of a BEFORE trigger to propagate changes to other rows.")));
3342
3343 if (TransactionIdIsCurrentTransactionId(context->tmfd.xmax))
3344 ereport(ERROR,
3345 (errcode(ERRCODE_CARDINALITY_VIOLATION),
3346 /* translator: %s is a SQL command name */
3347 errmsg("%s command cannot affect row a second time",
3348 "MERGE"),
3349 errhint("Ensure that not more than one source row matches any one target row.")));
3350
3351 /* This shouldn't happen */
3352 elog(ERROR, "attempted to update or delete invisible tuple");
3353 break;
3354
3355 case TM_Deleted:
3356 if (IsolationUsesXactSnapshot())
3357 ereport(ERROR,
3358 (errcode(ERRCODE_T_R_SERIALIZATION_FAILURE),
3359 errmsg("could not serialize access due to concurrent delete")));
3360
3361 /*
3362 * If the tuple was already deleted, set matched to false to
3363 * let caller handle it under NOT MATCHED [BY TARGET] clauses.
3364 */
3365 *matched = false;
3366 goto out;
3367
3368 case TM_Updated:
3369 {
3370 bool was_matched;
3371 Relation resultRelationDesc;
3372 TupleTableSlot *epqslot,
3373 *inputslot;
3374 LockTupleMode lockmode;
3375
3376 if (IsolationUsesXactSnapshot())
3377 ereport(ERROR,
3378 (errcode(ERRCODE_T_R_SERIALIZATION_FAILURE),
3379 errmsg("could not serialize access due to concurrent update")));
3380
3381 /*
3382 * The target tuple was concurrently updated by some other
3383 * transaction. If we are currently processing a MATCHED
3384 * action, use EvalPlanQual() with the new version of the
3385 * tuple and recheck the join qual, to detect a change
3386 * from the MATCHED to the NOT MATCHED cases. If we are
3387 * already processing a NOT MATCHED BY SOURCE action, we
3388 * skip this (cannot switch from NOT MATCHED BY SOURCE to
3389 * MATCHED).
3390 */
3391 was_matched = relaction->mas_action->matchKind == MERGE_WHEN_MATCHED;
3392 resultRelationDesc = resultRelInfo->ri_RelationDesc;
3393 lockmode = ExecUpdateLockMode(estate, resultRelInfo);
3394
3395 if (was_matched)
3396 inputslot = EvalPlanQualSlot(epqstate, resultRelationDesc,
3397 resultRelInfo->ri_RangeTableIndex);
3398 else
3399 inputslot = resultRelInfo->ri_oldTupleSlot;
3400
3401 result = table_tuple_lock(resultRelationDesc, tupleid,
3402 estate->es_snapshot,
3403 inputslot, estate->es_output_cid,
3404 lockmode, LockWaitBlock,
3405 TUPLE_LOCK_FLAG_FIND_LAST_VERSION,
3406 &context->tmfd);
3407 switch (result)
3408 {
3409 case TM_Ok:
3410
3411 /*
3412 * If the tuple was updated and migrated to
3413 * another partition concurrently, the current
3414 * MERGE implementation can't follow. There's
3415 * probably a better way to handle this case, but
3416 * it'd require recognizing the relation to which
3417 * the tuple moved, and setting our current
3418 * resultRelInfo to that.
3419 */
3420 if (ItemPointerIndicatesMovedPartitions(tupleid))
3421 ereport(ERROR,
3422 (errcode(ERRCODE_T_R_SERIALIZATION_FAILURE),
3423 errmsg("tuple to be merged was already moved to another partition due to concurrent update")));
3424
3425 /*
3426 * If this was a MATCHED case, use EvalPlanQual()
3427 * to recheck the join condition.
3428 */
3429 if (was_matched)
3430 {
3431 epqslot = EvalPlanQual(epqstate,
3432 resultRelationDesc,
3433 resultRelInfo->ri_RangeTableIndex,
3434 inputslot);
3435
3436 /*
3437 * If the subplan didn't return a tuple, then
3438 * we must be dealing with an inner join for
3439 * which the join condition no longer matches.
3440 * This can only happen if there are no NOT
3441 * MATCHED actions, and so there is nothing
3442 * more to do.
3443 */
3444 if (TupIsNull(epqslot))
3445 goto out;
3446
3447 /*
3448 * If we got a NULL ctid from the subplan, the
3449 * join quals no longer pass and we switch to
3450 * the NOT MATCHED BY SOURCE case.
3451 */
3452 (void) ExecGetJunkAttribute(epqslot,
3453 resultRelInfo->ri_RowIdAttNo,
3454 &isNull);
3455 if (isNull)
3456 *matched = false;
3457
3458 /*
3459 * Otherwise, recheck the join quals to see if
3460 * we need to switch to the NOT MATCHED BY
3461 * SOURCE case.
3462 */
3463 if (resultRelInfo->ri_needLockTagTuple)
3464 {
3465 if (ItemPointerIsValid(&lockedtid))
3466 UnlockTuple(resultRelInfo->ri_RelationDesc, &lockedtid,
3467 InplaceUpdateTupleLock);
3468 LockTuple(resultRelInfo->ri_RelationDesc, tupleid,
3469 InplaceUpdateTupleLock);
3470 lockedtid = *tupleid;
3471 }
3472
3473 if (!table_tuple_fetch_row_version(resultRelationDesc,
3474 tupleid,
3475 SnapshotAny,
3476 resultRelInfo->ri_oldTupleSlot))
3477 elog(ERROR, "failed to fetch the target tuple");
3478
3479 if (*matched)
3480 *matched = ExecQual(resultRelInfo->ri_MergeJoinCondition,
3481 econtext);
3482
3483 /* Switch lists, if necessary */
3484 if (!*matched)
3485 {
3486 actionStates = mergeActions[MERGE_WHEN_NOT_MATCHED_BY_SOURCE];
3487
3488 /*
3489 * If we have both NOT MATCHED BY SOURCE
3490 * and NOT MATCHED BY TARGET actions (a
3491 * full join between the source and target
3492 * relations), the single previously
3493 * matched tuple from the outer plan node
3494 * is treated as two not matched tuples,
3495 * in the same way as if they had not
3496 * matched to start with. Therefore, we
3497 * must adjust the outer plan node's tuple
3498 * count, if we're instrumenting the
3499 * query, to get the correct "skipped" row
3500 * count --- see show_modifytable_info().
3501 */
3502 if (outerPlanState(mtstate)->instrument &&
3503 mergeActions[MERGE_WHEN_NOT_MATCHED_BY_SOURCE] &&
3504 mergeActions[MERGE_WHEN_NOT_MATCHED_BY_TARGET])
3505 InstrUpdateTupleCount(outerPlanState(mtstate)->instrument, 1.0);
3506 }
3507 }
3508
3509 /*
3510 * Loop back and process the MATCHED or NOT
3511 * MATCHED BY SOURCE actions from the start.
3512 */
3513 goto lmerge_matched;
3514
3515 case TM_Deleted:
3516
3517 /*
3518 * tuple already deleted; tell caller to run NOT
3519 * MATCHED [BY TARGET] actions
3520 */
3521 *matched = false;
3522 goto out;
3523
3524 case TM_SelfModified:
3525
3526 /*
3527 * This can be reached when following an update
3528 * chain from a tuple updated by another session,
3529 * reaching a tuple that was already updated or
3530 * deleted by the current command, or by a later
3531 * command in the current transaction. As above,
3532 * this should always be treated as an error.
3533 */
3534 if (context->tmfd.cmax != estate->es_output_cid)
3535 ereport(ERROR,
3536 (errcode(ERRCODE_TRIGGERED_DATA_CHANGE_VIOLATION),
3537 errmsg("tuple to be updated or deleted was already modified by an operation triggered by the current command"),
3538 errhint("Consider using an AFTER trigger instead of a BEFORE trigger to propagate changes to other rows.")));
3539
3540 if (TransactionIdIsCurrentTransactionId(context->tmfd.xmax))
3541 ereport(ERROR,
3542 (errcode(ERRCODE_CARDINALITY_VIOLATION),
3543 /* translator: %s is a SQL command name */
3544 errmsg("%s command cannot affect row a second time",
3545 "MERGE"),
3546 errhint("Ensure that not more than one source row matches any one target row.")));
3547
3548 /* This shouldn't happen */
3549 elog(ERROR, "attempted to update or delete invisible tuple");
3550 goto out;
3551
3552 default:
3553 /* see table_tuple_lock call in ExecDelete() */
3554 elog(ERROR, "unexpected table_tuple_lock status: %u",
3555 result);
3556 goto out;
3557 }
3558 }
3559
3560 case TM_Invisible:
3561 case TM_WouldBlock:
3562 case TM_BeingModified:
3563 /* these should not occur */
3564 elog(ERROR, "unexpected tuple operation result: %d", result);
3565 break;
3566 }
3567
3568 /* Process RETURNING if present */
3569 if (resultRelInfo->ri_projectReturning)
3570 {
3571 switch (commandType)
3572 {
3573 case CMD_UPDATE:
3574 rslot = ExecProcessReturning(context,
3575 resultRelInfo,
3576 CMD_UPDATE,
3577 resultRelInfo->ri_oldTupleSlot,
3578 newslot,
3579 context->planSlot);
3580 break;
3581
3582 case CMD_DELETE:
3583 rslot = ExecProcessReturning(context,
3584 resultRelInfo,
3585 CMD_DELETE,
3586 resultRelInfo->ri_oldTupleSlot,
3587 NULL,
3588 context->planSlot);
3589 break;
3590
3591 case CMD_NOTHING:
3592 break;
3593
3594 default:
3595 elog(ERROR, "unrecognized commandType: %d",
3596 (int) commandType);
3597 }
3598 }
3599
3600 /*
3601 * We've activated one of the WHEN clauses, so we don't search
3602 * further. This is required behaviour, not an optimization.
3603 */
3604 break;
3605 }
3606
3607 /*
3608 * Successfully executed an action or no qualifying action was found.
3609 */
3610 out:
3611 if (ItemPointerIsValid(&lockedtid))
3612 UnlockTuple(resultRelInfo->ri_RelationDesc, &lockedtid,
3613 InplaceUpdateTupleLock);
3614 return rslot;
3615 }
3616
3617 /*
3618 * Execute the first qualifying NOT MATCHED [BY TARGET] action.
3619 */
3620 static TupleTableSlot *
3621 ExecMergeNotMatched(ModifyTableContext *context, ResultRelInfo *resultRelInfo,
3622 bool canSetTag)
3623 {
3624 ModifyTableState *mtstate = context->mtstate;
3625 ExprContext *econtext = mtstate->ps.ps_ExprContext;
3626 List *actionStates;
3627 TupleTableSlot *rslot = NULL;
3628 ListCell *l;
3629
3630 /*
3631 * For INSERT actions, the root relation's merge action is OK since the
3632 * INSERT's targetlist and the WHEN conditions can only refer to the
3633 * source relation and hence it does not matter which result relation we
3634 * work with.
3635 *
3636 * XXX does this mean that we can avoid creating copies of actionStates on
3637 * partitioned tables, for not-matched actions?
3638 */
3639 actionStates = resultRelInfo->ri_MergeActions[MERGE_WHEN_NOT_MATCHED_BY_TARGET];
3640
3641 /*
3642 * Make source tuple available to ExecQual and ExecProject. We don't need
3643 * the target tuple, since the WHEN quals and targetlist can't refer to
3644 * the target columns.
3645 */
3646 econtext->ecxt_scantuple = NULL;
3647 econtext->ecxt_innertuple = context->planSlot;
3648 econtext->ecxt_outertuple = NULL;
3649
3650 foreach(l, actionStates)
3651 {
3652 MergeActionState *action = (MergeActionState *) lfirst(l);
3653 CmdType commandType = action->mas_action->commandType;
3654 TupleTableSlot *newslot;
3655
3656 /*
3657 * Test condition, if any.
3658 *
3659 * In the absence of any condition, we perform the action
3660 * unconditionally (no need to check separately since ExecQual() will
3661 * return true if there are no conditions to evaluate).
3662 */
3663 if (!ExecQual(action->mas_whenqual, econtext))
3664 continue;
3665
3666 /* Perform stated action */
3667 switch (commandType)
3668 {
3669 case CMD_INSERT:
3670
3671 /*
3672 * Project the tuple. In case of a partitioned table, the
3673 * projection was already built to use the root's descriptor,
3674 * so we don't need to map the tuple here.
3675 */
3676 newslot = ExecProject(action->mas_proj);
3677 mtstate->mt_merge_action = action;
3678
3679 rslot = ExecInsert(context, mtstate->rootResultRelInfo,
3680 newslot, canSetTag, NULL, NULL);
3681 mtstate->mt_merge_inserted += 1;
3682 break;
3683 case CMD_NOTHING:
3684 /* Do nothing */
3685 break;
3686 default:
3687 elog(ERROR, "unknown action in MERGE WHEN NOT MATCHED clause");
3688 }
3689
3690 /*
3691 * We've activated one of the WHEN clauses, so we don't search
3692 * further. This is required behaviour, not an optimization.
3693 */
3694 break;
3695 }
3696
3697 return rslot;
3698 }
3699
3700 /*
3701 * Initialize state for execution of MERGE.
3702 */
3703 void
3704 ExecInitMerge(ModifyTableState *mtstate, EState *estate)
3705 {
3706 List *mergeActionLists = mtstate->mt_mergeActionLists;
3707 List *mergeJoinConditions = mtstate->mt_mergeJoinConditions;
3708 ResultRelInfo *rootRelInfo = mtstate->rootResultRelInfo;
3709 ResultRelInfo *resultRelInfo;
3710 ExprContext *econtext;
3711 ListCell *lc;
3712 int i;
3713
3714 if (mergeActionLists == NIL)
3715 return;
3716
3717 mtstate->mt_merge_subcommands = 0;
3718
3719 if (mtstate->ps.ps_ExprContext == NULL)
3720 ExecAssignExprContext(estate, &mtstate->ps);
3721 econtext = mtstate->ps.ps_ExprContext;
3722
3723 /*
3724 * Create a MergeActionState for each action on the mergeActionList and
3725 * add it to either a list of matched actions or not-matched actions.
3726 *
3727 * Similar logic appears in ExecInitPartitionInfo(), so if changing
3728 * anything here, do so there too.
3729 */
3730 i = 0;
3731 foreach(lc, mergeActionLists)
3732 {
3733 List *mergeActionList = lfirst(lc);
3734 Node *joinCondition;
3735 TupleDesc relationDesc;
3736 ListCell *l;
3737
3738 joinCondition = (Node *) list_nth(mergeJoinConditions, i);
3739 resultRelInfo = mtstate->resultRelInfo + i;
3740 i++;
3741 relationDesc = RelationGetDescr(resultRelInfo->ri_RelationDesc);
3742
3743 /* initialize slots for MERGE fetches from this rel */
3744 if (unlikely(!resultRelInfo->ri_projectNewInfoValid))
3745 ExecInitMergeTupleSlots(mtstate, resultRelInfo);
3746
3747 /* initialize state for join condition checking */
3748 resultRelInfo->ri_MergeJoinCondition =
3749 ExecInitQual((List *) joinCondition, &mtstate->ps);
3750
3751 foreach(l, mergeActionList)
3752 {
3753 MergeAction *action = (MergeAction *) lfirst(l);
3754 MergeActionState *action_state;
3755 TupleTableSlot *tgtslot;
3756 TupleDesc tgtdesc;
3757
3758 /*
3759 * Build action merge state for this rel. (For partitions,
3760 * equivalent code exists in ExecInitPartitionInfo.)
3761 */
3762 action_state = makeNode(MergeActionState);
3763 action_state->mas_action = action;
3764 action_state->mas_whenqual = ExecInitQual((List *) action->qual,
3765 &mtstate->ps);
3766
3767 /*
3768 * We create three lists - one for each MergeMatchKind - and stick
3769 * the MergeActionState into the appropriate list.
3770 */
3771 resultRelInfo->ri_MergeActions[action->matchKind] =
3772 lappend(resultRelInfo->ri_MergeActions[action->matchKind],
3773 action_state);
3774
3775 switch (action->commandType)
3776 {
3777 case CMD_INSERT:
3778 /* INSERT actions always use rootRelInfo */
3779 ExecCheckPlanOutput(rootRelInfo->ri_RelationDesc,
3780 action->targetList);
3781
3782 /*
3783 * If the MERGE targets a partitioned table, any INSERT
3784 * actions must be routed through it, not the child
3785 * relations. Initialize the routing struct and the root
3786 * table's "new" tuple slot for that, if not already done.
3787 * The projection we prepare, for all relations, uses the
3788 * root relation descriptor, and targets the plan's root
3789 * slot. (This is consistent with the fact that we
3790 * checked the plan output to match the root relation,
3791 * above.)
3792 */
3793 if (rootRelInfo->ri_RelationDesc->rd_rel->relkind ==
3794 RELKIND_PARTITIONED_TABLE)
3795 {
3796 if (mtstate->mt_partition_tuple_routing == NULL)
3797 {
3798 /*
3799 * Initialize planstate for routing if not already
3800 * done.
3801 *
3802 * Note that the slot is managed as a standalone
3803 * slot belonging to ModifyTableState, so we pass
3804 * NULL for the 2nd argument.
3805 */
3806 mtstate->mt_root_tuple_slot =
3807 table_slot_create(rootRelInfo->ri_RelationDesc,
3808 NULL);
3809 mtstate->mt_partition_tuple_routing =
3810 ExecSetupPartitionTupleRouting(estate,
3811 rootRelInfo->ri_RelationDesc);
3812 }
3813 tgtslot = mtstate->mt_root_tuple_slot;
3814 tgtdesc = RelationGetDescr(rootRelInfo->ri_RelationDesc);
3815 }
3816 else
3817 {
3818 /*
3819 * If the MERGE targets an inherited table, we insert
3820 * into the root table, so we must initialize its
3821 * "new" tuple slot, if not already done, and use its
3822 * relation descriptor for the projection.
3823 *
3824 * For non-inherited tables, rootRelInfo and
3825 * resultRelInfo are the same, and the "new" tuple
3826 * slot will already have been initialized.
3827 */
3828 if (rootRelInfo->ri_newTupleSlot == NULL)
3829 rootRelInfo->ri_newTupleSlot =
3830 table_slot_create(rootRelInfo->ri_RelationDesc,
3831 &estate->es_tupleTable);
3832
3833 tgtslot = rootRelInfo->ri_newTupleSlot;
3834 tgtdesc = RelationGetDescr(rootRelInfo->ri_RelationDesc);
3835 }
3836
3837 action_state->mas_proj =
3838 ExecBuildProjectionInfo(action->targetList, econtext,
3839 tgtslot,
3840 &mtstate->ps,
3841 tgtdesc);
3842
3843 mtstate->mt_merge_subcommands |= MERGE_INSERT;
3844 break;
3845 case CMD_UPDATE:
3846 action_state->mas_proj =
3847 ExecBuildUpdateProjection(action->targetList,
3848 true,
3849 action->updateColnos,
3850 relationDesc,
3851 econtext,
3852 resultRelInfo->ri_newTupleSlot,
3853 &mtstate->ps);
3854 mtstate->mt_merge_subcommands |= MERGE_UPDATE;
3855 break;
3856 case CMD_DELETE:
3857 mtstate->mt_merge_subcommands |= MERGE_DELETE;
3858 break;
3859 case CMD_NOTHING:
3860 break;
3861 default:
3862 elog(ERROR, "unknown action in MERGE WHEN clause");
3863 break;
3864 }
3865 }
3866 }
3867
3868 /*
3869 * If the MERGE targets an inherited table, any INSERT actions will use
3870 * rootRelInfo, and rootRelInfo will not be in the resultRelInfo array.
3871 * Therefore we must initialize its WITH CHECK OPTION constraints and
3872 * RETURNING projection, as ExecInitModifyTable did for the resultRelInfo
3873 * entries.
3874 *
3875 * Note that the planner does not build a withCheckOptionList or
3876 * returningList for the root relation, but as in ExecInitPartitionInfo,
3877 * we can use the first resultRelInfo entry as a reference to calculate
3878 * the attno's for the root table.
3879 */
3880 if (rootRelInfo != mtstate->resultRelInfo &&
3881 rootRelInfo->ri_RelationDesc->rd_rel->relkind != RELKIND_PARTITIONED_TABLE &&
3882 (mtstate->mt_merge_subcommands & MERGE_INSERT) != 0)
3883 {
3884 ModifyTable *node = (ModifyTable *) mtstate->ps.plan;
3885 Relation rootRelation = rootRelInfo->ri_RelationDesc;
3886 Relation firstResultRel = mtstate->resultRelInfo[0].ri_RelationDesc;
3887 int firstVarno = mtstate->resultRelInfo[0].ri_RangeTableIndex;
3888 AttrMap *part_attmap = NULL;
3889 bool found_whole_row;
3890
3891 if (node->withCheckOptionLists != NIL)
3892 {
3893 List *wcoList;
3894 List *wcoExprs = NIL;
3895
3896 /* There should be as many WCO lists as result rels */
3897 Assert(list_length(node->withCheckOptionLists) ==
3898 list_length(node->resultRelations));
3899
3900 /*
3901 * Use the first WCO list as a reference. In the most common case,
3902 * this will be for the same relation as rootRelInfo, and so there
3903 * will be no need to adjust its attno's.
3904 */
3905 wcoList = linitial(node->withCheckOptionLists);
3906 if (rootRelation != firstResultRel)
3907 {
3908 /* Convert any Vars in it to contain the root's attno's */
3909 part_attmap =
3910 build_attrmap_by_name(RelationGetDescr(rootRelation),
3911 RelationGetDescr(firstResultRel),
3912 false);
3913
3914 wcoList = (List *)
3915 map_variable_attnos((Node *) wcoList,
3916 firstVarno, 0,
3917 part_attmap,
3918 RelationGetForm(rootRelation)->reltype,
3919 &found_whole_row);
3920 }
3921
3922 foreach(lc, wcoList)
3923 {
3924 WithCheckOption *wco = lfirst_node(WithCheckOption, lc);
3925 ExprState *wcoExpr = ExecInitQual(castNode(List, wco->qual),
3926 &mtstate->ps);
3927
3928 wcoExprs = lappend(wcoExprs, wcoExpr);
3929 }
3930
3931 rootRelInfo->ri_WithCheckOptions = wcoList;
3932 rootRelInfo->ri_WithCheckOptionExprs = wcoExprs;
3933 }
3934
3935 if (node->returningLists != NIL)
3936 {
3937 List *returningList;
3938
3939 /* There should be as many returning lists as result rels */
3940 Assert(list_length(node->returningLists) ==
3941 list_length(node->resultRelations));
3942
3943 /*
3944 * Use the first returning list as a reference. In the most common
3945 * case, this will be for the same relation as rootRelInfo, and so
3946 * there will be no need to adjust its attno's.
3947 */
3948 returningList = linitial(node->returningLists);
3949 if (rootRelation != firstResultRel)
3950 {
3951 /* Convert any Vars in it to contain the root's attno's */
3952 if (part_attmap == NULL)
3953 part_attmap =
3954 build_attrmap_by_name(RelationGetDescr(rootRelation),
3955 RelationGetDescr(firstResultRel),
3956 false);
3957
3958 returningList = (List *)
3959 map_variable_attnos((Node *) returningList,
3960 firstVarno, 0,
3961 part_attmap,
3962 RelationGetForm(rootRelation)->reltype,
3963 &found_whole_row);
3964 }
3965 rootRelInfo->ri_returningList = returningList;
3966
3967 /* Initialize the RETURNING projection */
3968 rootRelInfo->ri_projectReturning =
3969 ExecBuildProjectionInfo(returningList, econtext,
3970 mtstate->ps.ps_ResultTupleSlot,
3971 &mtstate->ps,
3972 RelationGetDescr(rootRelation));
3973 }
3974 }
3975 }
3976
3977 /*
3978 * Initializes the tuple slots in a ResultRelInfo for any MERGE action.
3979 *
3980 * We mark 'projectNewInfoValid' even though the projections themselves
3981 * are not initialized here.
3982 */
3983 void
3984 ExecInitMergeTupleSlots(ModifyTableState *mtstate,
3985 ResultRelInfo *resultRelInfo)
3986 {
3987 EState *estate = mtstate->ps.state;
3988
3989 Assert(!resultRelInfo->ri_projectNewInfoValid);
3990
3991 resultRelInfo->ri_oldTupleSlot =
3992 table_slot_create(resultRelInfo->ri_RelationDesc,
3993 &estate->es_tupleTable);
3994 resultRelInfo->ri_newTupleSlot =
3995 table_slot_create(resultRelInfo->ri_RelationDesc,
3996 &estate->es_tupleTable);
3997 resultRelInfo->ri_projectNewInfoValid = true;
3998 }
3999
4000 /*
4001 * Process BEFORE EACH STATEMENT triggers
4002 */
4003 static void
4004 fireBSTriggers(ModifyTableState *node)
4005 {
4006 ModifyTable *plan = (ModifyTable *) node->ps.plan;
4007 ResultRelInfo *resultRelInfo = node->rootResultRelInfo;
4008
4009 switch (node->operation)
4010 {
4011 case CMD_INSERT:
4012 ExecBSInsertTriggers(node->ps.state, resultRelInfo);
4013 if (plan->onConflictAction == ONCONFLICT_UPDATE)
4014 ExecBSUpdateTriggers(node->ps.state,
4015 resultRelInfo);
4016 break;
4017 case CMD_UPDATE:
4018 ExecBSUpdateTriggers(node->ps.state, resultRelInfo);
4019 break;
4020 case CMD_DELETE:
4021 ExecBSDeleteTriggers(node->ps.state, resultRelInfo);
4022 break;
4023 case CMD_MERGE:
4024 if (node->mt_merge_subcommands & MERGE_INSERT)
4025 ExecBSInsertTriggers(node->ps.state, resultRelInfo);
4026 if (node->mt_merge_subcommands & MERGE_UPDATE)
4027 ExecBSUpdateTriggers(node->ps.state, resultRelInfo);
4028 if (node->mt_merge_subcommands & MERGE_DELETE)
4029 ExecBSDeleteTriggers(node->ps.state, resultRelInfo);
4030 break;
4031 default:
4032 elog(ERROR, "unknown operation");
4033 break;
4034 }
4035 }
4036
4037 /*
4038 * Process AFTER EACH STATEMENT triggers
4039 */
4040 static void
4041 fireASTriggers(ModifyTableState *node)
4042 {
4043 ModifyTable *plan = (ModifyTable *) node->ps.plan;
4044 ResultRelInfo *resultRelInfo = node->rootResultRelInfo;
4045
4046 switch (node->operation)
4047 {
4048 case CMD_INSERT:
4049 if (plan->onConflictAction == ONCONFLICT_UPDATE)
4050 ExecASUpdateTriggers(node->ps.state,
4051 resultRelInfo,
4052 node->mt_oc_transition_capture);
4053 ExecASInsertTriggers(node->ps.state, resultRelInfo,
4054 node->mt_transition_capture);
4055 break;
4056 case CMD_UPDATE:
4057 ExecASUpdateTriggers(node->ps.state, resultRelInfo,
4058 node->mt_transition_capture);
4059 break;
4060 case CMD_DELETE:
4061 ExecASDeleteTriggers(node->ps.state, resultRelInfo,
4062 node->mt_transition_capture);
4063 break;
4064 case CMD_MERGE:
4065 if (node->mt_merge_subcommands & MERGE_DELETE)
4066 ExecASDeleteTriggers(node->ps.state, resultRelInfo,
4067 node->mt_transition_capture);
4068 if (node->mt_merge_subcommands & MERGE_UPDATE)
4069 ExecASUpdateTriggers(node->ps.state, resultRelInfo,
4070 node->mt_transition_capture);
4071 if (node->mt_merge_subcommands & MERGE_INSERT)
4072 ExecASInsertTriggers(node->ps.state, resultRelInfo,
4073 node->mt_transition_capture);
4074 break;
4075 default:
4076 elog(ERROR, "unknown operation");
4077 break;
4078 }
4079 }
4080
4081 /*
4082 * Set up the state needed for collecting transition tuples for AFTER
4083 * triggers.
4084 */
4085 static void
4086 ExecSetupTransitionCaptureState(ModifyTableState *mtstate, EState *estate)
4087 {
4088 ModifyTable *plan = (ModifyTable *) mtstate->ps.plan;
4089 ResultRelInfo *targetRelInfo = mtstate->rootResultRelInfo;
4090
4091 /* Check for transition tables on the directly targeted relation. */
4092 mtstate->mt_transition_capture =
4093 MakeTransitionCaptureState(targetRelInfo->ri_TrigDesc,
4094 RelationGetRelid(targetRelInfo->ri_RelationDesc),
4095 mtstate->operation);
4096 if (plan->operation == CMD_INSERT &&
4097 plan->onConflictAction == ONCONFLICT_UPDATE)
4098 mtstate->mt_oc_transition_capture =
4099 MakeTransitionCaptureState(targetRelInfo->ri_TrigDesc,
4100 RelationGetRelid(targetRelInfo->ri_RelationDesc),
4101 CMD_UPDATE);
4102 }
4103
4104 /*
4105 * ExecPrepareTupleRouting --- prepare for routing one tuple
4106 *
4107 * Determine the partition in which the tuple in slot is to be inserted,
4108 * and return its ResultRelInfo in *partRelInfo. The return value is
4109 * a slot holding the tuple of the partition rowtype.
4110 *
4111 * This also sets the transition table information in mtstate based on the
4112 * selected partition.
4113 */
4114 static TupleTableSlot *
4115 ExecPrepareTupleRouting(ModifyTableState *mtstate,
4116 EState *estate,
4117 PartitionTupleRouting *proute,
4118 ResultRelInfo *targetRelInfo,
4119 TupleTableSlot *slot,
4120 ResultRelInfo **partRelInfo)
4121 {
4122 ResultRelInfo *partrel;
4123 TupleConversionMap *map;
4124
4125 /*
4126 * Lookup the target partition's ResultRelInfo. If ExecFindPartition does
4127 * not find a valid partition for the tuple in 'slot' then an error is
4128 * raised. An error may also be raised if the found partition is not a
4129 * valid target for INSERTs. This is required since a partitioned table
4130 * UPDATE to another partition becomes a DELETE+INSERT.
4131 */
4132 partrel = ExecFindPartition(mtstate, targetRelInfo, proute, slot, estate);
4133
4134 /*
4135 * If we're capturing transition tuples, we might need to convert from the
4136 * partition rowtype to root partitioned table's rowtype. But if there
4137 * are no BEFORE triggers on the partition that could change the tuple, we
4138 * can just remember the original unconverted tuple to avoid a needless
4139 * round trip conversion.
4140 */
4141 if (mtstate->mt_transition_capture != NULL)
4142 {
4143 bool has_before_insert_row_trig;
4144
4145 has_before_insert_row_trig = (partrel->ri_TrigDesc &&
4146 partrel->ri_TrigDesc->trig_insert_before_row);
4147
4148 mtstate->mt_transition_capture->tcs_original_insert_tuple =
4149 !has_before_insert_row_trig ? slot : NULL;
4150 }
4151
4152 /*
4153 * Convert the tuple, if necessary.
4154 */
4155 map = ExecGetRootToChildMap(partrel, estate);
4156 if (map != NULL)
4157 {
4158 TupleTableSlot *new_slot = partrel->ri_PartitionTupleSlot;
4159
4160 slot = execute_attr_map_slot(map->attrMap, slot, new_slot);
4161 }
4162
4163 *partRelInfo = partrel;
4164 return slot;
4165 }
4166
4167 /* ----------------------------------------------------------------
4168 * ExecModifyTable
4169 *
4170 * Perform table modifications as required, and return RETURNING results
4171 * if needed.
4172 * ----------------------------------------------------------------
4173 */
4174 static TupleTableSlot *
4175 ExecModifyTable(PlanState *pstate)
4176 {
4177 ModifyTableState *node = castNode(ModifyTableState, pstate);
4178 ModifyTableContext context;
4179 EState *estate = node->ps.state;
4180 CmdType operation = node->operation;
4181 ResultRelInfo *resultRelInfo;
4182 PlanState *subplanstate;
4183 TupleTableSlot *slot;
4184 TupleTableSlot *oldSlot;
4185 ItemPointerData tuple_ctid;
4186 HeapTupleData oldtupdata;
4187 HeapTuple oldtuple;
4188 ItemPointer tupleid;
4189 bool tuplock;
4190
4191 CHECK_FOR_INTERRUPTS();
4192
4193 /*
4194 * This should NOT get called during EvalPlanQual; we should have passed a
4195 * subplan tree to EvalPlanQual, instead. Use a runtime test not just
4196 * Assert because this condition is easy to miss in testing. (Note:
4197 * although ModifyTable should not get executed within an EvalPlanQual
4198 * operation, we do have to allow it to be initialized and shut down in
4199 * case it is within a CTE subplan. Hence this test must be here, not in
4200 * ExecInitModifyTable.)
4201 */
4202 if (estate->es_epq_active != NULL)
4203 elog(ERROR, "ModifyTable should not be called during EvalPlanQual");
4204
4205 /*
4206 * If we've already completed processing, don't try to do more. We need
4207 * this test because ExecPostprocessPlan might call us an extra time, and
4208 * our subplan's nodes aren't necessarily robust against being called
4209 * extra times.
4210 */
4211 if (node->mt_done)
4212 return NULL;
4213
4214 /*
4215 * On first call, fire BEFORE STATEMENT triggers before proceeding.
4216 */
4217 if (node->fireBSTriggers)
4218 {
4219 fireBSTriggers(node);
4220 node->fireBSTriggers = false;
4221 }
4222
4223 /* Preload local variables */
4224 resultRelInfo = node->resultRelInfo + node->mt_lastResultIndex;
4225 subplanstate = outerPlanState(node);
4226
4227 /* Set global context */
4228 context.mtstate = node;
4229 context.epqstate = &node->mt_epqstate;
4230 context.estate = estate;
4231
4232 /*
4233 * Fetch rows from subplan, and execute the required table modification
4234 * for each row.
4235 */
4236 for (;;)
4237 {
4238 /*
4239 * Reset the per-output-tuple exprcontext. This is needed because
4240 * triggers expect to use that context as workspace. It's a bit ugly
4241 * to do this below the top level of the plan, however. We might need
4242 * to rethink this later.
4243 */
4244 ResetPerTupleExprContext(estate);
4245
4246 /*
4247 * Reset per-tuple memory context used for processing on conflict and
4248 * returning clauses, to free any expression evaluation storage
4249 * allocated in the previous cycle.
4250 */
4251 if (pstate->ps_ExprContext)
4252 ResetExprContext(pstate->ps_ExprContext);
4253
4254 /*
4255 * If there is a pending MERGE ... WHEN NOT MATCHED [BY TARGET] action
4256 * to execute, do so now --- see the comments in ExecMerge().
4257 */
4258 if (node->mt_merge_pending_not_matched != NULL)
4259 {
4260 context.planSlot = node->mt_merge_pending_not_matched;
4261 context.cpDeletedSlot = NULL;
4262
4263 slot = ExecMergeNotMatched(&context, node->resultRelInfo,
4264 node->canSetTag);
4265
4266 /* Clear the pending action */
4267 node->mt_merge_pending_not_matched = NULL;
4268
4269 /*
4270 * If we got a RETURNING result, return it to the caller. We'll
4271 * continue the work on next call.
4272 */
4273 if (slot)
4274 return slot;
4275
4276 continue; /* continue with the next tuple */
4277 }
4278
4279 /* Fetch the next row from subplan */
4280 context.planSlot = ExecProcNode(subplanstate);
4281 context.cpDeletedSlot = NULL;
4282
4283 /* No more tuples to process? */
4284 if (TupIsNull(context.planSlot))
4285 break;
4286
4287 /*
4288 * When there are multiple result relations, each tuple contains a
4289 * junk column that gives the OID of the rel from which it came.
4290 * Extract it and select the correct result relation.
4291 */
4292 if (AttributeNumberIsValid(node->mt_resultOidAttno))
4293 {
4294 Datum datum;
4295 bool isNull;
4296 Oid resultoid;
4297
4298 datum = ExecGetJunkAttribute(context.planSlot, node->mt_resultOidAttno,
4299 &isNull);
4300 if (isNull)
4301 {
4302 /*
4303 * For commands other than MERGE, any tuples having InvalidOid
4304 * for tableoid are errors. For MERGE, we may need to handle
4305 * them as WHEN NOT MATCHED clauses if any, so do that.
4306 *
4307 * Note that we use the node's toplevel resultRelInfo, not any
4308 * specific partition's.
4309 */
4310 if (operation == CMD_MERGE)
4311 {
4312 EvalPlanQualSetSlot(&node->mt_epqstate, context.planSlot);
4313
4314 slot = ExecMerge(&context, node->resultRelInfo,
4315 NULL, NULL, node->canSetTag);
4316
4317 /*
4318 * If we got a RETURNING result, return it to the caller.
4319 * We'll continue the work on next call.
4320 */
4321 if (slot)
4322 return slot;
4323
4324 continue; /* continue with the next tuple */
4325 }
4326
4327 elog(ERROR, "tableoid is NULL");
4328 }
4329 resultoid = DatumGetObjectId(datum);
4330
4331 /* If it's not the same as last time, we need to locate the rel */
4332 if (resultoid != node->mt_lastResultOid)
4333 resultRelInfo = ExecLookupResultRelByOid(node, resultoid,
4334 false, true);
4335 }
4336
4337 /*
4338 * If resultRelInfo->ri_usesFdwDirectModify is true, all we need to do
4339 * here is compute the RETURNING expressions.
4340 */
4341 if (resultRelInfo->ri_usesFdwDirectModify)
4342 {
4343 Assert(resultRelInfo->ri_projectReturning);
4344
4345 /*
4346 * A scan slot containing the data that was actually inserted,
4347 * updated or deleted has already been made available to
4348 * ExecProcessReturning by IterateDirectModify, so no need to
4349 * provide it here. The individual old and new slots are not
4350 * needed, since direct-modify is disabled if the RETURNING list
4351 * refers to OLD/NEW values.
4352 */
4353 Assert((resultRelInfo->ri_projectReturning->pi_state.flags & EEO_FLAG_HAS_OLD) == 0 &&
4354 (resultRelInfo->ri_projectReturning->pi_state.flags & EEO_FLAG_HAS_NEW) == 0);
4355
4356 slot = ExecProcessReturning(&context, resultRelInfo, operation,
4357 NULL, NULL, context.planSlot);
4358
4359 return slot;
4360 }
4361
4362 EvalPlanQualSetSlot(&node->mt_epqstate, context.planSlot);
4363 slot = context.planSlot;
4364
4365 tupleid = NULL;
4366 oldtuple = NULL;
4367
4368 /*
4369 * For UPDATE/DELETE/MERGE, fetch the row identity info for the tuple
4370 * to be updated/deleted/merged. For a heap relation, that's a TID;
4371 * otherwise we may have a wholerow junk attr that carries the old
4372 * tuple in toto. Keep this in step with the part of
4373 * ExecInitModifyTable that sets up ri_RowIdAttNo.
4374 */
4375 if (operation == CMD_UPDATE || operation == CMD_DELETE ||
4376 operation == CMD_MERGE)
4377 {
4378 char relkind;
4379 Datum datum;
4380 bool isNull;
4381
4382 relkind = resultRelInfo->ri_RelationDesc->rd_rel->relkind;
4383 if (relkind == RELKIND_RELATION ||
4384 relkind == RELKIND_MATVIEW ||
4385 relkind == RELKIND_PARTITIONED_TABLE)
4386 {
4387 /*
4388 * ri_RowIdAttNo refers to a ctid attribute. See the comment
4389 * in ExecInitModifyTable().
4390 */
4391 Assert(AttributeNumberIsValid(resultRelInfo->ri_RowIdAttNo) ||
4392 relkind == RELKIND_PARTITIONED_TABLE);
4393 datum = ExecGetJunkAttribute(slot,
4394 resultRelInfo->ri_RowIdAttNo,
4395 &isNull);
4396
4397 /*
4398 * For commands other than MERGE, any tuples having a null row
4399 * identifier are errors. For MERGE, we may need to handle
4400 * them as WHEN NOT MATCHED clauses if any, so do that.
4401 *
4402 * Note that we use the node's toplevel resultRelInfo, not any
4403 * specific partition's.
4404 */
4405 if (isNull)
4406 {
4407 if (operation == CMD_MERGE)
4408 {
4409 EvalPlanQualSetSlot(&node->mt_epqstate, context.planSlot);
4410
4411 slot = ExecMerge(&context, node->resultRelInfo,
4412 NULL, NULL, node->canSetTag);
4413
4414 /*
4415 * If we got a RETURNING result, return it to the
4416 * caller. We'll continue the work on next call.
4417 */
4418 if (slot)
4419 return slot;
4420
4421 continue; /* continue with the next tuple */
4422 }
4423
4424 elog(ERROR, "ctid is NULL");
4425 }
4426
4427 tupleid = (ItemPointer) DatumGetPointer(datum);
4428 tuple_ctid = *tupleid; /* be sure we don't free ctid!! */
4429 tupleid = &tuple_ctid;
4430 }
4431
4432 /*
4433 * Use the wholerow attribute, when available, to reconstruct the
4434 * old relation tuple. The old tuple serves one or both of two
4435 * purposes: 1) it serves as the OLD tuple for row triggers, 2) it
4436 * provides values for any unchanged columns for the NEW tuple of
4437 * an UPDATE, because the subplan does not produce all the columns
4438 * of the target table.
4439 *
4440 * Note that the wholerow attribute does not carry system columns,
4441 * so foreign table triggers miss seeing those, except that we
4442 * know enough here to set t_tableOid. Quite separately from
4443 * this, the FDW may fetch its own junk attrs to identify the row.
4444 *
4445 * Other relevant relkinds, currently limited to views, always
4446 * have a wholerow attribute.
4447 */
4448 else if (AttributeNumberIsValid(resultRelInfo->ri_RowIdAttNo))
4449 {
4450 datum = ExecGetJunkAttribute(slot,
4451 resultRelInfo->ri_RowIdAttNo,
4452 &isNull);
4453
4454 /*
4455 * For commands other than MERGE, any tuples having a null row
4456 * identifier are errors. For MERGE, we may need to handle
4457 * them as WHEN NOT MATCHED clauses if any, so do that.
4458 *
4459 * Note that we use the node's toplevel resultRelInfo, not any
4460 * specific partition's.
4461 */
4462 if (isNull)
4463 {
4464 if (operation == CMD_MERGE)
4465 {
4466 EvalPlanQualSetSlot(&node->mt_epqstate, context.planSlot);
4467
4468 slot = ExecMerge(&context, node->resultRelInfo,
4469 NULL, NULL, node->canSetTag);
4470
4471 /*
4472 * If we got a RETURNING result, return it to the
4473 * caller. We'll continue the work on next call.
4474 */
4475 if (slot)
4476 return slot;
4477
4478 continue; /* continue with the next tuple */
4479 }
4480
4481 elog(ERROR, "wholerow is NULL");
4482 }
4483
4484 oldtupdata.t_data = DatumGetHeapTupleHeader(datum);
4485 oldtupdata.t_len =
4486 HeapTupleHeaderGetDatumLength(oldtupdata.t_data);
4487 ItemPointerSetInvalid(&(oldtupdata.t_self));
4488 /* Historically, view triggers see invalid t_tableOid. */
4489 oldtupdata.t_tableOid =
4490 (relkind == RELKIND_VIEW) ? InvalidOid :
4491 RelationGetRelid(resultRelInfo->ri_RelationDesc);
4492
4493 oldtuple = &oldtupdata;
4494 }
4495 else
4496 {
4497 /* Only foreign tables are allowed to omit a row-ID attr */
4498 Assert(relkind == RELKIND_FOREIGN_TABLE);
4499 }
4500 }
4501
4502 switch (operation)
4503 {
4504 case CMD_INSERT:
4505 /* Initialize projection info if first time for this table */
4506 if (unlikely(!resultRelInfo->ri_projectNewInfoValid))
4507 ExecInitInsertProjection(node, resultRelInfo);
4508 slot = ExecGetInsertNewTuple(resultRelInfo, context.planSlot);
4509 slot = ExecInsert(&context, resultRelInfo, slot,
4510 node->canSetTag, NULL, NULL);
4511 break;
4512
4513 case CMD_UPDATE:
4514 tuplock = false;
4515
4516 /* Initialize projection info if first time for this table */
4517 if (unlikely(!resultRelInfo->ri_projectNewInfoValid))
4518 ExecInitUpdateProjection(node, resultRelInfo);
4519
4520 /*
4521 * Make the new tuple by combining plan's output tuple with
4522 * the old tuple being updated.
4523 */
4524 oldSlot = resultRelInfo->ri_oldTupleSlot;
4525 if (oldtuple != NULL)
4526 {
4527 Assert(!resultRelInfo->ri_needLockTagTuple);
4528 /* Use the wholerow junk attr as the old tuple. */
4529 ExecForceStoreHeapTuple(oldtuple, oldSlot, false);
4530 }
4531 else
4532 {
4533 /* Fetch the most recent version of old tuple. */
4534 Relation relation = resultRelInfo->ri_RelationDesc;
4535
4536 if (resultRelInfo->ri_needLockTagTuple)
4537 {
4538 LockTuple(relation, tupleid, InplaceUpdateTupleLock);
4539 tuplock = true;
4540 }
4541 if (!table_tuple_fetch_row_version(relation, tupleid,
4542 SnapshotAny,
4543 oldSlot))
4544 elog(ERROR, "failed to fetch tuple being updated");
4545 }
4546 slot = ExecGetUpdateNewTuple(resultRelInfo, context.planSlot,
4547 oldSlot);
4548
4549 /* Now apply the update. */
4550 slot = ExecUpdate(&context, resultRelInfo, tupleid, oldtuple,
4551 oldSlot, slot, node->canSetTag);
4552 if (tuplock)
4553 UnlockTuple(resultRelInfo->ri_RelationDesc, tupleid,
4554 InplaceUpdateTupleLock);
4555 break;
4556
4557 case CMD_DELETE:
4558 slot = ExecDelete(&context, resultRelInfo, tupleid, oldtuple,
4559 true, false, node->canSetTag, NULL, NULL, NULL);
4560 break;
4561
4562 case CMD_MERGE:
4563 slot = ExecMerge(&context, resultRelInfo, tupleid, oldtuple,
4564 node->canSetTag);
4565 break;
4566
4567 default:
4568 elog(ERROR, "unknown operation");
4569 break;
4570 }
4571
4572 /*
4573 * If we got a RETURNING result, return it to caller. We'll continue
4574 * the work on next call.
4575 */
4576 if (slot)
4577 return slot;
4578 }
4579
4580 /*
4581 * Insert remaining tuples for batch insert.
4582 */
4583 if (estate->es_insert_pending_result_relations != NIL)
4584 ExecPendingInserts(estate);
4585
4586 /*
4587 * We're done, but fire AFTER STATEMENT triggers before exiting.
4588 */
4589 fireASTriggers(node);
4590
4591 node->mt_done = true;
4592
4593 return NULL;
4594 }
4595
4596 /*
4597 * ExecLookupResultRelByOid
4598 * If the table with given OID is among the result relations to be
4599 * updated by the given ModifyTable node, return its ResultRelInfo.
4600 *
4601 * If not found, return NULL if missing_ok, else raise error.
4602 *
4603 * If update_cache is true, then upon successful lookup, update the node's
4604 * one-element cache. ONLY ExecModifyTable may pass true for this.
4605 */
4606 ResultRelInfo *
4607 ExecLookupResultRelByOid(ModifyTableState *node, Oid resultoid,
4608 bool missing_ok, bool update_cache)
4609 {
4610 if (node->mt_resultOidHash)
4611 {
4612 /* Use the pre-built hash table to locate the rel */
4613 MTTargetRelLookup *mtlookup;
4614
4615 mtlookup = (MTTargetRelLookup *)
4616 hash_search(node->mt_resultOidHash, &resultoid, HASH_FIND, NULL);
4617 if (mtlookup)
4618 {
4619 if (update_cache)
4620 {
4621 node->mt_lastResultOid = resultoid;
4622 node->mt_lastResultIndex = mtlookup->relationIndex;
4623 }
4624 return node->resultRelInfo + mtlookup->relationIndex;
4625 }
4626 }
4627 else
4628 {
4629 /* With few target rels, just search the ResultRelInfo array */
4630 for (int ndx = 0; ndx < node->mt_nrels; ndx++)
4631 {
4632 ResultRelInfo *rInfo = node->resultRelInfo + ndx;
4633
4634 if (RelationGetRelid(rInfo->ri_RelationDesc) == resultoid)
4635 {
4636 if (update_cache)
4637 {
4638 node->mt_lastResultOid = resultoid;
4639 node->mt_lastResultIndex = ndx;
4640 }
4641 return rInfo;
4642 }
4643 }
4644 }
4645
4646 if (!missing_ok)
4647 elog(ERROR, "incorrect result relation OID %u", resultoid);
4648 return NULL;
4649 }
4650
4651 /* ----------------------------------------------------------------
4652 * ExecInitModifyTable
4653 * ----------------------------------------------------------------
4654 */
4655 ModifyTableState *
4656 ExecInitModifyTable(ModifyTable *node, EState *estate, int eflags)
4657 {
4658 ModifyTableState *mtstate;
4659 Plan *subplan = outerPlan(node);
4660 CmdType operation = node->operation;
4661 int total_nrels = list_length(node->resultRelations);
4662 int nrels;
4663 List *resultRelations = NIL;
4664 List *withCheckOptionLists = NIL;
4665 List *returningLists = NIL;
4666 List *updateColnosLists = NIL;
4667 List *mergeActionLists = NIL;
4668 List *mergeJoinConditions = NIL;
4669 List *fdwPrivLists = NIL;
4670 Bitmapset *fdwDirectModifyPlans = NULL;
4671 ResultRelInfo *resultRelInfo;
4672 List *arowmarks;
4673 ListCell *l;
4674 int i;
4675 Relation rel;
4676
4677 /* check for unsupported flags */
4678 Assert(!(eflags & (EXEC_FLAG_BACKWARD | EXEC_FLAG_MARK)));
4679
4680 /*
4681 * Only consider unpruned relations for initializing their ResultRelInfo
4682 * struct and other fields such as withCheckOptions, etc.
4683 *
4684 * Note: We must avoid pruning every result relation. This is important
4685 * for MERGE, since even if every result relation is pruned from the
4686 * subplan, there might still be NOT MATCHED rows, for which there may be
4687 * INSERT actions to perform. To allow these actions to be found, at
4688 * least one result relation must be kept. Also, when inserting into a
4689 * partitioned table, ExecInitPartitionInfo() needs a ResultRelInfo struct
4690 * as a reference for building the ResultRelInfo of the target partition.
4691 * In either case, it doesn't matter which result relation is kept, so we
4692 * just keep the first one, if all others have been pruned. See also,
4693 * ExecDoInitialPruning(), which ensures that this first result relation
4694 * has been locked.
4695 */
4696 i = 0;
4697 foreach(l, node->resultRelations)
4698 {
4699 Index rti = lfirst_int(l);
4700 bool keep_rel;
4701
4702 keep_rel = bms_is_member(rti, estate->es_unpruned_relids);
4703 if (!keep_rel && i == total_nrels - 1 && resultRelations == NIL)
4704 {
4705 /* all result relations pruned; keep the first one */
4706 keep_rel = true;
4707 rti = linitial_int(node->resultRelations);
4708 i = 0;
4709 }
4710
4711 if (keep_rel)
4712 {
4713 List *fdwPrivList = (List *) list_nth(node->fdwPrivLists, i);
4714
4715 resultRelations = lappend_int(resultRelations, rti);
4716 if (node->withCheckOptionLists)
4717 {
4718 List *withCheckOptions = list_nth_node(List,
4719 node->withCheckOptionLists,
4720 i);
4721
4722 withCheckOptionLists = lappend(withCheckOptionLists, withCheckOptions);
4723 }
4724 if (node->returningLists)
4725 {
4726 List *returningList = list_nth_node(List,
4727 node->returningLists,
4728 i);
4729
4730 returningLists = lappend(returningLists, returningList);
4731 }
4732 if (node->updateColnosLists)
4733 {
4734 List *updateColnosList = list_nth(node->updateColnosLists, i);
4735
4736 updateColnosLists = lappend(updateColnosLists, updateColnosList);
4737 }
4738 if (node->mergeActionLists)
4739 {
4740 List *mergeActionList = list_nth(node->mergeActionLists, i);
4741
4742 mergeActionLists = lappend(mergeActionLists, mergeActionList);
4743 }
4744 if (node->mergeJoinConditions)
4745 {
4746 List *mergeJoinCondition = list_nth(node->mergeJoinConditions, i);
4747
4748 mergeJoinConditions = lappend(mergeJoinConditions, mergeJoinCondition);
4749 }
4750
4751 /*
4752 * fdwPrivLists/fdwDirectModifyPlans are re-indexed to match
4753 * resultRelations
4754 */
4755 fdwPrivLists = lappend(fdwPrivLists, fdwPrivList);
4756 if (bms_is_member(i, node->fdwDirectModifyPlans))
4757 {
4758 int new_index = list_length(resultRelations) - 1;
4759
4760 fdwDirectModifyPlans = bms_add_member(fdwDirectModifyPlans,
4761 new_index);
4762 }
4763 }
4764 i++;
4765 }
4766 nrels = list_length(resultRelations);
4767 Assert(nrels > 0);
4768
4769 /*
4770 * create state structure
4771 */
4772 mtstate = makeNode(ModifyTableState);
4773 mtstate->ps.plan = (Plan *) node;
4774 mtstate->ps.state = estate;
4775 mtstate->ps.ExecProcNode = ExecModifyTable;
4776
4777 mtstate->operation = operation;
4778 mtstate->canSetTag = node->canSetTag;
4779 mtstate->mt_done = false;
4780
4781 mtstate->mt_nrels = nrels;
4782 mtstate->resultRelInfo = (ResultRelInfo *)
4783 palloc(nrels * sizeof(ResultRelInfo));
4784
4785 mtstate->mt_merge_pending_not_matched = NULL;
4786 mtstate->mt_merge_inserted = 0;
4787 mtstate->mt_merge_updated = 0;
4788 mtstate->mt_merge_deleted = 0;
4789 mtstate->mt_updateColnosLists = updateColnosLists;
4790 mtstate->mt_mergeActionLists = mergeActionLists;
4791 mtstate->mt_mergeJoinConditions = mergeJoinConditions;
4792
4793 /*----------
4794 * Resolve the target relation. This is the same as:
4795 *
4796 * - the relation for which we will fire FOR STATEMENT triggers,
4797 * - the relation into whose tuple format all captured transition tuples
4798 * must be converted, and
4799 * - the root partitioned table used for tuple routing.
4800 *
4801 * If it's a partitioned or inherited table, the root partition or
4802 * appendrel RTE doesn't appear elsewhere in the plan and its RT index is
4803 * given explicitly in node->rootRelation. Otherwise, the target relation
4804 * is the sole relation in the node->resultRelations list and, since it can
4805 * never be pruned, also in the resultRelations list constructed above.
4806 *----------
4807 */
4808 if (node->rootRelation > 0)
4809 {
4810 Assert(bms_is_member(node->rootRelation, estate->es_unpruned_relids));
4811 mtstate->rootResultRelInfo = makeNode(ResultRelInfo);
4812 ExecInitResultRelation(estate, mtstate->rootResultRelInfo,
4813 node->rootRelation);
4814 }
4815 else
4816 {
4817 Assert(list_length(node->resultRelations) == 1);
4818 Assert(list_length(resultRelations) == 1);
4819 mtstate->rootResultRelInfo = mtstate->resultRelInfo;
4820 ExecInitResultRelation(estate, mtstate->resultRelInfo,
4821 linitial_int(resultRelations));
4822 }
4823
4824 /* set up epqstate with dummy subplan data for the moment */
4825 EvalPlanQualInit(&mtstate->mt_epqstate, estate, NULL, NIL,
4826 node->epqParam, resultRelations);
4827 mtstate->fireBSTriggers = true;
4828
4829 /*
4830 * Build state for collecting transition tuples. This requires having a
4831 * valid trigger query context, so skip it in explain-only mode.
4832 */
4833 if (!(eflags & EXEC_FLAG_EXPLAIN_ONLY))
4834 ExecSetupTransitionCaptureState(mtstate, estate);
4835
4836 /*
4837 * Open all the result relations and initialize the ResultRelInfo structs.
4838 * (But root relation was initialized above, if it's part of the array.)
4839 * We must do this before initializing the subplan, because direct-modify
4840 * FDWs expect their ResultRelInfos to be available.
4841 */
4842 resultRelInfo = mtstate->resultRelInfo;
4843 i = 0;
4844 foreach(l, resultRelations)
4845 {
4846 Index resultRelation = lfirst_int(l);
4847 List *mergeActions = NIL;
4848
4849 if (mergeActionLists)
4850 mergeActions = list_nth(mergeActionLists, i);
4851
4852 if (resultRelInfo != mtstate->rootResultRelInfo)
4853 {
4854 ExecInitResultRelation(estate, resultRelInfo, resultRelation);
4855
4856 /*
4857 * For child result relations, store the root result relation
4858 * pointer. We do so for the convenience of places that want to
4859 * look at the query's original target relation but don't have the
4860 * mtstate handy.
4861 */
4862 resultRelInfo->ri_RootResultRelInfo = mtstate->rootResultRelInfo;
4863 }
4864
4865 /* Initialize the usesFdwDirectModify flag */
4866 resultRelInfo->ri_usesFdwDirectModify =
4867 bms_is_member(i, fdwDirectModifyPlans);
4868
4869 /*
4870 * Verify result relation is a valid target for the current operation
4871 */
4872 CheckValidResultRel(resultRelInfo, operation, node->onConflictAction,
4873 mergeActions);
4874
4875 resultRelInfo++;
4876 i++;
4877 }
4878
4879 /*
4880 * Now we may initialize the subplan.
4881 */
4882 outerPlanState(mtstate) = ExecInitNode(subplan, estate, eflags);
4883
4884 /*
4885 * Do additional per-result-relation initialization.
4886 */
4887 for (i = 0; i < nrels; i++)
4888 {
4889 resultRelInfo = &mtstate->resultRelInfo[i];
4890
4891 /* Let FDWs init themselves for foreign-table result rels */
4892 if (!resultRelInfo->ri_usesFdwDirectModify &&
4893 resultRelInfo->ri_FdwRoutine != NULL &&
4894 resultRelInfo->ri_FdwRoutine->BeginForeignModify != NULL)
4895 {
4896 List *fdw_private = (List *) list_nth(fdwPrivLists, i);
4897
4898 resultRelInfo->ri_FdwRoutine->BeginForeignModify(mtstate,
4899 resultRelInfo,
4900 fdw_private,
4901 i,
4902 eflags);
4903 }
4904
4905 /*
4906 * For UPDATE/DELETE/MERGE, find the appropriate junk attr now, either
4907 * a 'ctid' or 'wholerow' attribute depending on relkind. For foreign
4908 * tables, the FDW might have created additional junk attr(s), but
4909 * those are no concern of ours.
4910 */
4911 if (operation == CMD_UPDATE || operation == CMD_DELETE ||
4912 operation == CMD_MERGE)
4913 {
4914 char relkind;
4915
4916 relkind = resultRelInfo->ri_RelationDesc->rd_rel->relkind;
4917 if (relkind == RELKIND_RELATION ||
4918 relkind == RELKIND_MATVIEW ||
4919 relkind == RELKIND_PARTITIONED_TABLE)
4920 {
4921 resultRelInfo->ri_RowIdAttNo =
4922 ExecFindJunkAttributeInTlist(subplan->targetlist, "ctid");
4923
4924 /*
4925 * For heap relations, a ctid junk attribute must be present.
4926 * Partitioned tables should only appear here when all leaf
4927 * partitions were pruned, in which case no rows can be
4928 * produced and ctid is not needed.
4929 */
4930 if (relkind == RELKIND_PARTITIONED_TABLE)
4931 Assert(nrels == 1);
4932 else if (!AttributeNumberIsValid(resultRelInfo->ri_RowIdAttNo))
4933 elog(ERROR, "could not find junk ctid column");
4934 }
4935 else if (relkind == RELKIND_FOREIGN_TABLE)
4936 {
4937 /*
4938 * We don't support MERGE with foreign tables for now. (It's
4939 * problematic because the implementation uses CTID.)
4940 */
4941 Assert(operation != CMD_MERGE);
4942
4943 /*
4944 * When there is a row-level trigger, there should be a
4945 * wholerow attribute. We also require it to be present in
4946 * UPDATE and MERGE, so we can get the values of unchanged
4947 * columns.
4948 */
4949 resultRelInfo->ri_RowIdAttNo =
4950 ExecFindJunkAttributeInTlist(subplan->targetlist,
4951 "wholerow");
4952 if ((mtstate->operation == CMD_UPDATE || mtstate->operation == CMD_MERGE) &&
4953 !AttributeNumberIsValid(resultRelInfo->ri_RowIdAttNo))
4954 elog(ERROR, "could not find junk wholerow column");
4955 }
4956 else
4957 {
4958 /* Other valid target relkinds must provide wholerow */
4959 resultRelInfo->ri_RowIdAttNo =
4960 ExecFindJunkAttributeInTlist(subplan->targetlist,
4961 "wholerow");
4962 if (!AttributeNumberIsValid(resultRelInfo->ri_RowIdAttNo))
4963 elog(ERROR, "could not find junk wholerow column");
4964 }
4965 }
4966 }
4967
4968 /*
4969 * If this is an inherited update/delete/merge, there will be a junk
4970 * attribute named "tableoid" present in the subplan's targetlist. It
4971 * will be used to identify the result relation for a given tuple to be
4972 * updated/deleted/merged.
4973 */
4974 mtstate->mt_resultOidAttno =
4975 ExecFindJunkAttributeInTlist(subplan->targetlist, "tableoid");
4976 Assert(AttributeNumberIsValid(mtstate->mt_resultOidAttno) || total_nrels == 1);
4977 mtstate->mt_lastResultOid = InvalidOid; /* force lookup at first tuple */
4978 mtstate->mt_lastResultIndex = 0; /* must be zero if no such attr */
4979
4980 /* Get the root target relation */
4981 rel = mtstate->rootResultRelInfo->ri_RelationDesc;
4982
4983 /*
4984 * Build state for tuple routing if it's a partitioned INSERT. An UPDATE
4985 * or MERGE might need this too, but only if it actually moves tuples
4986 * between partitions; in that case setup is done by
4987 * ExecCrossPartitionUpdate.
4988 */
4989 if (rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE &&
4990 operation == CMD_INSERT)
4991 mtstate->mt_partition_tuple_routing =
4992 ExecSetupPartitionTupleRouting(estate, rel);
4993
4994 /*
4995 * Initialize any WITH CHECK OPTION constraints if needed.
4996 */
4997 resultRelInfo = mtstate->resultRelInfo;
4998 foreach(l, withCheckOptionLists)
4999 {
5000 List *wcoList = (List *) lfirst(l);
5001 List *wcoExprs = NIL;
5002 ListCell *ll;
5003
5004 foreach(ll, wcoList)
5005 {
5006 WithCheckOption *wco = (WithCheckOption *) lfirst(ll);
5007 ExprState *wcoExpr = ExecInitQual((List *) wco->qual,
5008 &mtstate->ps);
5009
5010 wcoExprs = lappend(wcoExprs, wcoExpr);
5011 }
5012
5013 resultRelInfo->ri_WithCheckOptions = wcoList;
5014 resultRelInfo->ri_WithCheckOptionExprs = wcoExprs;
5015 resultRelInfo++;
5016 }
5017
5018 /*
5019 * Initialize RETURNING projections if needed.
5020 */
5021 if (returningLists)
5022 {
5023 TupleTableSlot *slot;
5024 ExprContext *econtext;
5025
5026 /*
5027 * Initialize result tuple slot and assign its rowtype using the plan
5028 * node's declared targetlist, which the planner set up to be the same
5029 * as the first (before runtime pruning) RETURNING list. We assume
5030 * all the result rels will produce compatible output.
5031 */
5032 ExecInitResultTupleSlotTL(&mtstate->ps, &TTSOpsVirtual);
5033 slot = mtstate->ps.ps_ResultTupleSlot;
5034
5035 /* Need an econtext too */
5036 if (mtstate->ps.ps_ExprContext == NULL)
5037 ExecAssignExprContext(estate, &mtstate->ps);
5038 econtext = mtstate->ps.ps_ExprContext;
5039
5040 /*
5041 * Build a projection for each result rel.
5042 */
5043 resultRelInfo = mtstate->resultRelInfo;
5044 foreach(l, returningLists)
5045 {
5046 List *rlist = (List *) lfirst(l);
5047
5048 resultRelInfo->ri_returningList = rlist;
5049 resultRelInfo->ri_projectReturning =
5050 ExecBuildProjectionInfo(rlist, econtext, slot, &mtstate->ps,
5051 resultRelInfo->ri_RelationDesc->rd_att);
5052 resultRelInfo++;
5053 }
5054 }
5055 else
5056 {
5057 /*
5058 * We still must construct a dummy result tuple type, because InitPlan
5059 * expects one (maybe should change that?).
5060 */
5061 ExecInitResultTypeTL(&mtstate->ps);
5062
5063 mtstate->ps.ps_ExprContext = NULL;
5064 }
5065
5066 /* Set the list of arbiter indexes if needed for ON CONFLICT */
5067 resultRelInfo = mtstate->resultRelInfo;
5068 if (node->onConflictAction != ONCONFLICT_NONE)
5069 {
5070 /* insert may only have one relation, inheritance is not expanded */
5071 Assert(total_nrels == 1);
5072 resultRelInfo->ri_onConflictArbiterIndexes = node->arbiterIndexes;
5073 }
5074
5075 /*
5076 * If needed, Initialize target list, projection and qual for ON CONFLICT
5077 * DO UPDATE.
5078 */
5079 if (node->onConflictAction == ONCONFLICT_UPDATE)
5080 {
5081 OnConflictSetState *onconfl = makeNode(OnConflictSetState);
5082 ExprContext *econtext;
5083 TupleDesc relationDesc;
5084
5085 /* already exists if created by RETURNING processing above */
5086 if (mtstate->ps.ps_ExprContext == NULL)
5087 ExecAssignExprContext(estate, &mtstate->ps);
5088
5089 econtext = mtstate->ps.ps_ExprContext;
5090 relationDesc = resultRelInfo->ri_RelationDesc->rd_att;
5091
5092 /* create state for DO UPDATE SET operation */
5093 resultRelInfo->ri_onConflict = onconfl;
5094
5095 /* initialize slot for the existing tuple */
5096 onconfl->oc_Existing =
5097 table_slot_create(resultRelInfo->ri_RelationDesc,
5098 &mtstate->ps.state->es_tupleTable);
5099
5100 /*
5101 * Create the tuple slot for the UPDATE SET projection. We want a slot
5102 * of the table's type here, because the slot will be used to insert
5103 * into the table, and for RETURNING processing - which may access
5104 * system attributes.
5105 */
5106 onconfl->oc_ProjSlot =
5107 table_slot_create(resultRelInfo->ri_RelationDesc,
5108 &mtstate->ps.state->es_tupleTable);
5109
5110 /* build UPDATE SET projection state */
5111 onconfl->oc_ProjInfo =
5112 ExecBuildUpdateProjection(node->onConflictSet,
5113 true,
5114 node->onConflictCols,
5115 relationDesc,
5116 econtext,
5117 onconfl->oc_ProjSlot,
5118 &mtstate->ps);
5119
5120 /* initialize state to evaluate the WHERE clause, if any */
5121 if (node->onConflictWhere)
5122 {
5123 ExprState *qualexpr;
5124
5125 qualexpr = ExecInitQual((List *) node->onConflictWhere,
5126 &mtstate->ps);
5127 onconfl->oc_WhereClause = qualexpr;
5128 }
5129 }
5130
5131 /*
5132 * If we have any secondary relations in an UPDATE or DELETE, they need to
5133 * be treated like non-locked relations in SELECT FOR UPDATE, i.e., the
5134 * EvalPlanQual mechanism needs to be told about them. This also goes for
5135 * the source relations in a MERGE. Locate the relevant ExecRowMarks.
5136 */
5137 arowmarks = NIL;
5138 foreach(l, node->rowMarks)
5139 {
5140 PlanRowMark *rc = lfirst_node(PlanRowMark, l);
5141 RangeTblEntry *rte = exec_rt_fetch(rc->rti, estate);
5142 ExecRowMark *erm;
5143 ExecAuxRowMark *aerm;
5144
5145 /* ignore "parent" rowmarks; they are irrelevant at runtime */
5146 if (rc->isParent)
5147 continue;
5148
5149 /*
5150 * Also ignore rowmarks belonging to child tables that have been
5151 * pruned in ExecDoInitialPruning().
5152 */
5153 if (rte->rtekind == RTE_RELATION &&
5154 !bms_is_member(rc->rti, estate->es_unpruned_relids))
5155 continue;
5156
5157 /* Find ExecRowMark and build ExecAuxRowMark */
5158 erm = ExecFindRowMark(estate, rc->rti, false);
5159 aerm = ExecBuildAuxRowMark(erm, subplan->targetlist);
5160 arowmarks = lappend(arowmarks, aerm);
5161 }
5162
5163 /* For a MERGE command, initialize its state */
5164 if (mtstate->operation == CMD_MERGE)
5165 ExecInitMerge(mtstate, estate);
5166
5167 EvalPlanQualSetPlan(&mtstate->mt_epqstate, subplan, arowmarks);
5168
5169 /*
5170 * If there are a lot of result relations, use a hash table to speed the
5171 * lookups. If there are not a lot, a simple linear search is faster.
5172 *
5173 * It's not clear where the threshold is, but try 64 for starters. In a
5174 * debugging build, use a small threshold so that we get some test
5175 * coverage of both code paths.
5176 */
5177 #ifdef USE_ASSERT_CHECKING
5178 #define MT_NRELS_HASH 4
5179 #else
5180 #define MT_NRELS_HASH 64
5181 #endif
5182 if (nrels >= MT_NRELS_HASH)
5183 {
5184 HASHCTL hash_ctl;
5185
5186 hash_ctl.keysize = sizeof(Oid);
5187 hash_ctl.entrysize = sizeof(MTTargetRelLookup);
5188 hash_ctl.hcxt = CurrentMemoryContext;
5189 mtstate->mt_resultOidHash =
5190 hash_create("ModifyTable target hash",
5191 nrels, &hash_ctl,
5192 HASH_ELEM | HASH_BLOBS | HASH_CONTEXT);
5193 for (i = 0; i < nrels; i++)
5194 {
5195 Oid hashkey;
5196 MTTargetRelLookup *mtlookup;
5197 bool found;
5198
5199 resultRelInfo = &mtstate->resultRelInfo[i];
5200 hashkey = RelationGetRelid(resultRelInfo->ri_RelationDesc);
5201 mtlookup = (MTTargetRelLookup *)
5202 hash_search(mtstate->mt_resultOidHash, &hashkey,
5203 HASH_ENTER, &found);
5204 Assert(!found);
5205 mtlookup->relationIndex = i;
5206 }
5207 }
5208 else
5209 mtstate->mt_resultOidHash = NULL;
5210
5211 /*
5212 * Determine if the FDW supports batch insert and determine the batch size
5213 * (a FDW may support batching, but it may be disabled for the
5214 * server/table).
5215 *
5216 * We only do this for INSERT, so that for UPDATE/DELETE the batch size
5217 * remains set to 0.
5218 */
5219 if (operation == CMD_INSERT)
5220 {
5221 /* insert may only have one relation, inheritance is not expanded */
5222 Assert(total_nrels == 1);
5223 resultRelInfo = mtstate->resultRelInfo;
5224 if (!resultRelInfo->ri_usesFdwDirectModify &&
5225 resultRelInfo->ri_FdwRoutine != NULL &&
5226 resultRelInfo->ri_FdwRoutine->GetForeignModifyBatchSize &&
5227 resultRelInfo->ri_FdwRoutine->ExecForeignBatchInsert)
5228 {
5229 resultRelInfo->ri_BatchSize =
5230 resultRelInfo->ri_FdwRoutine->GetForeignModifyBatchSize(resultRelInfo);
5231 Assert(resultRelInfo->ri_BatchSize >= 1);
5232 }
5233 else
5234 resultRelInfo->ri_BatchSize = 1;
5235 }
5236
5237 /*
5238 * Lastly, if this is not the primary (canSetTag) ModifyTable node, add it
5239 * to estate->es_auxmodifytables so that it will be run to completion by
5240 * ExecPostprocessPlan. (It'd actually work fine to add the primary
5241 * ModifyTable node too, but there's no need.) Note the use of lcons not
5242 * lappend: we need later-initialized ModifyTable nodes to be shut down
5243 * before earlier ones. This ensures that we don't throw away RETURNING
5244 * rows that need to be seen by a later CTE subplan.
5245 */
5246 if (!mtstate->canSetTag)
5247 estate->es_auxmodifytables = lcons(mtstate,
5248 estate->es_auxmodifytables);
5249
5250 return mtstate;
5251 }
5252
5253 /* ----------------------------------------------------------------
5254 * ExecEndModifyTable
5255 *
5256 * Shuts down the plan.
5257 *
5258 * Returns nothing of interest.
5259 * ----------------------------------------------------------------
5260 */
5261 void
5262 ExecEndModifyTable(ModifyTableState *node)
5263 {
5264 int i;
5265
5266 /*
5267 * Allow any FDWs to shut down
5268 */
5269 for (i = 0; i < node->mt_nrels; i++)
5270 {
5271 int j;
5272 ResultRelInfo *resultRelInfo = node->resultRelInfo + i;
5273
5274 if (!resultRelInfo->ri_usesFdwDirectModify &&
5275 resultRelInfo->ri_FdwRoutine != NULL &&
5276 resultRelInfo->ri_FdwRoutine->EndForeignModify != NULL)
5277 resultRelInfo->ri_FdwRoutine->EndForeignModify(node->ps.state,
5278 resultRelInfo);
5279
5280 /*
5281 * Cleanup the initialized batch slots. This only matters for FDWs
5282 * with batching, but the other cases will have ri_NumSlotsInitialized
5283 * == 0.
5284 */
5285 for (j = 0; j < resultRelInfo->ri_NumSlotsInitialized; j++)
5286 {
5287 ExecDropSingleTupleTableSlot(resultRelInfo->ri_Slots[j]);
5288 ExecDropSingleTupleTableSlot(resultRelInfo->ri_PlanSlots[j]);
5289 }
5290 }
5291
5292 /*
5293 * Close all the partitioned tables, leaf partitions, and their indices
5294 * and release the slot used for tuple routing, if set.
5295 */
5296 if (node->mt_partition_tuple_routing)
5297 {
5298 ExecCleanupTupleRouting(node, node->mt_partition_tuple_routing);
5299
5300 if (node->mt_root_tuple_slot)
5301 ExecDropSingleTupleTableSlot(node->mt_root_tuple_slot);
5302 }
5303
5304 /*
5305 * Terminate EPQ execution if active
5306 */
5307 EvalPlanQualEnd(&node->mt_epqstate);
5308
5309 /*
5310 * shut down subplan
5311 */
5312 ExecEndNode(outerPlanState(node));
5313 }
5314
5315 void
5316 ExecReScanModifyTable(ModifyTableState *node)
5317 {
5318 /*
5319 * Currently, we don't need to support rescan on ModifyTable nodes. The
5320 * semantics of that would be a bit debatable anyway.
5321 */
5322 elog(ERROR, "ExecReScanModifyTable is not implemented");
5323 }