LCOV - differential code coverage report
Current view: top level - src/backend/replication/logical - relation.c (source / functions) Coverage Total Hit UBC GNC CBC
Current: b45a8d7d8b306b43f31a002f1b3f1dddc8defeaf vs 8767b449a3a1e75626dfb08f24da54933171d4c5 Lines: 93.3 % 285 266 19 3 263
Current Date: 2025-10-28 08:26:42 +0900 Functions: 100.0 % 18 18 2 16
Baseline: lcov-20251028-005825-baseline Branches: 79.3 % 174 138 36 2 136
Baseline Date: 2025-10-27 06:37:35 +0000 Line coverage date bins:
Legend: Lines:     hit not hit
Branches: + taken - not taken # not executed
(1,7] days: 100.0 % 3 3 3
(30,360] days: 92.3 % 39 36 3 36
(360..) days: 93.4 % 243 227 16 227
Function coverage date bins:
(30,360] days: 100.0 % 3 3 3
(360..) days: 100.0 % 15 15 2 13
Branch coverage date bins:
(1,7] days: 100.0 % 2 2 2
(30,360] days: 80.0 % 30 24 6 24
(360..) days: 78.9 % 142 112 30 112

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

Generated by: LCOV version 2.4-beta