PostgreSQL Source Code git master
Loading...
Searching...
No Matches
relation.c File Reference
Include dependency graph for relation.c:

Go to the source code of this file.

Data Structures

struct  LogicalRepPartMapEntry
 

Typedefs

typedef struct LogicalRepPartMapEntry LogicalRepPartMapEntry
 

Functions

static Oid FindLogicalRepLocalIndex (Relation localrel, LogicalRepRelation *remoterel, AttrMap *attrMap)
 
static void logicalrep_relmap_invalidate_cb (Datum arg, Oid reloid)
 
static void logicalrep_relmap_init (void)
 
static void logicalrep_relmap_free_entry (LogicalRepRelMapEntry *entry)
 
void logicalrep_relmap_update (LogicalRepRelation *remoterel)
 
static int logicalrep_rel_att_by_name (LogicalRepRelation *remoterel, const char *attname)
 
static charlogicalrep_get_attrs_str (LogicalRepRelation *remoterel, Bitmapset *atts)
 
static void logicalrep_report_missing_or_gen_attrs (LogicalRepRelation *remoterel, Bitmapset *missingatts, Bitmapset *generatedatts)
 
static void logicalrep_rel_mark_updatable (LogicalRepRelMapEntry *entry)
 
LogicalRepRelMapEntrylogicalrep_rel_open (LogicalRepRelId remoteid, LOCKMODE lockmode)
 
void logicalrep_rel_close (LogicalRepRelMapEntry *rel, LOCKMODE lockmode)
 
static void logicalrep_partmap_invalidate_cb (Datum arg, Oid reloid)
 
void logicalrep_partmap_reset_relmap (LogicalRepRelation *remoterel)
 
static void logicalrep_partmap_init (void)
 
LogicalRepRelMapEntrylogicalrep_partition_open (LogicalRepRelMapEntry *root, Relation partrel, AttrMap *map)
 
static Oid FindUsableIndexForReplicaIdentityFull (Relation localrel, AttrMap *attrmap)
 
bool IsIndexUsableForReplicaIdentityFull (Relation idxrel, AttrMap *attrmap)
 
Oid GetRelationIdentityOrPK (Relation rel)
 

Variables

static MemoryContext LogicalRepRelMapContext = NULL
 
static HTABLogicalRepRelMap = NULL
 
static MemoryContext LogicalRepPartMapContext = NULL
 
static HTABLogicalRepPartMap = NULL
 

Typedef Documentation

◆ LogicalRepPartMapEntry

Function Documentation

◆ FindLogicalRepLocalIndex()

static Oid FindLogicalRepLocalIndex ( Relation  localrel,
LogicalRepRelation remoterel,
AttrMap attrMap 
)
static

Definition at line 916 of file relation.c.

918{
919 Oid idxoid;
920
921 /*
922 * We never need index oid for partitioned tables, always rely on leaf
923 * partition's index.
924 */
925 if (localrel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE)
926 return InvalidOid;
927
928 /*
929 * Simple case, we already have a primary key or a replica identity index.
930 */
932 if (OidIsValid(idxoid))
933 return idxoid;
934
935 if (remoterel->replident == REPLICA_IDENTITY_FULL)
936 {
937 /*
938 * We are looking for one more opportunity for using an index. If
939 * there are any indexes defined on the local relation, try to pick a
940 * suitable index.
941 *
942 * The index selection safely assumes that all the columns are going
943 * to be available for the index scan given that remote relation has
944 * replica identity full.
945 *
946 * Note that we are not using the planner to find the cheapest method
947 * to scan the relation as that would require us to either use lower
948 * level planner functions which would be a maintenance burden in the
949 * long run or use the full-fledged planner which could cause
950 * overhead.
951 */
952 return FindUsableIndexForReplicaIdentityFull(localrel, attrMap);
953 }
954
955 return InvalidOid;
956}
#define OidIsValid(objectId)
Definition c.h:917
#define InvalidOid
unsigned int Oid
static int fb(int x)
Oid GetRelationIdentityOrPK(Relation rel)
Definition relation.c:899
static Oid FindUsableIndexForReplicaIdentityFull(Relation localrel, AttrMap *attrmap)
Definition relation.c:784
Form_pg_class rd_rel
Definition rel.h:111

References fb(), FindUsableIndexForReplicaIdentityFull(), GetRelationIdentityOrPK(), InvalidOid, OidIsValid, RelationData::rd_rel, and LogicalRepRelation::replident.

Referenced by logicalrep_partition_open(), and logicalrep_rel_open().

◆ FindUsableIndexForReplicaIdentityFull()

static Oid FindUsableIndexForReplicaIdentityFull ( Relation  localrel,
AttrMap attrmap 
)
static

Definition at line 784 of file relation.c.

785{
786 List *idxlist = RelationGetIndexList(localrel);
787
789 {
790 bool isUsableIdx;
792
796
797 /* Return the first eligible index found */
798 if (isUsableIdx)
799 return idxoid;
800 }
801
802 return InvalidOid;
803}
void index_close(Relation relation, LOCKMODE lockmode)
Definition indexam.c:178
Relation index_open(Oid relationId, LOCKMODE lockmode)
Definition indexam.c:134
#define AccessShareLock
Definition lockdefs.h:36
#define foreach_oid(var, lst)
Definition pg_list.h:503
List * RelationGetIndexList(Relation relation)
Definition relcache.c:4848
bool IsIndexUsableForReplicaIdentityFull(Relation idxrel, AttrMap *attrmap)
Definition relation.c:829
Definition pg_list.h:54

