PostgreSQL Source Code git master
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 char * logicalrep_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 904 of file relation.c.

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

References 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 775 of file relation.c.

776{
777 List *idxlist = RelationGetIndexList(localrel);
778
779 foreach_oid(idxoid, idxlist)
780 {
781 bool isUsableIdx;
782 Relation idxRel;
783
784 idxRel = index_open(idxoid, AccessShareLock);
785 isUsableIdx = IsIndexUsableForReplicaIdentityFull(idxRel, attrmap);
787
788 /* Return the first eligible index found */
789 if (isUsableIdx)
790 return idxoid;
791 }
792
793 return InvalidOid;
794}
void index_close(Relation relation, LOCKMODE lockmode)
Definition: indexam.c:177
Relation index_open(Oid relationId, LOCKMODE lockmode)
Definition: indexam.c:133
#define AccessShareLock
Definition: lockdefs.h:36
#define foreach_oid(var, lst)
Definition: pg_list.h:471
List * RelationGetIndexList(Relation relation)
Definition: relcache.c:4756
bool IsIndexUsableForReplicaIdentityFull(Relation idxrel, AttrMap *attrmap)
Definition: relation.c:820
Definition: pg_list.h:54

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

Referenced by FindLogicalRepLocalIndex().

◆ GetRelationIdentityOrPK()

Oid GetRelationIdentityOrPK ( Relation  rel)

Definition at line 887 of file relation.c.

888{
889 Oid idxoid;
890
891 idxoid = RelationGetReplicaIndex(rel);
892
893 if (!OidIsValid(idxoid))
894 idxoid = RelationGetPrimaryKeyIndex(rel, false);
895
896 return idxoid;
897}
Oid RelationGetPrimaryKeyIndex(Relation relation, bool deferrable_ok)
Definition: relcache.c:4967
Oid RelationGetReplicaIndex(Relation relation)
Definition: relcache.c:4992

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

Referenced by build_tuple_value_details(), check_relation_updatable(), FindLogicalRepLocalIndex(), FindReplTupleInLocalRel(), and RelationFindReplTupleByIndex().

◆ IsIndexUsableForReplicaIdentityFull()

bool IsIndexUsableForReplicaIdentityFull ( Relation  idxrel,
AttrMap attrmap 
)

Definition at line 820 of file relation.c.

821{
822 AttrNumber keycol;
823 oidvector *indclass;
824
825 /* The index must not be a partial index */
826 if (!heap_attisnull(idxrel->rd_indextuple, Anum_pg_index_indpred, NULL))
827 return false;
828
829 Assert(idxrel->rd_index->indnatts >= 1);
830
831 indclass = (oidvector *) DatumGetPointer(SysCacheGetAttrNotNull(INDEXRELID,
832 idxrel->rd_indextuple,
833 Anum_pg_index_indclass));
834
835 /* Ensure that the index has a valid equal strategy for each key column */
836 for (int i = 0; i < idxrel->rd_index->indnkeyatts; i++)
837 {
839 return false;
840 }
841
842 /*
843 * For indexes other than PK and REPLICA IDENTITY, we need to match the
844 * local and remote tuples. The equality routine tuples_equal() cannot
845 * accept a data type where the type cache cannot provide an equality
846 * operator.
847 */
848 for (int i = 0; i < idxrel->rd_att->natts; i++)
849 {
850 TypeCacheEntry *typentry;
851
852 typentry = lookup_type_cache(TupleDescAttr(idxrel->rd_att, i)->atttypid, TYPECACHE_EQ_OPR_FINFO);
853 if (!OidIsValid(typentry->eq_opr_finfo.fn_oid))
854 return false;
855 }
856
857 /* The leftmost index field must not be an expression */
858 keycol = idxrel->rd_index->indkey.values[0];
859 if (!AttributeNumberIsValid(keycol))
860 return false;
861
862 /*
863 * And the leftmost index field must reference the remote relation column.
864 * This is because if it doesn't, the sequential scan is favorable over
865 * index scan in most cases.
866 */
867 if (attrmap->maplen <= AttrNumberGetAttrOffset(keycol) ||
868 attrmap->attnums[AttrNumberGetAttrOffset(keycol)] < 0)
869 return false;
870
871 /*
872 * The given index access method must implement "amgettuple", which will
873 * be used later to fetch the tuples. See RelationFindReplTupleByIndex().
874 */
875 if (GetIndexAmRoutineByAmId(idxrel->rd_rel->relam, false)->amgettuple == NULL)
876 return false;
877
878 return true;
879}
IndexAmRoutine * GetIndexAmRoutineByAmId(Oid amoid, bool noerror)
Definition: amapi.c:56
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:815
StrategyNumber get_equal_strategy_number(Oid opclass)
bool heap_attisnull(HeapTuple tup, int attnum, TupleDesc tupleDesc)
Definition: heaptuple.c:456
int i
Definition: isn.c:72
static Pointer DatumGetPointer(Datum X)
Definition: postgres.h:317
#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:294
struct HeapTupleData * rd_indextuple
Definition: rel.h:194
TupleDesc rd_att
Definition: rel.h:112
Form_pg_index rd_index
Definition: rel.h:192
FmgrInfo eq_opr_finfo
Definition: typcache.h:75
Definition: c.h:683
Oid values[FLEXIBLE_ARRAY_MEMBER]
Definition: c.h:690
Datum SysCacheGetAttrNotNull(int cacheId, HeapTuple tup, AttrNumber attributeNumber)
Definition: syscache.c:631
static FormData_pg_attribute * TupleDescAttr(TupleDesc tupdesc, int i)
Definition: tupdesc.h:153
TypeCacheEntry * lookup_type_cache(Oid type_id, int flags)
Definition: typcache.c:386
#define TYPECACHE_EQ_OPR_FINFO
Definition: typcache.h:142

