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 144194 : build_replindex_scan_key(ScanKey skey, Relation rel, Relation idxrel,
56 : TupleTableSlot *searchslot)
57 : {
58 : int index_attoff;
59 144194 : int skey_attoff = 0;
60 : Datum indclassDatum;
61 : oidvector *opclass;
62 144194 : int2vector *indkey = &idxrel->rd_index->indkey;
63 :
64 144194 : indclassDatum = SysCacheGetAttrNotNull(INDEXRELID, idxrel->rd_indextuple,
65 : Anum_pg_index_indclass);
66 144194 : opclass = (oidvector *) DatumGetPointer(indclassDatum);
67 :
68 : /* Build scankey for every non-expression attribute in the index. */
69 288434 : for (index_attoff = 0; index_attoff < IndexRelationGetNumberOfKeyAttributes(idxrel);
70 144240 : index_attoff++)
71 : {
72 : Oid operator;
73 : Oid optype;
74 : Oid opfamily;
75 : RegProcedure regop;
76 144240 : int table_attno = indkey->values[index_attoff];
77 : StrategyNumber eq_strategy;
78 :
79 144240 : 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 144236 : optype = get_opclass_input_type(opclass->values[index_attoff]);
93 144236 : opfamily = get_opclass_family(opclass->values[index_attoff]);
94 144236 : eq_strategy = IndexAmTranslateCompareType(COMPARE_EQ, idxrel->rd_rel->relam, opfamily, false);
95 144236 : operator = get_opfamily_member(opfamily, optype,
96 : optype,
97 : eq_strategy);
98 :
99 144236 : if (!OidIsValid(operator))
100 0 : elog(ERROR, "missing operator %d(%u,%u) in opfamily %u",
101 : eq_strategy, optype, optype, opfamily);
102 :
103 144236 : regop = get_opcode(operator);
104 :
105 : /* Initialize the scankey. */
106 144236 : ScanKeyInit(&skey[skey_attoff],
107 144236 : index_attoff + 1,
108 : eq_strategy,
109 : regop,
110 144236 : searchslot->tts_values[table_attno - 1]);
111 :
112 144236 : skey[skey_attoff].sk_collation = idxrel->rd_indcollation[index_attoff];
113 :
114 : /* Check for null value. */
115 144236 : if (searchslot->tts_isnull[table_attno - 1])
116 2 : skey[skey_attoff].sk_flags |= (SK_ISNULL | SK_SEARCHNULL);
117 :
118 144236 : skey_attoff++;
119 : }
120 :
121 : /* There must always be at least one attribute for the index scan. */
122 : Assert(skey_attoff > 0);
123 :
124 144194 : 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 144478 : should_refetch_tuple(TM_Result res, TM_FailureData *tmfd)
135 : {
136 144478 : bool refetch = false;
137 :
138 144478 : switch (res)
139 : {
140 144478 : case TM_Ok:
141 144478 : 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 144478 : 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 144194 : 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 144194 : TypeCacheEntry **eq = NULL;
192 : bool isIdxSafeToSkipDuplicates;
193 :
194 : /* Open the index. */
195 144194 : idxrel = index_open(idxoid, RowExclusiveLock);
196 :
197 144194 : isIdxSafeToSkipDuplicates = (GetRelationIdentityOrPK(rel) == idxoid);
198 :
199 144194 : InitDirtySnapshot(snap);
200 :
201 : /* Build scan key. */
202 144194 : skey_attoff = build_replindex_scan_key(skey, rel, idxrel, searchslot);
203 :
204 : /* Start an index scan. */
205 144194 : scan = index_beginscan(rel, idxrel, &snap, skey_attoff, 0);
206 :
207 144194 : retry:
208 144194 : found = false;
209 :
210 144194 : index_rescan(scan, skey, skey_attoff, NULL, 0);
211 :
212 : /* Try to find the tuple */
213 144194 : 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 144170 : 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 144170 : ExecMaterializeSlot(outslot);
229 :
230 288340 : xwait = TransactionIdIsValid(snap.xmin) ?
231 144170 : snap.xmin : snap.xmax;
232 :
233 : /*
234 : * If the tuple is locked, wait for locking transaction to finish and
235 : * retry.
236 : */
237 144170 : 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 144170 : found = true;
245 144170 : break;
246 : }
247 :
248 : /* Found tuple, try to lock it in the lockmode. */
249 144194 : if (found)
250 : {
251 : TM_FailureData tmfd;
252 : TM_Result res;
253 :
254 144170 : PushActiveSnapshot(GetLatestSnapshot());
255 :
256 144170 : res = table_tuple_lock(rel, &(outslot->tts_tid), GetLatestSnapshot(),
257 : outslot,
258 : GetCurrentCommandId(false),
259 : lockmode,
260 : LockWaitBlock,
261 : 0 /* don't follow updates */ ,
262 : &tmfd);
263 :
264 144170 : PopActiveSnapshot();
265 :
266 144170 : if (should_refetch_tuple(res, &tmfd))
267 0 : goto retry;
268 : }
269 :
270 144194 : index_endscan(scan);
271 :
272 : /* Don't release lock until commit. */
273 144194 : index_close(idxrel, NoLock);
274 :
275 144194 : 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), GetLatestSnapshot(),
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 18 : FindConflictTuple(ResultRelInfo *resultRelInfo, EState *estate,
445 : Oid conflictindex, TupleTableSlot *slot,
446 : TupleTableSlot **conflictslot)
447 : {
448 18 : Relation rel = resultRelInfo->ri_RelationDesc;
449 : ItemPointerData conflictTid;
450 : TM_FailureData tmfd;
451 : TM_Result res;
452 :
453 18 : *conflictslot = NULL;
454 :
455 18 : retry:
456 18 : if (ExecCheckIndexConstraints(resultRelInfo, slot, estate,
457 : &conflictTid, &slot->tts_tid,
458 18 : 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 14 : *conflictslot = table_slot_create(rel, NULL);
468 :
469 14 : PushActiveSnapshot(GetLatestSnapshot());
470 :
471 14 : res = table_tuple_lock(rel, &conflictTid, GetLatestSnapshot(),
472 : *conflictslot,
473 : GetCurrentCommandId(false),
474 : LockTupleShare,
475 : LockWaitBlock,
476 : 0 /* don't follow updates */ ,
477 : &tmfd);
478 :
479 14 : PopActiveSnapshot();
480 :
481 14 : if (should_refetch_tuple(res, &tmfd))
482 0 : goto retry;
483 :
484 14 : 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 18 : CheckAndReportConflict(ResultRelInfo *resultRelInfo, EState *estate,
493 : ConflictType type, List *recheckIndexes,
494 : TupleTableSlot *searchslot, TupleTableSlot *remoteslot)
495 : {
496 : /* Check all the unique indexes for a conflict */
497 22 : foreach_oid(uniqueidx, resultRelInfo->ri_onConflictArbiterIndexes)
498 : {
499 : TupleTableSlot *conflictslot;
500 :
501 34 : if (list_member_oid(recheckIndexes, uniqueidx) &&
502 18 : FindConflictTuple(resultRelInfo, estate, uniqueidx, remoteslot,
503 : &conflictslot))
504 : {
505 : RepOriginId origin;
506 : TimestampTz committs;
507 : TransactionId xmin;
508 :
509 14 : GetTupleTransactionInfo(conflictslot, &xmin, &origin, &committs);
510 14 : ReportApplyConflict(estate, resultRelInfo, ERROR, type,
511 : searchslot, conflictslot, remoteslot,
512 : uniqueidx, xmin, origin, committs);
513 : }
514 : }
515 2 : }
516 :
517 : /*
518 : * Insert tuple represented in the slot to the relation, update the indexes,
519 : * and execute any constraints and per-row triggers.
520 : *
521 : * Caller is responsible for opening the indexes.
522 : */
523 : void
524 152418 : ExecSimpleRelationInsert(ResultRelInfo *resultRelInfo,
525 : EState *estate, TupleTableSlot *slot)
526 : {
527 152418 : bool skip_tuple = false;
528 152418 : Relation rel = resultRelInfo->ri_RelationDesc;
529 :
530 : /* For now we support only tables. */
531 : Assert(rel->rd_rel->relkind == RELKIND_RELATION);
532 :
533 152418 : CheckCmdReplicaIdentity(rel, CMD_INSERT);
534 :
535 : /* BEFORE ROW INSERT Triggers */
536 152418 : if (resultRelInfo->ri_TrigDesc &&
537 38 : resultRelInfo->ri_TrigDesc->trig_insert_before_row)
538 : {
539 6 : if (!ExecBRInsertTriggers(estate, resultRelInfo, slot))
540 2 : skip_tuple = true; /* "do nothing" */
541 : }
542 :
543 152418 : if (!skip_tuple)
544 : {
545 152416 : List *recheckIndexes = NIL;
546 : List *conflictindexes;
547 152416 : bool conflict = false;
548 :
549 : /* Compute stored generated columns */
550 152416 : if (rel->rd_att->constr &&
551 90922 : rel->rd_att->constr->has_generated_stored)
552 8 : ExecComputeStoredGenerated(resultRelInfo, estate, slot,
553 : CMD_INSERT);
554 :
555 : /* Check the constraints of the tuple */
556 152416 : if (rel->rd_att->constr)
557 90922 : ExecConstraints(resultRelInfo, slot, estate);
558 152416 : if (rel->rd_rel->relispartition)
559 120 : ExecPartitionCheck(resultRelInfo, slot, estate, true);
560 :
561 : /* OK, store the tuple and create index entries for it */
562 152416 : simple_table_tuple_insert(resultRelInfo->ri_RelationDesc, slot);
563 :
564 152416 : conflictindexes = resultRelInfo->ri_onConflictArbiterIndexes;
565 :
566 152416 : if (resultRelInfo->ri_NumIndices > 0)
567 111744 : recheckIndexes = ExecInsertIndexTuples(resultRelInfo,
568 : slot, estate, false,
569 : conflictindexes ? true : false,
570 : &conflict,
571 : conflictindexes, false);
572 :
573 : /*
574 : * Checks the conflict indexes to fetch the conflicting local tuple
575 : * and reports the conflict. We perform this check here, instead of
576 : * performing an additional index scan before the actual insertion and
577 : * reporting the conflict if any conflicting tuples are found. This is
578 : * to avoid the overhead of executing the extra scan for each INSERT
579 : * operation, even when no conflict arises, which could introduce
580 : * significant overhead to replication, particularly in cases where
581 : * conflicts are rare.
582 : *
583 : * XXX OTOH, this could lead to clean-up effort for dead tuples added
584 : * in heap and index in case of conflicts. But as conflicts shouldn't
585 : * be a frequent thing so we preferred to save the performance
586 : * overhead of extra scan before each insertion.
587 : */
588 152416 : if (conflict)
589 16 : CheckAndReportConflict(resultRelInfo, estate, CT_INSERT_EXISTS,
590 : recheckIndexes, NULL, slot);
591 :
592 : /* AFTER ROW INSERT Triggers */
593 152402 : ExecARInsertTriggers(estate, resultRelInfo, slot,
594 : recheckIndexes, NULL);
595 :
596 : /*
597 : * XXX we should in theory pass a TransitionCaptureState object to the
598 : * above to capture transition tuples, but after statement triggers
599 : * don't actually get fired by replication yet anyway
600 : */
601 :
602 152402 : list_free(recheckIndexes);
603 : }
604 152404 : }
605 :
606 : /*
607 : * Find the searchslot tuple and update it with data in the slot,
608 : * update the indexes, and execute any constraints and per-row triggers.
609 : *
610 : * Caller is responsible for opening the indexes.
611 : */
612 : void
613 63844 : ExecSimpleRelationUpdate(ResultRelInfo *resultRelInfo,
614 : EState *estate, EPQState *epqstate,
615 : TupleTableSlot *searchslot, TupleTableSlot *slot)
616 : {
617 63844 : bool skip_tuple = false;
618 63844 : Relation rel = resultRelInfo->ri_RelationDesc;
619 63844 : ItemPointer tid = &(searchslot->tts_tid);
620 :
621 : /*
622 : * We support only non-system tables, with
623 : * check_publication_add_relation() accountable.
624 : */
625 : Assert(rel->rd_rel->relkind == RELKIND_RELATION);
626 : Assert(!IsCatalogRelation(rel));
627 :
628 63844 : CheckCmdReplicaIdentity(rel, CMD_UPDATE);
629 :
630 : /* BEFORE ROW UPDATE Triggers */
631 63844 : if (resultRelInfo->ri_TrigDesc &&
632 20 : resultRelInfo->ri_TrigDesc->trig_update_before_row)
633 : {
634 6 : if (!ExecBRUpdateTriggers(estate, epqstate, resultRelInfo,
635 : tid, NULL, slot, NULL, NULL))
636 4 : skip_tuple = true; /* "do nothing" */
637 : }
638 :
639 63844 : if (!skip_tuple)
640 : {
641 63840 : List *recheckIndexes = NIL;
642 : TU_UpdateIndexes update_indexes;
643 : List *conflictindexes;
644 63840 : bool conflict = false;
645 :
646 : /* Compute stored generated columns */
647 63840 : if (rel->rd_att->constr &&
648 63750 : rel->rd_att->constr->has_generated_stored)
649 4 : ExecComputeStoredGenerated(resultRelInfo, estate, slot,
650 : CMD_UPDATE);
651 :
652 : /* Check the constraints of the tuple */
653 63840 : if (rel->rd_att->constr)
654 63750 : ExecConstraints(resultRelInfo, slot, estate);
655 63840 : if (rel->rd_rel->relispartition)
656 24 : ExecPartitionCheck(resultRelInfo, slot, estate, true);
657 :
658 63840 : simple_table_tuple_update(rel, tid, slot, estate->es_snapshot,
659 : &update_indexes);
660 :
661 63840 : conflictindexes = resultRelInfo->ri_onConflictArbiterIndexes;
662 :
663 63840 : if (resultRelInfo->ri_NumIndices > 0 && (update_indexes != TU_None))
664 40404 : recheckIndexes = ExecInsertIndexTuples(resultRelInfo,
665 : slot, estate, true,
666 : conflictindexes ? true : false,
667 : &conflict, conflictindexes,
668 : (update_indexes == TU_Summarizing));
669 :
670 : /*
671 : * Refer to the comments above the call to CheckAndReportConflict() in
672 : * ExecSimpleRelationInsert to understand why this check is done at
673 : * this point.
674 : */
675 63840 : if (conflict)
676 2 : CheckAndReportConflict(resultRelInfo, estate, CT_UPDATE_EXISTS,
677 : recheckIndexes, searchslot, slot);
678 :
679 : /* AFTER ROW UPDATE Triggers */
680 63838 : ExecARUpdateTriggers(estate, resultRelInfo,
681 : NULL, NULL,
682 : tid, NULL, slot,
683 : recheckIndexes, NULL, false);
684 :
685 63838 : list_free(recheckIndexes);
686 : }
687 63842 : }
688 :
689 : /*
690 : * Find the searchslot tuple and delete it, and execute any constraints
691 : * and per-row triggers.
692 : *
693 : * Caller is responsible for opening the indexes.
694 : */
695 : void
696 80620 : ExecSimpleRelationDelete(ResultRelInfo *resultRelInfo,
697 : EState *estate, EPQState *epqstate,
698 : TupleTableSlot *searchslot)
699 : {
700 80620 : bool skip_tuple = false;
701 80620 : Relation rel = resultRelInfo->ri_RelationDesc;
702 80620 : ItemPointer tid = &searchslot->tts_tid;
703 :
704 80620 : CheckCmdReplicaIdentity(rel, CMD_DELETE);
705 :
706 : /* BEFORE ROW DELETE Triggers */
707 80620 : if (resultRelInfo->ri_TrigDesc &&
708 20 : resultRelInfo->ri_TrigDesc->trig_delete_before_row)
709 : {
710 0 : skip_tuple = !ExecBRDeleteTriggers(estate, epqstate, resultRelInfo,
711 0 : tid, NULL, NULL, NULL, NULL);
712 : }
713 :
714 80620 : if (!skip_tuple)
715 : {
716 : /* OK, delete the tuple */
717 80620 : simple_table_tuple_delete(rel, tid, estate->es_snapshot);
718 :
719 : /* AFTER ROW DELETE Triggers */
720 80620 : ExecARDeleteTriggers(estate, resultRelInfo,
721 : tid, NULL, NULL, false);
722 : }
723 80620 : }
724 :
725 : /*
726 : * Check if command can be executed with current replica identity.
727 : */
728 : void
729 429268 : CheckCmdReplicaIdentity(Relation rel, CmdType cmd)
730 : {
731 : PublicationDesc pubdesc;
732 :
733 : /*
734 : * Skip checking the replica identity for partitioned tables, because the
735 : * operations are actually performed on the leaf partitions.
736 : */
737 429268 : if (rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE)
738 407552 : return;
739 :
740 : /* We only need to do checks for UPDATE and DELETE. */
741 423226 : if (cmd != CMD_UPDATE && cmd != CMD_DELETE)
742 250884 : return;
743 :
744 : /*
745 : * It is only safe to execute UPDATE/DELETE if the relation does not
746 : * publish UPDATEs or DELETEs, or all the following conditions are
747 : * satisfied:
748 : *
749 : * 1. All columns, referenced in the row filters from publications which
750 : * the relation is in, are valid - i.e. when all referenced columns are
751 : * part of REPLICA IDENTITY.
752 : *
753 : * 2. All columns, referenced in the column lists are valid - i.e. when
754 : * all columns referenced in the REPLICA IDENTITY are covered by the
755 : * column list.
756 : *
757 : * 3. All generated columns in REPLICA IDENTITY of the relation, are valid
758 : * - i.e. when all these generated columns are published.
759 : *
760 : * XXX We could optimize it by first checking whether any of the
761 : * publications have a row filter or column list for this relation, or if
762 : * the relation contains a generated column. If none of these exist and
763 : * the relation has replica identity then we can avoid building the
764 : * descriptor but as this happens only one time it doesn't seem worth the
765 : * additional complexity.
766 : */
767 172342 : RelationBuildPublicationDesc(rel, &pubdesc);
768 172342 : if (cmd == CMD_UPDATE && !pubdesc.rf_valid_for_update)
769 60 : ereport(ERROR,
770 : (errcode(ERRCODE_INVALID_COLUMN_REFERENCE),
771 : errmsg("cannot update table \"%s\"",
772 : RelationGetRelationName(rel)),
773 : errdetail("Column used in the publication WHERE expression is not part of the replica identity.")));
774 172282 : else if (cmd == CMD_UPDATE && !pubdesc.cols_valid_for_update)
775 108 : ereport(ERROR,
776 : (errcode(ERRCODE_INVALID_COLUMN_REFERENCE),
777 : errmsg("cannot update table \"%s\"",
778 : RelationGetRelationName(rel)),
779 : errdetail("Column list used by the publication does not cover the replica identity.")));
780 172174 : else if (cmd == CMD_UPDATE && !pubdesc.gencols_valid_for_update)
781 24 : ereport(ERROR,
782 : (errcode(ERRCODE_INVALID_COLUMN_REFERENCE),
783 : errmsg("cannot update table \"%s\"",
784 : RelationGetRelationName(rel)),
785 : errdetail("Replica identity must not contain unpublished generated columns.")));
786 172150 : else if (cmd == CMD_DELETE && !pubdesc.rf_valid_for_delete)
787 0 : ereport(ERROR,
788 : (errcode(ERRCODE_INVALID_COLUMN_REFERENCE),
789 : errmsg("cannot delete from table \"%s\"",
790 : RelationGetRelationName(rel)),
791 : errdetail("Column used in the publication WHERE expression is not part of the replica identity.")));
792 172150 : else if (cmd == CMD_DELETE && !pubdesc.cols_valid_for_delete)
793 0 : ereport(ERROR,
794 : (errcode(ERRCODE_INVALID_COLUMN_REFERENCE),
795 : errmsg("cannot delete from table \"%s\"",
796 : RelationGetRelationName(rel)),
797 : errdetail("Column list used by the publication does not cover the replica identity.")));
798 172150 : else if (cmd == CMD_DELETE && !pubdesc.gencols_valid_for_delete)
799 0 : ereport(ERROR,
800 : (errcode(ERRCODE_INVALID_COLUMN_REFERENCE),
801 : errmsg("cannot delete from table \"%s\"",
802 : RelationGetRelationName(rel)),
803 : errdetail("Replica identity must not contain unpublished generated columns.")));
804 :
805 : /* If relation has replica identity we are always good. */
806 172150 : if (OidIsValid(RelationGetReplicaIndex(rel)))
807 150176 : return;
808 :
809 : /* REPLICA IDENTITY FULL is also good for UPDATE/DELETE. */
810 21974 : if (rel->rd_rel->relreplident == REPLICA_IDENTITY_FULL)
811 450 : return;
812 :
813 : /*
814 : * This is UPDATE/DELETE and there is no replica identity.
815 : *
816 : * Check if the table publishes UPDATES or DELETES.
817 : */
818 21524 : if (cmd == CMD_UPDATE && pubdesc.pubactions.pubupdate)
819 106 : ereport(ERROR,
820 : (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
821 : errmsg("cannot update table \"%s\" because it does not have a replica identity and publishes updates",
822 : RelationGetRelationName(rel)),
823 : errhint("To enable updating the table, set REPLICA IDENTITY using ALTER TABLE.")));
824 21418 : else if (cmd == CMD_DELETE && pubdesc.pubactions.pubdelete)
825 10 : ereport(ERROR,
826 : (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
827 : errmsg("cannot delete from table \"%s\" because it does not have a replica identity and publishes deletes",
828 : RelationGetRelationName(rel)),
829 : errhint("To enable deleting from the table, set REPLICA IDENTITY using ALTER TABLE.")));
830 : }
831 :
832 :
833 : /*
834 : * Check if we support writing into specific relkind.
835 : *
836 : * The nspname and relname are only needed for error reporting.
837 : */
838 : void
839 1698 : CheckSubscriptionRelkind(char relkind, const char *nspname,
840 : const char *relname)
841 : {
842 1698 : if (relkind != RELKIND_RELATION && relkind != RELKIND_PARTITIONED_TABLE)
843 0 : ereport(ERROR,
844 : (errcode(ERRCODE_WRONG_OBJECT_TYPE),
845 : errmsg("cannot use relation \"%s.%s\" as logical replication target",
846 : nspname, relname),
847 : errdetail_relkind_not_supported(relkind)));
848 1698 : }
|