References AccessShareLock, fb(), foreach_oid, index_close(), index_open(), InvalidOid, IsIndexUsableForReplicaIdentityFull(), and RelationGetIndexList().

Referenced by FindLogicalRepLocalIndex().

◆ GetRelationIdentityOrPK()

Oid GetRelationIdentityOrPK ( Relation  rel)

Definition at line 899 of file relation.c.

900{
901 Oid idxoid;
902
904
905 if (!OidIsValid(idxoid))
907
908 return idxoid;
909}
Oid RelationGetPrimaryKeyIndex(Relation relation, bool deferrable_ok)
Definition relcache.c:5059
Oid RelationGetReplicaIndex(Relation relation)
Definition relcache.c:5084

References fb(), OidIsValid, RelationGetPrimaryKeyIndex(), and RelationGetReplicaIndex().

Referenced by check_concurrent_repack_requirements(), check_relation_updatable(), FindLogicalRepLocalIndex(), FindReplTupleInLocalRel(), get_tuple_desc(), RelationFindDeletedTupleInfoByIndex(), and RelationFindReplTupleByIndex().

◆ IsIndexUsableForReplicaIdentityFull()

bool IsIndexUsableForReplicaIdentityFull ( Relation  idxrel,
AttrMap attrmap 
)

Definition at line 829 of file relation.c.

