Line data Source code
1 : /*-------------------------------------------------------------------------
2 : *
3 : * execReplication.c
4 : * miscellaneous executor routines for logical replication
5 : *
6 : * Portions Copyright (c) 1996-2025, PostgreSQL Global Development Group
7 : * Portions Copyright (c) 1994, Regents of the University of California
8 : *
9 : * IDENTIFICATION
10 : * src/backend/executor/execReplication.c
11 : *
12 : *-------------------------------------------------------------------------
13 : */
14 :
15 : #include "postgres.h"
16 :
17 : #include "access/genam.h"
18 : #include "access/gist.h"
19 : #include "access/relscan.h"
20 : #include "access/tableam.h"
21 : #include "access/transam.h"
22 : #include "access/xact.h"
23 : #include "catalog/pg_am_d.h"
24 : #include "commands/trigger.h"
25 : #include "executor/executor.h"
26 : #include "executor/nodeModifyTable.h"
27 : #include "replication/conflict.h"
28 : #include "replication/logicalrelation.h"
29 : #include "storage/lmgr.h"
30 : #include "utils/builtins.h"
31 : #include "utils/lsyscache.h"
32 : #include "utils/rel.h"
33 : #include "utils/snapmgr.h"
34 : #include "utils/syscache.h"
35 : #include "utils/typcache.h"
36 :
37 :
38 : static bool tuples_equal(TupleTableSlot *slot1, TupleTableSlot *slot2,
39 : TypeCacheEntry **eq);
40 :
41 : /*
42 : * Setup a ScanKey for a search in the relation 'rel' for a tuple 'key' that
43 : * is setup to match 'rel' (*NOT* idxrel!).
44 : *
45 : * Returns how many columns to use for the index scan.
46 : *
47 : * This is not generic routine, idxrel must be PK, RI, or an index that can be
48 : * used for REPLICA IDENTITY FULL table. See FindUsableIndexForReplicaIdentityFull()
49 : * for details.
50 : *
51 : * By definition, replication identity of a rel meets all limitations associated
52 : * with that. Note that any other index could also meet these limitations.
53 : */
54 : static int
55 144196 : build_replindex_scan_key(ScanKey skey, Relation rel, Relation idxrel,
56 : TupleTableSlot *searchslot)
57 : {
58 : int index_attoff;
59 144196 : int skey_attoff = 0;
60 : Datum indclassDatum;
61 : oidvector *opclass;
62 144196 : int2vector *indkey = &idxrel->rd_index->indkey;
63 :
64 144196 : indclassDatum = SysCacheGetAttrNotNull(INDEXRELID, idxrel->rd_indextuple,
65 : Anum_pg_index_indclass);
66 144196 : opclass = (oidvector *) DatumGetPointer(indclassDatum);
67 :
68 : /* Build scankey for every non-expression attribute in the index. */
69 288438 : for (index_attoff = 0; index_attoff < IndexRelationGetNumberOfKeyAttributes(idxrel);
70 144242 : index_attoff++)
71 : {
72 : Oid operator;
73 : Oid optype;
74 : Oid opfamily;
75 : RegProcedure regop;
76 144242 : int table_attno = indkey->values[index_attoff];
77 : StrategyNumber eq_strategy;
78 :
79 144242 : if (!AttributeNumberIsValid(table_attno))
80 : {
81 : /*
82 : * XXX: Currently, we don't support expressions in the scan key,
83 : * see code below.
84 : */
85 4 : continue;
86 : }
87 :
88 : /*
89 : * Load the operator info. We need this to get the equality operator
90 : * function for the scan key.
91 : */
92 144238 : optype = get_opclass_input_type(opclass->values[index_attoff]);
93 144238 : opfamily = get_opclass_family(opclass->values[index_attoff]);
94 144238 : eq_strategy = IndexAmTranslateCompareType(COMPARE_EQ, idxrel->rd_rel->relam, opfamily, false);
95 144238 : operator = get_opfamily_member(opfamily, optype,
96 : optype,
97 : eq_strategy);
98 :
99 144238 : if (!OidIsValid(operator))
100 0 : elog(ERROR, "missing operator %d(%u,%u) in opfamily %u",
101 : eq_strategy, optype, optype, opfamily);
102 :
103 144238 : regop = get_opcode(operator);
104 :
105 : /* Initialize the scankey. */
106 144238 : ScanKeyInit(&skey[skey_attoff],
107 144238 : index_attoff + 1,
108 : eq_strategy,
109 : regop,
110 144238 : searchslot->tts_values[table_attno - 1]);
111 :
112 144238 : skey[skey_attoff].sk_collation = idxrel->rd_indcollation[index_attoff];
113 :
114 : /* Check for null value. */
115 144238 : if (searchslot->tts_isnull[table_attno - 1])
116 2 : skey[skey_attoff].sk_flags |= (SK_ISNULL | SK_SEARCHNULL);
117 :
118 144238 : skey_attoff++;
119 : }
120 :
121 : /* There must always be at least one attribute for the index scan. */
122 : Assert(skey_attoff > 0);
123 :
124 144196 : return skey_attoff;
125 : }
126 :
127 :
128 : /*
129 : * Helper function to check if it is necessary to re-fetch and lock the tuple
130 : * due to concurrent modifications. This function should be called after
131 : * invoking table_tuple_lock.
132 : */
133 : static bool
134 144492 : should_refetch_tuple(TM_Result res, TM_FailureData *tmfd)
135 : {
136 144492 : bool refetch = false;
137 :
138 144492 : switch (res)
139 : {
140 144492 : case TM_Ok:
141 144492 : break;
142 0 : case TM_Updated:
143 : /* XXX: Improve handling here */
144 0 : if (ItemPointerIndicatesMovedPartitions(&tmfd->ctid))
145 0 : ereport(LOG,
146 : (errcode(ERRCODE_T_R_SERIALIZATION_FAILURE),
147 : errmsg("tuple to be locked was already moved to another partition due to concurrent update, retrying")));
148 : else
149 0 : ereport(LOG,
150 : (errcode(ERRCODE_T_R_SERIALIZATION_FAILURE),
151 : errmsg("concurrent update, retrying")));
152 0 : refetch = true;
153 0 : break;
154 0 : case TM_Deleted:
155 : /* XXX: Improve handling here */
156 0 : ereport(LOG,
157 : (errcode(ERRCODE_T_R_SERIALIZATION_FAILURE),
158 : errmsg("concurrent delete, retrying")));
159 0 : refetch = true;
160 0 : break;
161 0 : case TM_Invisible:
162 0 : elog(ERROR, "attempted to lock invisible tuple");
163 : break;
164 0 : default:
165 0 : elog(ERROR, "unexpected table_tuple_lock status: %u", res);
166 : break;
167 : }
168 :
169 144492 : return refetch;
170 : }
171 :
172 : /*
173 : * Search the relation 'rel' for tuple using the index.
174 : *
175 : * If a matching tuple is found, lock it with lockmode, fill the slot with its
176 : * contents, and return true. Return false otherwise.
177 : */
178 : bool
179 144196 : RelationFindReplTupleByIndex(Relation rel, Oid idxoid,
180 : LockTupleMode lockmode,
181 : TupleTableSlot *searchslot,
182 : TupleTableSlot *outslot)
183 : {
184 : ScanKeyData skey[INDEX_MAX_KEYS];
185 : int skey_attoff;
186 : IndexScanDesc scan;
187 : SnapshotData snap;
188 : TransactionId xwait;
189 : Relation idxrel;
190 : bool found;
191 144196 : TypeCacheEntry **eq = NULL;
192 : bool isIdxSafeToSkipDuplicates;
193 :
194 : /* Open the index. */
195 144196 : idxrel = index_open(idxoid, RowExclusiveLock);
196 :
197 144196 : isIdxSafeToSkipDuplicates = (GetRelationIdentityOrPK(rel) == idxoid);
198 :
199 144196 : InitDirtySnapshot(snap);
200 :
201 : /* Build scan key. */
202 144196 : skey_attoff = build_replindex_scan_key(skey, rel, idxrel, searchslot);
203 :
204 : /* Start an index scan. */
205 144196 : scan = index_beginscan(rel, idxrel, &snap, NULL, skey_attoff, 0);
206 :
207 144196 : retry:
208 144196 : found = false;
209 :
210 144196 : index_rescan(scan, skey, skey_attoff, NULL, 0);
211 :
212 : /* Try to find the tuple */
213 144196 : while (index_getnext_slot(scan, ForwardScanDirection, outslot))
214 : {
215 : /*
216 : * Avoid expensive equality check if the index is primary key or
217 : * replica identity index.
218 : */
219 144172 : if (!isIdxSafeToSkipDuplicates)
220 : {
221 34 : if (eq == NULL)
222 34 : eq = palloc0(sizeof(*eq) * outslot->tts_tupleDescriptor->natts);
223 :
224 34 : if (!tuples_equal(outslot, searchslot, eq))
225 0 : continue;
226 : }
227 :
228 144172 : ExecMaterializeSlot(outslot);
229 :
230 288344 : xwait = TransactionIdIsValid(snap.xmin) ?
231 144172 : snap.xmin : snap.xmax;
232 :
233 : /*
234 : * If the tuple is locked, wait for locking transaction to finish and
235 : * retry.
236 : */
237 144172 : if (TransactionIdIsValid(xwait))
238 : {
239 0 : XactLockTableWait(xwait, NULL, NULL, XLTW_None);
240 0 : goto retry;
241 : }
242 :
243 : /* Found our tuple and it's not locked */
244 144172 : found = true;
245 144172 : break;
246 : }
247 :
248 : /* Found tuple, try to lock it in the lockmode. */
249 144196 : if (found)
250 : {
251 : TM_FailureData tmfd;
252 : TM_Result res;
253 :
254 144172 : PushActiveSnapshot(GetLatestSnapshot());
255 :
256 144172 : res = table_tuple_lock(rel, &(outslot->tts_tid), GetActiveSnapshot(),
257 : outslot,
258 : GetCurrentCommandId(false),
259 : lockmode,
260 : LockWaitBlock,
261 : 0 /* don't follow updates */ ,
262 : &tmfd);
263 :
264 144172 : PopActiveSnapshot();
265 :
266 144172 : if (should_refetch_tuple(res, &tmfd))
267 0 : goto retry;
268 : }
269 :
270 144196 : index_endscan(scan);
271 :
272 : /* Don't release lock until commit. */
273 144196 : index_close(idxrel, NoLock);
274 :
275 144196 : return found;
276 : }
277 :
278 : /*
279 : * Compare the tuples in the slots by checking if they have equal values.
280 : */
281 : static bool
282 210646 : tuples_equal(TupleTableSlot *slot1, TupleTableSlot *slot2,
283 : TypeCacheEntry **eq)
284 : {
285 : int attrnum;
286 :
287 : Assert(slot1->tts_tupleDescriptor->natts ==
288 : slot2->tts_tupleDescriptor->natts);
289 :
290 210646 : slot_getallattrs(slot1);
291 210646 : slot_getallattrs(slot2);
292 :
293 : /* Check equality of the attributes. */
294 211046 : for (attrnum = 0; attrnum < slot1->tts_tupleDescriptor->natts; attrnum++)
295 : {
296 : Form_pg_attribute att;
297 : TypeCacheEntry *typentry;
298 :
299 210718 : att = TupleDescAttr(slot1->tts_tupleDescriptor, attrnum);
300 :
301 : /*
302 : * Ignore dropped and generated columns as the publisher doesn't send
303 : * those
304 : */
305 210718 : if (att->attisdropped || att->attgenerated)
306 2 : continue;
307 :
308 : /*
309 : * If one value is NULL and other is not, then they are certainly not
310 : * equal
311 : */
312 210716 : if (slot1->tts_isnull[attrnum] != slot2->tts_isnull[attrnum])
313 0 : return false;
314 :
315 : /*
316 : * If both are NULL, they can be considered equal.
317 : */
318 210716 : if (slot1->tts_isnull[attrnum] || slot2->tts_isnull[attrnum])
319 2 : continue;
320 :
321 210714 : typentry = eq[attrnum];
322 210714 : if (typentry == NULL)
323 : {
324 400 : typentry = lookup_type_cache(att->atttypid,
325 : TYPECACHE_EQ_OPR_FINFO);
326 400 : if (!OidIsValid(typentry->eq_opr_finfo.fn_oid))
327 0 : ereport(ERROR,
328 : (errcode(ERRCODE_UNDEFINED_FUNCTION),
329 : errmsg("could not identify an equality operator for type %s",
330 : format_type_be(att->atttypid))));
331 400 : eq[attrnum] = typentry;
332 : }
333 :
334 210714 : if (!DatumGetBool(FunctionCall2Coll(&typentry->eq_opr_finfo,
335 : att->attcollation,
336 210714 : slot1->tts_values[attrnum],
337 210714 : slot2->tts_values[attrnum])))
338 210318 : return false;
339 : }
340 :
341 328 : return true;
342 : }
343 :
344 : /*
345 : * Search the relation 'rel' for tuple using the sequential scan.
346 : *
347 : * If a matching tuple is found, lock it with lockmode, fill the slot with its
348 : * contents, and return true. Return false otherwise.
349 : *
350 : * Note that this stops on the first matching tuple.
351 : *
352 : * This can obviously be quite slow on tables that have more than few rows.
353 : */
354 : bool
355 298 : RelationFindReplTupleSeq(Relation rel, LockTupleMode lockmode,
356 : TupleTableSlot *searchslot, TupleTableSlot *outslot)
357 : {
358 : TupleTableSlot *scanslot;
359 : TableScanDesc scan;
360 : SnapshotData snap;
361 : TypeCacheEntry **eq;
362 : TransactionId xwait;
363 : bool found;
364 298 : TupleDesc desc PG_USED_FOR_ASSERTS_ONLY = RelationGetDescr(rel);
365 :
366 : Assert(equalTupleDescs(desc, outslot->tts_tupleDescriptor));
367 :
368 298 : eq = palloc0(sizeof(*eq) * outslot->tts_tupleDescriptor->natts);
369 :
370 : /* Start a heap scan. */
371 298 : InitDirtySnapshot(snap);
372 298 : scan = table_beginscan(rel, &snap, 0, NULL);
373 298 : scanslot = table_slot_create(rel, NULL);
374 :
375 298 : retry:
376 298 : found = false;
377 :
378 298 : table_rescan(scan, NULL);
379 :
380 : /* Try to find the tuple */
381 210616 : while (table_scan_getnextslot(scan, ForwardScanDirection, scanslot))
382 : {
383 210612 : if (!tuples_equal(scanslot, searchslot, eq))
384 210318 : continue;
385 :
386 294 : found = true;
387 294 : ExecCopySlot(outslot, scanslot);
388 :
389 588 : xwait = TransactionIdIsValid(snap.xmin) ?
390 294 : snap.xmin : snap.xmax;
391 :
392 : /*
393 : * If the tuple is locked, wait for locking transaction to finish and
394 : * retry.
395 : */
396 294 : if (TransactionIdIsValid(xwait))
397 : {
398 0 : XactLockTableWait(xwait, NULL, NULL, XLTW_None);
399 0 : goto retry;
400 : }
401 :
402 : /* Found our tuple and it's not locked */
403 294 : break;
404 : }
405 :
406 : /* Found tuple, try to lock it in the lockmode. */
407 298 : if (found)
408 : {
409 : TM_FailureData tmfd;
410 : TM_Result res;
411 :
412 294 : PushActiveSnapshot(GetLatestSnapshot());
413 :
414 294 : res = table_tuple_lock(rel, &(outslot->tts_tid), GetActiveSnapshot(),
415 : outslot,
416 : GetCurrentCommandId(false),
417 : lockmode,
418 : LockWaitBlock,
419 : 0 /* don't follow updates */ ,
420 : &tmfd);
421 :
422 294 : PopActiveSnapshot();
423 :
424 294 : if (should_refetch_tuple(res, &tmfd))
425 0 : goto retry;
426 : }
427 :
428 298 : table_endscan(scan);
429 298 : ExecDropSingleTupleTableSlot(scanslot);
430 :
431 298 : return found;
432 : }
433 :
434 : /*
435 : * Find the tuple that violates the passed unique index (conflictindex).
436 : *
437 : * If the conflicting tuple is found return true, otherwise false.
438 : *
439 : * We lock the tuple to avoid getting it deleted before the caller can fetch
440 : * the required information. Note that if the tuple is deleted before a lock
441 : * is acquired, we will retry to find the conflicting tuple again.
442 : */
443 : static bool
444 30 : FindConflictTuple(ResultRelInfo *resultRelInfo, EState *estate,
445 : Oid conflictindex, TupleTableSlot *slot,
446 : TupleTableSlot **conflictslot)
447 : {
448 30 : Relation rel = resultRelInfo->ri_RelationDesc;
449 : ItemPointerData conflictTid;
450 : TM_FailureData tmfd;
451 : TM_Result res;
452 :
453 30 : *conflictslot = NULL;
454 :
455 30 : retry:
456 30 : if (ExecCheckIndexConstraints(resultRelInfo, slot, estate,
457 : &conflictTid, &slot->tts_tid,
458 30 : list_make1_oid(conflictindex)))
459 : {
460 2 : if (*conflictslot)
461 0 : ExecDropSingleTupleTableSlot(*conflictslot);
462 :
463 2 : *conflictslot = NULL;
464 2 : return false;
465 : }
466 :
467 26 : *conflictslot = table_slot_create(rel, NULL);
468 :
469 26 : PushActiveSnapshot(GetLatestSnapshot());
470 :
471 26 : res = table_tuple_lock(rel, &conflictTid, GetActiveSnapshot(),
472 : *conflictslot,
473 : GetCurrentCommandId(false),
474 : LockTupleShare,
475 : LockWaitBlock,
476 : 0 /* don't follow updates */ ,
477 : &tmfd);
478 :
479 26 : PopActiveSnapshot();
480 :
481 26 : if (should_refetch_tuple(res, &tmfd))
482 0 : goto retry;
483 :
484 26 : return true;
485 : }
486 :
487 : /*
488 : * Check all the unique indexes in 'recheckIndexes' for conflict with the
489 : * tuple in 'remoteslot' and report if found.
490 : */
491 : static void
492 22 : CheckAndReportConflict(ResultRelInfo *resultRelInfo, EState *estate,
493 : ConflictType type, List *recheckIndexes,
494 : TupleTableSlot *searchslot, TupleTableSlot *remoteslot)
495 : {
496 22 : List *conflicttuples = NIL;
497 : TupleTableSlot *conflictslot;
498 :
499 : /* Check all the unique indexes for conflicts */
500 70 : foreach_oid(uniqueidx, resultRelInfo->ri_onConflictArbiterIndexes)
501 : {
502 58 : if (list_member_oid(recheckIndexes, uniqueidx) &&
503 30 : FindConflictTuple(resultRelInfo, estate, uniqueidx, remoteslot,
504 : &conflictslot))
505 : {
506 26 : ConflictTupleInfo *conflicttuple = palloc0_object(ConflictTupleInfo);
507 :
508 26 : conflicttuple->slot = conflictslot;
509 26 : conflicttuple->indexoid = uniqueidx;
510 :
511 26 : GetTupleTransactionInfo(conflictslot, &conflicttuple->xmin,
512 : &conflicttuple->origin, &conflicttuple->ts);
513 :
514 26 : conflicttuples = lappend(conflicttuples, conflicttuple);
515 : }
516 : }
517 :
518 : /* Report the conflict, if found */
519 20 : if (conflicttuples)
520 18 : ReportApplyConflict(estate, resultRelInfo, ERROR,
521 18 : list_length(conflicttuples) > 1 ? CT_MULTIPLE_UNIQUE_CONFLICTS : type,
522 : searchslot, remoteslot, conflicttuples);
523 2 : }
524 :
525 : /*
526 : * Insert tuple represented in the slot to the relation, update the indexes,
527 : * and execute any constraints and per-row triggers.
528 : *
529 : * Caller is responsible for opening the indexes.
530 : */
531 : void
532 152418 : ExecSimpleRelationInsert(ResultRelInfo *resultRelInfo,
533 : EState *estate, TupleTableSlot *slot)
534 : {
535 152418 : bool skip_tuple = false;
536 152418 : Relation rel = resultRelInfo->ri_RelationDesc;
537 :
538 : /* For now we support only tables. */
539 : Assert(rel->rd_rel->relkind == RELKIND_RELATION);
540 :
541 152418 : CheckCmdReplicaIdentity(rel, CMD_INSERT);
542 :
543 : /* BEFORE ROW INSERT Triggers */
544 152418 : if (resultRelInfo->ri_TrigDesc &&
545 38 : resultRelInfo->ri_TrigDesc->trig_insert_before_row)
546 : {
547 6 : if (!ExecBRInsertTriggers(estate, resultRelInfo, slot))
548 2 : skip_tuple = true; /* "do nothing" */
549 : }
550 :
551 152418 : if (!skip_tuple)
552 : {
553 152416 : List *recheckIndexes = NIL;
554 : List *conflictindexes;
555 152416 : bool conflict = false;
556 :
557 : /* Compute stored generated columns */
558 152416 : if (rel->rd_att->constr &&
559 90930 : rel->rd_att->constr->has_generated_stored)
560 8 : ExecComputeStoredGenerated(resultRelInfo, estate, slot,
561 : CMD_INSERT);
562 :
563 : /* Check the constraints of the tuple */
564 152416 : if (rel->rd_att->constr)
565 90930 : ExecConstraints(resultRelInfo, slot, estate);
566 152416 : if (rel->rd_rel->relispartition)
567 120 : ExecPartitionCheck(resultRelInfo, slot, estate, true);
568 :
569 : /* OK, store the tuple and create index entries for it */
570 152416 : simple_table_tuple_insert(resultRelInfo->ri_RelationDesc, slot);
571 :
572 152416 : conflictindexes = resultRelInfo->ri_onConflictArbiterIndexes;
573 :
574 152416 : if (resultRelInfo->ri_NumIndices > 0)
575 111738 : recheckIndexes = ExecInsertIndexTuples(resultRelInfo,
576 : slot, estate, false,
577 : conflictindexes ? true : false,
578 : &conflict,
579 : conflictindexes, false);
580 :
581 : /*
582 : * Checks the conflict indexes to fetch the conflicting local tuple
583 : * and reports the conflict. We perform this check here, instead of
584 : * performing an additional index scan before the actual insertion and
585 : * reporting the conflict if any conflicting tuples are found. This is
586 : * to avoid the overhead of executing the extra scan for each INSERT
587 : * operation, even when no conflict arises, which could introduce
588 : * significant overhead to replication, particularly in cases where
589 : * conflicts are rare.
590 : *
591 : * XXX OTOH, this could lead to clean-up effort for dead tuples added
592 : * in heap and index in case of conflicts. But as conflicts shouldn't
593 : * be a frequent thing so we preferred to save the performance
594 : * overhead of extra scan before each insertion.
595 : */
596 152416 : if (conflict)
597 18 : CheckAndReportConflict(resultRelInfo, estate, CT_INSERT_EXISTS,
598 : recheckIndexes, NULL, slot);
599 :
600 : /* AFTER ROW INSERT Triggers */
601 152400 : ExecARInsertTriggers(estate, resultRelInfo, slot,
602 : recheckIndexes, NULL);
603 :
604 : /*
605 : * XXX we should in theory pass a TransitionCaptureState object to the
606 : * above to capture transition tuples, but after statement triggers
607 : * don't actually get fired by replication yet anyway
608 : */
609 :
610 152400 : list_free(recheckIndexes);
611 : }
612 152402 : }
613 :
614 : /*
615 : * Find the searchslot tuple and update it with data in the slot,
616 : * update the indexes, and execute any constraints and per-row triggers.
617 : *
618 : * Caller is responsible for opening the indexes.
619 : */
620 : void
621 63846 : ExecSimpleRelationUpdate(ResultRelInfo *resultRelInfo,
622 : EState *estate, EPQState *epqstate,
623 : TupleTableSlot *searchslot, TupleTableSlot *slot)
624 : {
625 63846 : bool skip_tuple = false;
626 63846 : Relation rel = resultRelInfo->ri_RelationDesc;
627 63846 : ItemPointer tid = &(searchslot->tts_tid);
628 :
629 : /*
630 : * We support only non-system tables, with
631 : * check_publication_add_relation() accountable.
632 : */
633 : Assert(rel->rd_rel->relkind == RELKIND_RELATION);
634 : Assert(!IsCatalogRelation(rel));
635 :
636 63846 : CheckCmdReplicaIdentity(rel, CMD_UPDATE);
637 :
638 : /* BEFORE ROW UPDATE Triggers */
639 63846 : if (resultRelInfo->ri_TrigDesc &&
640 20 : resultRelInfo->ri_TrigDesc->trig_update_before_row)
641 : {
642 6 : if (!ExecBRUpdateTriggers(estate, epqstate, resultRelInfo,
643 : tid, NULL, slot, NULL, NULL))
644 4 : skip_tuple = true; /* "do nothing" */
645 : }
646 :
647 63846 : if (!skip_tuple)
648 : {
649 63842 : List *recheckIndexes = NIL;
650 : TU_UpdateIndexes update_indexes;
651 : List *conflictindexes;
652 63842 : bool conflict = false;
653 :
654 : /* Compute stored generated columns */
655 63842 : if (rel->rd_att->constr &&
656 63752 : rel->rd_att->constr->has_generated_stored)
657 4 : ExecComputeStoredGenerated(resultRelInfo, estate, slot,
658 : CMD_UPDATE);
659 :
660 : /* Check the constraints of the tuple */
661 63842 : if (rel->rd_att->constr)
662 63752 : ExecConstraints(resultRelInfo, slot, estate);
663 63842 : if (rel->rd_rel->relispartition)
664 24 : ExecPartitionCheck(resultRelInfo, slot, estate, true);
665 :
666 63842 : simple_table_tuple_update(rel, tid, slot, estate->es_snapshot,
667 : &update_indexes);
668 :
669 63842 : conflictindexes = resultRelInfo->ri_onConflictArbiterIndexes;
670 :
671 63842 : if (resultRelInfo->ri_NumIndices > 0 && (update_indexes != TU_None))
672 40400 : recheckIndexes = ExecInsertIndexTuples(resultRelInfo,
673 : slot, estate, true,
674 : conflictindexes ? true : false,
675 : &conflict, conflictindexes,
676 : (update_indexes == TU_Summarizing));
677 :
678 : /*
679 : * Refer to the comments above the call to CheckAndReportConflict() in
680 : * ExecSimpleRelationInsert to understand why this check is done at
681 : * this point.
682 : */
683 63842 : if (conflict)
684 4 : CheckAndReportConflict(resultRelInfo, estate, CT_UPDATE_EXISTS,
685 : recheckIndexes, searchslot, slot);
686 :
687 : /* AFTER ROW UPDATE Triggers */
688 63838 : ExecARUpdateTriggers(estate, resultRelInfo,
689 : NULL, NULL,
690 : tid, NULL, slot,
691 : recheckIndexes, NULL, false);
692 :
693 63838 : list_free(recheckIndexes);
694 : }
695 63842 : }
696 :
697 : /*
698 : * Find the searchslot tuple and delete it, and execute any constraints
699 : * and per-row triggers.
700 : *
701 : * Caller is responsible for opening the indexes.
702 : */
703 : void
704 80620 : ExecSimpleRelationDelete(ResultRelInfo *resultRelInfo,
705 : EState *estate, EPQState *epqstate,
706 : TupleTableSlot *searchslot)
707 : {
708 80620 : bool skip_tuple = false;
709 80620 : Relation rel = resultRelInfo->ri_RelationDesc;
710 80620 : ItemPointer tid = &searchslot->tts_tid;
711 :
712 80620 : CheckCmdReplicaIdentity(rel, CMD_DELETE);
713 :
714 : /* BEFORE ROW DELETE Triggers */
715 80620 : if (resultRelInfo->ri_TrigDesc &&
716 20 : resultRelInfo->ri_TrigDesc->trig_delete_before_row)
717 : {
718 0 : skip_tuple = !ExecBRDeleteTriggers(estate, epqstate, resultRelInfo,
719 0 : tid, NULL, NULL, NULL, NULL);
720 : }
721 :
722 80620 : if (!skip_tuple)
723 : {
724 : /* OK, delete the tuple */
725 80620 : simple_table_tuple_delete(rel, tid, estate->es_snapshot);
726 :
727 : /* AFTER ROW DELETE Triggers */
728 80620 : ExecARDeleteTriggers(estate, resultRelInfo,
729 : tid, NULL, NULL, false);
730 : }
731 80620 : }
732 :
733 : /*
734 : * Check if command can be executed with current replica identity.
735 : */
736 : void
737 429318 : CheckCmdReplicaIdentity(Relation rel, CmdType cmd)
738 : {
739 : PublicationDesc pubdesc;
740 :
741 : /*
742 : * Skip checking the replica identity for partitioned tables, because the
743 : * operations are actually performed on the leaf partitions.
744 : */
745 429318 : if (rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE)
746 407362 : return;
747 :
748 : /* We only need to do checks for UPDATE and DELETE. */
749 423316 : if (cmd != CMD_UPDATE && cmd != CMD_DELETE)
750 250922 : return;
751 :
752 : /*
753 : * It is only safe to execute UPDATE/DELETE if the relation does not
754 : * publish UPDATEs or DELETEs, or all the following conditions are
755 : * satisfied:
756 : *
757 : * 1. All columns, referenced in the row filters from publications which
758 : * the relation is in, are valid - i.e. when all referenced columns are
759 : * part of REPLICA IDENTITY.
760 : *
761 : * 2. All columns, referenced in the column lists are valid - i.e. when
762 : * all columns referenced in the REPLICA IDENTITY are covered by the
763 : * column list.
764 : *
765 : * 3. All generated columns in REPLICA IDENTITY of the relation, are valid
766 : * - i.e. when all these generated columns are published.
767 : *
768 : * XXX We could optimize it by first checking whether any of the
769 : * publications have a row filter or column list for this relation, or if
770 : * the relation contains a generated column. If none of these exist and
771 : * the relation has replica identity then we can avoid building the
772 : * descriptor but as this happens only one time it doesn't seem worth the
773 : * additional complexity.
774 : */
775 172394 : RelationBuildPublicationDesc(rel, &pubdesc);
776 172394 : if (cmd == CMD_UPDATE && !pubdesc.rf_valid_for_update)
777 60 : ereport(ERROR,
778 : (errcode(ERRCODE_INVALID_COLUMN_REFERENCE),
779 : errmsg("cannot update table \"%s\"",
780 : RelationGetRelationName(rel)),
781 : errdetail("Column used in the publication WHERE expression is not part of the replica identity.")));
782 172334 : else if (cmd == CMD_UPDATE && !pubdesc.cols_valid_for_update)
783 108 : ereport(ERROR,
784 : (errcode(ERRCODE_INVALID_COLUMN_REFERENCE),
785 : errmsg("cannot update table \"%s\"",
786 : RelationGetRelationName(rel)),
787 : errdetail("Column list used by the publication does not cover the replica identity.")));
788 172226 : else if (cmd == CMD_UPDATE && !pubdesc.gencols_valid_for_update)
789 24 : ereport(ERROR,
790 : (errcode(ERRCODE_INVALID_COLUMN_REFERENCE),
791 : errmsg("cannot update table \"%s\"",
792 : RelationGetRelationName(rel)),
793 : errdetail("Replica identity must not contain unpublished generated columns.")));
794 172202 : else if (cmd == CMD_DELETE && !pubdesc.rf_valid_for_delete)
795 0 : ereport(ERROR,
796 : (errcode(ERRCODE_INVALID_COLUMN_REFERENCE),
797 : errmsg("cannot delete from table \"%s\"",
798 : RelationGetRelationName(rel)),
799 : errdetail("Column used in the publication WHERE expression is not part of the replica identity.")));
800 172202 : else if (cmd == CMD_DELETE && !pubdesc.cols_valid_for_delete)
801 0 : ereport(ERROR,
802 : (errcode(ERRCODE_INVALID_COLUMN_REFERENCE),
803 : errmsg("cannot delete from table \"%s\"",
804 : RelationGetRelationName(rel)),
805 : errdetail("Column list used by the publication does not cover the replica identity.")));
806 172202 : else if (cmd == CMD_DELETE && !pubdesc.gencols_valid_for_delete)
807 0 : ereport(ERROR,
808 : (errcode(ERRCODE_INVALID_COLUMN_REFERENCE),
809 : errmsg("cannot delete from table \"%s\"",
810 : RelationGetRelationName(rel)),
811 : errdetail("Replica identity must not contain unpublished generated columns.")));
812 :
813 : /* If relation has replica identity we are always good. */
814 172202 : if (OidIsValid(RelationGetReplicaIndex(rel)))
815 149988 : return;
816 :
817 : /* REPLICA IDENTITY FULL is also good for UPDATE/DELETE. */
818 22214 : if (rel->rd_rel->relreplident == REPLICA_IDENTITY_FULL)
819 450 : return;
820 :
821 : /*
822 : * This is UPDATE/DELETE and there is no replica identity.
823 : *
824 : * Check if the table publishes UPDATES or DELETES.
825 : */
826 21764 : if (cmd == CMD_UPDATE && pubdesc.pubactions.pubupdate)
827 106 : ereport(ERROR,
828 : (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
829 : errmsg("cannot update table \"%s\" because it does not have a replica identity and publishes updates",
830 : RelationGetRelationName(rel)),
831 : errhint("To enable updating the table, set REPLICA IDENTITY using ALTER TABLE.")));
832 21658 : else if (cmd == CMD_DELETE && pubdesc.pubactions.pubdelete)
833 10 : ereport(ERROR,
834 : (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
835 : errmsg("cannot delete from table \"%s\" because it does not have a replica identity and publishes deletes",
836 : RelationGetRelationName(rel)),
837 : errhint("To enable deleting from the table, set REPLICA IDENTITY using ALTER TABLE.")));
838 : }
839 :
840 :
841 : /*
842 : * Check if we support writing into specific relkind.
843 : *
844 : * The nspname and relname are only needed for error reporting.
845 : */
846 : void
847 1732 : CheckSubscriptionRelkind(char relkind, const char *nspname,
848 : const char *relname)
849 : {
850 1732 : if (relkind != RELKIND_RELATION && relkind != RELKIND_PARTITIONED_TABLE)
851 0 : ereport(ERROR,
852 : (errcode(ERRCODE_WRONG_OBJECT_TYPE),
853 : errmsg("cannot use relation \"%s.%s\" as logical replication target",
854 : nspname, relname),
855 : errdetail_relkind_not_supported(relkind)));
856 1732 : }
|