References IndexAmRoutine::amgettuple, Assert, AttrMap::attnums, AttributeNumberIsValid, AttrNumberGetAttrOffset, DatumGetPointer(), TypeCacheEntry::eq_opr_finfo, FmgrInfo::fn_oid, get_equal_strategy_number(), GetIndexAmRoutineByAmId(), heap_attisnull(), i, InvalidStrategy, lookup_type_cache(), AttrMap::maplen, TupleDescData::natts, OidIsValid, RelationData::rd_att, RelationData::rd_index, RelationData::rd_indextuple, RelationData::rd_rel, SysCacheGetAttrNotNull(), TupleDescAttr(), TYPECACHE_EQ_OPR_FINFO, and oidvector::values.

Referenced by FindReplTupleInLocalRel(), and FindUsableIndexForReplicaIdentityFull().

◆ logicalrep_get_attrs_str()

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

Definition at line 226 of file relation.c.

227{
228 StringInfoData attsbuf;
229 int attcnt = 0;
230 int i = -1;
231
232 Assert(!bms_is_empty(atts));
233
234 initStringInfo(&attsbuf);
235
236 while ((i = bms_next_member(atts, i)) >= 0)
237 {
238 attcnt++;
239 if (attcnt > 1)
240 appendStringInfo(&attsbuf, _(", "));
241
242 appendStringInfo(&attsbuf, _("\"%s\""), remoterel->attnames[i]);
243 }
244
245 return attsbuf.data;
246}
int bms_next_member(const Bitmapset *a, int prevbit)
Definition: bitmapset.c:1306
#define bms_is_empty(a)
Definition: bitmapset.h:118
#define _(x)
Definition: elog.c:90
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(), StringInfoData::data, 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 632 of file relation.c.

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

References LogicalRepRelation::attkeys, LogicalRepRelation::attnames, AttrMap::attnums, LogicalRepRelMapEntry::attrmap, LogicalRepRelation::atttyps, bms_copy(), 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, MemoryContextSwitchTo(), LogicalRepRelation::natts, LogicalRepRelation::nspname, palloc(), LogicalRepPartMapEntry::partoid, pstrdup(), RelationGetRelid, LogicalRepPartMapEntry::relmapentry, 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 597 of file relation.c.