830{
833
834 /* The index must not be a partial index */
835 if (!heap_attisnull(idxrel->rd_indextuple, Anum_pg_index_indpred, NULL))
836 return false;
837
838 Assert(idxrel->rd_index->indnatts >= 1);
839
841 idxrel->rd_indextuple,
843
844 /* Ensure that the index has a valid equal strategy for each key column */
845 for (int i = 0; i < idxrel->rd_index->indnkeyatts; i++)
846 {
847 Oid opfamily;
848
849 opfamily = get_opclass_family(indclass->values[i]);
850 if (IndexAmTranslateCompareType(COMPARE_EQ, idxrel->rd_rel->relam, opfamily, true) == InvalidStrategy)
851 return false;
852 }
853
854 /*
855 * For indexes other than PK and REPLICA IDENTITY, we need to match the
856 * local and remote tuples. The equality routine tuples_equal() cannot
857 * accept a data type where the type cache cannot provide an equality
858 * operator.
859 */
860 for (int i = 0; i < idxrel->rd_att->natts; i++)
861 {
862 TypeCacheEntry *typentry;
863
864 typentry = lookup_type_cache(TupleDescAttr(idxrel->rd_att, i)->atttypid, TYPECACHE_EQ_OPR_FINFO);
865 if (!OidIsValid(typentry->eq_opr_finfo.fn_oid))
866 return false;
867 }
868
869 /* The leftmost index field must not be an expression */
870 keycol = idxrel->rd_index->indkey.values[0];
872 return false;
873
874 /*
875 * And the leftmost index field must reference the remote relation column.
876 * This is because if it doesn't, the sequential scan is favorable over
877 * index scan in most cases.
878 */
879 if (attrmap->maplen <= AttrNumberGetAttrOffset(keycol) ||
881 return false;
882
883 /*
884 * The given index access method must implement "amgettuple", which will
885 * be used later to fetch the tuples. See RelationFindReplTupleByIndex().
886 */
887 if (GetIndexAmRoutineByAmId(idxrel->rd_rel->relam, false)->amgettuple == NULL)
888 return false;
889
890 return true;
891}
const IndexAmRoutine * GetIndexAmRoutineByAmId(Oid amoid, bool noerror)
Definition amapi.c:69
StrategyNumber IndexAmTranslateCompareType(CompareType cmptype, Oid amoid, Oid opfamily, bool missing_ok)
Definition amapi.c:161
int16 AttrNumber
Definition attnum.h:21
#define AttributeNumberIsValid(attributeNumber)
Definition attnum.h:34
#define AttrNumberGetAttrOffset(attNum)
Definition attnum.h:51
#define Assert(condition)
Definition c.h:1002
@ COMPARE_EQ
Definition cmptype.h:36
bool heap_attisnull(HeapTuple tup, int attnum, TupleDesc tupleDesc)
Definition heaptuple.c:456
int i
Definition isn.c:77
Oid get_opclass_family(Oid opclass)
Definition lsyscache.c:1442
static Pointer DatumGetPointer(Datum X)
Definition postgres.h:332
#define InvalidStrategy
Definition stratnum.h:24
int maplen
Definition attmap.h:37
AttrNumber * attnums
Definition attmap.h:36
Oid fn_oid
Definition fmgr.h:59
amgettuple_function amgettuple
Definition amapi.h:312
FmgrInfo eq_opr_finfo
Definition typcache.h:76
Definition c.h:874
Datum SysCacheGetAttrNotNull(SysCacheIdentifier cacheId, HeapTuple tup, AttrNumber attributeNumber)
Definition syscache.c:626
static FormData_pg_attribute * TupleDescAttr(TupleDesc tupdesc, int i)
Definition tupdesc.h:178
TypeCacheEntry * lookup_type_cache(Oid type_id, int flags)
Definition typcache.c:389
#define TYPECACHE_EQ_OPR_FINFO
Definition typcache.h:143

References IndexAmRoutine::amgettuple, Assert, AttrMap::attnums, AttributeNumberIsValid, AttrNumberGetAttrOffset, COMPARE_EQ, DatumGetPointer(), TypeCacheEntry::eq_opr_finfo, fb(), FmgrInfo::fn_oid, get_opclass_family(), GetIndexAmRoutineByAmId(), heap_attisnull(), i, IndexAmTranslateCompareType(), InvalidStrategy, lookup_type_cache(), AttrMap::maplen, OidIsValid, SysCacheGetAttrNotNull(), TupleDescAttr(), and TYPECACHE_EQ_OPR_FINFO.

Referenced by FindReplTupleInLocalRel(), and FindUsableIndexForReplicaIdentityFull().

◆ logicalrep_get_attrs_str()

static char * logicalrep_get_attrs_str ( LogicalRepRelation remoterel,
Bitmapset atts 
)
static

Definition at line 239 of file relation.c.

240{
242 bool first = true;
243 int i = -1;
244
245 Assert(!bms_is_empty(atts));
246
248
249 while ((i = bms_next_member(atts, i)) >= 0)
250 {
251 if (first)
252 appendStringInfo(&attsbuf, _("\"%s\""), remoterel->attnames[i]);
253 else
254 appendStringInfo(&attsbuf, _(", \"%s\""), remoterel->attnames[i]);
255 first = false;
256 }
257
258 return attsbuf.data;
259}
int bms_next_member(const Bitmapset *a, int prevbit)
Definition bitmapset.c:1425
#define bms_is_empty(a)
Definition bitmapset.h:119
#define _(x)
Definition elog.c:96
void appendStringInfo(StringInfo str, const char *fmt,...)
Definition stringinfo.c:145
void initStringInfo(StringInfo str)
Definition stringinfo.c:97

References _, appendStringInfo(), Assert, LogicalRepRelation::attnames, bms_is_empty, bms_next_member(), fb(), i, and initStringInfo().

Referenced by logicalrep_report_missing_or_gen_attrs().

◆ logicalrep_partition_open()

LogicalRepRelMapEntry * logicalrep_partition_open ( LogicalRepRelMapEntry root,
Relation  partrel,
AttrMap map 
)

Definition at line 640 of file relation.c.

642{
645 LogicalRepRelation *remoterel = &root->remoterel;
646 Oid partOid = RelationGetRelid(partrel);
647 AttrMap *attrmap = root->attrmap;
648 bool found;
650
651 if (LogicalRepPartMap == NULL)
653
654 /* Search for existing entry. */
656 &partOid,
657 HASH_ENTER, &found);
658
659 entry = &part_entry->relmapentry;
660
661 /*
662 * We must always overwrite entry->localrel with the latest partition
663 * Relation pointer, because the Relation pointed to by the old value may
664 * have been cleared after the caller would have closed the partition
665 * relation after the last use of this entry. Note that localrelvalid is
666 * only updated by the relcache invalidation callback, so it may still be
667 * true irrespective of whether the Relation pointed to by localrel has
668 * been cleared or not.
669 */
670 if (found && entry->localrelvalid)
671 {
672 Assert(entry->localreloid == partOid);
673 entry->localrel = partrel;
674 return entry;
675 }
676
677 /* Switch to longer-lived context. */
679
680 if (!found)
681 {
683 part_entry->partoid = partOid;
684 }
685
686 /* Release the no-longer-useful attrmap, if any. */
687 if (entry->attrmap)
688 {
689 free_attrmap(entry->attrmap);
690 entry->attrmap = NULL;
691 }
692
693 if (!entry->remoterel.remoteid)
694 {
695 int i;
696
697 /* Remote relation is copied as-is from the root entry. */
698 entry->remoterel.remoteid = remoterel->remoteid;
699 entry->remoterel.nspname = pstrdup(remoterel->nspname);
700 entry->remoterel.relname = pstrdup(remoterel->relname);
701 entry->remoterel.natts = remoterel->natts;
702 entry->remoterel.attnames = palloc_array(char *, remoterel->natts);
703 entry->remoterel.atttyps = palloc_array(Oid, remoterel->natts);
704 for (i = 0; i < remoterel->natts; i++)
705 {
706 entry->remoterel.attnames[i] = pstrdup(remoterel->attnames[i]);
707 entry->remoterel.atttyps[i] = remoterel->atttyps[i];
708 }
709 entry->remoterel.replident = remoterel->replident;
710 entry->remoterel.attkeys = bms_copy(remoterel->attkeys);
711 }
712
713 entry->localrel = partrel;
714 entry->localreloid = partOid;
715
716 /*
717 * If the partition's attributes don't match the root relation's, we'll
718 * need to make a new attrmap which maps partition attribute numbers to
719 * remoterel's, instead of the original which maps root relation's
720 * attribute numbers to remoterel's.
721 *
722 * Note that 'map' which comes from the tuple routing data structure
723 * contains 1-based attribute numbers (of the parent relation). However,
724 * the map in 'entry', a logical replication data structure, contains
725 * 0-based attribute numbers (of the remote relation).
726 */
727 if (map)
728 {
729 AttrNumber attno;
730
731 entry->attrmap = make_attrmap(map->maplen);
732 for (attno = 0; attno < entry->attrmap->maplen; attno++)
733 {
734 AttrNumber root_attno = map->attnums[attno];
735
736 /* 0 means it's a dropped attribute. See comments atop AttrMap. */
737 if (root_attno == 0)
738 entry->attrmap->attnums[attno] = -1;
739 else
740 entry->attrmap->attnums[attno] = attrmap->attnums[root_attno - 1];
741 }
742 }
743 else
744 {
745 /* Lacking copy_attmap, do this the hard way. */
746 entry->attrmap = make_attrmap(attrmap->maplen);
747 memcpy(entry->attrmap->attnums, attrmap->attnums,
748 attrmap->maplen * sizeof(AttrNumber));
749 }
750
751 /* Set if the table's replica identity is enough to apply update/delete. */
753
754 /* state and statelsn are left set to 0. */
756
757 /*
758 * Finding a usable index is an infrequent task. It occurs when an
759 * operation is first performed on the relation, or after invalidation of
760 * the relation cache entry (such as ANALYZE or CREATE/DROP index on the
761 * relation).
762 *
763 * We also prefer to run this code on the oldctx so that we do not leak
764 * anything in the LogicalRepPartMapContext (hence CacheMemoryContext).
765 */
766 entry->localindexoid = FindLogicalRepLocalIndex(partrel, remoterel,
767 entry->attrmap);
768
769 entry->localrelvalid = true;
770
771 return entry;
772}
void free_attrmap(AttrMap *map)
Definition attmap.c:56
AttrMap * make_attrmap(int maplen)
Definition attmap.c:40
Bitmapset * bms_copy(const Bitmapset *a)
Definition bitmapset.c:123
memcpy(sums, checksumBaseOffsets, sizeof(checksumBaseOffsets))
void * hash_search(HTAB *hashp, const void *keyPtr, HASHACTION action, bool *foundPtr)
Definition dynahash.c:889
#define palloc_array(type, count)
Definition fe_memutils.h:91
@ HASH_ENTER
Definition hsearch.h:109
char * pstrdup(const char *in)
Definition mcxt.c:1910
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition palloc.h:138
tree ctl root
Definition radixtree.h:1857
#define RelationGetRelid(relation)
Definition rel.h:516
static MemoryContext LogicalRepPartMapContext
Definition relation.c:50
static void logicalrep_partmap_init(void)
Definition relation.c:605
static HTAB * LogicalRepPartMap
Definition relation.c:51
static void logicalrep_rel_mark_updatable(LogicalRepRelMapEntry *entry)
Definition relation.c:308
static Oid FindLogicalRepLocalIndex(Relation localrel, LogicalRepRelation *remoterel, AttrMap *attrMap)
Definition relation.c:916
LogicalRepRelation remoterel
LogicalRepRelId remoteid
Bitmapset * attkeys

