LCOV - differential code coverage report
Current view: top level - src/backend/replication/logical - relation.c (source / functions) Coverage Total Hit UBC GNC CBC DCB
Current: 0e5ff9b9b45a657aea12440478dc002e9b01f138 vs 0123ce131fca454009439dfa3b2266d1d40737d7 Lines: 93.3 % 285 266 19 7 259 4
Current Date: 2026-03-14 14:10:32 -0400 Functions: 100.0 % 18 18 4 14
Baseline: lcov-20260315-024220-baseline Branches: 79.3 % 174 138 36 2 136
Baseline Date: 2026-03-14 15:27:56 +0100 Line coverage date bins:
Legend: Lines:     hit not hit
Branches: + taken - not taken # not executed
(30,360] days: 100.0 % 8 8 7 1
(360..) days: 93.1 % 277 258 19 258
Function coverage date bins:
(360..) days: 100.0 % 18 18 4 14
Branch coverage date bins:
(30,360] days: 100.0 % 2 2 2
(360..) days: 79.1 % 172 136 36 136

 Age         Owner                    Branch data    TLA  Line data    Source code
                                  1                 :                : /*-------------------------------------------------------------------------
                                  2                 :                :  * relation.c
                                  3                 :                :  *     PostgreSQL logical replication relation mapping cache
                                  4                 :                :  *
                                  5                 :                :  * Copyright (c) 2016-2026, PostgreSQL Global Development Group
                                  6                 :                :  *
                                  7                 :                :  * IDENTIFICATION
                                  8                 :                :  *    src/backend/replication/logical/relation.c
                                  9                 :                :  *
                                 10                 :                :  * NOTES
                                 11                 :                :  *    Routines in this file mainly have to do with mapping the properties
                                 12                 :                :  *    of local replication target relations to the properties of their
                                 13                 :                :  *    remote counterpart.
                                 14                 :                :  *
                                 15                 :                :  *-------------------------------------------------------------------------
                                 16                 :                :  */
                                 17                 :                : 
                                 18                 :                : #include "postgres.h"
                                 19                 :                : 
                                 20                 :                : #include "access/amapi.h"
                                 21                 :                : #include "access/genam.h"
                                 22                 :                : #include "access/table.h"
                                 23                 :                : #include "catalog/namespace.h"
                                 24                 :                : #include "catalog/pg_subscription_rel.h"
                                 25                 :                : #include "executor/executor.h"
                                 26                 :                : #include "nodes/makefuncs.h"
                                 27                 :                : #include "replication/logicalrelation.h"
                                 28                 :                : #include "replication/worker_internal.h"
                                 29                 :                : #include "utils/inval.h"
                                 30                 :                : #include "utils/lsyscache.h"
                                 31                 :                : #include "utils/syscache.h"
                                 32                 :                : #include "utils/typcache.h"
                                 33                 :                : 
                                 34                 :                : 
                                 35                 :                : static MemoryContext LogicalRepRelMapContext = NULL;
                                 36                 :                : 
                                 37                 :                : static HTAB *LogicalRepRelMap = NULL;
                                 38                 :                : 
                                 39                 :                : /*
                                 40                 :                :  * Partition map (LogicalRepPartMap)
                                 41                 :                :  *
                                 42                 :                :  * When a partitioned table is used as replication target, replicated
                                 43                 :                :  * operations are actually performed on its leaf partitions, which requires
                                 44                 :                :  * the partitions to also be mapped to the remote relation.  Parent's entry
                                 45                 :                :  * (LogicalRepRelMapEntry) cannot be used as-is for all partitions, because
                                 46                 :                :  * individual partitions may have different attribute numbers, which means
                                 47                 :                :  * attribute mappings to remote relation's attributes must be maintained
                                 48                 :                :  * separately for each partition.
                                 49                 :                :  */
                                 50                 :                : static MemoryContext LogicalRepPartMapContext = NULL;
                                 51                 :                : static HTAB *LogicalRepPartMap = NULL;
                                 52                 :                : typedef struct LogicalRepPartMapEntry
                                 53                 :                : {
                                 54                 :                :     Oid         partoid;        /* LogicalRepPartMap's key */
                                 55                 :                :     LogicalRepRelMapEntry relmapentry;
                                 56                 :                : } LogicalRepPartMapEntry;
                                 57                 :                : 
                                 58                 :                : static Oid  FindLogicalRepLocalIndex(Relation localrel, LogicalRepRelation *remoterel,
                                 59                 :                :                                      AttrMap *attrMap);
                                 60                 :                : 
                                 61                 :                : /*
                                 62                 :                :  * Relcache invalidation callback for our relation map cache.
                                 63                 :                :  */
                                 64                 :                : static void
 3342 peter_e@gmx.net            65                 :CBC         726 : logicalrep_relmap_invalidate_cb(Datum arg, Oid reloid)
                                 66                 :                : {
                                 67                 :                :     LogicalRepRelMapEntry *entry;
                                 68                 :                : 
                                 69                 :                :     /* Just to be sure. */
                                 70         [ -  + ]:            726 :     if (LogicalRepRelMap == NULL)
 3342 peter_e@gmx.net            71                 :UBC           0 :         return;
                                 72                 :                : 
 3342 peter_e@gmx.net            73         [ +  - ]:CBC         726 :     if (reloid != InvalidOid)
                                 74                 :                :     {
                                 75                 :                :         HASH_SEQ_STATUS status;
                                 76                 :                : 
                                 77                 :            726 :         hash_seq_init(&status, LogicalRepRelMap);
                                 78                 :                : 
                                 79                 :                :         /* TODO, use inverse lookup hashtable? */
                                 80         [ +  + ]:           3132 :         while ((entry = (LogicalRepRelMapEntry *) hash_seq_search(&status)) != NULL)
                                 81                 :                :         {
                                 82         [ +  + ]:           2537 :             if (entry->localreloid == reloid)
                                 83                 :                :             {
 2006 tgl@sss.pgh.pa.us          84                 :            131 :                 entry->localrelvalid = false;
 3342 peter_e@gmx.net            85                 :            131 :                 hash_seq_term(&status);
                                 86                 :            131 :                 break;
                                 87                 :                :             }
                                 88                 :                :         }
                                 89                 :                :     }
                                 90                 :                :     else
                                 91                 :                :     {
                                 92                 :                :         /* invalidate all cache entries */
                                 93                 :                :         HASH_SEQ_STATUS status;
                                 94                 :                : 
 3342 peter_e@gmx.net            95                 :UBC           0 :         hash_seq_init(&status, LogicalRepRelMap);
                                 96                 :                : 
                                 97         [ #  # ]:              0 :         while ((entry = (LogicalRepRelMapEntry *) hash_seq_search(&status)) != NULL)
 2006 tgl@sss.pgh.pa.us          98                 :              0 :             entry->localrelvalid = false;
                                 99                 :                :     }
                                100                 :                : }
                                101                 :                : 
                                102                 :                : /*
                                103                 :                :  * Initialize the relation map cache.
                                104                 :                :  */
                                105                 :                : static void
 3248 andres@anarazel.de        106                 :CBC         402 : logicalrep_relmap_init(void)
                                107                 :                : {
                                108                 :                :     HASHCTL     ctl;
                                109                 :                : 
 3342 peter_e@gmx.net           110         [ +  - ]:            402 :     if (!LogicalRepRelMapContext)
                                111                 :            402 :         LogicalRepRelMapContext =
                                112                 :            402 :             AllocSetContextCreate(CacheMemoryContext,
                                113                 :                :                                   "LogicalRepRelMapContext",
                                114                 :                :                                   ALLOCSET_DEFAULT_SIZES);
                                115                 :                : 
                                116                 :                :     /* Initialize the relation hash table. */
                                117                 :            402 :     ctl.keysize = sizeof(LogicalRepRelId);
                                118                 :            402 :     ctl.entrysize = sizeof(LogicalRepRelMapEntry);
                                119                 :            402 :     ctl.hcxt = LogicalRepRelMapContext;
                                120                 :                : 
                                121                 :            402 :     LogicalRepRelMap = hash_create("logicalrep relation map cache", 128, &ctl,
                                122                 :                :                                    HASH_ELEM | HASH_BLOBS | HASH_CONTEXT);
                                123                 :                : 
                                124                 :                :     /* Watch for invalidation events. */
                                125                 :            402 :     CacheRegisterRelcacheCallback(logicalrep_relmap_invalidate_cb,
                                126                 :                :                                   (Datum) 0);
                                127                 :            402 : }
                                128                 :                : 
                                129                 :                : /*
                                130                 :                :  * Free the entry of a relation map cache.
                                131                 :                :  */
                                132                 :                : static void
                                133                 :            142 : logicalrep_relmap_free_entry(LogicalRepRelMapEntry *entry)
                                134                 :                : {
                                135                 :                :     LogicalRepRelation *remoterel;
                                136                 :                : 
                                137                 :            142 :     remoterel = &entry->remoterel;
                                138                 :                : 
                                139                 :            142 :     pfree(remoterel->nspname);
                                140                 :            142 :     pfree(remoterel->relname);
                                141                 :                : 
                                142         [ +  - ]:            142 :     if (remoterel->natts > 0)
                                143                 :                :     {
                                144                 :                :         int         i;
                                145                 :                : 
                                146         [ +  + ]:            426 :         for (i = 0; i < remoterel->natts; i++)
                                147                 :            284 :             pfree(remoterel->attnames[i]);
                                148                 :                : 
                                149                 :            142 :         pfree(remoterel->attnames);
                                150                 :            142 :         pfree(remoterel->atttyps);
                                151                 :                :     }
                                152                 :            142 :     bms_free(remoterel->attkeys);
                                153                 :                : 
                                154         [ +  + ]:            142 :     if (entry->attrmap)
 1361 akapila@postgresql.o      155                 :            120 :         free_attrmap(entry->attrmap);
 3342 peter_e@gmx.net           156                 :            142 : }
                                157                 :                : 
                                158                 :                : /*
                                159                 :                :  * Add new entry or update existing entry in the relation map cache.
                                160                 :                :  *
                                161                 :                :  * Called when new relation mapping is sent by the publisher to update
                                162                 :                :  * our expected view of incoming data from said publisher.
                                163                 :                :  */
                                164                 :                : void
                                165                 :            655 : logicalrep_relmap_update(LogicalRepRelation *remoterel)
                                166                 :                : {
                                167                 :                :     MemoryContext oldctx;
                                168                 :                :     LogicalRepRelMapEntry *entry;
                                169                 :                :     bool        found;
                                170                 :                :     int         i;
                                171                 :                : 
                                172         [ +  + ]:            655 :     if (LogicalRepRelMap == NULL)
                                173                 :            402 :         logicalrep_relmap_init();
                                174                 :                : 
                                175                 :                :     /*
                                176                 :                :      * HASH_ENTER returns the existing entry if present or creates a new one.
                                177                 :                :      */
 1133 peter@eisentraut.org      178                 :            655 :     entry = hash_search(LogicalRepRelMap, &remoterel->remoteid,
                                179                 :                :                         HASH_ENTER, &found);
                                180                 :                : 
 3342 peter_e@gmx.net           181         [ +  + ]:            655 :     if (found)
                                182                 :            134 :         logicalrep_relmap_free_entry(entry);
                                183                 :                : 
 3248 andres@anarazel.de        184                 :            655 :     memset(entry, 0, sizeof(LogicalRepRelMapEntry));
                                185                 :                : 
                                186                 :                :     /* Make cached copy of the data */
 3342 peter_e@gmx.net           187                 :            655 :     oldctx = MemoryContextSwitchTo(LogicalRepRelMapContext);
                                188                 :            655 :     entry->remoterel.remoteid = remoterel->remoteid;
                                189                 :            655 :     entry->remoterel.nspname = pstrdup(remoterel->nspname);
                                190                 :            655 :     entry->remoterel.relname = pstrdup(remoterel->relname);
                                191                 :            655 :     entry->remoterel.natts = remoterel->natts;
   95 michael@paquier.xyz       192                 :GNC         655 :     entry->remoterel.attnames = palloc_array(char *, remoterel->natts);
                                193                 :            655 :     entry->remoterel.atttyps = palloc_array(Oid, remoterel->natts);
 3342 peter_e@gmx.net           194         [ +  + ]:CBC        1842 :     for (i = 0; i < remoterel->natts; i++)
                                195                 :                :     {
                                196                 :           1187 :         entry->remoterel.attnames[i] = pstrdup(remoterel->attnames[i]);
                                197                 :           1187 :         entry->remoterel.atttyps[i] = remoterel->atttyps[i];
                                198                 :                :     }
                                199                 :            655 :     entry->remoterel.replident = remoterel->replident;
                                200                 :                : 
                                201                 :                :     /*
                                202                 :                :      * XXX The walsender currently does not transmit the relkind of the remote
                                203                 :                :      * relation when replicating changes. Since we support replicating only
                                204                 :                :      * table changes at present, we default to initializing relkind as
                                205                 :                :      * RELKIND_RELATION. This is needed in CheckSubscriptionRelkind() to check
                                206                 :                :      * if the publisher and subscriber relation kinds are compatible.
                                207                 :                :      */
  143 akapila@postgresql.o      208                 :GNC         655 :     entry->remoterel.relkind =
                                209         [ +  + ]:            655 :         (remoterel->relkind == 0) ? RELKIND_RELATION : remoterel->relkind;
                                210                 :                : 
 3342 peter_e@gmx.net           211                 :CBC         655 :     entry->remoterel.attkeys = bms_copy(remoterel->attkeys);
                                212                 :            655 :     MemoryContextSwitchTo(oldctx);
                                213                 :            655 : }
                                214                 :                : 
                                215                 :                : /*
                                216                 :                :  * Find attribute index in TupleDesc struct by attribute name.
                                217                 :                :  *
                                218                 :                :  * Returns -1 if not found.
                                219                 :                :  */
                                220                 :                : static int
                                221                 :           1348 : logicalrep_rel_att_by_name(LogicalRepRelation *remoterel, const char *attname)
                                222                 :                : {
                                223                 :                :     int         i;
                                224                 :                : 
                                225         [ +  + ]:           2540 :     for (i = 0; i < remoterel->natts; i++)
                                226                 :                :     {
                                227         [ +  + ]:           2260 :         if (strcmp(remoterel->attnames[i], attname) == 0)
                                228                 :           1068 :             return i;
                                229                 :                :     }
                                230                 :                : 
                                231                 :            280 :     return -1;
                                232                 :                : }
                                233                 :                : 
                                234                 :                : /*
                                235                 :                :  * Returns a comma-separated string of attribute names based on the provided
                                236                 :                :  * relation and bitmap indicating which attributes to include.
                                237                 :                :  */
                                238                 :                : static char *
  473 akapila@postgresql.o      239                 :              2 : logicalrep_get_attrs_str(LogicalRepRelation *remoterel, Bitmapset *atts)
                                240                 :                : {
                                241                 :                :     StringInfoData attsbuf;
                                242                 :              2 :     int         attcnt = 0;
                                243                 :              2 :     int         i = -1;
                                244                 :                : 
                                245         [ -  + ]:              2 :     Assert(!bms_is_empty(atts));
                                246                 :                : 
                                247                 :              2 :     initStringInfo(&attsbuf);
                                248                 :                : 
                                249         [ +  + ]:              6 :     while ((i = bms_next_member(atts, i)) >= 0)
                                250                 :                :     {
                                251                 :              4 :         attcnt++;
                                252         [ +  + ]:              4 :         if (attcnt > 1)
                                253                 :                :             /* translator: This is a separator in a list of entity names. */
  338 drowley@postgresql.o      254                 :              2 :             appendStringInfoString(&attsbuf, _(", "));
                                255                 :                : 
  473 akapila@postgresql.o      256                 :              4 :         appendStringInfo(&attsbuf, _("\"%s\""), remoterel->attnames[i]);
                                257                 :                :     }
                                258                 :                : 
                                259                 :              2 :     return attsbuf.data;
                                260                 :                : }
                                261                 :                : 
                                262                 :                : /*
                                263                 :                :  * If attempting to replicate missing or generated columns, report an error.
                                264                 :                :  * Prioritize 'missing' errors if both occur though the prioritization is
                                265                 :                :  * arbitrary.
                                266                 :                :  */
                                267                 :                : static void
                                268                 :            590 : logicalrep_report_missing_or_gen_attrs(LogicalRepRelation *remoterel,
                                269                 :                :                                        Bitmapset *missingatts,
                                270                 :                :                                        Bitmapset *generatedatts)
                                271                 :                : {
                                272         [ +  + ]:            590 :     if (!bms_is_empty(missingatts))
 1985                           273         [ +  - ]:              1 :         ereport(ERROR,
                                274                 :                :                 errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
                                275                 :                :                 errmsg_plural("logical replication target relation \"%s.%s\" is missing replicated column: %s",
                                276                 :                :                               "logical replication target relation \"%s.%s\" is missing replicated columns: %s",
                                277                 :                :                               bms_num_members(missingatts),
                                278                 :                :                               remoterel->nspname,
                                279                 :                :                               remoterel->relname,
                                280                 :                :                               logicalrep_get_attrs_str(remoterel,
                                281                 :                :                                                        missingatts)));
                                282                 :                : 
  473                           283         [ +  + ]:            589 :     if (!bms_is_empty(generatedatts))
                                284         [ +  - ]:              1 :         ereport(ERROR,
                                285                 :                :                 errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
                                286                 :                :                 errmsg_plural("logical replication target relation \"%s.%s\" has incompatible generated column: %s",
                                287                 :                :                               "logical replication target relation \"%s.%s\" has incompatible generated columns: %s",
                                288                 :                :                               bms_num_members(generatedatts),
                                289                 :                :                               remoterel->nspname,
                                290                 :                :                               remoterel->relname,
                                291                 :                :                               logicalrep_get_attrs_str(remoterel,
                                292                 :                :                                                        generatedatts)));
 1985                           293                 :            588 : }
                                294                 :                : 
                                295                 :                : /*
                                296                 :                :  * Check if replica identity matches and mark the updatable flag.
                                297                 :                :  *
                                298                 :                :  * We allow for stricter replica identity (fewer columns) on subscriber as
                                299                 :                :  * that will not stop us from finding unique tuple. IE, if publisher has
                                300                 :                :  * identity (id,timestamp) and subscriber just (id) this will not be a
                                301                 :                :  * problem, but in the opposite scenario it will.
                                302                 :                :  *
                                303                 :                :  * We just mark the relation entry as not updatable here if the local
                                304                 :                :  * replica identity is found to be insufficient for applying
                                305                 :                :  * updates/deletes (inserts don't care!) and leave it to
                                306                 :                :  * check_relation_updatable() to throw the actual error if needed.
                                307                 :                :  */
                                308                 :                : static void
 1363                           309                 :            603 : logicalrep_rel_mark_updatable(LogicalRepRelMapEntry *entry)
                                310                 :                : {
                                311                 :                :     Bitmapset  *idkey;
                                312                 :            603 :     LogicalRepRelation *remoterel = &entry->remoterel;
                                313                 :                :     int         i;
                                314                 :                : 
                                315                 :            603 :     entry->updatable = true;
                                316                 :                : 
                                317                 :            603 :     idkey = RelationGetIndexAttrBitmap(entry->localrel,
                                318                 :                :                                        INDEX_ATTR_BITMAP_IDENTITY_KEY);
                                319                 :                :     /* fallback to PK if no replica identity */
                                320         [ +  + ]:            603 :     if (idkey == NULL)
                                321                 :                :     {
                                322                 :            222 :         idkey = RelationGetIndexAttrBitmap(entry->localrel,
                                323                 :                :                                            INDEX_ATTR_BITMAP_PRIMARY_KEY);
                                324                 :                : 
                                325                 :                :         /*
                                326                 :                :          * If no replica identity index and no PK, the published table must
                                327                 :                :          * have replica identity FULL.
                                328                 :                :          */
                                329   [ +  +  +  + ]:            222 :         if (idkey == NULL && remoterel->replident != REPLICA_IDENTITY_FULL)
                                330                 :            143 :             entry->updatable = false;
                                331                 :                :     }
                                332                 :                : 
                                333                 :            603 :     i = -1;
                                334         [ +  + ]:            985 :     while ((i = bms_next_member(idkey, i)) >= 0)
                                335                 :                :     {
                                336                 :            398 :         int         attnum = i + FirstLowInvalidHeapAttributeNumber;
                                337                 :                : 
                                338         [ -  + ]:            398 :         if (!AttrNumberIsForUserDefinedAttr(attnum))
 1363 akapila@postgresql.o      339         [ #  # ]:UBC           0 :             ereport(ERROR,
                                340                 :                :                     (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
                                341                 :                :                      errmsg("logical replication target relation \"%s.%s\" uses "
                                342                 :                :                             "system columns in REPLICA IDENTITY index",
                                343                 :                :                             remoterel->nspname, remoterel->relname)));
                                344                 :                : 
 1363 akapila@postgresql.o      345         [ -  + ]:CBC         398 :         attnum = AttrNumberGetAttrOffset(attnum);
                                346                 :                : 
                                347         [ +  + ]:            398 :         if (entry->attrmap->attnums[attnum] < 0 ||
                                348         [ +  + ]:            397 :             !bms_is_member(entry->attrmap->attnums[attnum], remoterel->attkeys))
                                349                 :                :         {
                                350                 :             16 :             entry->updatable = false;
                                351                 :             16 :             break;
                                352                 :                :         }
                                353                 :                :     }
                                354                 :            603 : }
                                355                 :                : 
                                356                 :                : /*
                                357                 :                :  * Open the local relation associated with the remote one.
                                358                 :                :  *
                                359                 :                :  * Rebuilds the Relcache mapping if it was invalidated by local DDL.
                                360                 :                :  */
                                361                 :                : LogicalRepRelMapEntry *
 3342 peter_e@gmx.net           362                 :         148577 : logicalrep_rel_open(LogicalRepRelId remoteid, LOCKMODE lockmode)
                                363                 :                : {
                                364                 :                :     LogicalRepRelMapEntry *entry;
                                365                 :                :     bool        found;
                                366                 :                :     LogicalRepRelation *remoterel;
                                367                 :                : 
                                368         [ -  + ]:         148577 :     if (LogicalRepRelMap == NULL)
 3342 peter_e@gmx.net           369                 :UBC           0 :         logicalrep_relmap_init();
                                370                 :                : 
                                371                 :                :     /* Search for existing entry. */
 1133 peter@eisentraut.org      372                 :CBC      148577 :     entry = hash_search(LogicalRepRelMap, &remoteid,
                                373                 :                :                         HASH_FIND, &found);
                                374                 :                : 
 3342 peter_e@gmx.net           375         [ -  + ]:         148577 :     if (!found)
 3342 peter_e@gmx.net           376         [ #  # ]:UBC           0 :         elog(ERROR, "no relation map entry for remote relation ID %u",
                                377                 :                :              remoteid);
                                378                 :                : 
 2281 akapila@postgresql.o      379                 :CBC      148577 :     remoterel = &entry->remoterel;
                                380                 :                : 
                                381                 :                :     /* Ensure we don't leak a relcache refcount. */
 2006 tgl@sss.pgh.pa.us         382         [ -  + ]:         148577 :     if (entry->localrel)
 2006 tgl@sss.pgh.pa.us         383         [ #  # ]:UBC           0 :         elog(ERROR, "remote relation ID %u is already open", remoteid);
                                384                 :                : 
                                385                 :                :     /*
                                386                 :                :      * When opening and locking a relation, pending invalidation messages are
                                387                 :                :      * processed which can invalidate the relation.  Hence, if the entry is
                                388                 :                :      * currently considered valid, try to open the local relation by OID and
                                389                 :                :      * see if invalidation ensues.
                                390                 :                :      */
 2006 tgl@sss.pgh.pa.us         391         [ +  + ]:CBC      148577 :     if (entry->localrelvalid)
                                392                 :                :     {
                                393                 :         147980 :         entry->localrel = try_table_open(entry->localreloid, lockmode);
                                394         [ -  + ]:         147980 :         if (!entry->localrel)
                                395                 :                :         {
                                396                 :                :             /* Table was renamed or dropped. */
 2006 tgl@sss.pgh.pa.us         397                 :UBC           0 :             entry->localrelvalid = false;
                                398                 :                :         }
 2006 tgl@sss.pgh.pa.us         399         [ -  + ]:CBC      147980 :         else if (!entry->localrelvalid)
                                400                 :                :         {
                                401                 :                :             /* Note we release the no-longer-useful lock here. */
 2006 tgl@sss.pgh.pa.us         402                 :UBC           0 :             table_close(entry->localrel, lockmode);
                                403                 :              0 :             entry->localrel = NULL;
                                404                 :                :         }
                                405                 :                :     }
                                406                 :                : 
                                407                 :                :     /*
                                408                 :                :      * If the entry has been marked invalid since we last had lock on it,
                                409                 :                :      * re-open the local relation by name and rebuild all derived data.
                                410                 :                :      */
 2006 tgl@sss.pgh.pa.us         411         [ +  + ]:CBC      148577 :     if (!entry->localrelvalid)
                                412                 :                :     {
                                413                 :                :         Oid         relid;
                                414                 :                :         TupleDesc   desc;
                                415                 :                :         MemoryContext oldctx;
                                416                 :                :         int         i;
                                417                 :                :         Bitmapset  *missingatts;
  473 akapila@postgresql.o      418                 :            597 :         Bitmapset  *generatedattrs = NULL;
                                419                 :                : 
                                420                 :                :         /* Release the no-longer-useful attrmap, if any. */
 1361                           421         [ +  + ]:            597 :         if (entry->attrmap)
                                422                 :                :         {
                                423                 :             13 :             free_attrmap(entry->attrmap);
                                424                 :             13 :             entry->attrmap = NULL;
                                425                 :                :         }
                                426                 :                : 
                                427                 :                :         /* Try to find and lock the relation by name. */
 3342 peter_e@gmx.net           428                 :            597 :         relid = RangeVarGetRelid(makeRangeVar(remoterel->nspname,
                                429                 :                :                                               remoterel->relname, -1),
                                430                 :                :                                  lockmode, true);
                                431         [ +  + ]:            597 :         if (!OidIsValid(relid))
                                432         [ +  - ]:              7 :             ereport(ERROR,
                                433                 :                :                     (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
                                434                 :                :                      errmsg("logical replication target relation \"%s.%s\" does not exist",
                                435                 :                :                             remoterel->nspname, remoterel->relname)));
 2610 andres@anarazel.de        436                 :            590 :         entry->localrel = table_open(relid, NoLock);
 2006 tgl@sss.pgh.pa.us         437                 :            590 :         entry->localreloid = relid;
                                438                 :                : 
                                439                 :                :         /* Check for supported relkind. */
 3225 peter_e@gmx.net           440                 :            590 :         CheckSubscriptionRelkind(entry->localrel->rd_rel->relkind,
  143 akapila@postgresql.o      441                 :GNC         590 :                                  remoterel->relkind,
 3225 peter_e@gmx.net           442                 :CBC         590 :                                  remoterel->nspname, remoterel->relname);
                                443                 :                : 
                                444                 :                :         /*
                                445                 :                :          * Build the mapping of local attribute numbers to remote attribute
                                446                 :                :          * numbers and validate that we don't miss any replicated columns as
                                447                 :                :          * that would result in potentially unwanted data loss.
                                448                 :                :          */
 3342                           449                 :            590 :         desc = RelationGetDescr(entry->localrel);
                                450                 :            590 :         oldctx = MemoryContextSwitchTo(LogicalRepRelMapContext);
 2279 michael@paquier.xyz       451                 :            590 :         entry->attrmap = make_attrmap(desc->natts);
 3342 peter_e@gmx.net           452                 :            590 :         MemoryContextSwitchTo(oldctx);
                                453                 :                : 
                                454                 :                :         /* check and report missing attrs, if any */
 1985 akapila@postgresql.o      455                 :            590 :         missingatts = bms_add_range(NULL, 0, remoterel->natts - 1);
 3342 peter_e@gmx.net           456         [ +  + ]:           1940 :         for (i = 0; i < desc->natts; i++)
                                457                 :                :         {
                                458                 :                :             int         attnum;
 3129 andres@anarazel.de        459                 :           1350 :             Form_pg_attribute attr = TupleDescAttr(desc, i);
                                460                 :                : 
  473 akapila@postgresql.o      461         [ +  + ]:           1350 :             if (attr->attisdropped)
                                462                 :                :             {
 2279 michael@paquier.xyz       463                 :              2 :                 entry->attrmap->attnums[i] = -1;
 3223 peter_e@gmx.net           464                 :              2 :                 continue;
                                465                 :                :             }
                                466                 :                : 
                                467                 :           1348 :             attnum = logicalrep_rel_att_by_name(remoterel,
 3129 andres@anarazel.de        468                 :           1348 :                                                 NameStr(attr->attname));
                                469                 :                : 
 2279 michael@paquier.xyz       470                 :           1348 :             entry->attrmap->attnums[i] = attnum;
 3342 peter_e@gmx.net           471         [ +  + ]:           1348 :             if (attnum >= 0)
                                472                 :                :             {
                                473                 :                :                 /* Remember which subscriber columns are generated. */
  473 akapila@postgresql.o      474         [ +  + ]:           1068 :                 if (attr->attgenerated)
                                475                 :              2 :                     generatedattrs = bms_add_member(generatedattrs, attnum);
                                476                 :                : 
 1985                           477                 :           1068 :                 missingatts = bms_del_member(missingatts, attnum);
                                478                 :                :             }
                                479                 :                :         }
                                480                 :                : 
  473                           481                 :            590 :         logicalrep_report_missing_or_gen_attrs(remoterel, missingatts,
                                482                 :                :                                                generatedattrs);
                                483                 :                : 
                                484                 :                :         /* be tidy */
                                485                 :            588 :         bms_free(generatedattrs);
 1985                           486                 :            588 :         bms_free(missingatts);
                                487                 :                : 
                                488                 :                :         /*
                                489                 :                :          * Set if the table's replica identity is enough to apply
                                490                 :                :          * update/delete.
                                491                 :                :          */
 1363                           492                 :            588 :         logicalrep_rel_mark_updatable(entry);
                                493                 :                : 
                                494                 :                :         /*
                                495                 :                :          * Finding a usable index is an infrequent task. It occurs when an
                                496                 :                :          * operation is first performed on the relation, or after invalidation
                                497                 :                :          * of the relation cache entry (such as ANALYZE or CREATE/DROP index
                                498                 :                :          * on the relation).
                                499                 :                :          */
 1096                           500                 :            588 :         entry->localindexoid = FindLogicalRepLocalIndex(entry->localrel, remoterel,
                                501                 :                :                                                         entry->attrmap);
                                502                 :                : 
 2006 tgl@sss.pgh.pa.us         503                 :            588 :         entry->localrelvalid = true;
                                504                 :                :     }
                                505                 :                : 
 3279 peter_e@gmx.net           506         [ +  + ]:         148568 :     if (entry->state != SUBREL_STATE_READY)
                                507                 :            634 :         entry->state = GetSubscriptionRelState(MySubscription->oid,
                                508                 :                :                                                entry->localreloid,
                                509                 :                :                                                &entry->statelsn);
                                510                 :                : 
 3342                           511                 :         148568 :     return entry;
                                512                 :                : }
                                513                 :                : 
                                514                 :                : /*
                                515                 :                :  * Close the previously opened logical relation.
                                516                 :                :  */
                                517                 :                : void
                                518                 :         148509 : logicalrep_rel_close(LogicalRepRelMapEntry *rel, LOCKMODE lockmode)
                                519                 :                : {
 2610 andres@anarazel.de        520                 :         148509 :     table_close(rel->localrel, lockmode);
 3342 peter_e@gmx.net           521                 :         148509 :     rel->localrel = NULL;
                                522                 :         148509 : }
                                523                 :                : 
                                524                 :                : /*
                                525                 :                :  * Partition cache: look up partition LogicalRepRelMapEntry's
                                526                 :                :  *
                                527                 :                :  * Unlike relation map cache, this is keyed by partition OID, not remote
                                528                 :                :  * relation OID, because we only have to use this cache in the case where
                                529                 :                :  * partitions are not directly mapped to any remote relation, such as when
                                530                 :                :  * replication is occurring with one of their ancestors as target.
                                531                 :                :  */
                                532                 :                : 
                                533                 :                : /*
                                534                 :                :  * Relcache invalidation callback
                                535                 :                :  */
                                536                 :                : static void
 2169 peter@eisentraut.org      537                 :            288 : logicalrep_partmap_invalidate_cb(Datum arg, Oid reloid)
                                538                 :                : {
                                539                 :                :     LogicalRepPartMapEntry *entry;
                                540                 :                : 
                                541                 :                :     /* Just to be sure. */
                                542         [ -  + ]:            288 :     if (LogicalRepPartMap == NULL)
 2169 peter@eisentraut.org      543                 :UBC           0 :         return;
                                544                 :                : 
 2169 peter@eisentraut.org      545         [ +  - ]:CBC         288 :     if (reloid != InvalidOid)
                                546                 :                :     {
                                547                 :                :         HASH_SEQ_STATUS status;
                                548                 :                : 
                                549                 :            288 :         hash_seq_init(&status, LogicalRepPartMap);
                                550                 :                : 
                                551                 :                :         /* TODO, use inverse lookup hashtable? */
 1369 akapila@postgresql.o      552         [ +  + ]:            822 :         while ((entry = (LogicalRepPartMapEntry *) hash_seq_search(&status)) != NULL)
                                553                 :                :         {
                                554         [ +  + ]:            540 :             if (entry->relmapentry.localreloid == reloid)
                                555                 :                :             {
                                556                 :              6 :                 entry->relmapentry.localrelvalid = false;
 2169 peter@eisentraut.org      557                 :              6 :                 hash_seq_term(&status);
                                558                 :              6 :                 break;
                                559                 :                :             }
                                560                 :                :         }
                                561                 :                :     }
                                562                 :                :     else
                                563                 :                :     {
                                564                 :                :         /* invalidate all cache entries */
                                565                 :                :         HASH_SEQ_STATUS status;
                                566                 :                : 
 2169 peter@eisentraut.org      567                 :UBC           0 :         hash_seq_init(&status, LogicalRepPartMap);
                                568                 :                : 
 1369 akapila@postgresql.o      569         [ #  # ]:              0 :         while ((entry = (LogicalRepPartMapEntry *) hash_seq_search(&status)) != NULL)
                                570                 :              0 :             entry->relmapentry.localrelvalid = false;
                                571                 :                :     }
                                572                 :                : }
                                573                 :                : 
                                574                 :                : /*
                                575                 :                :  * Reset the entries in the partition map that refer to remoterel.
                                576                 :                :  *
                                577                 :                :  * Called when new relation mapping is sent by the publisher to update our
                                578                 :                :  * expected view of incoming data from said publisher.
                                579                 :                :  *
                                580                 :                :  * Note that we don't update the remoterel information in the entry here,
                                581                 :                :  * we will update the information in logicalrep_partition_open to avoid
                                582                 :                :  * unnecessary work.
                                583                 :                :  */
                                584                 :                : void
 1368 akapila@postgresql.o      585                 :CBC         449 : logicalrep_partmap_reset_relmap(LogicalRepRelation *remoterel)
                                586                 :                : {
                                587                 :                :     HASH_SEQ_STATUS status;
                                588                 :                :     LogicalRepPartMapEntry *part_entry;
                                589                 :                :     LogicalRepRelMapEntry *entry;
                                590                 :                : 
                                591         [ +  + ]:            449 :     if (LogicalRepPartMap == NULL)
                                592                 :            415 :         return;
                                593                 :                : 
                                594                 :             34 :     hash_seq_init(&status, LogicalRepPartMap);
                                595         [ +  + ]:             87 :     while ((part_entry = (LogicalRepPartMapEntry *) hash_seq_search(&status)) != NULL)
                                596                 :                :     {
                                597                 :             53 :         entry = &part_entry->relmapentry;
                                598                 :                : 
                                599         [ +  + ]:             53 :         if (entry->remoterel.remoteid != remoterel->remoteid)
                                600                 :             45 :             continue;
                                601                 :                : 
                                602                 :              8 :         logicalrep_relmap_free_entry(entry);
                                603                 :                : 
                                604                 :              8 :         memset(entry, 0, sizeof(LogicalRepRelMapEntry));
                                605                 :                :     }
                                606                 :                : }
                                607                 :                : 
                                608                 :                : /*
                                609                 :                :  * Initialize the partition map cache.
                                610                 :                :  */
                                611                 :                : static void
 2169 peter@eisentraut.org      612                 :              6 : logicalrep_partmap_init(void)
                                613                 :                : {
                                614                 :                :     HASHCTL     ctl;
                                615                 :                : 
                                616         [ +  - ]:              6 :     if (!LogicalRepPartMapContext)
                                617                 :              6 :         LogicalRepPartMapContext =
                                618                 :              6 :             AllocSetContextCreate(CacheMemoryContext,
                                619                 :                :                                   "LogicalRepPartMapContext",
                                620                 :                :                                   ALLOCSET_DEFAULT_SIZES);
                                621                 :                : 
                                622                 :                :     /* Initialize the relation hash table. */
                                623                 :              6 :     ctl.keysize = sizeof(Oid);  /* partition OID */
                                624                 :              6 :     ctl.entrysize = sizeof(LogicalRepPartMapEntry);
                                625                 :              6 :     ctl.hcxt = LogicalRepPartMapContext;
                                626                 :                : 
                                627                 :              6 :     LogicalRepPartMap = hash_create("logicalrep partition map cache", 64, &ctl,
                                628                 :                :                                     HASH_ELEM | HASH_BLOBS | HASH_CONTEXT);
                                629                 :                : 
                                630                 :                :     /* Watch for invalidation events. */
                                631                 :              6 :     CacheRegisterRelcacheCallback(logicalrep_partmap_invalidate_cb,
                                632                 :                :                                   (Datum) 0);
                                633                 :              6 : }
                                634                 :                : 
                                635                 :                : /*
                                636                 :                :  * logicalrep_partition_open
                                637                 :                :  *
                                638                 :                :  * Returned entry reuses most of the values of the root table's entry, save
                                639                 :                :  * the attribute map, which can be different for the partition.  However,
                                640                 :                :  * we must physically copy all the data, in case the root table's entry
                                641                 :                :  * gets freed/rebuilt.
                                642                 :                :  *
                                643                 :                :  * Note there's no logicalrep_partition_close, because the caller closes the
                                644                 :                :  * component relation.
                                645                 :                :  */
                                646                 :                : LogicalRepRelMapEntry *
                                647                 :             30 : logicalrep_partition_open(LogicalRepRelMapEntry *root,
                                648                 :                :                           Relation partrel, AttrMap *map)
                                649                 :                : {
                                650                 :                :     LogicalRepRelMapEntry *entry;
                                651                 :                :     LogicalRepPartMapEntry *part_entry;
                                652                 :             30 :     LogicalRepRelation *remoterel = &root->remoterel;
                                653                 :             30 :     Oid         partOid = RelationGetRelid(partrel);
                                654                 :             30 :     AttrMap    *attrmap = root->attrmap;
                                655                 :                :     bool        found;
                                656                 :                :     MemoryContext oldctx;
                                657                 :                : 
                                658         [ +  + ]:             30 :     if (LogicalRepPartMap == NULL)
                                659                 :              6 :         logicalrep_partmap_init();
                                660                 :                : 
                                661                 :                :     /* Search for existing entry. */
                                662                 :             30 :     part_entry = (LogicalRepPartMapEntry *) hash_search(LogicalRepPartMap,
                                663                 :                :                                                         &partOid,
                                664                 :                :                                                         HASH_ENTER, &found);
                                665                 :                : 
 1369 akapila@postgresql.o      666                 :             30 :     entry = &part_entry->relmapentry;
                                667                 :                : 
                                668                 :                :     /*
                                669                 :                :      * We must always overwrite entry->localrel with the latest partition
                                670                 :                :      * Relation pointer, because the Relation pointed to by the old value may
                                671                 :                :      * have been cleared after the caller would have closed the partition
                                672                 :                :      * relation after the last use of this entry.  Note that localrelvalid is
                                673                 :                :      * only updated by the relcache invalidation callback, so it may still be
                                674                 :                :      * true irrespective of whether the Relation pointed to by localrel has
                                675                 :                :      * been cleared or not.
                                676                 :                :      */
                                677   [ +  +  +  + ]:             30 :     if (found && entry->localrelvalid)
                                678                 :                :     {
 1363                           679                 :             15 :         entry->localrel = partrel;
 1369                           680                 :             15 :         return entry;
                                681                 :                :     }
                                682                 :                : 
                                683                 :                :     /* Switch to longer-lived context. */
 2169 peter@eisentraut.org      684                 :             15 :     oldctx = MemoryContextSwitchTo(LogicalRepPartMapContext);
                                685                 :                : 
 1369 akapila@postgresql.o      686         [ +  + ]:             15 :     if (!found)
                                687                 :                :     {
                                688                 :              9 :         memset(part_entry, 0, sizeof(LogicalRepPartMapEntry));
                                689                 :              9 :         part_entry->partoid = partOid;
                                690                 :                :     }
                                691                 :                : 
                                692                 :                :     /* Release the no-longer-useful attrmap, if any. */
 1361                           693         [ +  + ]:             15 :     if (entry->attrmap)
                                694                 :                :     {
                                695                 :              1 :         free_attrmap(entry->attrmap);
                                696                 :              1 :         entry->attrmap = NULL;
                                697                 :                :     }
                                698                 :                : 
 1369                           699         [ +  + ]:             15 :     if (!entry->remoterel.remoteid)
                                700                 :                :     {
                                701                 :                :         int         i;
                                702                 :                : 
                                703                 :                :         /* Remote relation is copied as-is from the root entry. */
                                704                 :             14 :         entry->remoterel.remoteid = remoterel->remoteid;
                                705                 :             14 :         entry->remoterel.nspname = pstrdup(remoterel->nspname);
                                706                 :             14 :         entry->remoterel.relname = pstrdup(remoterel->relname);
                                707                 :             14 :         entry->remoterel.natts = remoterel->natts;
   95 michael@paquier.xyz       708                 :GNC          14 :         entry->remoterel.attnames = palloc_array(char *, remoterel->natts);
                                709                 :             14 :         entry->remoterel.atttyps = palloc_array(Oid, remoterel->natts);
 1369 akapila@postgresql.o      710         [ +  + ]:CBC          44 :         for (i = 0; i < remoterel->natts; i++)
                                711                 :                :         {
                                712                 :             30 :             entry->remoterel.attnames[i] = pstrdup(remoterel->attnames[i]);
                                713                 :             30 :             entry->remoterel.atttyps[i] = remoterel->atttyps[i];
                                714                 :                :         }
                                715                 :             14 :         entry->remoterel.replident = remoterel->replident;
                                716                 :             14 :         entry->remoterel.attkeys = bms_copy(remoterel->attkeys);
                                717                 :                :     }
                                718                 :                : 
 2169 peter@eisentraut.org      719                 :             15 :     entry->localrel = partrel;
                                720                 :             15 :     entry->localreloid = partOid;
                                721                 :                : 
                                722                 :                :     /*
                                723                 :                :      * If the partition's attributes don't match the root relation's, we'll
                                724                 :                :      * need to make a new attrmap which maps partition attribute numbers to
                                725                 :                :      * remoterel's, instead of the original which maps root relation's
                                726                 :                :      * attribute numbers to remoterel's.
                                727                 :                :      *
                                728                 :                :      * Note that 'map' which comes from the tuple routing data structure
                                729                 :                :      * contains 1-based attribute numbers (of the parent relation).  However,
                                730                 :                :      * the map in 'entry', a logical replication data structure, contains
                                731                 :                :      * 0-based attribute numbers (of the remote relation).
                                732                 :                :      */
                                733         [ +  + ]:             15 :     if (map)
                                734                 :                :     {
                                735                 :                :         AttrNumber  attno;
                                736                 :                : 
                                737                 :              8 :         entry->attrmap = make_attrmap(map->maplen);
                                738         [ +  + ]:             34 :         for (attno = 0; attno < entry->attrmap->maplen; attno++)
                                739                 :                :         {
                                740                 :             26 :             AttrNumber  root_attno = map->attnums[attno];
                                741                 :                : 
                                742                 :                :             /* 0 means it's a dropped attribute.  See comments atop AttrMap. */
 1369 akapila@postgresql.o      743         [ +  + ]:             26 :             if (root_attno == 0)
                                744                 :              2 :                 entry->attrmap->attnums[attno] = -1;
                                745                 :                :             else
                                746                 :             24 :                 entry->attrmap->attnums[attno] = attrmap->attnums[root_attno - 1];
                                747                 :                :         }
                                748                 :                :     }
                                749                 :                :     else
                                750                 :                :     {
                                751                 :                :         /* Lacking copy_attmap, do this the hard way. */
 1738 tgl@sss.pgh.pa.us         752                 :              7 :         entry->attrmap = make_attrmap(attrmap->maplen);
                                753                 :              7 :         memcpy(entry->attrmap->attnums, attrmap->attnums,
                                754                 :              7 :                attrmap->maplen * sizeof(AttrNumber));
                                755                 :                :     }
                                756                 :                : 
                                757                 :                :     /* Set if the table's replica identity is enough to apply update/delete. */
 1363 akapila@postgresql.o      758                 :             15 :     logicalrep_rel_mark_updatable(entry);
                                759                 :                : 
                                760                 :                :     /* state and statelsn are left set to 0. */
 2169 peter@eisentraut.org      761                 :             15 :     MemoryContextSwitchTo(oldctx);
                                762                 :                : 
                                763                 :                :     /*
                                764                 :                :      * Finding a usable index is an infrequent task. It occurs when an
                                765                 :                :      * operation is first performed on the relation, or after invalidation of
                                766                 :                :      * the relation cache entry (such as ANALYZE or CREATE/DROP index on the
                                767                 :                :      * relation).
                                768                 :                :      *
                                769                 :                :      * We also prefer to run this code on the oldctx so that we do not leak
                                770                 :                :      * anything in the LogicalRepPartMapContext (hence CacheMemoryContext).
                                771                 :                :      */
 1096 akapila@postgresql.o      772                 :             15 :     entry->localindexoid = FindLogicalRepLocalIndex(partrel, remoterel,
                                773                 :                :                                                     entry->attrmap);
                                774                 :                : 
                                775                 :             15 :     entry->localrelvalid = true;
                                776                 :                : 
 2169 peter@eisentraut.org      777                 :             15 :     return entry;
                                778                 :                : }
                                779                 :                : 
                                780                 :                : /*
                                781                 :                :  * Returns the oid of an index that can be used by the apply worker to scan
                                782                 :                :  * the relation.
                                783                 :                :  *
                                784                 :                :  * We expect to call this function when REPLICA IDENTITY FULL is defined for
                                785                 :                :  * the remote relation.
                                786                 :                :  *
                                787                 :                :  * If no suitable index is found, returns InvalidOid.
                                788                 :                :  */
                                789                 :                : static Oid
 1096 akapila@postgresql.o      790                 :             67 : FindUsableIndexForReplicaIdentityFull(Relation localrel, AttrMap *attrmap)
                                791                 :                : {
                                792                 :             67 :     List       *idxlist = RelationGetIndexList(localrel);
                                793                 :                : 
  801 nathan@postgresql.or      794   [ +  +  +  +  :            122 :     foreach_oid(idxoid, idxlist)
                                              +  + ]
                                795                 :                :     {
                                796                 :                :         bool        isUsableIdx;
                                797                 :                :         Relation    idxRel;
                                798                 :                : 
 1096 akapila@postgresql.o      799                 :             20 :         idxRel = index_open(idxoid, AccessShareLock);
  466 peter@eisentraut.org      800                 :             20 :         isUsableIdx = IsIndexUsableForReplicaIdentityFull(idxRel, attrmap);
 1096 akapila@postgresql.o      801                 :             20 :         index_close(idxRel, AccessShareLock);
                                802                 :                : 
                                803                 :                :         /* Return the first eligible index found */
  964 msawada@postgresql.o      804         [ +  + ]:             20 :         if (isUsableIdx)
 1096 akapila@postgresql.o      805                 :             16 :             return idxoid;
                                806                 :                :     }
                                807                 :                : 
                                808                 :             51 :     return InvalidOid;
                                809                 :                : }
                                810                 :                : 
                                811                 :                : /*
                                812                 :                :  * Returns true if the index is usable for replica identity full.
                                813                 :                :  *
                                814                 :                :  * The index must have an equal strategy for each key column, be non-partial,
                                815                 :                :  * and the leftmost field must be a column (not an expression) that references
                                816                 :                :  * the remote relation column. These limitations help to keep the index scan
                                817                 :                :  * similar to PK/RI index scans.
                                818                 :                :  *
                                819                 :                :  * attrmap is a map of local attributes to remote ones. We can consult this
                                820                 :                :  * map to check whether the local index attribute has a corresponding remote
                                821                 :                :  * attribute.
                                822                 :                :  *
                                823                 :                :  * Note that the limitations of index scans for replica identity full only
                                824                 :                :  * adheres to a subset of the limitations of PK/RI. For example, we support
                                825                 :                :  * columns that are marked as [NULL] or we are not interested in the [NOT
                                826                 :                :  * DEFERRABLE] aspect of constraints here. It works for us because we always
                                827                 :                :  * compare the tuples for non-PK/RI index scans. See
                                828                 :                :  * RelationFindReplTupleByIndex().
                                829                 :                :  *
                                830                 :                :  * XXX: To support partial indexes, the required changes are likely to be larger.
                                831                 :                :  * If none of the tuples satisfy the expression for the index scan, we fall-back
                                832                 :                :  * to sequential execution, which might not be a good idea in some cases.
                                833                 :                :  */
                                834                 :                : bool
  466 peter@eisentraut.org      835                 :             37 : IsIndexUsableForReplicaIdentityFull(Relation idxrel, AttrMap *attrmap)
                                836                 :                : {
                                837                 :                :     AttrNumber  keycol;
                                838                 :                :     oidvector  *indclass;
                                839                 :                : 
                                840                 :                :     /* The index must not be a partial index */
                                841         [ +  + ]:             37 :     if (!heap_attisnull(idxrel->rd_indextuple, Anum_pg_index_indpred, NULL))
  975 akapila@postgresql.o      842                 :              2 :         return false;
                                843                 :                : 
  466 peter@eisentraut.org      844         [ -  + ]:             35 :     Assert(idxrel->rd_index->indnatts >= 1);
                                845                 :                : 
  460                           846                 :             35 :     indclass = (oidvector *) DatumGetPointer(SysCacheGetAttrNotNull(INDEXRELID,
                                847                 :             35 :                                                                     idxrel->rd_indextuple,
                                848                 :                :                                                                     Anum_pg_index_indclass));
                                849                 :                : 
                                850                 :                :     /* Ensure that the index has a valid equal strategy for each key column */
                                851         [ +  + ]:            101 :     for (int i = 0; i < idxrel->rd_index->indnkeyatts; i++)
                                852                 :                :     {
                                853                 :                :         Oid         opfamily;
                                854                 :                : 
  387                           855                 :             66 :         opfamily = get_opclass_family(indclass->values[i]);
                                856         [ -  + ]:             66 :         if (IndexAmTranslateCompareType(COMPARE_EQ, idxrel->rd_rel->relam, opfamily, true) == InvalidStrategy)
  460 peter@eisentraut.org      857                 :UBC           0 :             return false;
                                858                 :                :     }
                                859                 :                : 
                                860                 :                :     /*
                                861                 :                :      * For indexes other than PK and REPLICA IDENTITY, we need to match the
                                862                 :                :      * local and remote tuples.  The equality routine tuples_equal() cannot
                                863                 :                :      * accept a data type where the type cache cannot provide an equality
                                864                 :                :      * operator.
                                865                 :                :      */
  460 peter@eisentraut.org      866         [ +  + ]:CBC         101 :     for (int i = 0; i < idxrel->rd_att->natts; i++)
                                867                 :                :     {
                                868                 :                :         TypeCacheEntry *typentry;
                                869                 :                : 
                                870                 :             66 :         typentry = lookup_type_cache(TupleDescAttr(idxrel->rd_att, i)->atttypid, TYPECACHE_EQ_OPR_FINFO);
                                871         [ -  + ]:             66 :         if (!OidIsValid(typentry->eq_opr_finfo.fn_oid))
  460 peter@eisentraut.org      872                 :UBC           0 :             return false;
                                873                 :                :     }
                                874                 :                : 
                                875                 :                :     /* The leftmost index field must not be an expression */
  466 peter@eisentraut.org      876                 :CBC          35 :     keycol = idxrel->rd_index->indkey.values[0];
  964 msawada@postgresql.o      877         [ +  + ]:             35 :     if (!AttributeNumberIsValid(keycol))
                                878                 :              2 :         return false;
                                879                 :                : 
                                880                 :                :     /*
                                881                 :                :      * And the leftmost index field must reference the remote relation column.
                                882                 :                :      * This is because if it doesn't, the sequential scan is favorable over
                                883                 :                :      * index scan in most cases.
                                884                 :                :      */
                                885   [ -  +  +  - ]:             33 :     if (attrmap->maplen <= AttrNumberGetAttrOffset(keycol) ||
                                886   [ -  +  -  + ]:             33 :         attrmap->attnums[AttrNumberGetAttrOffset(keycol)] < 0)
  975 akapila@postgresql.o      887                 :UBC           0 :         return false;
                                888                 :                : 
                                889                 :                :     /*
                                890                 :                :      * The given index access method must implement "amgettuple", which will
                                891                 :                :      * be used later to fetch the tuples.  See RelationFindReplTupleByIndex().
                                892                 :                :      */
  460 peter@eisentraut.org      893         [ -  + ]:CBC          33 :     if (GetIndexAmRoutineByAmId(idxrel->rd_rel->relam, false)->amgettuple == NULL)
  460 peter@eisentraut.org      894                 :UBC           0 :         return false;
                                895                 :                : 
  975 akapila@postgresql.o      896                 :CBC          33 :     return true;
                                897                 :                : }
                                898                 :                : 
                                899                 :                : /*
                                900                 :                :  * Return the OID of the replica identity index if one is defined;
                                901                 :                :  * the OID of the PK if one exists and is not deferrable;
                                902                 :                :  * otherwise, InvalidOid.
                                903                 :                :  */
                                904                 :                : Oid
 1096                           905                 :         144773 : GetRelationIdentityOrPK(Relation rel)
                                906                 :                : {
                                907                 :                :     Oid         idxoid;
                                908                 :                : 
                                909                 :         144773 :     idxoid = RelationGetReplicaIndex(rel);
                                910                 :                : 
                                911         [ +  + ]:         144773 :     if (!OidIsValid(idxoid))
  492 alvherre@alvh.no-ip.      912                 :            260 :         idxoid = RelationGetPrimaryKeyIndex(rel, false);
                                913                 :                : 
 1096 akapila@postgresql.o      914                 :         144773 :     return idxoid;
                                915                 :                : }
                                916                 :                : 
                                917                 :                : /*
                                918                 :                :  * Returns the index oid if we can use an index for subscriber. Otherwise,
                                919                 :                :  * returns InvalidOid.
                                920                 :                :  */
                                921                 :                : static Oid
                                922                 :            603 : FindLogicalRepLocalIndex(Relation localrel, LogicalRepRelation *remoterel,
                                923                 :                :                          AttrMap *attrMap)
                                924                 :                : {
                                925                 :                :     Oid         idxoid;
                                926                 :                : 
                                927                 :                :     /*
                                928                 :                :      * We never need index oid for partitioned tables, always rely on leaf
                                929                 :                :      * partition's index.
                                930                 :                :      */
                                931         [ +  + ]:            603 :     if (localrel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE)
                                932                 :             73 :         return InvalidOid;
                                933                 :                : 
                                934                 :                :     /*
                                935                 :                :      * Simple case, we already have a primary key or a replica identity index.
                                936                 :                :      */
                                937                 :            530 :     idxoid = GetRelationIdentityOrPK(localrel);
                                938         [ +  + ]:            530 :     if (OidIsValid(idxoid))
                                939                 :            334 :         return idxoid;
                                940                 :                : 
                                941         [ +  + ]:            196 :     if (remoterel->replident == REPLICA_IDENTITY_FULL)
                                942                 :                :     {
                                943                 :                :         /*
                                944                 :                :          * We are looking for one more opportunity for using an index. If
                                945                 :                :          * there are any indexes defined on the local relation, try to pick a
                                946                 :                :          * suitable index.
                                947                 :                :          *
                                948                 :                :          * The index selection safely assumes that all the columns are going
                                949                 :                :          * to be available for the index scan given that remote relation has
                                950                 :                :          * replica identity full.
                                951                 :                :          *
                                952                 :                :          * Note that we are not using the planner to find the cheapest method
                                953                 :                :          * to scan the relation as that would require us to either use lower
                                954                 :                :          * level planner functions which would be a maintenance burden in the
                                955                 :                :          * long run or use the full-fledged planner which could cause
                                956                 :                :          * overhead.
                                957                 :                :          */
                                958                 :             67 :         return FindUsableIndexForReplicaIdentityFull(localrel, attrMap);
                                959                 :                :     }
                                960                 :                : 
                                961                 :            129 :     return InvalidOid;
                                962                 :                : }
        

Generated by: LCOV version 2.4-beta