598{
599 HASHCTL ctl;
600
604 "LogicalRepPartMapContext",
606
607 /* Initialize the relation hash table. */
608 ctl.keysize = sizeof(Oid); /* partition OID */
609 ctl.entrysize = sizeof(LogicalRepPartMapEntry);
611
612 LogicalRepPartMap = hash_create("logicalrep partition map cache", 64, &ctl,
614
615 /* Watch for invalidation events. */
617 (Datum) 0);
618}
HTAB * hash_create(const char *tabname, long nelem, const HASHCTL *info, int flags)
Definition: dynahash.c:352
#define HASH_CONTEXT
Definition: hsearch.h:102
#define HASH_ELEM
Definition: hsearch.h:95
#define HASH_BLOBS
Definition: hsearch.h:97
void CacheRegisterRelcacheCallback(RelcacheCallbackFunction func, Datum arg)
Definition: inval.c:1746
MemoryContext CacheMemoryContext
Definition: mcxt.c:152
#define AllocSetContextCreate
Definition: memutils.h:129
#define ALLOCSET_DEFAULT_SIZES
Definition: memutils.h:160
uintptr_t Datum
Definition: postgres.h:69
tree ctl
Definition: radixtree.h:1838
struct LogicalRepPartMapEntry LogicalRepPartMapEntry
static void logicalrep_partmap_invalidate_cb(Datum arg, Oid reloid)
Definition: relation.c:522

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 522 of file relation.c.

523{
525
526 /* Just to be sure. */
527 if (LogicalRepPartMap == NULL)
528 return;
529
530 if (reloid != InvalidOid)
531 {
532 HASH_SEQ_STATUS status;
533
535
536 /* TODO, use inverse lookup hashtable? */
537 while ((entry = (LogicalRepPartMapEntry *) hash_seq_search(&status)) != NULL)
538 {
539 if (entry->relmapentry.localreloid == reloid)
540 {
541 entry->relmapentry.localrelvalid = false;
542 hash_seq_term(&status);
543 break;
544 }
545 }
546 }
547 else
548 {
549 /* invalidate all cache entries */
550 HASH_SEQ_STATUS status;
551
553
554 while ((entry = (LogicalRepPartMapEntry *) hash_seq_search(&status)) != NULL)
555 entry->relmapentry.localrelvalid = false;
556 }
557}
void * hash_seq_search(HASH_SEQ_STATUS *status)
Definition: dynahash.c:1420
void hash_seq_term(HASH_SEQ_STATUS *status)
Definition: dynahash.c:1514
void hash_seq_init(HASH_SEQ_STATUS *status, HTAB *hashp)
Definition: dynahash.c:1385

References hash_seq_init(), hash_seq_search(), hash_seq_term(), InvalidOid, LogicalRepRelMapEntry::localreloid, 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 570 of file relation.c.

571{
572 HASH_SEQ_STATUS status;
573 LogicalRepPartMapEntry *part_entry;
575
576 if (LogicalRepPartMap == NULL)
577 return;
578
580 while ((part_entry = (LogicalRepPartMapEntry *) hash_seq_search(&status)) != NULL)
581 {
582 entry = &part_entry->relmapentry;
583
584 if (entry->remoterel.remoteid != remoterel->remoteid)
585 continue;
586
588
589 memset(entry, 0, sizeof(LogicalRepRelMapEntry));
590 }
591}
static void logicalrep_relmap_free_entry(LogicalRepRelMapEntry *entry)
Definition: relation.c:131

References hash_seq_init(), hash_seq_search(), logicalrep_relmap_free_entry(), LogicalRepPartMap, LogicalRepPartMapEntry::relmapentry, 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 208 of file relation.c.

209{
210 int i;
211
212 for (i = 0; i < remoterel->natts; i++)
213 {
214 if (strcmp(remoterel->attnames[i], attname) == 0)
215 return i;
216 }
217
218 return -1;
219}
NameData attname
Definition: pg_attribute.h:41

References attname, LogicalRepRelation::attnames, i, and LogicalRepRelation::natts.

Referenced by logicalrep_rel_open().

◆ logicalrep_rel_close()

void logicalrep_rel_close ( LogicalRepRelMapEntry rel,
LOCKMODE  lockmode 
)

Definition at line 503 of file relation.c.

504{
505 table_close(rel->localrel, lockmode);
506 rel->localrel = NULL;
507}
void table_close(Relation relation, LOCKMODE lockmode)
Definition: table.c:126

References 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 295 of file relation.c.