References Assert, LogicalRepRelation::attkeys, LogicalRepRelation::attnames, AttrMap::attnums, LogicalRepRelMapEntry::attrmap, LogicalRepRelation::atttyps, bms_copy(), fb(), FindLogicalRepLocalIndex(), free_attrmap(), HASH_ENTER, hash_search(), i, LogicalRepRelMapEntry::localindexoid, LogicalRepRelMapEntry::localrel, LogicalRepRelMapEntry::localreloid, LogicalRepRelMapEntry::localrelvalid, logicalrep_partmap_init(), logicalrep_rel_mark_updatable(), LogicalRepPartMap, LogicalRepPartMapContext, make_attrmap(), AttrMap::maplen, memcpy(), MemoryContextSwitchTo(), LogicalRepRelation::natts, LogicalRepRelation::nspname, palloc_array, pstrdup(), RelationGetRelid, LogicalRepRelation::relname, LogicalRepRelation::remoteid, LogicalRepRelMapEntry::remoterel, LogicalRepRelation::replident, and root.

Referenced by apply_handle_tuple_routing().

◆ logicalrep_partmap_init()

static void logicalrep_partmap_init ( void  )
static

Definition at line 605 of file relation.c.

606{
607 HASHCTL ctl;
608
612 "LogicalRepPartMapContext",
614
615 /* Initialize the relation hash table. */
616 ctl.keysize = sizeof(Oid); /* partition OID */
617 ctl.entrysize = sizeof(LogicalRepPartMapEntry);
619
620 LogicalRepPartMap = hash_create("logicalrep partition map cache", 64, &ctl,
622
623 /* Watch for invalidation events. */
625 (Datum) 0);
626}
HTAB * hash_create(const char *tabname, int64 nelem, const HASHCTL *info, int flags)
Definition dynahash.c:360
#define HASH_CONTEXT
Definition hsearch.h:97
#define HASH_ELEM
Definition hsearch.h:90
#define HASH_BLOBS
Definition hsearch.h:92
void CacheRegisterRelcacheCallback(RelcacheCallbackFunction func, Datum arg)
Definition inval.c:1855
MemoryContext CacheMemoryContext
Definition mcxt.c:170
#define AllocSetContextCreate
Definition memutils.h:129
#define ALLOCSET_DEFAULT_SIZES
Definition memutils.h:160
uint64_t Datum
Definition postgres.h:70
tree ctl
Definition radixtree.h:1838
static void logicalrep_partmap_invalidate_cb(Datum arg, Oid reloid)
Definition relation.c:536

References ALLOCSET_DEFAULT_SIZES, AllocSetContextCreate, CacheMemoryContext, CacheRegisterRelcacheCallback(), ctl, HASH_BLOBS, HASH_CONTEXT, hash_create(), HASH_ELEM, logicalrep_partmap_invalidate_cb(), LogicalRepPartMap, and LogicalRepPartMapContext.

Referenced by logicalrep_partition_open().

◆ logicalrep_partmap_invalidate_cb()

static void logicalrep_partmap_invalidate_cb ( Datum  arg,
Oid  reloid 
)
static

Definition at line 536 of file relation.c.

