LCOV - differential code coverage report
Current view: top level - src/backend/executor - execReplication.c (source / functions) Coverage Total Hit UNC UBC GNC CBC DCB
Current: 4b3c9325757dfd8f2312e9f1a8decf4431f344ae vs e87b024bfb8dd55e3049b1b6e6ab4e810cf1abc8 Lines: 86.5 % 385 333 52 12 321 9
Current Date: 2026-11-28 16:48:44 +0900 Functions: 100.0 % 17 17 7 10
Baseline: lcov-20261128-baseline Branches: 67.7 % 319 216 1 102 7 209
Baseline Date: 2026-11-28 16:48:48 +0900 Line coverage date bins:
Legend: Lines:     hit not hit
Branches: + taken - not taken # not executed
(1,7] days: 100.0 % 5 5 5
(7,30] days: 88.9 % 9 8 1 3 5
(30,360] days: 80.8 % 52 42 10 4 38
(360..) days: 87.1 % 319 278 41 278
Function coverage date bins:
(7,30] days: 100.0 % 1 1 1
(30,360] days: 100.0 % 2 2 1 1
(360..) days: 100.0 % 14 14 5 9
Branch coverage date bins:
(7,30] days: 58.3 % 12 7 1 4 3 4
(30,360] days: 66.7 % 42 28 14 4 24
(360..) days: 68.3 % 265 181 84 181

 Age         Owner                    Branch data    TLA  Line data    Source code
                                  1                 :                : /*-------------------------------------------------------------------------
                                  2                 :                :  *
                                  3                 :                :  * execReplication.c
                                  4                 :                :  *    miscellaneous executor routines for logical replication
                                  5                 :                :  *
                                  6                 :                :  * Portions Copyright (c) 1996-2026, 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/amapi.h"
                                 18                 :                : #include "access/commit_ts.h"
                                 19                 :                : #include "access/genam.h"
                                 20                 :                : #include "access/gist.h"
                                 21                 :                : #include "access/relscan.h"
                                 22                 :                : #include "access/tableam.h"
                                 23                 :                : #include "access/transam.h"
                                 24                 :                : #include "access/xact.h"
                                 25                 :                : #include "access/heapam.h"
                                 26                 :                : #include "catalog/catalog.h"
                                 27                 :                : #include "catalog/pg_am_d.h"
                                 28                 :                : #include "commands/trigger.h"
                                 29                 :                : #include "executor/executor.h"
                                 30                 :                : #include "executor/nodeModifyTable.h"
                                 31                 :                : #include "replication/conflict.h"
                                 32                 :                : #include "replication/logicalrelation.h"
                                 33                 :                : #include "storage/lmgr.h"
                                 34                 :                : #include "utils/builtins.h"
                                 35                 :                : #include "utils/lsyscache.h"
                                 36                 :                : #include "utils/rel.h"
                                 37                 :                : #include "utils/snapmgr.h"
                                 38                 :                : #include "utils/syscache.h"
                                 39                 :                : #include "utils/typcache.h"
                                 40                 :                : 
                                 41                 :                : 
                                 42                 :                : static bool tuples_equal(TupleTableSlot *slot1, TupleTableSlot *slot2,
                                 43                 :                :                          TypeCacheEntry **eq, Bitmapset *columns);
                                 44                 :                : static bool repl_index_key_equal(Relation idxrel, TupleTableSlot *slot1,
                                 45                 :                :                                  TupleTableSlot *slot2, ScanKey skey);
                                 46                 :                : 
                                 47                 :                : /*
                                 48                 :                :  * Setup a ScanKey for a search in the relation 'rel' for a tuple 'key' that
                                 49                 :                :  * is setup to match 'rel' (*NOT* idxrel!).
                                 50                 :                :  *
                                 51                 :                :  * Returns how many columns to use for the index scan.
                                 52                 :                :  *
                                 53                 :                :  * This is not a generic routine, idxrel must be PK, RI, or an index that can be
                                 54                 :                :  * used for a REPLICA IDENTITY FULL table. See FindUsableIndexForReplicaIdentityFull()
                                 55                 :                :  * for details.
                                 56                 :                :  *
                                 57                 :                :  * By definition, replication identity of a rel meets all limitations associated
                                 58                 :                :  * with that. Note that any other index could also meet these limitations.
                                 59                 :                :  */
                                 60                 :                : static int
 3600 peter_e@gmx.net            61                 :CBC       72115 : build_replindex_scan_key(ScanKey skey, Relation rel, Relation idxrel,
                                 62                 :                :                          TupleTableSlot *searchslot)
                                 63                 :                : {
                                 64                 :                :     int         index_attoff;
 1354 akapila@postgresql.o       65                 :          72115 :     int         skey_attoff = 0;
                                 66                 :                :     Datum       indclassDatum;
                                 67                 :                :     oidvector  *opclass;
 3600 peter_e@gmx.net            68                 :          72115 :     int2vector *indkey = &idxrel->rd_index->indkey;
                                 69                 :                : 
 1344 dgustafsson@postgres       70                 :          72115 :     indclassDatum = SysCacheGetAttrNotNull(INDEXRELID, idxrel->rd_indextuple,
                                 71                 :                :                                            Anum_pg_index_indclass);
 3600 peter_e@gmx.net            72                 :          72115 :     opclass = (oidvector *) DatumGetPointer(indclassDatum);
                                 73                 :                : 
                                 74                 :                :     /* Build scankey for every non-expression attribute in the index. */
 1354 akapila@postgresql.o       75         [ +  + ]:         144258 :     for (index_attoff = 0; index_attoff < IndexRelationGetNumberOfKeyAttributes(idxrel);
                                 76                 :          72143 :          index_attoff++)
                                 77                 :                :     {
                                 78                 :                :         Oid         operator;
                                 79                 :                :         Oid         optype;
                                 80                 :                :         Oid         opfamily;
                                 81                 :                :         RegProcedure regop;
                                 82                 :          72143 :         int         table_attno = indkey->values[index_attoff];
                                 83                 :                :         StrategyNumber eq_strategy;
                                 84                 :                : 
                                 85         [ +  + ]:          72143 :         if (!AttributeNumberIsValid(table_attno))
                                 86                 :                :         {
                                 87                 :                :             /*
                                 88                 :                :              * XXX: Currently, we don't support expressions in the scan key,
                                 89                 :                :              * see code below.
                                 90                 :                :              */
                                 91                 :              2 :             continue;
                                 92                 :                :         }
                                 93                 :                : 
                                 94                 :                :         /*
                                 95                 :                :          * Load the operator info.  We need this to get the equality operator
                                 96                 :                :          * function for the scan key.
                                 97                 :                :          */
                                 98                 :          72141 :         optype = get_opclass_input_type(opclass->values[index_attoff]);
                                 99                 :          72141 :         opfamily = get_opclass_family(opclass->values[index_attoff]);
  645 peter@eisentraut.org      100                 :          72141 :         eq_strategy = IndexAmTranslateCompareType(COMPARE_EQ, idxrel->rd_rel->relam, opfamily, false);
 3600 peter_e@gmx.net           101                 :          72141 :         operator = get_opfamily_member(opfamily, optype,
                                102                 :                :                                        optype,
                                103                 :                :                                        eq_strategy);
                                104                 :                : 
                                105         [ -  + ]:          72141 :         if (!OidIsValid(operator))
 3414 tgl@sss.pgh.pa.us         106         [ #  # ]:UBC           0 :             elog(ERROR, "missing operator %d(%u,%u) in opfamily %u",
                                107                 :                :                  eq_strategy, optype, optype, opfamily);
                                108                 :                : 
 3600 peter_e@gmx.net           109                 :CBC       72141 :         regop = get_opcode(operator);
                                110                 :                : 
                                111                 :                :         /* Initialize the scankey. */
 1354 akapila@postgresql.o      112                 :          72141 :         ScanKeyInit(&skey[skey_attoff],
                                113                 :          72141 :                     index_attoff + 1,
                                114                 :                :                     eq_strategy,
                                115                 :                :                     regop,
                                116                 :          72141 :                     searchslot->tts_values[table_attno - 1]);
                                117                 :                : 
                                118                 :          72141 :         skey[skey_attoff].sk_collation = idxrel->rd_indcollation[index_attoff];
                                119                 :                : 
                                120                 :                :         /* Check for null value. */
                                121         [ +  + ]:          72141 :         if (searchslot->tts_isnull[table_attno - 1])
                                122                 :              1 :             skey[skey_attoff].sk_flags |= (SK_ISNULL | SK_SEARCHNULL);
                                123                 :                : 
                                124                 :          72141 :         skey_attoff++;
                                125                 :                :     }
                                126                 :                : 
                                127                 :                :     /* There must always be at least one attribute for the index scan. */
                                128         [ -  + ]:          72115 :     Assert(skey_attoff > 0);
                                129                 :                : 
                                130                 :          72115 :     return skey_attoff;
                                131                 :                : }
                                132                 :                : 
                                133                 :                : 
                                134                 :                : /*
                                135                 :                :  * Helper function to check if it is necessary to re-fetch and lock the tuple
                                136                 :                :  * due to concurrent modifications. This function should be called after
                                137                 :                :  * invoking table_tuple_lock.
                                138                 :                :  */
                                139                 :                : static bool
  830                           140                 :          72356 : should_refetch_tuple(TM_Result res, TM_FailureData *tmfd)
                                141                 :                : {
                                142                 :          72356 :     bool        refetch = false;
                                143                 :                : 
                                144   [ +  -  -  -  :          72356 :     switch (res)
                                                 - ]
                                145                 :                :     {
                                146                 :          72356 :         case TM_Ok:
                                147                 :          72356 :             break;
  830 akapila@postgresql.o      148                 :UBC           0 :         case TM_Updated:
                                149                 :                :             /* XXX: Improve handling here */
                                150         [ #  # ]:              0 :             if (ItemPointerIndicatesMovedPartitions(&tmfd->ctid))
                                151         [ #  # ]:              0 :                 ereport(LOG,
                                152                 :                :                         (errcode(ERRCODE_T_R_SERIALIZATION_FAILURE),
                                153                 :                :                          errmsg("tuple to be locked was already moved to another partition due to concurrent update, retrying")));
                                154                 :                :             else
                                155         [ #  # ]:              0 :                 ereport(LOG,
                                156                 :                :                         (errcode(ERRCODE_T_R_SERIALIZATION_FAILURE),
                                157                 :                :                          errmsg("concurrent update, retrying")));
                                158                 :              0 :             refetch = true;
                                159                 :              0 :             break;
                                160                 :              0 :         case TM_Deleted:
                                161                 :                :             /* XXX: Improve handling here */
                                162         [ #  # ]:              0 :             ereport(LOG,
                                163                 :                :                     (errcode(ERRCODE_T_R_SERIALIZATION_FAILURE),
                                164                 :                :                      errmsg("concurrent delete, retrying")));
                                165                 :              0 :             refetch = true;
                                166                 :              0 :             break;
                                167                 :              0 :         case TM_Invisible:
                                168         [ #  # ]:              0 :             elog(ERROR, "attempted to lock invisible tuple");
                                169                 :                :             break;
                                170                 :              0 :         default:
                                171         [ #  # ]:              0 :             elog(ERROR, "unexpected table_tuple_lock status: %u", res);
                                172                 :                :             break;
                                173                 :                :     }
                                174                 :                : 
  830 akapila@postgresql.o      175                 :CBC       72356 :     return refetch;
                                176                 :                : }
                                177                 :                : 
                                178                 :                : /*
                                179                 :                :  * Search the relation 'rel' for tuple using the index.
                                180                 :                :  *
                                181                 :                :  * If a matching tuple is found, lock it with lockmode, fill the slot with its
                                182                 :                :  * contents, and return true.  Return false otherwise.
                                183                 :                :  *
                                184                 :                :  * 'skipduplicates' specifies whether the first matching tuple can be used
                                185                 :                :  * without comparing it against 'searchslot', unless the index scan sets
                                186                 :                :  * xs_recheck (as with a lossy GiST index for WITHOUT OVERLAPS), in which case
                                187                 :                :  * only the index key columns are compared, using the index's own equality
                                188                 :                :  * semantics. If false, all matching tuples are compared against 'searchslot',
                                189                 :                :  * which must contain a complete row.
                                190                 :                :  */
                                191                 :                : bool
 3600 peter_e@gmx.net           192                 :          72113 : RelationFindReplTupleByIndex(Relation rel, Oid idxoid,
                                193                 :                :                              bool skipduplicates,
                                194                 :                :                              LockTupleMode lockmode,
                                195                 :                :                              TupleTableSlot *searchslot,
                                196                 :                :                              TupleTableSlot *outslot)
                                197                 :                : {
                                198                 :                :     ScanKeyData skey[INDEX_MAX_KEYS];
                                199                 :                :     int         skey_attoff;
                                200                 :                :     IndexScanDesc scan;
                                201                 :                :     SnapshotData snap;
                                202                 :                :     TransactionId xwait;
                                203                 :                :     Relation    idxrel;
                                204                 :                :     bool        found;
 1354 akapila@postgresql.o      205                 :          72113 :     TypeCacheEntry **eq = NULL;
                                206                 :                : 
                                207                 :                :     /* Open the index. */
 3600 peter_e@gmx.net           208                 :          72113 :     idxrel = index_open(idxoid, RowExclusiveLock);
                                209                 :                : 
                                210                 :          72113 :     InitDirtySnapshot(snap);
                                211                 :                : 
                                212                 :                :     /* Build scan key. */
 1354 akapila@postgresql.o      213                 :          72113 :     skey_attoff = build_replindex_scan_key(skey, rel, idxrel, searchslot);
                                214                 :                : 
                                215                 :                :     /* Start an index scan. */
   74 pg@bowt.ie                216                 :GNC       72113 :     scan = index_beginscan(rel, idxrel, false,
                                217                 :                :                            &snap, NULL, skey_attoff, 0, SO_NONE);
                                218                 :                : 
 3600 peter_e@gmx.net           219                 :UBC           0 : retry:
 3600 peter_e@gmx.net           220                 :CBC       72113 :     found = false;
                                221                 :                : 
 1354 akapila@postgresql.o      222                 :          72113 :     index_rescan(scan, skey, skey_attoff, NULL, 0);
                                223                 :                : 
                                224                 :                :     /* Try to find the tuple */
   74 pg@bowt.ie                225         [ +  + ]:GNC       72115 :     while (table_index_getnext_slot(scan, ForwardScanDirection, outslot))
                                226                 :                :     {
                                227                 :                :         /*
                                228                 :                :          * Avoid expensive equality check if the index is primary key or
                                229                 :                :          * replica identity index, unless the index scan indicates that a
                                230                 :                :          * recheck is needed.
                                231                 :                :          */
   61 akapila@postgresql.o      232         [ +  + ]:CBC       72095 :         if (!skipduplicates)
                                233                 :                :         {
 1354                           234         [ +  - ]:             17 :             if (eq == NULL)
  353 michael@paquier.xyz       235                 :             17 :                 eq = palloc0_array(TypeCacheEntry *, outslot->tts_tupleDescriptor->natts);
                                236                 :                : 
  481 akapila@postgresql.o      237         [ -  + ]:             17 :             if (!tuples_equal(outslot, searchslot, eq, NULL))
 1354 akapila@postgresql.o      238                 :UBC           0 :                 continue;
                                239                 :                :         }
   38 akapila@postgresql.o      240         [ +  + ]:CBC       72078 :         else if (scan->xs_recheck &&
                                241         [ +  + ]:              5 :                  !repl_index_key_equal(idxrel, outslot, searchslot, skey))
                                242                 :              2 :             continue;
                                243                 :                : 
 3600 peter_e@gmx.net           244                 :          72093 :         ExecMaterializeSlot(outslot);
                                245                 :                : 
                                246                 :         144186 :         xwait = TransactionIdIsValid(snap.xmin) ?
                                247         [ -  + ]:          72093 :             snap.xmin : snap.xmax;
                                248                 :                : 
                                249                 :                :         /*
                                250                 :                :          * If the tuple is locked, wait for locking transaction to finish and
                                251                 :                :          * retry.
                                252                 :                :          */
                                253         [ -  + ]:          72093 :         if (TransactionIdIsValid(xwait))
                                254                 :                :         {
 3600 peter_e@gmx.net           255                 :UBC           0 :             XactLockTableWait(xwait, NULL, NULL, XLTW_None);
                                256                 :              0 :             goto retry;
                                257                 :                :         }
                                258                 :                : 
                                259                 :                :         /* Found our tuple and it's not locked */
 1354 akapila@postgresql.o      260                 :CBC       72093 :         found = true;
                                261                 :          72093 :         break;
                                262                 :                :     }
                                263                 :                : 
                                264                 :                :     /* Found tuple, try to lock it in the lockmode. */
 3600 peter_e@gmx.net           265         [ +  + ]:          72113 :     if (found)
                                266                 :                :     {
                                267                 :                :         TM_FailureData tmfd;
                                268                 :                :         TM_Result   res;
                                269                 :                : 
                                270                 :          72093 :         PushActiveSnapshot(GetLatestSnapshot());
                                271                 :                : 
  628 heikki.linnakangas@i      272                 :          72093 :         res = table_tuple_lock(rel, &(outslot->tts_tid), GetActiveSnapshot(),
                                273                 :                :                                outslot,
                                274                 :                :                                GetCurrentCommandId(false),
                                275                 :                :                                lockmode,
                                276                 :                :                                LockWaitBlock,
                                277                 :                :                                0 /* don't follow updates */ ,
                                278                 :                :                                &tmfd);
                                279                 :                : 
 3600 peter_e@gmx.net           280                 :          72093 :         PopActiveSnapshot();
                                281                 :                : 
  830 akapila@postgresql.o      282         [ -  + ]:          72093 :         if (should_refetch_tuple(res, &tmfd))
  830 akapila@postgresql.o      283                 :UBC           0 :             goto retry;
                                284                 :                :     }
                                285                 :                : 
 3600 peter_e@gmx.net           286                 :CBC       72113 :     index_endscan(scan);
                                287                 :                : 
                                288                 :                :     /* Don't release lock until commit. */
                                289                 :          72113 :     index_close(idxrel, NoLock);
                                290                 :                : 
                                291                 :          72113 :     return found;
                                292                 :                : }
                                293                 :                : 
                                294                 :                : /*
                                295                 :                :  * Compare the tuples in the slots by checking if they have equal values.
                                296                 :                :  *
                                297                 :                :  * If 'columns' is not null, only the columns specified within it will be
                                298                 :                :  * considered for the equality check, ignoring all other columns.
                                299                 :                :  */
                                300                 :                : static bool
 2422 noah@leadboat.com         301                 :         105333 : tuples_equal(TupleTableSlot *slot1, TupleTableSlot *slot2,
                                302                 :                :              TypeCacheEntry **eq, Bitmapset *columns)
                                303                 :                : {
                                304                 :                :     int         attrnum;
                                305                 :                : 
 2819 andres@anarazel.de        306         [ -  + ]:         105333 :     Assert(slot1->tts_tupleDescriptor->natts ==
                                307                 :                :            slot2->tts_tupleDescriptor->natts);
                                308                 :                : 
                                309                 :         105333 :     slot_getallattrs(slot1);
                                310                 :         105333 :     slot_getallattrs(slot2);
                                311                 :                : 
                                312                 :                :     /* Check equality of the attributes. */
                                313         [ +  + ]:         105538 :     for (attrnum = 0; attrnum < slot1->tts_tupleDescriptor->natts; attrnum++)
                                314                 :                :     {
                                315                 :                :         Form_pg_attribute att;
                                316                 :                :         TypeCacheEntry *typentry;
                                317                 :                : 
 1348 akapila@postgresql.o      318                 :         105372 :         att = TupleDescAttr(slot1->tts_tupleDescriptor, attrnum);
                                319                 :                : 
                                320                 :                :         /*
                                321                 :                :          * Ignore dropped and generated columns as the publisher doesn't send
                                322                 :                :          * those
                                323                 :                :          */
 1346                           324   [ +  +  -  + ]:         105372 :         if (att->attisdropped || att->attgenerated)
 1348                           325                 :              1 :             continue;
                                326                 :                : 
                                327                 :                :         /*
                                328                 :                :          * Ignore columns that are not listed for checking.
                                329                 :                :          */
  481                           330         [ -  + ]:         105371 :         if (columns &&
  481 akapila@postgresql.o      331         [ #  # ]:UBC           0 :             !bms_is_member(att->attnum - FirstLowInvalidHeapAttributeNumber,
                                332                 :                :                            columns))
                                333                 :              0 :             continue;
                                334                 :                : 
                                335                 :                :         /*
                                336                 :                :          * If one value is NULL and other is not, then they are certainly not
                                337                 :                :          * equal
                                338                 :                :          */
 2819 andres@anarazel.de        339         [ -  + ]:CBC      105371 :         if (slot1->tts_isnull[attrnum] != slot2->tts_isnull[attrnum])
 3600 peter_e@gmx.net           340                 :UBC           0 :             return false;
                                341                 :                : 
                                342                 :                :         /*
                                343                 :                :          * If both are NULL, they can be considered equal.
                                344                 :                :          */
 2819 andres@anarazel.de        345   [ +  +  -  + ]:CBC      105371 :         if (slot1->tts_isnull[attrnum] || slot2->tts_isnull[attrnum])
 3600 peter_e@gmx.net           346                 :              1 :             continue;
                                347                 :                : 
 2422 noah@leadboat.com         348                 :         105370 :         typentry = eq[attrnum];
                                349         [ +  + ]:         105370 :         if (typentry == NULL)
                                350                 :                :         {
                                351                 :            206 :             typentry = lookup_type_cache(att->atttypid,
                                352                 :                :                                          TYPECACHE_EQ_OPR_FINFO);
                                353         [ -  + ]:            206 :             if (!OidIsValid(typentry->eq_opr_finfo.fn_oid))
 2422 noah@leadboat.com         354         [ #  # ]:UBC           0 :                 ereport(ERROR,
                                355                 :                :                         (errcode(ERRCODE_UNDEFINED_FUNCTION),
                                356                 :                :                          errmsg("could not identify an equality operator for type %s",
                                357                 :                :                                 format_type_be(att->atttypid))));
 2422 noah@leadboat.com         358                 :CBC         206 :             eq[attrnum] = typentry;
                                359                 :                :         }
                                360                 :                : 
 2808 peter@eisentraut.org      361         [ +  + ]:         105370 :         if (!DatumGetBool(FunctionCall2Coll(&typentry->eq_opr_finfo,
                                362                 :                :                                             att->attcollation,
 2747 tgl@sss.pgh.pa.us         363                 :         105370 :                                             slot1->tts_values[attrnum],
                                364                 :         105370 :                                             slot2->tts_values[attrnum])))
 3600 peter_e@gmx.net           365                 :         105167 :             return false;
                                366                 :                :     }
                                367                 :                : 
                                368                 :            166 :     return true;
                                369                 :                : }
                                370                 :                : 
                                371                 :                : /*
                                372                 :                :  * Compare the key columns of index 'idxrel' between the two slots, using the
                                373                 :                :  * equality operators and collations of the scan key 'skey' built by
                                374                 :                :  * build_replindex_scan_key().
                                375                 :                :  */
                                376                 :                : static bool
   38 akapila@postgresql.o      377                 :              6 : repl_index_key_equal(Relation idxrel, TupleTableSlot *slot1,
                                378                 :                :                      TupleTableSlot *slot2, ScanKey skey)
                                379                 :                : {
                                380         [ -  + ]:              6 :     Assert(slot1->tts_tupleDescriptor->natts ==
                                381                 :                :            slot2->tts_tupleDescriptor->natts);
                                382                 :                : 
                                383         [ +  + ]:             12 :     for (int i = 0; i < idxrel->rd_index->indnkeyatts; i++)
                                384                 :                :     {
                                385                 :              9 :         AttrNumber  keycol = idxrel->rd_index->indkey.values[i];
                                386                 :                :         Datum       value1;
                                387                 :                :         Datum       value2;
                                388                 :                :         bool        isnull1;
                                389                 :                :         bool        isnull2;
                                390                 :                : 
                                391                 :              9 :         value1 = slot_getattr(slot1, keycol, &isnull1);
                                392                 :              9 :         value2 = slot_getattr(slot2, keycol, &isnull2);
                                393                 :                : 
                                394                 :                :         /*
                                395                 :                :          * If one value is NULL and other is not, then they are certainly not
                                396                 :                :          * equal
                                397                 :                :          */
                                398         [ -  + ]:              9 :         if (isnull1 != isnull2)
                                399                 :              3 :             return false;
                                400                 :                : 
                                401                 :                :         /*
                                402                 :                :          * If both are NULL, they can be considered equal.
                                403                 :                :          */
                                404   [ +  -  -  + ]:              9 :         if (isnull1 || isnull2)
   38 akapila@postgresql.o      405                 :UBC           0 :             continue;
                                406                 :                : 
   38 akapila@postgresql.o      407         [ +  + ]:CBC           9 :         if (!DatumGetBool(FunctionCall2Coll(&skey[i].sk_func,
                                408                 :              9 :                                             skey[i].sk_collation,
                                409                 :                :                                             value1, value2)))
                                410                 :              3 :             return false;
                                411                 :                :     }
                                412                 :                : 
                                413                 :              3 :     return true;
                                414                 :                : }
                                415                 :                : 
                                416                 :                : /*
                                417                 :                :  * Search the relation 'rel' for tuple using the sequential scan.
                                418                 :                :  *
                                419                 :                :  * If a matching tuple is found, lock it with lockmode, fill the slot with its
                                420                 :                :  * contents, and return true.  Return false otherwise.
                                421                 :                :  *
                                422                 :                :  * Note that this stops on the first matching tuple.
                                423                 :                :  *
                                424                 :                :  * This can obviously be quite slow on tables that have more than few rows.
                                425                 :                :  */
                                426                 :                : bool
 3600 peter_e@gmx.net           427                 :            151 : RelationFindReplTupleSeq(Relation rel, LockTupleMode lockmode,
                                428                 :                :                          TupleTableSlot *searchslot, TupleTableSlot *outslot)
                                429                 :                : {
                                430                 :                :     TupleTableSlot *scanslot;
                                431                 :                :     TableScanDesc scan;
                                432                 :                :     SnapshotData snap;
                                433                 :                :     TypeCacheEntry **eq;
                                434                 :                :     TransactionId xwait;
                                435                 :                :     bool        found;
 2819 andres@anarazel.de        436                 :            151 :     TupleDesc   desc PG_USED_FOR_ASSERTS_ONLY = RelationGetDescr(rel);
                                437                 :                : 
 3600 peter_e@gmx.net           438         [ -  + ]:            151 :     Assert(equalTupleDescs(desc, outslot->tts_tupleDescriptor));
                                439                 :                : 
  353 michael@paquier.xyz       440                 :            151 :     eq = palloc0_array(TypeCacheEntry *, outslot->tts_tupleDescriptor->natts);
                                441                 :                : 
                                442                 :                :     /* Start a heap scan. */
 3600 peter_e@gmx.net           443                 :            151 :     InitDirtySnapshot(snap);
  243 melanieplageman@gmai      444                 :            151 :     scan = table_beginscan(rel, &snap, 0, NULL,
                                445                 :                :                            SO_NONE);
 2819 andres@anarazel.de        446                 :            151 :     scanslot = table_slot_create(rel, NULL);
                                447                 :                : 
 3600 peter_e@gmx.net           448                 :UBC           0 : retry:
 3600 peter_e@gmx.net           449                 :CBC         151 :     found = false;
                                450                 :                : 
 2819 andres@anarazel.de        451                 :            151 :     table_rescan(scan, NULL);
                                452                 :                : 
                                453                 :                :     /* Try to find the tuple */
                                454         [ +  + ]:         105316 :     while (table_scan_getnextslot(scan, ForwardScanDirection, scanslot))
                                455                 :                :     {
  481 akapila@postgresql.o      456         [ +  + ]:         105312 :         if (!tuples_equal(scanslot, searchslot, eq, NULL))
 3600 peter_e@gmx.net           457                 :         105165 :             continue;
                                458                 :                : 
                                459                 :            147 :         found = true;
 2819 andres@anarazel.de        460                 :            147 :         ExecCopySlot(outslot, scanslot);
                                461                 :                : 
 3600 peter_e@gmx.net           462                 :            294 :         xwait = TransactionIdIsValid(snap.xmin) ?
                                463         [ -  + ]:            147 :             snap.xmin : snap.xmax;
                                464                 :                : 
                                465                 :                :         /*
                                466                 :                :          * If the tuple is locked, wait for locking transaction to finish and
                                467                 :                :          * retry.
                                468                 :                :          */
                                469         [ -  + ]:            147 :         if (TransactionIdIsValid(xwait))
                                470                 :                :         {
 3600 peter_e@gmx.net           471                 :UBC           0 :             XactLockTableWait(xwait, NULL, NULL, XLTW_None);
                                472                 :              0 :             goto retry;
                                473                 :                :         }
                                474                 :                : 
                                475                 :                :         /* Found our tuple and it's not locked */
 2490 alvherre@alvh.no-ip.      476                 :CBC         147 :         break;
                                477                 :                :     }
                                478                 :                : 
                                479                 :                :     /* Found tuple, try to lock it in the lockmode. */
 3600 peter_e@gmx.net           480         [ +  + ]:            151 :     if (found)
                                481                 :                :     {
                                482                 :                :         TM_FailureData tmfd;
                                483                 :                :         TM_Result   res;
                                484                 :                : 
                                485                 :            147 :         PushActiveSnapshot(GetLatestSnapshot());
                                486                 :                : 
  628 heikki.linnakangas@i      487                 :            147 :         res = table_tuple_lock(rel, &(outslot->tts_tid), GetActiveSnapshot(),
                                488                 :                :                                outslot,
                                489                 :                :                                GetCurrentCommandId(false),
                                490                 :                :                                lockmode,
                                491                 :                :                                LockWaitBlock,
                                492                 :                :                                0 /* don't follow updates */ ,
                                493                 :                :                                &tmfd);
                                494                 :                : 
 3600 peter_e@gmx.net           495                 :            147 :         PopActiveSnapshot();
                                496                 :                : 
  830 akapila@postgresql.o      497         [ -  + ]:            147 :         if (should_refetch_tuple(res, &tmfd))
  830 akapila@postgresql.o      498                 :UBC           0 :             goto retry;
                                499                 :                :     }
                                500                 :                : 
 2819 andres@anarazel.de        501                 :CBC         151 :     table_endscan(scan);
                                502                 :            151 :     ExecDropSingleTupleTableSlot(scanslot);
                                503                 :                : 
 3600 peter_e@gmx.net           504                 :            151 :     return found;
                                505                 :                : }
                                506                 :                : 
                                507                 :                : /*
                                508                 :                :  * Build additional index information necessary for conflict detection.
                                509                 :                :  */
                                510                 :                : static void
  599 akapila@postgresql.o      511                 :            119 : BuildConflictIndexInfo(ResultRelInfo *resultRelInfo, Oid conflictindex)
                                512                 :                : {
                                513         [ +  + ]:            356 :     for (int i = 0; i < resultRelInfo->ri_NumIndices; i++)
                                514                 :                :     {
                                515                 :            237 :         Relation    indexRelation = resultRelInfo->ri_IndexRelationDescs[i];
                                516                 :            237 :         IndexInfo  *indexRelationInfo = resultRelInfo->ri_IndexRelationInfo[i];
                                517                 :                : 
                                518         [ +  + ]:            237 :         if (conflictindex != RelationGetRelid(indexRelation))
                                519                 :            118 :             continue;
                                520                 :                : 
                                521                 :                :         /*
                                522                 :                :          * This Assert will fail if BuildSpeculativeIndexInfo() is called
                                523                 :                :          * twice for the given index.
                                524                 :                :          */
                                525         [ -  + ]:            119 :         Assert(indexRelationInfo->ii_UniqueOps == NULL);
                                526                 :                : 
                                527                 :            119 :         BuildSpeculativeIndexInfo(indexRelation, indexRelationInfo);
                                528                 :                :     }
                                529                 :            119 : }
                                530                 :                : 
                                531                 :                : /*
                                532                 :                :  * If the tuple is recently dead and was deleted by a transaction with a newer
                                533                 :                :  * commit timestamp than previously recorded, update the associated transaction
                                534                 :                :  * ID, commit time, and origin. This helps ensure that conflict detection uses
                                535                 :                :  * the most recent and relevant deletion metadata.
                                536                 :                :  */
                                537                 :                : static void
  481                           538                 :              3 : update_most_recent_deletion_info(TupleTableSlot *scanslot,
                                539                 :                :                                  TransactionId oldestxmin,
                                540                 :                :                                  FullTransactionId *delete_xid,
                                541                 :                :                                  TimestampTz *delete_time,
                                542                 :                :                                  ReplOriginId *delete_origin)
                                543                 :                : {
                                544                 :                :     BufferHeapTupleTableSlot *hslot;
                                545                 :                :     HeapTuple   tuple;
                                546                 :                :     Buffer      buf;
                                547                 :              3 :     bool        recently_dead = false;
                                548                 :                :     TransactionId xmax;
                                549                 :                :     TimestampTz localts;
                                550                 :                :     ReplOriginId localorigin;
                                551                 :                : 
                                552                 :              3 :     hslot = (BufferHeapTupleTableSlot *) scanslot;
                                553                 :                : 
                                554                 :              3 :     tuple = ExecFetchSlotHeapTuple(scanslot, false, NULL);
                                555                 :              3 :     buf = hslot->buffer;
                                556                 :                : 
                                557                 :              3 :     LockBuffer(buf, BUFFER_LOCK_SHARE);
                                558                 :                : 
                                559                 :                :     /*
                                560                 :                :      * We do not consider HEAPTUPLE_DEAD status because it indicates either
                                561                 :                :      * tuples whose inserting transaction was aborted (meaning there is no
                                562                 :                :      * commit timestamp or origin), or tuples deleted by a transaction older
                                563                 :                :      * than oldestxmin, making it safe to ignore them during conflict
                                564                 :                :      * detection (See comments atop worker.c for details).
                                565                 :                :      */
                                566         [ +  - ]:              3 :     if (HeapTupleSatisfiesVacuum(tuple, oldestxmin, buf) == HEAPTUPLE_RECENTLY_DEAD)
                                567                 :              3 :         recently_dead = true;
                                568                 :                : 
                                569                 :              3 :     LockBuffer(buf, BUFFER_LOCK_UNLOCK);
                                570                 :                : 
                                571         [ -  + ]:              3 :     if (!recently_dead)
  481 akapila@postgresql.o      572                 :UBC           0 :         return;
                                573                 :                : 
  481 akapila@postgresql.o      574                 :CBC           3 :     xmax = HeapTupleHeaderGetUpdateXid(tuple->t_data);
                                575         [ -  + ]:              3 :     if (!TransactionIdIsValid(xmax))
  481 akapila@postgresql.o      576                 :UBC           0 :         return;
                                577                 :                : 
                                578                 :                :     /* Select the dead tuple with the most recent commit timestamp */
  481 akapila@postgresql.o      579   [ +  -  +  - ]:CBC           6 :     if (TransactionIdGetCommitTsData(xmax, &localts, &localorigin) &&
                                580                 :              3 :         TimestampDifferenceExceeds(*delete_time, localts, 0))
                                581                 :                :     {
                                582                 :                :         /*
                                583                 :                :          * Convert xmax to a full transaction ID while the buffer is pinned.
                                584                 :                :          * This is safe because VACUUM cannot advance relfrozenxid past an
                                585                 :                :          * xmax on a pinned page. The result is absolute, so it stays valid
                                586                 :                :          * after the pin is released.
                                587                 :                :          *
                                588                 :                :          * XXX We can't rely on the conflict detection slot's xmin instead, as
                                589                 :                :          * a parallel apply worker uses the leader's oldest_nonremovable_xid,
                                590                 :                :          * which the leader can advance or clear at any time.
                                591                 :                :          */
    4 akapila@postgresql.o      592                 :GNC           3 :         *delete_xid = FullTransactionIdFromAllowableAt(ReadNextFullTransactionId(),
                                593                 :                :                                                        xmax);
  481 akapila@postgresql.o      594                 :CBC           3 :         *delete_time = localts;
                                595                 :              3 :         *delete_origin = localorigin;
                                596                 :                :     }
                                597                 :                : }
                                598                 :                : 
                                599                 :                : /*
                                600                 :                :  * Searches the relation 'rel' for the most recently deleted tuple that matches
                                601                 :                :  * the values in 'searchslot' and is not yet removable by VACUUM. The function
                                602                 :                :  * returns the transaction ID, origin, and commit timestamp of the transaction
                                603                 :                :  * that deleted this tuple.
                                604                 :                :  *
                                605                 :                :  * If 'identidxoid' is valid, it is the replica identity or primary key
                                606                 :                :  * index, and only its key columns are compared. Otherwise, all columns are
                                607                 :                :  * compared.
                                608                 :                :  *
                                609                 :                :  * 'oldestxmin' acts as a cutoff transaction ID. Tuples deleted by transactions
                                610                 :                :  * with IDs >= 'oldestxmin' are considered recently dead and are eligible for
                                611                 :                :  * conflict detection.
                                612                 :                :  *
                                613                 :                :  * Instead of stopping at the first match, we scan all matching dead tuples to
                                614                 :                :  * identify most recent deletion. This is crucial because only the latest
                                615                 :                :  * deletion is relevant for resolving conflicts.
                                616                 :                :  *
                                617                 :                :  * For example, consider a scenario on the subscriber where a row is deleted,
                                618                 :                :  * re-inserted, and then deleted again only on the subscriber:
                                619                 :                :  *
                                620                 :                :  *   - (pk, 1) - deleted at 9:00,
                                621                 :                :  *   - (pk, 1) - deleted at 9:02,
                                622                 :                :  *
                                623                 :                :  * Now, a remote update arrives: (pk, 1) -> (pk, 2), timestamped at 9:01.
                                624                 :                :  *
                                625                 :                :  * If we mistakenly return the older deletion (9:00), the system may wrongly
                                626                 :                :  * apply the remote update using a last-update-wins strategy. Instead, we must
                                627                 :                :  * recognize the more recent deletion at 9:02 and skip the update. See
                                628                 :                :  * comments atop worker.c for details. Note, as of now, conflict resolution
                                629                 :                :  * is not implemented. Consequently, the system may incorrectly report the
                                630                 :                :  * older tuple as the conflicted one, leading to misleading results.
                                631                 :                :  *
                                632                 :                :  * The commit timestamp of the deleting transaction is used to determine which
                                633                 :                :  * tuple was deleted most recently.
                                634                 :                :  */
                                635                 :                : bool
   57                           636                 :              3 : RelationFindDeletedTupleInfoSeq(Relation rel, Oid identidxoid,
                                637                 :                :                                 TupleTableSlot *searchslot,
                                638                 :                :                                 TransactionId oldestxmin,
                                639                 :                :                                 FullTransactionId *delete_xid,
                                640                 :                :                                 ReplOriginId *delete_origin,
                                641                 :                :                                 TimestampTz *delete_time)
                                642                 :                : {
                                643                 :                :     TupleTableSlot *scanslot;
                                644                 :                :     TableScanDesc scan;
                                645                 :                :     TypeCacheEntry **eq;
                                646                 :              3 :     Bitmapset  *indexbitmap = NULL;
  481                           647                 :              3 :     TupleDesc   desc PG_USED_FOR_ASSERTS_ONLY = RelationGetDescr(rel);
                                648                 :                : 
                                649         [ -  + ]:              3 :     Assert(equalTupleDescs(desc, searchslot->tts_tupleDescriptor));
                                650                 :                : 
    4 akapila@postgresql.o      651                 :GNC           3 :     *delete_xid = InvalidFullTransactionId;
  304 msawada@postgresql.o      652                 :CBC           3 :     *delete_origin = InvalidReplOriginId;
  481 akapila@postgresql.o      653                 :              3 :     *delete_time = 0;
                                654                 :                : 
                                655                 :                :     /*
                                656                 :                :      * If the caller's replica identity key or primary key is unusable for
                                657                 :                :      * locating deleted tuples (see IsIndexUsableForFindingDeletedTuple), a
                                658                 :                :      * full table scan becomes necessary. In such cases, comparing the entire
                                659                 :                :      * tuple is not required, since the remote tuple might not include all
                                660                 :                :      * column values. Instead, the indexed columns alone are sufficient to
                                661                 :                :      * identify the target tuple (see logicalrep_rel_mark_updatable).
                                662                 :                :      */
   57                           663         [ -  + ]:              3 :     if (OidIsValid(identidxoid))
                                664                 :                :     {
                                665                 :                :         /* The index must have been locked already */
   57 akapila@postgresql.o      666                 :UBC           0 :         Relation    idxrel = index_open(identidxoid, NoLock);
                                667                 :                : 
                                668                 :                :         /*
                                669                 :                :          * The index may no longer be the replica identity if DROP INDEX
                                670                 :                :          * CONCURRENTLY or REINDEX CONCURRENTLY ran meanwhile, but it stays
                                671                 :                :          * unique and non-partial, which is all we rely on. See
                                672                 :                :          * FindReplTupleInLocalRel().
                                673                 :                :          */
                                674         [ #  # ]:              0 :         Assert(idxrel->rd_index->indisunique);
                                675         [ #  # ]:              0 :         Assert(heap_attisnull(idxrel->rd_indextuple, Anum_pg_index_indpred,
                                676                 :                :                               NULL));
                                677                 :                : 
                                678         [ #  # ]:              0 :         for (int i = 0; i < idxrel->rd_index->indnkeyatts; i++)
                                679                 :              0 :             indexbitmap = bms_add_member(indexbitmap,
                                680                 :              0 :                                          idxrel->rd_index->indkey.values[i] -
                                681                 :                :                                          FirstLowInvalidHeapAttributeNumber);
                                682                 :                : 
                                683                 :              0 :         index_close(idxrel, NoLock);
                                684                 :                :     }
                                685                 :                : 
  353 michael@paquier.xyz       686                 :CBC           3 :     eq = palloc0_array(TypeCacheEntry *, searchslot->tts_tupleDescriptor->natts);
                                687                 :                : 
                                688                 :                :     /*
                                689                 :                :      * Start a heap scan using SnapshotAny to identify dead tuples that are
                                690                 :                :      * not visible under a standard MVCC snapshot. Tuples from transactions
                                691                 :                :      * not yet committed or those just committed prior to the scan are
                                692                 :                :      * excluded in update_most_recent_deletion_info().
                                693                 :                :      */
  243 melanieplageman@gmai      694                 :              3 :     scan = table_beginscan(rel, SnapshotAny, 0, NULL,
                                695                 :                :                            SO_NONE);
  481 akapila@postgresql.o      696                 :              3 :     scanslot = table_slot_create(rel, NULL);
                                697                 :                : 
                                698                 :              3 :     table_rescan(scan, NULL);
                                699                 :                : 
                                700                 :                :     /* Try to find the tuple */
                                701         [ +  + ]:              7 :     while (table_scan_getnextslot(scan, ForwardScanDirection, scanslot))
                                702                 :                :     {
                                703         [ +  + ]:              4 :         if (!tuples_equal(scanslot, searchslot, eq, indexbitmap))
                                704                 :              2 :             continue;
                                705                 :                : 
                                706                 :              2 :         update_most_recent_deletion_info(scanslot, oldestxmin, delete_xid,
                                707                 :                :                                          delete_time, delete_origin);
                                708                 :                :     }
                                709                 :                : 
                                710                 :              3 :     table_endscan(scan);
                                711                 :              3 :     ExecDropSingleTupleTableSlot(scanslot);
                                712                 :                : 
                                713                 :              3 :     return *delete_time != 0;
                                714                 :                : }
                                715                 :                : 
                                716                 :                : /*
                                717                 :                :  * Similar to RelationFindDeletedTupleInfoSeq() but using index scan to locate
                                718                 :                :  * the deleted tuple.
                                719                 :                :  *
                                720                 :                :  * 'skipduplicates' works as in RelationFindReplTupleByIndex().
                                721                 :                :  */
                                722                 :                : bool
                                723                 :              2 : RelationFindDeletedTupleInfoByIndex(Relation rel, Oid idxoid,
                                724                 :                :                                     bool skipduplicates,
                                725                 :                :                                     TupleTableSlot *searchslot,
                                726                 :                :                                     TransactionId oldestxmin,
                                727                 :                :                                     FullTransactionId *delete_xid,
                                728                 :                :                                     ReplOriginId *delete_origin,
                                729                 :                :                                     TimestampTz *delete_time)
                                730                 :                : {
                                731                 :                :     Relation    idxrel;
                                732                 :                :     ScanKeyData skey[INDEX_MAX_KEYS];
                                733                 :                :     int         skey_attoff;
                                734                 :                :     IndexScanDesc scan;
                                735                 :                :     TupleTableSlot *scanslot;
                                736                 :              2 :     TypeCacheEntry **eq = NULL;
                                737                 :              2 :     TupleDesc   desc PG_USED_FOR_ASSERTS_ONLY = RelationGetDescr(rel);
                                738                 :                : 
                                739         [ -  + ]:              2 :     Assert(equalTupleDescs(desc, searchslot->tts_tupleDescriptor));
                                740         [ -  + ]:              2 :     Assert(OidIsValid(idxoid));
                                741                 :                : 
    4 akapila@postgresql.o      742                 :GNC           2 :     *delete_xid = InvalidFullTransactionId;
  481 akapila@postgresql.o      743                 :CBC           2 :     *delete_time = 0;
  304 msawada@postgresql.o      744                 :              2 :     *delete_origin = InvalidReplOriginId;
                                745                 :                : 
  481 akapila@postgresql.o      746                 :              2 :     scanslot = table_slot_create(rel, NULL);
                                747                 :                : 
                                748                 :              2 :     idxrel = index_open(idxoid, RowExclusiveLock);
                                749                 :                : 
                                750                 :                :     /* Build scan key. */
                                751                 :              2 :     skey_attoff = build_replindex_scan_key(skey, rel, idxrel, searchslot);
                                752                 :                : 
                                753                 :                :     /*
                                754                 :                :      * Start an index scan using SnapshotAny to identify dead tuples that are
                                755                 :                :      * not visible under a standard MVCC snapshot. Tuples from transactions
                                756                 :                :      * not yet committed or those just committed prior to the scan are
                                757                 :                :      * excluded in update_most_recent_deletion_info().
                                758                 :                :      */
   74 pg@bowt.ie                759                 :GNC           2 :     scan = index_beginscan(rel, idxrel, false,
                                760                 :                :                            SnapshotAny, NULL, skey_attoff, 0, SO_NONE);
                                761                 :                : 
  481 akapila@postgresql.o      762                 :CBC           2 :     index_rescan(scan, skey, skey_attoff, NULL, 0);
                                763                 :                : 
                                764                 :                :     /* Try to find the tuple */
   74 pg@bowt.ie                765         [ +  + ]:GNC           4 :     while (table_index_getnext_slot(scan, ForwardScanDirection, scanslot))
                                766                 :                :     {
                                767                 :                :         /*
                                768                 :                :          * Avoid expensive equality check if the index is primary key or
                                769                 :                :          * replica identity index, unless the index scan indicates that a
                                770                 :                :          * recheck is needed.
                                771                 :                :          */
   61 akapila@postgresql.o      772         [ -  + ]:CBC           2 :         if (!skipduplicates)
                                773                 :                :         {
  481 akapila@postgresql.o      774         [ #  # ]:UBC           0 :             if (eq == NULL)
  353 michael@paquier.xyz       775                 :              0 :                 eq = palloc0_array(TypeCacheEntry *, scanslot->tts_tupleDescriptor->natts);
                                776                 :                : 
  481 akapila@postgresql.o      777         [ #  # ]:              0 :             if (!tuples_equal(scanslot, searchslot, eq, NULL))
                                778                 :              0 :                 continue;
                                779                 :                :         }
   38 akapila@postgresql.o      780         [ +  + ]:CBC           2 :         else if (scan->xs_recheck &&
                                781         [ +  - ]:              1 :                  !repl_index_key_equal(idxrel, scanslot, searchslot, skey))
                                782                 :              1 :             continue;
                                783                 :                : 
  481                           784                 :              1 :         update_most_recent_deletion_info(scanslot, oldestxmin, delete_xid,
                                785                 :                :                                          delete_time, delete_origin);
                                786                 :                :     }
                                787                 :                : 
                                788                 :              2 :     index_endscan(scan);
                                789                 :                : 
                                790                 :              2 :     index_close(idxrel, NoLock);
                                791                 :                : 
                                792                 :              2 :     ExecDropSingleTupleTableSlot(scanslot);
                                793                 :                : 
                                794                 :              2 :     return *delete_time != 0;
                                795                 :                : }
                                796                 :                : 
                                797                 :                : /*
                                798                 :                :  * Find the tuple that violates the passed unique index (conflictindex).
                                799                 :                :  *
                                800                 :                :  * If the conflicting tuple is found return true, otherwise false.
                                801                 :                :  *
                                802                 :                :  * We lock the tuple to avoid getting it deleted before the caller can fetch
                                803                 :                :  * the required information. Note that if the tuple is deleted before a lock
                                804                 :                :  * is acquired, we will retry to find the conflicting tuple again.
                                805                 :                :  */
                                806                 :                : static bool
  830                           807                 :            119 : FindConflictTuple(ResultRelInfo *resultRelInfo, EState *estate,
                                808                 :                :                   Oid conflictindex, TupleTableSlot *slot,
                                809                 :                :                   TupleTableSlot **conflictslot)
                                810                 :                : {
                                811                 :            119 :     Relation    rel = resultRelInfo->ri_RelationDesc;
                                812                 :                :     ItemPointerData conflictTid;
                                813                 :                :     TM_FailureData tmfd;
                                814                 :                :     TM_Result   res;
                                815                 :                : 
                                816                 :            119 :     *conflictslot = NULL;
                                817                 :                : 
                                818                 :                :     /*
                                819                 :                :      * Build additional information required to check constraints violations.
                                820                 :                :      * See check_exclusion_or_unique_constraint().
                                821                 :                :      */
  599                           822                 :            119 :     BuildConflictIndexInfo(resultRelInfo, conflictindex);
                                823                 :                : 
  830                           824                 :            119 : retry:
                                825         [ +  + ]:            237 :     if (ExecCheckIndexConstraints(resultRelInfo, slot, estate,
                                826                 :            119 :                                   &conflictTid, &slot->tts_tid,
                                827                 :                :                                   list_make1_oid(conflictindex)))
                                828                 :                :     {
                                829         [ -  + ]:              2 :         if (*conflictslot)
  830 akapila@postgresql.o      830                 :UBC           0 :             ExecDropSingleTupleTableSlot(*conflictslot);
                                831                 :                : 
  830 akapila@postgresql.o      832                 :CBC           2 :         *conflictslot = NULL;
                                833                 :              2 :         return false;
                                834                 :                :     }
                                835                 :                : 
                                836                 :            116 :     *conflictslot = table_slot_create(rel, NULL);
                                837                 :                : 
                                838                 :            116 :     PushActiveSnapshot(GetLatestSnapshot());
                                839                 :                : 
  628 heikki.linnakangas@i      840                 :            116 :     res = table_tuple_lock(rel, &conflictTid, GetActiveSnapshot(),
                                841                 :                :                            *conflictslot,
                                842                 :                :                            GetCurrentCommandId(false),
                                843                 :                :                            LockTupleShare,
                                844                 :                :                            LockWaitBlock,
                                845                 :                :                            0 /* don't follow updates */ ,
                                846                 :                :                            &tmfd);
                                847                 :                : 
  830 akapila@postgresql.o      848                 :            116 :     PopActiveSnapshot();
                                849                 :                : 
                                850         [ -  + ]:            116 :     if (should_refetch_tuple(res, &tmfd))
  830 akapila@postgresql.o      851                 :UBC           0 :         goto retry;
                                852                 :                : 
  830 akapila@postgresql.o      853                 :CBC         116 :     return true;
                                854                 :                : }
                                855                 :                : 
                                856                 :                : /*
                                857                 :                :  * Check all the unique indexes in 'recheckIndexes' for conflict with the
                                858                 :                :  * tuple in 'remoteslot' and report if found.
                                859                 :                :  */
                                860                 :                : static void
                                861                 :             63 : CheckAndReportConflict(ResultRelInfo *resultRelInfo, EState *estate,
                                862                 :                :                        ConflictType type, List *recheckIndexes,
                                863                 :                :                        TupleTableSlot *searchslot, TupleTableSlot *remoteslot)
                                864                 :                : {
  614                           865                 :             63 :     List       *conflicttuples = NIL;
                                866                 :                :     TupleTableSlot *conflictslot;
                                867                 :                : 
                                868                 :                :     /* Check all the unique indexes for conflicts */
  830                           869   [ +  -  +  +  :            243 :     foreach_oid(uniqueidx, resultRelInfo->ri_onConflictArbiterIndexes)
                                              +  + ]
                                870                 :                :     {
                                871   [ +  -  +  + ]:            237 :         if (list_member_oid(recheckIndexes, uniqueidx) &&
                                872                 :            119 :             FindConflictTuple(resultRelInfo, estate, uniqueidx, remoteslot,
                                873                 :                :                               &conflictslot))
                                874                 :                :         {
  614                           875                 :            116 :             ConflictTupleInfo *conflicttuple = palloc0_object(ConflictTupleInfo);
                                876                 :                :             TransactionId xmin;
                                877                 :                : 
                                878                 :            116 :             conflicttuple->slot = conflictslot;
                                879                 :            116 :             conflicttuple->indexoid = uniqueidx;
                                880                 :                : 
    4 akapila@postgresql.o      881                 :GNC         116 :             GetTupleTransactionInfo(conflictslot, &xmin,
                                882                 :                :                                     &conflicttuple->origin, &conflicttuple->ts);
                                883                 :                : 
                                884                 :                :             /*
                                885                 :                :              * Convert xmin to a full transaction ID. This is safe because the
                                886                 :                :              * tuple's buffer is pinned, preventing VACUUM from freezing it.
                                887                 :                :              */
                                888                 :                :             conflicttuple->xmin =
                                889                 :            116 :                 FullTransactionIdFromAllowableAt(ReadNextFullTransactionId(),
                                890                 :                :                                                  xmin);
                                891                 :                : 
  614 akapila@postgresql.o      892                 :CBC         116 :             conflicttuples = lappend(conflicttuples, conflicttuple);
                                893                 :                :         }
                                894                 :                :     }
                                895                 :                : 
                                896                 :                :     /* Report the conflict, if found */
                                897         [ +  + ]:             62 :     if (conflicttuples)
                                898         [ +  + ]:             60 :         ReportApplyConflict(estate, resultRelInfo, ERROR,
                                899                 :             60 :                             list_length(conflicttuples) > 1 ? CT_MULTIPLE_UNIQUE_CONFLICTS : type,
                                900                 :                :                             NULL, searchslot, remoteslot, conflicttuples);
  830                           901                 :              2 : }
                                902                 :                : 
                                903                 :                : /*
                                904                 :                :  * Insert tuple represented in the slot to the relation, update the indexes,
                                905                 :                :  * and execute any constraints and per-row triggers.
                                906                 :                :  *
                                907                 :                :  * Caller is responsible for opening the indexes.
                                908                 :                :  */
                                909                 :                : void
 2236 heikki.linnakangas@i      910                 :          96172 : ExecSimpleRelationInsert(ResultRelInfo *resultRelInfo,
                                911                 :                :                          EState *estate, TupleTableSlot *slot)
                                912                 :                : {
 3482 bruce@momjian.us          913                 :          96172 :     bool        skip_tuple = false;
                                914                 :          96172 :     Relation    rel = resultRelInfo->ri_RelationDesc;
                                915                 :                : 
                                916                 :                :     /* For now we support only tables. */
 3600 peter_e@gmx.net           917         [ -  + ]:          96172 :     Assert(rel->rd_rel->relkind == RELKIND_RELATION);
                                918                 :                : 
                                919                 :          96172 :     CheckCmdReplicaIdentity(rel, CMD_INSERT);
                                920                 :                : 
                                921                 :                :     /* BEFORE ROW INSERT Triggers */
                                922         [ +  + ]:          96172 :     if (resultRelInfo->ri_TrigDesc &&
                                923         [ +  + ]:             20 :         resultRelInfo->ri_TrigDesc->trig_insert_before_row)
                                924                 :                :     {
 2832 andres@anarazel.de        925         [ +  + ]:              3 :         if (!ExecBRInsertTriggers(estate, resultRelInfo, slot))
 2747 tgl@sss.pgh.pa.us         926                 :              1 :             skip_tuple = true;  /* "do nothing" */
                                927                 :                :     }
                                928                 :                : 
 3600 peter_e@gmx.net           929         [ +  + ]:          96172 :     if (!skip_tuple)
                                930                 :                :     {
                                931                 :          96171 :         List       *recheckIndexes = NIL;
                                932                 :                :         List       *conflictindexes;
  830 akapila@postgresql.o      933                 :          96171 :         bool        conflict = false;
                                934                 :                : 
                                935                 :                :         /* Compute stored generated columns */
 2800 peter@eisentraut.org      936         [ +  + ]:          96171 :         if (rel->rd_att->constr &&
                                937         [ +  + ]:          65938 :             rel->rd_att->constr->has_generated_stored)
 2236 heikki.linnakangas@i      938                 :              4 :             ExecComputeStoredGenerated(resultRelInfo, estate, slot,
                                939                 :                :                                        CMD_INSERT);
                                940                 :                : 
                                941                 :                :         /* Check the constraints of the tuple */
 3600 peter_e@gmx.net           942         [ +  + ]:          96171 :         if (rel->rd_att->constr)
 3092 alvherre@alvh.no-ip.      943                 :          65938 :             ExecConstraints(resultRelInfo, slot, estate);
 2264 tgl@sss.pgh.pa.us         944         [ +  + ]:          96171 :         if (rel->rd_rel->relispartition)
 3092 alvherre@alvh.no-ip.      945                 :            110 :             ExecPartitionCheck(resultRelInfo, slot, estate, true);
                                946                 :                : 
                                947                 :                :         /* OK, store the tuple and create index entries for it */
  961 akorotkov@postgresql      948                 :          96171 :         simple_table_tuple_insert(resultRelInfo->ri_RelationDesc, slot);
                                949                 :                : 
  830 akapila@postgresql.o      950                 :          96171 :         conflictindexes = resultRelInfo->ri_onConflictArbiterIndexes;
                                951                 :                : 
  961 akorotkov@postgresql      952         [ +  + ]:          96171 :         if (resultRelInfo->ri_NumIndices > 0)
                                953                 :                :         {
                                954                 :                :             uint32      flags;
                                955                 :                : 
  284 alvherre@kurilemu.de      956         [ +  + ]:          75740 :             if (conflictindexes != NIL)
                                957                 :          75736 :                 flags = EIIT_NO_DUPE_ERROR;
                                958                 :                :             else
                                959                 :              4 :                 flags = 0;
 2236 heikki.linnakangas@i      960                 :          75740 :             recheckIndexes = ExecInsertIndexTuples(resultRelInfo,
                                961                 :                :                                                    estate, flags,
                                962                 :                :                                                    slot, conflictindexes,
                                963                 :                :                                                    &conflict);
                                964                 :                :         }
                                965                 :                : 
                                966                 :                :         /*
                                967                 :                :          * Checks the conflict indexes to fetch the conflicting local row and
                                968                 :                :          * reports the conflict. We perform this check here, instead of
                                969                 :                :          * performing an additional index scan before the actual insertion and
                                970                 :                :          * reporting the conflict if any conflicting rows are found. This is
                                971                 :                :          * to avoid the overhead of executing the extra scan for each INSERT
                                972                 :                :          * operation, even when no conflict arises, which could introduce
                                973                 :                :          * significant overhead to replication, particularly in cases where
                                974                 :                :          * conflicts are rare.
                                975                 :                :          *
                                976                 :                :          * XXX OTOH, this could lead to clean-up effort for dead tuples added
                                977                 :                :          * in heap and index in case of conflicts. But as conflicts shouldn't
                                978                 :                :          * be a frequent thing so we preferred to save the performance
                                979                 :                :          * overhead of extra scan before each insertion.
                                980                 :                :          */
  830 akapila@postgresql.o      981         [ +  + ]:          96171 :         if (conflict)
                                982                 :             61 :             CheckAndReportConflict(resultRelInfo, estate, CT_INSERT_EXISTS,
                                983                 :                :                                    recheckIndexes, NULL, slot);
                                984                 :                : 
                                985                 :                :         /* AFTER ROW INSERT Triggers */
   19 heikki.linnakangas@i      986                 :GNC       96112 :         ExecARInsertTriggers(estate, resultRelInfo, slot, NULL,
                                987                 :                :                              recheckIndexes, NULL);
                                988                 :                : 
                                989                 :                :         /*
                                990                 :                :          * XXX we should in theory pass a TransitionCaptureState object to the
                                991                 :                :          * above to capture transition tuples, but after statement triggers
                                992                 :                :          * don't actually get fired by replication yet anyway
                                993                 :                :          */
                                994                 :                : 
 3600 peter_e@gmx.net           995                 :CBC       96112 :         list_free(recheckIndexes);
                                996                 :                :     }
                                997                 :          96113 : }
                                998                 :                : 
                                999                 :                : /*
                               1000                 :                :  * Find the searchslot tuple and update it with data in the slot,
                               1001                 :                :  * update the indexes, and execute any constraints and per-row triggers.
                               1002                 :                :  *
                               1003                 :                :  * Caller is responsible for opening the indexes.
                               1004                 :                :  */
                               1005                 :                : void
 2236 heikki.linnakangas@i     1006                 :          31926 : ExecSimpleRelationUpdate(ResultRelInfo *resultRelInfo,
                               1007                 :                :                          EState *estate, EPQState *epqstate,
                               1008                 :                :                          TupleTableSlot *searchslot, TupleTableSlot *slot)
                               1009                 :                : {
 3482 bruce@momjian.us         1010                 :          31926 :     bool        skip_tuple = false;
                               1011                 :          31926 :     Relation    rel = resultRelInfo->ri_RelationDesc;
 2807 andres@anarazel.de       1012                 :          31926 :     ItemPointer tid = &(searchslot->tts_tid);
                               1013                 :                : 
                               1014                 :                :     /*
                               1015                 :                :      * Relations that must not be a logical replication target are rejected
                               1016                 :                :      * before we get here; see CheckSubscriptionTargetRel().
                               1017                 :                :      */
 3600 peter_e@gmx.net          1018         [ -  + ]:          31926 :     Assert(rel->rd_rel->relkind == RELKIND_RELATION);
  795 noah@leadboat.com        1019         [ -  + ]:          31926 :     Assert(!IsCatalogRelation(rel));
                               1020                 :                : 
 3600 peter_e@gmx.net          1021                 :          31926 :     CheckCmdReplicaIdentity(rel, CMD_UPDATE);
                               1022                 :                : 
                               1023                 :                :     /* BEFORE ROW UPDATE Triggers */
                               1024         [ +  + ]:          31926 :     if (resultRelInfo->ri_TrigDesc &&
                               1025         [ +  + ]:             10 :         resultRelInfo->ri_TrigDesc->trig_update_before_row)
                               1026                 :                :     {
 2832 andres@anarazel.de       1027         [ +  + ]:              3 :         if (!ExecBRUpdateTriggers(estate, epqstate, resultRelInfo,
                               1028                 :                :                                   tid, NULL, slot, NULL, NULL, false))
 2747 tgl@sss.pgh.pa.us        1029                 :              2 :             skip_tuple = true;  /* "do nothing" */
                               1030                 :                :     }
                               1031                 :                : 
 3600 peter_e@gmx.net          1032         [ +  + ]:          31926 :     if (!skip_tuple)
                               1033                 :                :     {
                               1034                 :          31924 :         List       *recheckIndexes = NIL;
                               1035                 :                :         TU_UpdateIndexes update_indexes;
                               1036                 :                :         List       *conflictindexes;
  830 akapila@postgresql.o     1037                 :          31924 :         bool        conflict = false;
                               1038                 :                : 
                               1039                 :                :         /* Compute stored generated columns */
 2800 peter@eisentraut.org     1040         [ +  + ]:          31924 :         if (rel->rd_att->constr &&
                               1041         [ +  + ]:          31879 :             rel->rd_att->constr->has_generated_stored)
 2236 heikki.linnakangas@i     1042                 :              2 :             ExecComputeStoredGenerated(resultRelInfo, estate, slot,
                               1043                 :                :                                        CMD_UPDATE);
                               1044                 :                : 
                               1045                 :                :         /* Check the constraints of the tuple */
 3600 peter_e@gmx.net          1046         [ +  + ]:          31924 :         if (rel->rd_att->constr)
 3092 alvherre@alvh.no-ip.     1047                 :          31879 :             ExecConstraints(resultRelInfo, slot, estate);
 2264 tgl@sss.pgh.pa.us        1048         [ +  + ]:          31924 :         if (rel->rd_rel->relispartition)
 3092 alvherre@alvh.no-ip.     1049                 :             12 :             ExecPartitionCheck(resultRelInfo, slot, estate, true);
                               1050                 :                : 
 2746 andres@anarazel.de       1051                 :          31924 :         simple_table_tuple_update(rel, tid, slot, estate->es_snapshot,
                               1052                 :                :                                   &update_indexes);
                               1053                 :                : 
  830 akapila@postgresql.o     1054                 :          31924 :         conflictindexes = resultRelInfo->ri_onConflictArbiterIndexes;
                               1055                 :                : 
 1349 tomas.vondra@postgre     1056   [ +  +  +  + ]:          31924 :         if (resultRelInfo->ri_NumIndices > 0 && (update_indexes != TU_None))
                               1057                 :                :         {
  243 nathan@postgresql.or     1058                 :          20203 :             uint32      flags = EIIT_IS_UPDATE;
                               1059                 :                : 
  284 alvherre@kurilemu.de     1060         [ +  + ]:          20203 :             if (conflictindexes != NIL)
                               1061                 :          20193 :                 flags |= EIIT_NO_DUPE_ERROR;
                               1062         [ -  + ]:          20203 :             if (update_indexes == TU_Summarizing)
  284 alvherre@kurilemu.de     1063                 :UBC           0 :                 flags |= EIIT_ONLY_SUMMARIZING;
 2236 heikki.linnakangas@i     1064                 :CBC       20203 :             recheckIndexes = ExecInsertIndexTuples(resultRelInfo,
                               1065                 :                :                                                    estate, flags,
                               1066                 :                :                                                    slot, conflictindexes,
                               1067                 :                :                                                    &conflict);
                               1068                 :                :         }
                               1069                 :                : 
                               1070                 :                :         /*
                               1071                 :                :          * Refer to the comments above the call to CheckAndReportConflict() in
                               1072                 :                :          * ExecSimpleRelationInsert to understand why this check is done at
                               1073                 :                :          * this point.
                               1074                 :                :          */
  830 akapila@postgresql.o     1075         [ +  + ]:          31924 :         if (conflict)
                               1076                 :              2 :             CheckAndReportConflict(resultRelInfo, estate, CT_UPDATE_EXISTS,
                               1077                 :                :                                    recheckIndexes, searchslot, slot);
                               1078                 :                : 
                               1079                 :                :         /* AFTER ROW UPDATE Triggers */
 3600 peter_e@gmx.net          1080                 :          31922 :         ExecARUpdateTriggers(estate, resultRelInfo,
                               1081                 :                :                              NULL, NULL,
                               1082                 :                :                              tid, NULL, slot, NULL,
                               1083                 :                :                              recheckIndexes, NULL, false);
                               1084                 :                : 
                               1085                 :          31922 :         list_free(recheckIndexes);
                               1086                 :                :     }
                               1087                 :          31924 : }
                               1088                 :                : 
                               1089                 :                : /*
                               1090                 :                :  * Find the searchslot tuple and delete it, and execute any constraints
                               1091                 :                :  * and per-row triggers.
                               1092                 :                :  *
                               1093                 :                :  * Caller is responsible for opening the indexes.
                               1094                 :                :  */
                               1095                 :                : void
 2236 heikki.linnakangas@i     1096                 :          40314 : ExecSimpleRelationDelete(ResultRelInfo *resultRelInfo,
                               1097                 :                :                          EState *estate, EPQState *epqstate,
                               1098                 :                :                          TupleTableSlot *searchslot)
                               1099                 :                : {
 3482 bruce@momjian.us         1100                 :          40314 :     bool        skip_tuple = false;
                               1101                 :          40314 :     Relation    rel = resultRelInfo->ri_RelationDesc;
 2807 andres@anarazel.de       1102                 :          40314 :     ItemPointer tid = &searchslot->tts_tid;
                               1103                 :                : 
 3600 peter_e@gmx.net          1104                 :          40314 :     CheckCmdReplicaIdentity(rel, CMD_DELETE);
                               1105                 :                : 
                               1106                 :                :     /* BEFORE ROW DELETE Triggers */
                               1107         [ +  + ]:          40314 :     if (resultRelInfo->ri_TrigDesc &&
 3334 rhaas@postgresql.org     1108         [ -  + ]:             10 :         resultRelInfo->ri_TrigDesc->trig_delete_before_row)
                               1109                 :                :     {
 3600 peter_e@gmx.net          1110                 :UBC           0 :         skip_tuple = !ExecBRDeleteTriggers(estate, epqstate, resultRelInfo,
  498 dean.a.rasheed@gmail     1111                 :              0 :                                            tid, NULL, NULL, NULL, NULL, false);
                               1112                 :                :     }
                               1113                 :                : 
 3600 peter_e@gmx.net          1114         [ +  - ]:CBC       40314 :     if (!skip_tuple)
                               1115                 :                :     {
                               1116                 :                :         /* OK, delete the tuple */
  961 akorotkov@postgresql     1117                 :          40314 :         simple_table_tuple_delete(rel, tid, estate->es_snapshot);
                               1118                 :                : 
                               1119                 :                :         /* AFTER ROW DELETE Triggers */
 3600 peter_e@gmx.net          1120                 :          40314 :         ExecARDeleteTriggers(estate, resultRelInfo,
                               1121                 :                :                              tid, NULL, NULL, false);
                               1122                 :                :     }
                               1123                 :          40314 : }
                               1124                 :                : 
                               1125                 :                : /*
                               1126                 :                :  * Check if command can be executed with current replica identity.
                               1127                 :                :  */
                               1128                 :                : void
                               1129                 :         264149 : CheckCmdReplicaIdentity(Relation rel, CmdType cmd)
                               1130                 :                : {
                               1131                 :                :     PublicationDesc pubdesc;
                               1132                 :                : 
                               1133                 :                :     /*
                               1134                 :                :      * Skip checking the replica identity for partitioned tables, because the
                               1135                 :                :      * operations are actually performed on the leaf partitions.
                               1136                 :                :      */
 1565 akapila@postgresql.o     1137         [ +  + ]:         264149 :     if (rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE)
                               1138                 :         248227 :         return;
                               1139                 :                : 
                               1140                 :                :     /* We only need to do checks for UPDATE and DELETE. */
 3600 peter_e@gmx.net          1141   [ +  +  +  + ]:         261158 :     if (cmd != CMD_UPDATE && cmd != CMD_DELETE)
                               1142                 :         167972 :         return;
                               1143                 :                : 
                               1144                 :                :     /*
                               1145                 :                :      * It is only safe to execute UPDATE/DELETE if the relation does not
                               1146                 :                :      * publish UPDATEs or DELETEs, or all the following conditions are
                               1147                 :                :      * satisfied:
                               1148                 :                :      *
                               1149                 :                :      * 1. All columns, referenced in the row filters from publications which
                               1150                 :                :      * the relation is in, are valid - i.e. when all referenced columns are
                               1151                 :                :      * part of REPLICA IDENTITY.
                               1152                 :                :      *
                               1153                 :                :      * 2. All columns, referenced in the column lists are valid - i.e. when
                               1154                 :                :      * all columns referenced in the REPLICA IDENTITY are covered by the
                               1155                 :                :      * column list.
                               1156                 :                :      *
                               1157                 :                :      * 3. All generated columns in REPLICA IDENTITY of the relation, are valid
                               1158                 :                :      * - i.e. when all these generated columns are published.
                               1159                 :                :      *
                               1160                 :                :      * XXX We could optimize it by first checking whether any of the
                               1161                 :                :      * publications have a row filter or column list for this relation, or if
                               1162                 :                :      * the relation contains a generated column. If none of these exist and
                               1163                 :                :      * the relation has replica identity then we can avoid building the
                               1164                 :                :      * descriptor but as this happens only one time it doesn't seem worth the
                               1165                 :                :      * additional complexity.
                               1166                 :                :      */
 1740 akapila@postgresql.o     1167                 :          93186 :     RelationBuildPublicationDesc(rel, &pubdesc);
                               1168   [ +  +  +  + ]:          93186 :     if (cmd == CMD_UPDATE && !pubdesc.rf_valid_for_update)
                               1169         [ +  - ]:             40 :         ereport(ERROR,
                               1170                 :                :                 (errcode(ERRCODE_INVALID_COLUMN_REFERENCE),
                               1171                 :                :                  errmsg("cannot update table \"%s\"",
                               1172                 :                :                         RelationGetRelationName(rel)),
                               1173                 :                :                  errdetail("Column used in the publication WHERE expression is not part of the replica identity.")));
 1708 tomas.vondra@postgre     1174   [ +  +  +  + ]:          93146 :     else if (cmd == CMD_UPDATE && !pubdesc.cols_valid_for_update)
                               1175         [ +  - ]:             72 :         ereport(ERROR,
                               1176                 :                :                 (errcode(ERRCODE_INVALID_COLUMN_REFERENCE),
                               1177                 :                :                  errmsg("cannot update table \"%s\"",
                               1178                 :                :                         RelationGetRelationName(rel)),
                               1179                 :                :                  errdetail("Column list used by the publication does not cover the replica identity.")));
  724 akapila@postgresql.o     1180   [ +  +  +  + ]:          93074 :     else if (cmd == CMD_UPDATE && !pubdesc.gencols_valid_for_update)
                               1181         [ +  - ]:             16 :         ereport(ERROR,
                               1182                 :                :                 (errcode(ERRCODE_INVALID_COLUMN_REFERENCE),
                               1183                 :                :                  errmsg("cannot update table \"%s\"",
                               1184                 :                :                         RelationGetRelationName(rel)),
                               1185                 :                :                  errdetail("Replica identity must not contain unpublished generated columns.")));
 1740                          1186   [ +  +  -  + ]:          93058 :     else if (cmd == CMD_DELETE && !pubdesc.rf_valid_for_delete)
 1740 akapila@postgresql.o     1187         [ #  # ]:UBC           0 :         ereport(ERROR,
                               1188                 :                :                 (errcode(ERRCODE_INVALID_COLUMN_REFERENCE),
                               1189                 :                :                  errmsg("cannot delete from table \"%s\"",
                               1190                 :                :                         RelationGetRelationName(rel)),
                               1191                 :                :                  errdetail("Column used in the publication WHERE expression is not part of the replica identity.")));
 1708 tomas.vondra@postgre     1192   [ +  +  -  + ]:CBC       93058 :     else if (cmd == CMD_DELETE && !pubdesc.cols_valid_for_delete)
 1708 tomas.vondra@postgre     1193         [ #  # ]:UBC           0 :         ereport(ERROR,
                               1194                 :                :                 (errcode(ERRCODE_INVALID_COLUMN_REFERENCE),
                               1195                 :                :                  errmsg("cannot delete from table \"%s\"",
                               1196                 :                :                         RelationGetRelationName(rel)),
                               1197                 :                :                  errdetail("Column list used by the publication does not cover the replica identity.")));
  724 akapila@postgresql.o     1198   [ +  +  -  + ]:CBC       93058 :     else if (cmd == CMD_DELETE && !pubdesc.gencols_valid_for_delete)
  724 akapila@postgresql.o     1199         [ #  # ]:UBC           0 :         ereport(ERROR,
                               1200                 :                :                 (errcode(ERRCODE_INVALID_COLUMN_REFERENCE),
                               1201                 :                :                  errmsg("cannot delete from table \"%s\"",
                               1202                 :                :                         RelationGetRelationName(rel)),
                               1203                 :                :                  errdetail("Replica identity must not contain unpublished generated columns.")));
                               1204                 :                : 
                               1205                 :                :     /* If relation has replica identity we are always good. */
 1740 akapila@postgresql.o     1206         [ +  + ]:CBC       93058 :     if (OidIsValid(RelationGetReplicaIndex(rel)))
 3600 peter_e@gmx.net          1207                 :          77026 :         return;
                               1208                 :                : 
                               1209                 :                :     /* REPLICA IDENTITY FULL is also good for UPDATE/DELETE. */
 1708 tomas.vondra@postgre     1210         [ +  + ]:          16032 :     if (rel->rd_rel->relreplident == REPLICA_IDENTITY_FULL)
                               1211                 :            238 :         return;
                               1212                 :                : 
                               1213                 :                :     /*
                               1214                 :                :      * This is UPDATE/DELETE and there is no replica identity.
                               1215                 :                :      *
                               1216                 :                :      * Check if the table publishes UPDATES or DELETES.
                               1217                 :                :      */
 1740 akapila@postgresql.o     1218   [ +  +  +  + ]:          15794 :     if (cmd == CMD_UPDATE && pubdesc.pubactions.pubupdate)
 3600 peter_e@gmx.net          1219         [ +  - ]:             81 :         ereport(ERROR,
                               1220                 :                :                 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
                               1221                 :                :                  errmsg("cannot update table \"%s\" because it does not have a replica identity and publishes updates",
                               1222                 :                :                         RelationGetRelationName(rel)),
                               1223                 :                :                  errhint("To enable updating the table, set REPLICA IDENTITY using ALTER TABLE.")));
 1740 akapila@postgresql.o     1224   [ +  +  +  + ]:          15713 :     else if (cmd == CMD_DELETE && pubdesc.pubactions.pubdelete)
 3600 peter_e@gmx.net          1225         [ +  - ]:              9 :         ereport(ERROR,
                               1226                 :                :                 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
                               1227                 :                :                  errmsg("cannot delete from table \"%s\" because it does not have a replica identity and publishes deletes",
                               1228                 :                :                         RelationGetRelationName(rel)),
                               1229                 :                :                  errhint("To enable deleting from the table, set REPLICA IDENTITY using ALTER TABLE.")));
                               1230                 :                : }
                               1231                 :                : 
                               1232                 :                : 
                               1233                 :                : /*
                               1234                 :                :  * Check that the local relation can be used as a logical replication target,
                               1235                 :                :  * and that its relkind aligns with the relkind of the relation on the
                               1236                 :                :  * publisher.
                               1237                 :                :  *
                               1238                 :                :  * The nspname and relname are only needed for error reporting.
                               1239                 :                :  */
                               1240                 :                : void
   19 msawada@postgresql.o     1241                 :           1110 : CheckSubscriptionTargetRel(Oid relid, char remoterelkind,
                               1242                 :                :                            const char *nspname, const char *relname)
                               1243                 :                : {
                               1244                 :           1110 :     char        localrelkind = get_rel_relkind(relid);
                               1245                 :                : 
  401 akapila@postgresql.o     1246   [ +  +  +  + ]:           1110 :     if (localrelkind != RELKIND_RELATION &&
                               1247         [ +  + ]:             24 :         localrelkind != RELKIND_PARTITIONED_TABLE &&
                               1248                 :                :         localrelkind != RELKIND_SEQUENCE)
 3483 peter_e@gmx.net          1249         [ +  - ]:              2 :         ereport(ERROR,
                               1250                 :                :                 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
                               1251                 :                :                  errmsg("cannot use relation \"%s.%s\" as logical replication target",
                               1252                 :                :                         nspname, relname),
                               1253                 :                :                  errdetail_relkind_not_supported(localrelkind)));
                               1254                 :                : 
                               1255                 :                :     /*
                               1256                 :                :      * Some relations must never be written by an apply worker.  System
                               1257                 :                :      * catalogs and conflict log tables hold data that the server maintains
                               1258                 :                :      * for itself, and a temporary relation belongs to the session that
                               1259                 :                :      * created it.  A PostgreSQL publisher refuses to publish any of them, but
                               1260                 :                :      * the target relation is named by the publisher, which doesn't have to be
                               1261                 :                :      * a PostgreSQL server, so we can't rely on that.
                               1262                 :                :      */
   19 msawada@postgresql.o     1263         [ +  + ]:           1108 :     if (IsCatalogRelationOid(relid))
                               1264         [ +  - ]:              1 :         ereport(ERROR,
                               1265                 :                :                 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
                               1266                 :                :                  errmsg("cannot use relation \"%s.%s\" as logical replication target",
                               1267                 :                :                         nspname, relname),
                               1268                 :                :                  errdetail("This operation is not supported for system tables.")));
                               1269                 :                : 
   19 msawada@postgresql.o     1270         [ +  + ]:GNC        1107 :     if (IsConflictLogTableNamespace(get_rel_namespace(relid)))
                               1271         [ +  - ]:              1 :         ereport(ERROR,
                               1272                 :                :                 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
                               1273                 :                :                  errmsg("cannot use relation \"%s.%s\" as logical replication target",
                               1274                 :                :                         nspname, relname),
                               1275                 :                :                  errdetail("This operation is not supported for conflict log tables.")));
                               1276                 :                : 
                               1277                 :                :     /*
                               1278                 :                :      * Reject temporary relations.  Accessing a temporary relation of another
                               1279                 :                :      * session is rejected when its buffers are read, but that is much later
                               1280                 :                :      * than here, after we have already looked at its metadata.
                               1281                 :                :      */
   19 msawada@postgresql.o     1282         [ -  + ]:CBC        1106 :     if (get_rel_persistence(relid) == RELPERSISTENCE_TEMP)
   19 msawada@postgresql.o     1283         [ #  # ]:UBC           0 :         ereport(ERROR,
                               1284                 :                :                 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
                               1285                 :                :                  errmsg("cannot use relation \"%s.%s\" as logical replication target",
                               1286                 :                :                         nspname, relname),
                               1287                 :                :                  errdetail("This operation is not supported for temporary tables.")));
                               1288                 :                : 
                               1289                 :                :     /*
                               1290                 :                :      * Allow RELKIND_RELATION and RELKIND_PARTITIONED_TABLE to be treated
                               1291                 :                :      * interchangeably, but ensure that sequences (RELKIND_SEQUENCE) match
                               1292                 :                :      * exactly on both publisher and subscriber.
                               1293                 :                :      */
  401 akapila@postgresql.o     1294   [ +  +  +  -  :CBC        1106 :     if ((localrelkind == RELKIND_SEQUENCE && remoterelkind != RELKIND_SEQUENCE) ||
                                              +  + ]
                               1295         [ -  + ]:           1084 :         (localrelkind != RELKIND_SEQUENCE && remoterelkind == RELKIND_SEQUENCE))
  401 akapila@postgresql.o     1296   [ #  #  #  #  :UBC           0 :         ereport(ERROR,
                                              #  # ]
                               1297                 :                :                 errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
                               1298                 :                :         /* translator: 3rd and 4th %s are "sequence" or "table" */
                               1299                 :                :                 errmsg("relation \"%s.%s\" type mismatch: source \"%s\", target \"%s\"",
                               1300                 :                :                        nspname, relname,
                               1301                 :                :                        remoterelkind == RELKIND_SEQUENCE ? "sequence" : "table",
                               1302                 :                :                        localrelkind == RELKIND_SEQUENCE ? "sequence" : "table"));
 3483 peter_e@gmx.net          1303                 :CBC        1106 : }
        

Generated by: LCOV version 2.0-1