296{
297 Bitmapset *idkey;
298 LogicalRepRelation *remoterel = &entry->remoterel;
299 int i;
300
301 entry->updatable = true;
302
305 /* fallback to PK if no replica identity */
306 if (idkey == NULL)
307 {
310
311 /*
312 * If no replica identity index and no PK, the published table must
313 * have replica identity FULL.
314 */
315 if (idkey == NULL && remoterel->replident != REPLICA_IDENTITY_FULL)
316 entry->updatable = false;
317 }
318
319 i = -1;
320 while ((i = bms_next_member(idkey, i)) >= 0)
321 {
323
326 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
327 errmsg("logical replication target relation \"%s.%s\" uses "
328 "system columns in REPLICA IDENTITY index",
329 remoterel->nspname, remoterel->relname)));
330
332
333 if (entry->attrmap->attnums[attnum] < 0 ||
334 !bms_is_member(entry->attrmap->attnums[attnum], remoterel->attkeys))
335 {
336 entry->updatable = false;
337 break;
338 }
339 }
340}
#define AttrNumberIsForUserDefinedAttr(attributeNumber)
Definition: attnum.h:41
bool bms_is_member(int x, const Bitmapset *a)
Definition: bitmapset.c:510
int errcode(int sqlerrcode)
Definition: elog.c:853
int errmsg(const char *fmt,...)
Definition: elog.c:1070
#define ERROR
Definition: elog.h:39
#define ereport(elevel,...)
Definition: elog.h:149
int16 attnum
Definition: pg_attribute.h:74
Bitmapset * RelationGetIndexAttrBitmap(Relation relation, IndexAttrBitmapKind attrKind)
Definition: relcache.c:5223
@ INDEX_ATTR_BITMAP_PRIMARY_KEY
Definition: relcache.h:62
@ INDEX_ATTR_BITMAP_IDENTITY_KEY
Definition: relcache.h:63
#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, 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 348 of file relation.c.