537{
539
540 /* Just to be sure. */
541 if (LogicalRepPartMap == NULL)
542 return;
543
544 if (reloid != InvalidOid)
545 {
546 /*
547 * LogicalRepPartMap is keyed by partition OID, matching with
548 * entry->relmapentry.localreloid (see logicalrep_partition_open), so
549 * we can invalidate via a direct hash lookup.
550 */
551 entry = hash_search(LogicalRepPartMap, &reloid, HASH_FIND, NULL);
552 if (entry != NULL)
553 entry->relmapentry.localrelvalid = false;
554 }
555 else
556 {
557 /* invalidate all cache entries */
558 HASH_SEQ_STATUS status;
559
561
562 while ((entry = (LogicalRepPartMapEntry *) hash_seq_search(&status)) != NULL)
563 entry->relmapentry.localrelvalid = false;
564 }
565}
void * hash_seq_search(HASH_SEQ_STATUS *status)
Definition dynahash.c:1352
void hash_seq_init(HASH_SEQ_STATUS *status, HTAB *hashp)
Definition dynahash.c:1317
@ HASH_FIND
Definition hsearch.h:108
LogicalRepRelMapEntry relmapentry
Definition relation.c:55

References fb(), HASH_FIND, hash_search(), hash_seq_init(), hash_seq_search(), InvalidOid, LogicalRepRelMapEntry::localrelvalid, LogicalRepPartMap, and LogicalRepPartMapEntry::relmapentry.

Referenced by logicalrep_partmap_init().

◆ logicalrep_partmap_reset_relmap()

void logicalrep_partmap_reset_relmap ( LogicalRepRelation remoterel)

Definition at line 578 of file relation.c.

579{
580 HASH_SEQ_STATUS status;
583
584 if (LogicalRepPartMap == NULL)
585 return;
586
588 while ((part_entry = (LogicalRepPartMapEntry *) hash_seq_search(&status)) != NULL)
589 {
590 entry = &part_entry->relmapentry;
591
592 if (entry->remoterel.remoteid != remoterel->remoteid)
593 continue;
594
596
597 memset(entry, 0, sizeof(LogicalRepRelMapEntry));
598 }
599}
static void logicalrep_relmap_free_entry(LogicalRepRelMapEntry *entry)
Definition relation.c:133

References fb(), hash_seq_init(), hash_seq_search(), logicalrep_relmap_free_entry(), LogicalRepPartMap, LogicalRepRelation::remoteid, and LogicalRepRelMapEntry::remoterel.

Referenced by apply_handle_relation().

◆ logicalrep_rel_att_by_name()

static int logicalrep_rel_att_by_name ( LogicalRepRelation remoterel,
const char attname 
)
static

Definition at line 221 of file relation.c.

222{
223 int i;
224
225 for (i = 0; i < remoterel->natts; i++)
226 {
227 if (strcmp(remoterel->attnames[i], attname) == 0)
228 return i;
229 }
230
231 return -1;
232}
NameData attname

References attname, LogicalRepRelation::attnames, fb(), i, and LogicalRepRelation::natts.

Referenced by logicalrep_rel_open().

◆ logicalrep_rel_close()

void logicalrep_rel_close ( LogicalRepRelMapEntry rel,
LOCKMODE  lockmode 
)

Definition at line 517 of file relation.c.

518{
519 table_close(rel->localrel, lockmode);
520 rel->localrel = NULL;
521}
void table_close(Relation relation, LOCKMODE lockmode)
Definition table.c:126

References fb(), LogicalRepRelMapEntry::localrel, and table_close().

Referenced by apply_handle_delete(), apply_handle_insert(), apply_handle_truncate(), apply_handle_update(), and copy_table().

◆ logicalrep_rel_mark_updatable()

static void logicalrep_rel_mark_updatable ( LogicalRepRelMapEntry entry)
static

Definition at line 308 of file relation.c.

309{
311 LogicalRepRelation *remoterel = &entry->remoterel;
312 int i;
313
314 entry->updatable = true;
315
318 /* fallback to PK if no replica identity */
319 if (idkey == NULL)
320 {
323
324 /*
325 * If no replica identity index and no PK, the published table must
326 * have replica identity FULL.
327 */
328 if (idkey == NULL && remoterel->replident != REPLICA_IDENTITY_FULL)
329 entry->updatable = false;
330 }
331
332 i = -1;
333 while ((i = bms_next_member(idkey, i)) >= 0)
334 {
336
340 errmsg("logical replication target relation \"%s.%s\" uses "
341 "system columns in REPLICA IDENTITY index",
342 remoterel->nspname, remoterel->relname)));
343
345
346 if (entry->attrmap->attnums[attnum] < 0 ||
347 !bms_is_member(entry->attrmap->attnums[attnum], remoterel->attkeys))
348 {
349 entry->updatable = false;
350 break;
351 }
352 }
353}
#define AttrNumberIsForUserDefinedAttr(attributeNumber)
Definition attnum.h:41
bool bms_is_member(int x, const Bitmapset *a)
Definition bitmapset.c:645
int errcode(int sqlerrcode)
Definition elog.c:875
#define ERROR
Definition elog.h:40
#define ereport(elevel,...)
Definition elog.h:152
static char * errmsg
int16 attnum
Bitmapset * RelationGetIndexAttrBitmap(Relation relation, IndexAttrBitmapKind attrKind)
Definition relcache.c:5315
@ INDEX_ATTR_BITMAP_PRIMARY_KEY
Definition relcache.h:71
@ INDEX_ATTR_BITMAP_IDENTITY_KEY
Definition relcache.h:72
#define FirstLowInvalidHeapAttributeNumber
Definition sysattr.h:27

