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