349{
351 bool found;
352 LogicalRepRelation *remoterel;
353
354 if (LogicalRepRelMap == NULL)
356
357 /* Search for existing entry. */
358 entry = hash_search(LogicalRepRelMap, &remoteid,
359 HASH_FIND, &found);
360
361 if (!found)
362 elog(ERROR, "no relation map entry for remote relation ID %u",
363 remoteid);
364
365 remoterel = &entry->remoterel;
366
367 /* Ensure we don't leak a relcache refcount. */
368 if (entry->localrel)
369 elog(ERROR, "remote relation ID %u is already open", remoteid);
370
371 /*
372 * When opening and locking a relation, pending invalidation messages are
373 * processed which can invalidate the relation. Hence, if the entry is
374 * currently considered valid, try to open the local relation by OID and
375 * see if invalidation ensues.
376 */
377 if (entry->localrelvalid)
378 {
379 entry->localrel = try_table_open(entry->localreloid, lockmode);
380 if (!entry->localrel)
381 {
382 /* Table was renamed or dropped. */
383 entry->localrelvalid = false;
384 }
385 else if (!entry->localrelvalid)
386 {
387 /* Note we release the no-longer-useful lock here. */
388 table_close(entry->localrel, lockmode);
389 entry->localrel = NULL;
390 }
391 }
392
393 /*
394 * If the entry has been marked invalid since we last had lock on it,
395 * re-open the local relation by name and rebuild all derived data.
396 */
397 if (!entry->localrelvalid)
398 {
399 Oid relid;
400 TupleDesc desc;
401 MemoryContext oldctx;
402 int i;
403 Bitmapset *missingatts;
404 Bitmapset *generatedattrs = NULL;
405
406 /* Release the no-longer-useful attrmap, if any. */
407 if (entry->attrmap)
408 {
409 free_attrmap(entry->attrmap);
410 entry->attrmap = NULL;
411 }
412
413 /* Try to find and lock the relation by name. */
414 relid = RangeVarGetRelid(makeRangeVar(remoterel->nspname,
415 remoterel->relname, -1),
416 lockmode, true);
417 if (!OidIsValid(relid))
419 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
420 errmsg("logical replication target relation \"%s.%s\" does not exist",
421 remoterel->nspname, remoterel->relname)));
422 entry->localrel = table_open(relid, NoLock);
423 entry->localreloid = relid;
424
425 /* Check for supported relkind. */
427 remoterel->nspname, remoterel->relname);
428
429 /*
430 * Build the mapping of local attribute numbers to remote attribute
431 * numbers and validate that we don't miss any replicated columns as
432 * that would result in potentially unwanted data loss.
433 */
434 desc = RelationGetDescr(entry->localrel);
436 entry->attrmap = make_attrmap(desc->natts);
437 MemoryContextSwitchTo(oldctx);
438
439 /* check and report missing attrs, if any */
440 missingatts = bms_add_range(NULL, 0, remoterel->natts - 1);
441 for (i = 0; i < desc->natts; i++)
442 {
443 int attnum;
444 Form_pg_attribute attr = TupleDescAttr(desc, i);
445
446 if (attr->attisdropped)
447 {
448 entry->attrmap->attnums[i] = -1;
449 continue;
450 }
451
453 NameStr(attr->attname));
454
455 entry->attrmap->attnums[i] = attnum;
456 if (attnum >= 0)
457 {
458 /* Remember which subscriber columns are generated. */
459 if (attr->attgenerated)
460 generatedattrs = bms_add_member(generatedattrs, attnum);
461
462 missingatts = bms_del_member(missingatts, attnum);
463 }
464 }
465
466 logicalrep_report_missing_or_gen_attrs(remoterel, missingatts,
467 generatedattrs);
468
469 /* be tidy */
470 bms_free(generatedattrs);
471 bms_free(missingatts);
472
473 /*
474 * Set if the table's replica identity is enough to apply
475 * update/delete.
476 */
478
479 /*
480 * Finding a usable index is an infrequent task. It occurs when an
481 * operation is first performed on the relation, or after invalidation
482 * of the relation cache entry (such as ANALYZE or CREATE/DROP index
483 * on the relation).
484 */
485 entry->localindexoid = FindLogicalRepLocalIndex(entry->localrel, remoterel,
486 entry->attrmap);
487
488 entry->localrelvalid = true;
489 }
490
491 if (entry->state != SUBREL_STATE_READY)
493 entry->localreloid,
494 &entry->statelsn);
495
496 return entry;
497}
Subscription * MySubscription
Definition: worker.c:299
Bitmapset * bms_add_range(Bitmapset *a, int lower, int upper)
Definition: bitmapset.c:1019
Bitmapset * bms_del_member(Bitmapset *a, int x)
Definition: bitmapset.c:868
void bms_free(Bitmapset *a)
Definition: bitmapset.c:239
Bitmapset * bms_add_member(Bitmapset *a, int x)
Definition: bitmapset.c:815
#define NameStr(name)
Definition: c.h:703
#define elog(elevel,...)
Definition: elog.h:225
void CheckSubscriptionRelkind(char relkind, const char *nspname, const char *relname)
@ HASH_FIND
Definition: hsearch.h:113
#define NoLock
Definition: lockdefs.h:34
RangeVar * makeRangeVar(char *schemaname, char *relname, int location)
Definition: makefuncs.c:426
#define RangeVarGetRelid(relation, lockmode, missing_ok)
Definition: namespace.h:80
FormData_pg_attribute * Form_pg_attribute
Definition: pg_attribute.h:200
char GetSubscriptionRelState(Oid subid, Oid relid, XLogRecPtr *sublsn)
#define RelationGetDescr(relation)
Definition: rel.h:531
static void logicalrep_report_missing_or_gen_attrs(LogicalRepRelation *remoterel, Bitmapset *missingatts, Bitmapset *generatedatts)
Definition: relation.c:254
static HTAB * LogicalRepRelMap
Definition: relation.c:35
static MemoryContext LogicalRepRelMapContext
Definition: relation.c:33
static void logicalrep_relmap_init(void)
Definition: relation.c:104
static int logicalrep_rel_att_by_name(LogicalRepRelation *remoterel, const char *attname)
Definition: relation.c:208
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, 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::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 131 of file relation.c.

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

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 104 of file relation.c.