References LogicalRepRelation::attkeys, attnum, AttrMap::attnums, LogicalRepRelMapEntry::attrmap, AttrNumberGetAttrOffset, AttrNumberIsForUserDefinedAttr, bms_is_member(), bms_next_member(), ereport, errcode(), errmsg, ERROR, fb(), FirstLowInvalidHeapAttributeNumber, i, INDEX_ATTR_BITMAP_IDENTITY_KEY, INDEX_ATTR_BITMAP_PRIMARY_KEY, LogicalRepRelMapEntry::localrel, LogicalRepRelation::nspname, RelationGetIndexAttrBitmap(), LogicalRepRelation::relname, LogicalRepRelMapEntry::remoterel, LogicalRepRelation::replident, and LogicalRepRelMapEntry::updatable.

Referenced by logicalrep_partition_open(), and logicalrep_rel_open().

◆ logicalrep_rel_open()

LogicalRepRelMapEntry * logicalrep_rel_open ( LogicalRepRelId  remoteid,
LOCKMODE  lockmode 
)

Definition at line 361 of file relation.c.

362{
364 bool found;
365 LogicalRepRelation *remoterel;
366
367 if (LogicalRepRelMap == NULL)
369
370 /* Search for existing entry. */
371 entry = hash_search(LogicalRepRelMap, &remoteid,
372 HASH_FIND, &found);
373
374 if (!found)
375 elog(ERROR, "no relation map entry for remote relation ID %u",
376 remoteid);
377
378 remoterel = &entry->remoterel;
379
380 /* Ensure we don't leak a relcache refcount. */
381 if (entry->localrel)
382 elog(ERROR, "remote relation ID %u is already open", remoteid);
383
384 /*
385 * When opening and locking a relation, pending invalidation messages are
386 * processed which can invalidate the relation. Hence, if the entry is
387 * currently considered valid, try to open the local relation by OID and
388 * see if invalidation ensues.
389 */
390 if (entry->localrelvalid)
391 {
392 entry->localrel = try_table_open(entry->localreloid, lockmode);
393 if (!entry->localrel)
394 {
395 /* Table was renamed or dropped. */
396 entry->localrelvalid = false;
397 }
398 else if (!entry->localrelvalid)
399 {
400 /* Note we release the no-longer-useful lock here. */
401 table_close(entry->localrel, lockmode);
402 entry->localrel = NULL;
403 }
404 }
405
406 /*
407 * If the entry has been marked invalid since we last had lock on it,
408 * re-open the local relation by name and rebuild all derived data.
409 */
410 if (!entry->localrelvalid)
411 {
412 Oid relid;
413 TupleDesc desc;
415 int i;
418
419 /* Release the no-longer-useful attrmap, if any. */
420 if (entry->attrmap)
421 {
422 free_attrmap(entry->attrmap);
423 entry->attrmap = NULL;
424 }
425
426 /* Try to find and lock the relation by name. */
427 relid = RangeVarGetRelid(makeRangeVar(remoterel->nspname,
428 remoterel->relname, -1),
429 lockmode, true);
430 if (!OidIsValid(relid))
433 errmsg("logical replication target relation \"%s.%s\" does not exist",
434 remoterel->nspname, remoterel->relname)));
435 entry->localrel = table_open(relid, NoLock);
436 entry->localreloid = relid;
437
438 /* Check for supported relkind. */
440 remoterel->relkind,
441 remoterel->nspname, remoterel->relname);
442
443 /*
444 * Build the mapping of local attribute numbers to remote attribute
445 * numbers and validate that we don't miss any replicated columns as
446 * that would result in potentially unwanted data loss.
447 */
448 desc = RelationGetDescr(entry->localrel);
450 entry->attrmap = make_attrmap(desc->natts);
452
453 /* check and report missing attrs, if any */
454 missingatts = bms_add_range(NULL, 0, remoterel->natts - 1);
455 for (i = 0; i < desc->natts; i++)
456 {
457 int attnum;
458 Form_pg_attribute attr = TupleDescAttr(desc, i);
459
460 if (attr->attisdropped)
461 {
462 entry->attrmap->attnums[i] = -1;
463 continue;
464 }
465
467 NameStr(attr->attname));
468
469 entry->attrmap->attnums[i] = attnum;
470 if (attnum >= 0)
471 {
472 /* Remember which subscriber columns are generated. */
473 if (attr->attgenerated)
475
477 }
478 }
479
482
483 /* be tidy */
486
487 /*
488 * Set if the table's replica identity is enough to apply
489 * update/delete.
490 */
492
493 /*
494 * Finding a usable index is an infrequent task. It occurs when an
495 * operation is first performed on the relation, or after invalidation
496 * of the relation cache entry (such as ANALYZE or CREATE/DROP index
497 * on the relation).
498 */
499 entry->localindexoid = FindLogicalRepLocalIndex(entry->localrel, remoterel,
500 entry->attrmap);
501
502 entry->localrelvalid = true;
503 }
504
505 if (entry->state != SUBREL_STATE_READY)
507 entry->localreloid,
508 &entry->statelsn);
509
510 return entry;
511}
Subscription * MySubscription
Definition worker.c:484
Bitmapset * bms_add_range(Bitmapset *a, int lower, int upper)
Definition bitmapset.c:1138
Bitmapset * bms_del_member(Bitmapset *a, int x)
Definition bitmapset.c:987
void bms_free(Bitmapset *a)
Definition bitmapset.c:240
Bitmapset * bms_add_member(Bitmapset *a, int x)
Definition bitmapset.c:934
#define NameStr(name)
Definition c.h:894
#define elog(elevel,...)
Definition elog.h:228
void CheckSubscriptionRelkind(char localrelkind, char remoterelkind, const char *nspname, const char *relname)
#define NoLock
Definition lockdefs.h:34
RangeVar * makeRangeVar(char *schemaname, char *relname, int location)
Definition makefuncs.c:473
#define RangeVarGetRelid(relation, lockmode, missing_ok)
Definition namespace.h:98
FormData_pg_attribute * Form_pg_attribute
char GetSubscriptionRelState(Oid subid, Oid relid, XLogRecPtr *sublsn)
#define RelationGetDescr(relation)
Definition rel.h:542
static void logicalrep_report_missing_or_gen_attrs(LogicalRepRelation *remoterel, Bitmapset *missingatts, Bitmapset *generatedatts)
Definition relation.c:267
static HTAB * LogicalRepRelMap
Definition relation.c:37
static MemoryContext LogicalRepRelMapContext
Definition relation.c:35
static void logicalrep_relmap_init(void)
Definition relation.c:106
static int logicalrep_rel_att_by_name(LogicalRepRelation *remoterel, const char *attname)
Definition relation.c:221
Relation try_table_open(Oid relationId, LOCKMODE lockmode)
Definition table.c:60
Relation table_open(Oid relationId, LOCKMODE lockmode)
Definition table.c:40

References attnum, AttrMap::attnums, LogicalRepRelMapEntry::attrmap, bms_add_member(), bms_add_range(), bms_del_member(), bms_free(), CheckSubscriptionRelkind(), elog, ereport, errcode(), errmsg, ERROR, fb(), FindLogicalRepLocalIndex(), free_attrmap(), GetSubscriptionRelState(), HASH_FIND, hash_search(), i, LogicalRepRelMapEntry::localindexoid, LogicalRepRelMapEntry::localrel, LogicalRepRelMapEntry::localreloid, LogicalRepRelMapEntry::localrelvalid, logicalrep_rel_att_by_name(), logicalrep_rel_mark_updatable(), logicalrep_relmap_init(), logicalrep_report_missing_or_gen_attrs(), LogicalRepRelMap, LogicalRepRelMapContext, make_attrmap(), makeRangeVar(), MemoryContextSwitchTo(), MySubscription, NameStr, TupleDescData::natts, LogicalRepRelation::natts, NoLock, LogicalRepRelation::nspname, Subscription::oid, OidIsValid, RangeVarGetRelid, RelationData::rd_rel, RelationGetDescr, LogicalRepRelation::relkind, LogicalRepRelation::relname, LogicalRepRelMapEntry::remoterel, LogicalRepRelMapEntry::state, LogicalRepRelMapEntry::statelsn, table_close(), table_open(), try_table_open(), and TupleDescAttr().

Referenced by apply_handle_delete(), apply_handle_insert(), apply_handle_truncate(), apply_handle_update(), and copy_table().

◆ logicalrep_relmap_free_entry()

static void logicalrep_relmap_free_entry ( LogicalRepRelMapEntry entry)
static

Definition at line 133 of file relation.c.

134{
135 LogicalRepRelation *remoterel;
136
137 remoterel = &entry->remoterel;
138
139 pfree(remoterel->nspname);
140 pfree(remoterel->relname);
141
142 if (remoterel->natts > 0)
143 {
144 int i;
145
146 for (i = 0; i < remoterel->natts; i++)
147 pfree(remoterel->attnames[i]);
148
149 pfree(remoterel->attnames);
150 pfree(remoterel->atttyps);
151 }
152 bms_free(remoterel->attkeys);
153
154 if (entry->attrmap)
155 free_attrmap(entry->attrmap);
156}
void pfree(void *pointer)
Definition mcxt.c:1619

References LogicalRepRelation::attkeys, LogicalRepRelation::attnames, LogicalRepRelMapEntry::attrmap, LogicalRepRelation::atttyps, bms_free(), free_attrmap(), i, LogicalRepRelation::natts, LogicalRepRelation::nspname, pfree(), LogicalRepRelation::relname, and LogicalRepRelMapEntry::remoterel.

Referenced by logicalrep_partmap_reset_relmap(), and logicalrep_relmap_update().

◆ logicalrep_relmap_init()

static void logicalrep_relmap_init ( void  )
static

Definition at line 106 of file relation.c.

107{
108 HASHCTL ctl;
109
113 "LogicalRepRelMapContext",
115
116 /* Initialize the relation hash table. */
117 ctl.keysize = sizeof(LogicalRepRelId);
118 ctl.entrysize = sizeof(LogicalRepRelMapEntry);
120
121 LogicalRepRelMap = hash_create("logicalrep relation map cache", 128, &ctl,
123
124 /* Watch for invalidation events. */
126 (Datum) 0);
127}
uint32 LogicalRepRelId
static void logicalrep_relmap_invalidate_cb(Datum arg, Oid reloid)
Definition relation.c:65

References ALLOCSET_DEFAULT_SIZES, AllocSetContextCreate, CacheMemoryContext, CacheRegisterRelcacheCallback(), ctl, HASH_BLOBS, HASH_CONTEXT, hash_create(), HASH_ELEM, logicalrep_relmap_invalidate_cb(), LogicalRepRelMap, and LogicalRepRelMapContext.

Referenced by logicalrep_rel_open(), and logicalrep_relmap_update().

◆ logicalrep_relmap_invalidate_cb()

static void logicalrep_relmap_invalidate_cb ( Datum  arg,
Oid  reloid 
)
static

Definition at line 65 of file relation.c.