105{
106 HASHCTL ctl;
107
111 "LogicalRepRelMapContext",
113
114 /* Initialize the relation hash table. */
115 ctl.keysize = sizeof(LogicalRepRelId);
116 ctl.entrysize = sizeof(LogicalRepRelMapEntry);
118
119 LogicalRepRelMap = hash_create("logicalrep relation map cache", 128, &ctl,
121
122 /* Watch for invalidation events. */
124 (Datum) 0);
125}
uint32 LogicalRepRelId
Definition: logicalproto.h:101
struct LogicalRepRelMapEntry LogicalRepRelMapEntry
static void logicalrep_relmap_invalidate_cb(Datum arg, Oid reloid)
Definition: relation.c:63

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 63 of file relation.c.

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

References 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 163 of file relation.c.

164{
165 MemoryContext oldctx;
167 bool found;
168 int i;
169
170 if (LogicalRepRelMap == NULL)
172
173 /*
174 * HASH_ENTER returns the existing entry if present or creates a new one.
175 */
176 entry = hash_search(LogicalRepRelMap, &remoterel->remoteid,
177 HASH_ENTER, &found);
178
179 if (found)
181
182 memset(entry, 0, sizeof(LogicalRepRelMapEntry));
183
184 /* Make cached copy of the data */
186 entry->remoterel.remoteid = remoterel->remoteid;
187 entry->remoterel.nspname = pstrdup(remoterel->nspname);
188 entry->remoterel.relname = pstrdup(remoterel->relname);
189 entry->remoterel.natts = remoterel->natts;
190 entry->remoterel.attnames = palloc(remoterel->natts * sizeof(char *));
191 entry->remoterel.atttyps = palloc(remoterel->natts * sizeof(Oid));
192 for (i = 0; i < remoterel->natts; i++)
193 {
194 entry->remoterel.attnames[i] = pstrdup(remoterel->attnames[i]);
195 entry->remoterel.atttyps[i] = remoterel->atttyps[i];
196 }
197 entry->remoterel.replident = remoterel->replident;
198 entry->remoterel.attkeys = bms_copy(remoterel->attkeys);
199 MemoryContextSwitchTo(oldctx);
200}

References LogicalRepRelation::attkeys, LogicalRepRelation::attnames, LogicalRepRelation::atttyps, bms_copy(), HASH_ENTER, hash_search(), i, logicalrep_relmap_free_entry(), logicalrep_relmap_init(), LogicalRepRelMap, LogicalRepRelMapContext, MemoryContextSwitchTo(), LogicalRepRelation::natts, LogicalRepRelation::nspname, palloc(), pstrdup(), 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 254 of file relation.c.

257{
258 if (!bms_is_empty(missingatts))
260 errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
261 errmsg_plural("logical replication target relation \"%s.%s\" is missing replicated column: %s",
262 "logical replication target relation \"%s.%s\" is missing replicated columns: %s",
263 bms_num_members(missingatts),
264 remoterel->nspname,
265 remoterel->relname,
266 logicalrep_get_attrs_str(remoterel,
267 missingatts)));
268
269 if (!bms_is_empty(generatedatts))
271 errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
272 errmsg_plural("logical replication target relation \"%s.%s\" has incompatible generated column: %s",
273 "logical replication target relation \"%s.%s\" has incompatible generated columns: %s",
274 bms_num_members(generatedatts),
275 remoterel->nspname,
276 remoterel->relname,
277 logicalrep_get_attrs_str(remoterel,
278 generatedatts)));
279}
int bms_num_members(const Bitmapset *a)
Definition: bitmapset.c:751
int errmsg_plural(const char *fmt_singular, const char *fmt_plural, unsigned long n,...)
Definition: elog.c:1180
static char * logicalrep_get_attrs_str(LogicalRepRelation *remoterel, Bitmapset *atts)
Definition: relation.c:226

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

Referenced by logicalrep_rel_open().

Variable Documentation

◆ LogicalRepPartMap

HTAB* LogicalRepPartMap = NULL
static

◆ LogicalRepPartMapContext

MemoryContext LogicalRepPartMapContext = NULL
static

Definition at line 48 of file relation.c.

Referenced by logicalrep_partition_open(), and logicalrep_partmap_init().

◆ LogicalRepRelMap

HTAB* LogicalRepRelMap = NULL
static

◆ LogicalRepRelMapContext

MemoryContext LogicalRepRelMapContext = NULL
static