66{
68
69 /* Just to be sure. */
71 return;
72
73 if (reloid != InvalidOid)
74 {
75 HASH_SEQ_STATUS status;
76
78
79 /* TODO, use inverse lookup hashtable? */
80 while ((entry = (LogicalRepRelMapEntry *) hash_seq_search(&status)) != NULL)
81 {
82 if (entry->localreloid == reloid)
83 {
84 entry->localrelvalid = false;
85 hash_seq_term(&status);
86 break;
87 }
88 }
89 }
90 else
91 {
92 /* invalidate all cache entries */
93 HASH_SEQ_STATUS status;
94
96
97 while ((entry = (LogicalRepRelMapEntry *) hash_seq_search(&status)) != NULL)
98 entry->localrelvalid = false;
99 }
100}
void hash_seq_term(HASH_SEQ_STATUS *status)
Definition dynahash.c:1444

References fb(), hash_seq_init(), hash_seq_search(), hash_seq_term(), InvalidOid, LogicalRepRelMapEntry::localreloid, LogicalRepRelMapEntry::localrelvalid, and LogicalRepRelMap.

Referenced by logicalrep_relmap_init().

◆ logicalrep_relmap_update()

void logicalrep_relmap_update ( LogicalRepRelation remoterel)

Definition at line 165 of file relation.c.

166{
169 bool found;
170 int i;
171
172 if (LogicalRepRelMap == NULL)
174
175 /*
176 * HASH_ENTER returns the existing entry if present or creates a new one.
177 */
178 entry = hash_search(LogicalRepRelMap, &remoterel->remoteid,
179 HASH_ENTER, &found);
180
181 if (found)
183
184 memset(entry, 0, sizeof(LogicalRepRelMapEntry));
185
186 /* Make cached copy of the data */
188 entry->remoterel.remoteid = remoterel->remoteid;
189 entry->remoterel.nspname = pstrdup(remoterel->nspname);
190 entry->remoterel.relname = pstrdup(remoterel->relname);
191 entry->remoterel.natts = remoterel->natts;
192 entry->remoterel.attnames = palloc_array(char *, remoterel->natts);
193 entry->remoterel.atttyps = palloc_array(Oid, remoterel->natts);
194 for (i = 0; i < remoterel->natts; i++)
195 {
196 entry->remoterel.attnames[i] = pstrdup(remoterel->attnames[i]);
197 entry->remoterel.atttyps[i] = remoterel->atttyps[i];
198 }
199 entry->remoterel.replident = remoterel->replident;
200
201 /*
202 * XXX The walsender currently does not transmit the relkind of the remote
203 * relation when replicating changes. Since we support replicating only
204 * table changes at present, we default to initializing relkind as
205 * RELKIND_RELATION. This is needed in CheckSubscriptionRelkind() to check
206 * if the publisher and subscriber relation kinds are compatible.
207 */
208 entry->remoterel.relkind =
209 (remoterel->relkind == 0) ? RELKIND_RELATION : remoterel->relkind;
210
211 entry->remoterel.attkeys = bms_copy(remoterel->attkeys);
213}

References LogicalRepRelation::attkeys, LogicalRepRelation::attnames, LogicalRepRelation::atttyps, bms_copy(), fb(), HASH_ENTER, hash_search(), i, logicalrep_relmap_free_entry(), logicalrep_relmap_init(), LogicalRepRelMap, LogicalRepRelMapContext, MemoryContextSwitchTo(), LogicalRepRelation::natts, LogicalRepRelation::nspname, palloc_array, pstrdup(), LogicalRepRelation::relkind, LogicalRepRelation::relname, LogicalRepRelation::remoteid, LogicalRepRelMapEntry::remoterel, and LogicalRepRelation::replident.

Referenced by apply_handle_relation(), and copy_table().

◆ logicalrep_report_missing_or_gen_attrs()

static void logicalrep_report_missing_or_gen_attrs ( LogicalRepRelation remoterel,
Bitmapset missingatts,
Bitmapset generatedatts 
)
static

Definition at line 267 of file relation.c.

270{
274 errmsg_plural("logical replication target relation \"%s.%s\" is missing replicated column: %s",
275 "logical replication target relation \"%s.%s\" is missing replicated columns: %s",
277 remoterel->nspname,
278 remoterel->relname,
279 logicalrep_get_attrs_str(remoterel,
280 missingatts)));
281
285 errmsg_plural("logical replication target relation \"%s.%s\" has incompatible generated column: %s",
286 "logical replication target relation \"%s.%s\" has incompatible generated columns: %s",
288 remoterel->nspname,
289 remoterel->relname,
290 logicalrep_get_attrs_str(remoterel,
291 generatedatts)));
292}
int bms_num_members(const Bitmapset *a)
Definition bitmapset.c:879
int int int errmsg_plural(const char *fmt_singular, const char *fmt_plural, unsigned long n,...) pg_attribute_printf(1
static char * logicalrep_get_attrs_str(LogicalRepRelation *remoterel, Bitmapset *atts)
Definition relation.c:239

References bms_is_empty, bms_num_members(), ereport, errcode(), errmsg_plural(), ERROR, fb(), logicalrep_get_attrs_str(), LogicalRepRelation::nspname, and LogicalRepRelation::relname.

Referenced by logicalrep_rel_open().

Variable Documentation

◆ LogicalRepPartMap

◆ LogicalRepPartMapContext

MemoryContext LogicalRepPartMapContext = NULL
static

Definition at line 50 of file relation.c.

Referenced by logicalrep_partition_open(), and logicalrep_partmap_init().

◆ LogicalRepRelMap

HTAB* LogicalRepRelMap = NULL
static

◆ LogicalRepRelMapContext

MemoryContext LogicalRepRelMapContext = NULL
static