On 10/18/26 13:42, David Geier wrote:
>>> Move the definition of RelationData into utils/rel_internal.h.  Otherwise,
>>> gen_node_support.pl cannot process rel.h after the anonymous unions are
>>> introduced by the following commit, because the script does not support
>>> parsing anonymous unions.
>>
>> I really dislike this.  Why not do it the other way around, and put the
>> one struct that gen_node_support.pl wants in a separate file instead?
>> As in the attached WIP.  New file name TBD, of course.
> That's indeed nicer.
> 
> I had moved struct RelationData to rel_internal.h as a quick workaround
> when I started to be able to make progress without bothering. Now it's
> time to fix this properly.
> 
> We can do what you suggest, or alternatively, teach gen_node_support.pl
> to skip anonymous structs/unions in non-node structs. Then we can keep
> all code as before in rel.h. See attached patch.
> 
> Once we settle on how to go forward, I'll update the main patch set.
Since there were no objections, I went ahead and changed
gen_node_support.pl to skip anonymous unions inside structs, see patch
0003. This way there's no longer the need to move struct RelationData to
a new header.

Attached is the new patch set, also rebased on master.

-- 
David Geier
From e32598094e3dea2f0b912e0ed98dda0ec25160ef Mon Sep 17 00:00:00 2001
From: David Geier <[email protected]>
Date: Fri, 18 Sep 2026 12:52:47 +0200
Subject: [PATCH v7 1/7] Assert CacheMemoryContext exists in relcache callers

RelationCacheInitialize() creates CacheMemoryContext before catalog
or relcache access can occur. Replace defensive creation in later
code paths with assertions so calls made before relcache initialization
fail immediately in assertion-enabled builds.
---
 src/backend/utils/cache/relcache.c | 10 +++-------
 1 file changed, 3 insertions(+), 7 deletions(-)

diff --git a/src/backend/utils/cache/relcache.c b/src/backend/utils/cache/relcache.c
index ad8aee8447c..039750c7615 100644
--- a/src/backend/utils/cache/relcache.c
+++ b/src/backend/utils/cache/relcache.c
@@ -1671,15 +1671,13 @@ LookupOpclassInfo(Oid operatorClassOid,
 	HeapTuple	htup;
 	bool		indexOK;
 
+	Assert(CacheMemoryContext != NULL);
+
 	if (OpClassCache == NULL)
 	{
 		/* First time through: initialize the opclass cache */
 		HASHCTL		ctl;
 
-		/* Also make sure CacheMemoryContext exists */
-		if (!CacheMemoryContext)
-			CreateCacheMemoryContext();
-
 		ctl.keysize = sizeof(Oid);
 		ctl.entrysize = sizeof(OpClassCacheEnt);
 		OpClassCache = hash_create("Operator class cache", 64,
@@ -3562,13 +3560,11 @@ RelationBuildLocalRelation(const char *relname,
 
 	/* Shared relations had better be mapped, too */
 	Assert(mapped_relation || !shared_relation);
+	Assert(CacheMemoryContext != NULL);
 
 	/*
 	 * switch to the cache context to create the relcache entry.
 	 */
-	if (!CacheMemoryContext)
-		CreateCacheMemoryContext();
-
 	oldcxt = MemoryContextSwitchTo(CacheMemoryContext);
 
 	/*
-- 
2.53.0

From 259e6fd96640ff50de19115b157b5e1629451044 Mon Sep 17 00:00:00 2001
From: David Geier <[email protected]>
Date: Fri, 18 Sep 2026 12:17:11 +0200
Subject: [PATCH v7 2/7] Allocate RelationData structs in a dedicated slab
 context

The power-of-two size classes of aset mean that reductions in the size
of RelationData often yield no actual memory savings, as the allocation
is rounded up to the next size class anyway.

RelationData objects are fixed-size and numerous, so they are a good fit
for a slab allocator.  Create a slab context as a child of
CacheMemoryContext in RelationCacheInitialize() and allocate all
RelationData structs there; subsidiary allocations remain in
CacheMemoryContext itself.
---
 src/backend/utils/cache/relcache.c | 43 +++++++++++++++++++++++-------
 1 file changed, 33 insertions(+), 10 deletions(-)

diff --git a/src/backend/utils/cache/relcache.c b/src/backend/utils/cache/relcache.c
index 039750c7615..ace569d4cb6 100644
--- a/src/backend/utils/cache/relcache.c
+++ b/src/backend/utils/cache/relcache.c
@@ -137,6 +137,17 @@ typedef struct relidcacheent
 
 static HTAB *RelationIdCache;
 
+/*
+ * Slab memory context holding all the relcache's RelationData structs.
+ * It is a child of CacheMemoryContext; only the fixed-size RelationData
+ * objects are allocated there, while all subsidiary data stays in
+ * CacheMemoryContext itself.
+ */
+static MemoryContext RelationSlabContext = NULL;
+
+#define AllocRelationData() \
+	MemoryContextAllocZero(RelationSlabContext, sizeof(RelationData))
+
 /*
  * This flag is false until we have prepared the critical relcache entries
  * that are needed to do indexscans on the tables read by relcache building.
@@ -420,13 +431,15 @@ AllocateRelationDesc(Form_pg_class relp)
 	MemoryContext oldcxt;
 	Form_pg_class relationForm;
 
-	/* Relcache entries must live in CacheMemoryContext */
-	oldcxt = MemoryContextSwitchTo(CacheMemoryContext);
-
 	/*
-	 * allocate and zero space for new relation descriptor
+	 * Allocate and zero space for new relation descriptor.  The RelationData
+	 * struct goes into RelationSlabContext; all subsidiary data is allocated
+	 * in CacheMemoryContext.
 	 */
-	relation = palloc0_object(RelationData);
+	relation = AllocRelationData();
+
+	/* Relcache subsidiary data must live in CacheMemoryContext */
+	oldcxt = MemoryContextSwitchTo(CacheMemoryContext);
 
 	/* make sure relation is marked as having no open file yet */
 	relation->rd_smgr = NULL;
@@ -1894,9 +1907,10 @@ formrdesc(const char *relationName, Oid relationReltype,
 	bool		has_not_null;
 
 	/*
-	 * allocate new relation desc, clear all fields of reldesc
+	 * allocate new relation desc, clear all fields of reldesc; the
+	 * RelationData struct itself goes into RelationSlabContext
 	 */
-	relation = palloc0_object(RelationData);
+	relation = AllocRelationData();
 
 	/* make sure relation is marked as having no open file yet */
 	relation->rd_smgr = NULL;
@@ -3568,9 +3582,10 @@ RelationBuildLocalRelation(const char *relname,
 	oldcxt = MemoryContextSwitchTo(CacheMemoryContext);
 
 	/*
-	 * allocate a new relation descriptor and fill in basic state fields.
+	 * allocate a new relation descriptor and fill in basic state fields; the
+	 * RelationData struct itself goes into RelationSlabContext
 	 */
-	rel = palloc0_object(RelationData);
+	rel = AllocRelationData();
 
 	/* make sure relation is marked as having no open file yet */
 	rel->rd_smgr = NULL;
@@ -4003,6 +4018,14 @@ RelationCacheInitialize(void)
 	if (!CacheMemoryContext)
 		CreateCacheMemoryContext();
 
+	/*
+	 * create the slab context holding the relcache's RelationData structs
+	 */
+	RelationSlabContext = SlabContextCreate(CacheMemoryContext,
+											"RelationSlabContext",
+											SLAB_DEFAULT_BLOCK_SIZE,
+											sizeof(RelationData));
+
 	/*
 	 * create hashtable that indexes the relcache
 	 */
@@ -6302,7 +6325,7 @@ load_relcache_init_file(bool shared)
 			rels = repalloc_array(rels, Relation, max_rels);
 		}
 
-		rel = rels[num_rels++] = (Relation) palloc(len);
+		rel = rels[num_rels++] = AllocRelationData();
 
 		/* then, read the Relation structure */
 		if (fread(rel, 1, len, fp) != len)
-- 
2.53.0

From 25ca50e7d7d424e010fd4f31505e23b143fa8888 Mon Sep 17 00:00:00 2001
From: David Geier <[email protected]>
Date: Sun, 18 Oct 2026 13:33:35 +0200
Subject: [PATCH v7 3/7] gen_node_support.pl skips anonymous structs/unions

---
 src/backend/nodes/gen_node_support.pl | 33 +++++++++++++++++++++++++++
 1 file changed, 33 insertions(+)

diff --git a/src/backend/nodes/gen_node_support.pl b/src/backend/nodes/gen_node_support.pl
index 0b766272018..a2d198f72b3 100644
--- a/src/backend/nodes/gen_node_support.pl
+++ b/src/backend/nodes/gen_node_support.pl
@@ -193,6 +193,9 @@ foreach my $infile (@ARGV)
 	my %my_field_types;
 	my %my_field_attrs;
 
+	# nesting depth of an anonymous union/struct; the outermost level is 1
+	my $anon_nest = 0;
+
 	# open file with name from command line, which may have a path prefix
 	open my $ifh, '<', $infile or die "could not open \"$infile\": $!";
 
@@ -229,6 +232,34 @@ foreach my $infile (@ARGV)
 		next if $line eq '';
 		next if $line =~ /^#(define|ifdef|endif)/;
 
+		# Skip anonymous union/struct blocks. These are only allowed in
+		# non-node structs, whose fields we do not process.  Anonymous unions
+		# are not supported in node structs because their copy, equal, and
+		# serialization functions cannot be generated automatically.
+		if ($in_struct)
+		{
+			if ($anon_nest > 0)
+			{
+				$anon_nest += ($line =~ tr/{//) - ($line =~ tr/}//);
+				next;
+			}
+			elsif ($anon_nest == -1)
+			{
+				die "$infile:$lineno: expected '{' after anonymous union/struct\n"
+				  unless $line =~ /^\s*\{\s*$/;
+				$anon_nest = 1;
+				next;
+			}
+			elsif ($line =~ /^\s*(?:union|struct)(?:\s*\{)?\s*$/)
+			{
+				die
+				  "$infile:$lineno: anonymous union/struct not supported in node struct \"$in_struct\"\n"
+				  if $is_node_struct;
+				$anon_nest = ($line =~ /\{/) ? 1 : -1;
+				next;
+			}
+		}
+
 		# within a struct, don't process until we have whole logical line
 		if ($in_struct && $subline > 0)
 		{
@@ -421,6 +452,7 @@ foreach my $infile (@ARGV)
 				@my_fields = ();
 				%my_field_types = ();
 				%my_field_attrs = ();
+				$anon_nest = 0;
 			}
 			# normal struct field
 			elsif ($line =~
@@ -532,6 +564,7 @@ foreach my $infile (@ARGV)
 				$in_struct = $1;
 				$in_struct_lineno = $lineno;
 				$subline = 0;
+				$anon_nest = 0;
 			}
 			# one node type typedef'ed directly from another
 			elsif ($line =~ /^typedef (\w+) (\w+);$/ and elem $1, @node_types)
-- 
2.53.0

From 725c265099fd9a3c0c627f0723e9681bdf6f76f0 Mon Sep 17 00:00:00 2001
From: David Geier <[email protected]>
Date: Thu, 3 Sep 2026 09:46:30 +0200
Subject: [PATCH v7 4/7] Overlay relation-kind-specific relcache fields

Table-like relations and indexes use disjoint sets of cached metadata. Put
those fields in an anonymous union so each relcache entry pays only for the
larger of both sets, instead of the sum of both sets.

sizeof(RelationData): 368 bytes
---
 src/backend/access/spgist/spgutils.c |   2 +-
 src/backend/commands/repack.c        |   2 +-
 src/backend/commands/tablecmds.c     |  12 +-
 src/backend/rewrite/rewriteHandler.c |   7 +
 src/backend/storage/lmgr/predicate.c |   6 +-
 src/backend/utils/cache/relcache.c   | 455 ++++++++++++++-------------
 src/include/utils/rel.h              | 253 ++++++++-------
 7 files changed, 397 insertions(+), 340 deletions(-)

diff --git a/src/backend/access/spgist/spgutils.c b/src/backend/access/spgist/spgutils.c
index f2ee333f60d..a33dcfe8ecf 100644
--- a/src/backend/access/spgist/spgutils.c
+++ b/src/backend/access/spgist/spgutils.c
@@ -126,7 +126,7 @@ GetIndexInputType(Relation index, AttrNumber indexcol)
 	List	   *indexprs;
 	ListCell   *indexpr_item;
 
-	Assert(index->rd_index != NULL);
+	Assert(RelationIsIndex(index));
 	Assert(indexcol > 0 && indexcol <= index->rd_index->indnkeyatts);
 	opcintype = index->rd_opcintype[indexcol - 1];
 	if (!IsPolymorphicType(opcintype))
diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index c2a27b7ad05..4f74e161942 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -790,7 +790,7 @@ check_index_is_clusterable(Relation OldHeap, Oid indexOid, LOCKMODE lockmode)
 	/*
 	 * Check that index is in fact an index on the given relation
 	 */
-	if (OldIndex->rd_index == NULL ||
+	if (!RelationIsIndex(OldIndex) ||
 		OldIndex->rd_index->indrelid != RelationGetRelid(OldHeap))
 		ereport(ERROR,
 				(errcode(ERRCODE_WRONG_OBJECT_TYPE),
diff --git a/src/backend/commands/tablecmds.c b/src/backend/commands/tablecmds.c
index 47f55121574..c308c247765 100644
--- a/src/backend/commands/tablecmds.c
+++ b/src/backend/commands/tablecmds.c
@@ -4370,9 +4370,7 @@ RenameRelationInternal(Oid myrelid, const char *newrelname, bool is_internal, bo
 	 * let's not be totally oblivious to it.  We can process an index as
 	 * not-an-index, but not the other way around.
 	 */
-	Assert(!is_index ||
-		   is_index == (targetrelation->rd_rel->relkind == RELKIND_INDEX ||
-						targetrelation->rd_rel->relkind == RELKIND_PARTITIONED_INDEX));
+	Assert(!is_index || is_index == RelationIsIndex(targetrelation));
 
 	/*
 	 * Update pg_class tuple with new relname.  (Scribbling on reltup is OK
@@ -4399,8 +4397,7 @@ RenameRelationInternal(Oid myrelid, const char *newrelname, bool is_internal, bo
 	/*
 	 * Also rename the associated constraint, if any.
 	 */
-	if (targetrelation->rd_rel->relkind == RELKIND_INDEX ||
-		targetrelation->rd_rel->relkind == RELKIND_PARTITIONED_INDEX)
+	if (RelationIsIndex(targetrelation))
 	{
 		Oid			constraintId = get_index_constraint(myrelid);
 
@@ -9083,8 +9080,7 @@ ATExecSetStatistics(Relation rel, const char *colName, int16 colNum, Node *newVa
 				 errmsg("cannot alter statistics on virtual generated column \"%s\"",
 						colName)));
 
-	if (rel->rd_rel->relkind == RELKIND_INDEX ||
-		rel->rd_rel->relkind == RELKIND_PARTITIONED_INDEX)
+	if (RelationIsIndex(rel))
 	{
 		if (attnum > rel->rd_index->indnkeyatts)
 			ereport(ERROR,
@@ -19222,7 +19218,7 @@ ATExecReplicaIdentity(Relation rel, ReplicaIdentityStmt *stmt, LOCKMODE lockmode
 	indexRel = index_open(indexOid, ShareLock);
 
 	/* Check that the index is on the relation we're altering. */
-	if (indexRel->rd_index == NULL ||
+	if (!RelationIsIndex(indexRel) ||
 		indexRel->rd_index->indrelid != RelationGetRelid(rel))
 		ereport(ERROR,
 				(errcode(ERRCODE_WRONG_OBJECT_TYPE),
diff --git a/src/backend/rewrite/rewriteHandler.c b/src/backend/rewrite/rewriteHandler.c
index 27964cb83c6..3f5e16054a6 100644
--- a/src/backend/rewrite/rewriteHandler.c
+++ b/src/backend/rewrite/rewriteHandler.c
@@ -2982,6 +2982,13 @@ relation_is_updatable(Oid reloid,
 		return ALL_EVENTS;
 	}
 
+	/* Indexes are not updatable */
+	if (RelationIsIndex(rel))
+	{
+		relation_close(rel, AccessShareLock);
+		return 0;
+	}
+
 	/* Look for unconditional DO INSTEAD rules, and note supported events */
 	rulelocks = rel->rd_rules;
 	if (rulelocks != NULL)
diff --git a/src/backend/storage/lmgr/predicate.c b/src/backend/storage/lmgr/predicate.c
index fc038dc9ab4..3684e6ce40a 100644
--- a/src/backend/storage/lmgr/predicate.c
+++ b/src/backend/storage/lmgr/predicate.c
@@ -2478,7 +2478,7 @@ PredicateLockTID(Relation relation, const ItemPointerData *tid, Snapshot snapsho
 	/*
 	 * Return if this xact wrote it.
 	 */
-	if (relation->rd_index == NULL)
+	if (!RelationIsIndex(relation))
 	{
 		/* If we wrote it; we already have a write lock. */
 		if (TransactionIdIsCurrentTransactionId(tuple_xid))
@@ -2810,7 +2810,7 @@ DropAllPredicateLocksFromTable(Relation relation, bool transfer)
 
 	dbId = relation->rd_locator.dbOid;
 	relId = relation->rd_id;
-	if (relation->rd_index == NULL)
+	if (!RelationIsIndex(relation))
 	{
 		isIndex = false;
 		heapId = relId;
@@ -4291,7 +4291,7 @@ CheckTableForSerializableConflictIn(Relation relation)
 	 */
 	MyXactDidWrite = true;
 
-	Assert(relation->rd_index == NULL); /* not an index relation */
+	Assert(!RelationIsIndex(relation));
 
 	dbId = relation->rd_locator.dbOid;
 	heapId = relation->rd_id;
diff --git a/src/backend/utils/cache/relcache.c b/src/backend/utils/cache/relcache.c
index ace569d4cb6..a9b7568951d 100644
--- a/src/backend/utils/cache/relcache.c
+++ b/src/backend/utils/cache/relcache.c
@@ -93,7 +93,7 @@
 #include "utils/snapmgr.h"
 #include "utils/syscache.h"
 
-#define RELCACHE_INIT_FILEMAGIC		0x573266	/* version ID value */
+#define RELCACHE_INIT_FILEMAGIC		0x573267	/* version ID value */
 
 /*
  * Whether to bother checking if relation cache memory needs to be freed
@@ -1214,71 +1214,10 @@ retry:
 	 */
 	RelationBuildTupleDesc(relation);
 
-	/* foreign key data is not loaded till asked for */
-	relation->rd_fkeylist = NIL;
-	relation->rd_fkeyvalid = false;
-
-	/* TOAST type data is not loaded till asked for */
-	relation->rd_toastchunkidtype = InvalidOid;
-
-	/* partitioning data is not loaded till asked for */
-	relation->rd_partkey = NULL;
-	relation->rd_partkeycxt = NULL;
-	relation->rd_partdesc = NULL;
-	relation->rd_partdesc_nodetached = NULL;
-	relation->rd_partdesc_nodetached_xmin = InvalidTransactionId;
-	relation->rd_pdcxt = NULL;
-	relation->rd_pddcxt = NULL;
 	relation->rd_partcheck = NIL;
 	relation->rd_partcheckvalid = false;
 	relation->rd_partcheckcxt = NULL;
 
-	/*
-	 * initialize access method information
-	 */
-	if (relation->rd_rel->relkind == RELKIND_INDEX ||
-		relation->rd_rel->relkind == RELKIND_PARTITIONED_INDEX)
-		RelationInitIndexAccessInfo(relation);
-	else if (RELKIND_HAS_TABLE_AM(relation->rd_rel->relkind) ||
-			 relation->rd_rel->relkind == RELKIND_SEQUENCE)
-		RelationInitTableAccessMethod(relation);
-	else if (relation->rd_rel->relkind == RELKIND_PARTITIONED_TABLE)
-	{
-		/*
-		 * Do nothing: access methods are a setting that partitions can
-		 * inherit.
-		 */
-	}
-	else
-		Assert(relation->rd_rel->relam == InvalidOid);
-
-	/* extract reloptions if any */
-	RelationParseRelOptions(relation, pg_class_tuple);
-
-	/*
-	 * Fetch rules and triggers that affect this relation.
-	 *
-	 * Note that RelationBuildRuleLock() relies on this being done after
-	 * extracting the relation's reloptions.
-	 */
-	if (relation->rd_rel->relhasrules)
-		RelationBuildRuleLock(relation);
-	else
-	{
-		relation->rd_rules = NULL;
-		relation->rd_rulescxt = NULL;
-	}
-
-	if (relation->rd_rel->relhastriggers)
-		RelationBuildTriggers(relation);
-	else
-		relation->trigdesc = NULL;
-
-	if (relation->rd_rel->relrowsecurity)
-		RelationBuildRowSecurity(relation);
-	else
-		relation->rd_rsdesc = NULL;
-
 	/*
 	 * initialize the relation lock manager information
 	 */
@@ -1292,6 +1231,75 @@ retry:
 	/* make sure relation is marked as having no open file yet */
 	relation->rd_smgr = NULL;
 
+	if (RelationIsIndex(relation))
+	{
+		RelationInitIndexAccessInfo(relation);
+
+		/* extract reloptions if any */
+		RelationParseRelOptions(relation, pg_class_tuple);
+	}
+	else
+	{
+		/* partitioning data is not loaded till asked for */
+		relation->rd_partkey = NULL;
+		relation->rd_partkeycxt = NULL;
+		relation->rd_partdesc = NULL;
+		relation->rd_partdesc_nodetached = NULL;
+		relation->rd_partdesc_nodetached_xmin = InvalidTransactionId;
+		relation->rd_pdcxt = NULL;
+		relation->rd_pddcxt = NULL;
+
+		/*
+		 * initialize access method information
+		 */
+		if (RELKIND_HAS_TABLE_AM(relation->rd_rel->relkind) ||
+			relation->rd_rel->relkind == RELKIND_SEQUENCE)
+			RelationInitTableAccessMethod(relation);
+		else if (relation->rd_rel->relkind == RELKIND_PARTITIONED_TABLE)
+		{
+			/*
+			 * Do nothing: access methods are a setting that partitions can
+			 * inherit.
+			 */
+		}
+		else
+			Assert(relation->rd_rel->relam == InvalidOid);
+
+		/* extract reloptions if any */
+		RelationParseRelOptions(relation, pg_class_tuple);
+
+		/* foreign key data is not loaded till asked for */
+		relation->rd_fkeylist = NIL;
+		relation->rd_fkeyvalid = false;
+
+		/* TOAST type data is not loaded till asked for */
+		relation->rd_toastchunkidtype = InvalidOid;
+
+		/*
+		 * Fetch rules and triggers that affect this relation.
+		 *
+		 * Note that RelationBuildRuleLock() relies on this being done after
+		 * extracting the relation's reloptions.
+		 */
+		if (relation->rd_rel->relhasrules)
+			RelationBuildRuleLock(relation);
+		else
+		{
+			relation->rd_rules = NULL;
+			relation->rd_rulescxt = NULL;
+		}
+
+		if (relation->rd_rel->relhastriggers)
+			RelationBuildTriggers(relation);
+		else
+			relation->trigdesc = NULL;
+
+		if (relation->rd_rel->relrowsecurity)
+			RelationBuildRowSecurity(relation);
+		else
+			relation->rd_rsdesc = NULL;
+	}
+
 	/*
 	 * now we can free the memory allocated for pg_class_tuple
 	 */
@@ -2240,7 +2248,7 @@ RelationCloseCleanup(Relation relation)
 	 * stale partition descriptors it has.  This is unlikely, so check to see
 	 * if there are child contexts before expending a call to mcxt.c.
 	 */
-	if (RelationHasReferenceCountZero(relation))
+	if (RelationHasReferenceCountZero(relation) && !RelationIsIndex(relation))
 	{
 		if (relation->rd_pdcxt != NULL &&
 			relation->rd_pdcxt->firstchild != NULL)
@@ -2287,9 +2295,7 @@ RelationReloadIndexInfo(Relation relation)
 	Form_pg_class relp;
 
 	/* Should be called only for invalidated, live indexes */
-	Assert((relation->rd_rel->relkind == RELKIND_INDEX ||
-			relation->rd_rel->relkind == RELKIND_PARTITIONED_INDEX) &&
-		   !relation->rd_isvalid &&
+	Assert(RelationIsIndex(relation) && !relation->rd_isvalid &&
 		   relation->rd_droppedSubid == InvalidSubTransactionId);
 
 	/*
@@ -2446,6 +2452,8 @@ RelationReloadNailed(Relation relation)
 static void
 RelationDestroyRelation(Relation relation, bool remember_tupdesc)
 {
+	const bool is_index = relation->rd_rel && RelationIsIndex(relation);
+
 	Assert(RelationHasReferenceCountZero(relation));
 
 	/*
@@ -2481,39 +2489,45 @@ RelationDestroyRelation(Relation relation, bool remember_tupdesc)
 		else
 			FreeTupleDesc(relation->rd_att);
 	}
-	FreeTriggerDesc(relation->trigdesc);
-	list_free_deep(relation->rd_fkeylist);
-	list_free(relation->rd_indexlist);
-	list_free(relation->rd_statlist);
-	bms_free(relation->rd_keyattr);
-	bms_free(relation->rd_pkattr);
-	bms_free(relation->rd_idattr);
-	bms_free(relation->rd_hotblockingattr);
-	bms_free(relation->rd_summarizedattr);
-	if (relation->rd_pubdesc)
-		pfree(relation->rd_pubdesc);
 	if (relation->rd_options)
 		pfree(relation->rd_options);
-	if (relation->rd_indextuple)
-		pfree(relation->rd_indextuple);
 	if (relation->rd_amcache)
 		pfree(relation->rd_amcache);
-	if (relation->rd_fdwroutine)
-		pfree(relation->rd_fdwroutine);
-	if (relation->rd_indexcxt)
-		MemoryContextDelete(relation->rd_indexcxt);
-	if (relation->rd_rulescxt)
-		MemoryContextDelete(relation->rd_rulescxt);
-	if (relation->rd_rsdesc)
-		MemoryContextDelete(relation->rd_rsdesc->rscxt);
-	if (relation->rd_partkeycxt)
-		MemoryContextDelete(relation->rd_partkeycxt);
-	if (relation->rd_pdcxt)
-		MemoryContextDelete(relation->rd_pdcxt);
-	if (relation->rd_pddcxt)
-		MemoryContextDelete(relation->rd_pddcxt);
 	if (relation->rd_partcheckcxt)
 		MemoryContextDelete(relation->rd_partcheckcxt);
+	if (!is_index)
+	{
+		list_free(relation->rd_indexlist);
+		list_free(relation->rd_statlist);
+		FreeTriggerDesc(relation->trigdesc);
+		list_free_deep(relation->rd_fkeylist);
+		bms_free(relation->rd_keyattr);
+		bms_free(relation->rd_pkattr);
+		bms_free(relation->rd_idattr);
+		bms_free(relation->rd_hotblockingattr);
+		bms_free(relation->rd_summarizedattr);
+		if (relation->rd_pubdesc)
+			pfree(relation->rd_pubdesc);
+		if (relation->rd_fdwroutine)
+			pfree(relation->rd_fdwroutine);
+		if (relation->rd_rulescxt)
+			MemoryContextDelete(relation->rd_rulescxt);
+		if (relation->rd_rsdesc)
+			MemoryContextDelete(relation->rd_rsdesc->rscxt);
+		if (relation->rd_partkeycxt)
+			MemoryContextDelete(relation->rd_partkeycxt);
+		if (relation->rd_pdcxt)
+			MemoryContextDelete(relation->rd_pdcxt);
+		if (relation->rd_pddcxt)
+			MemoryContextDelete(relation->rd_pddcxt);
+	}
+	else
+	{
+		if (relation->rd_indextuple)
+			pfree(relation->rd_indextuple);
+		if (relation->rd_indexcxt)
+			MemoryContextDelete(relation->rd_indexcxt);
+	}
 	pfree(relation);
 }
 
@@ -2611,9 +2625,7 @@ RelationRebuildRelation(Relation relation)
 	 * pg_index tuple only after that, and then relies on
 	 * CommandCounterIncrement to load the pg_index contents.
 	 */
-	if ((relation->rd_rel->relkind == RELKIND_INDEX ||
-		 relation->rd_rel->relkind == RELKIND_PARTITIONED_INDEX) &&
-		relation->rd_indexcxt != NULL)
+	if (RelationIsIndex(relation) && relation->rd_indexcxt != NULL)
 	{
 		RelationReloadIndexInfo(relation);
 		return;
@@ -2658,10 +2670,11 @@ RelationRebuildRelation(Relation relation)
 		 */
 		Relation	newrel;
 		Oid			save_relid = RelationGetRelid(relation);
+		bool		is_index = RelationIsIndex(relation);
 		bool		keep_tupdesc;
-		bool		keep_rules;
-		bool		keep_policies;
-		bool		keep_partkey;
+		bool		keep_rules = false;
+		bool		keep_policies = false;
+		bool		keep_partkey = false;
 
 		/* Build temporary entry, but don't link it into hashtable */
 		newrel = RelationBuildDesc(save_relid, false);
@@ -2705,10 +2718,14 @@ RelationRebuildRelation(Relation relation)
 		Assert(relation->rd_rel->relkind == newrel->rd_rel->relkind);
 
 		keep_tupdesc = equalTupleDescs(relation->rd_att, newrel->rd_att);
-		keep_rules = equalRuleLocks(relation->rd_rules, newrel->rd_rules);
-		keep_policies = equalRSDesc(relation->rd_rsdesc, newrel->rd_rsdesc);
-		/* partkey is immutable once set up, so we can always keep it */
-		keep_partkey = (relation->rd_partkey != NULL);
+
+		if (!is_index)
+		{
+			keep_rules = equalRuleLocks(relation->rd_rules, newrel->rd_rules);
+			keep_policies = equalRSDesc(relation->rd_rsdesc, newrel->rd_rsdesc);
+			/* partkey is immutable once set up, so we can always keep it */
+			keep_partkey = (relation->rd_partkey != NULL);
+		}
 
 		/*
 		 * Perform swapping of the relcache entry contents.  Within this
@@ -2751,71 +2768,78 @@ RelationRebuildRelation(Relation relation)
 		SWAPFIELD(Form_pg_class, rd_rel);
 		/* ... but actually, we don't have to update newrel->rd_rel */
 		memcpy(relation->rd_rel, newrel->rd_rel, CLASS_TUPLE_SIZE);
-		/* preserve old tupledesc, rules, policies if no logical change */
+		/* preserve old tupledesc if there was no logical change */
 		if (keep_tupdesc)
 			SWAPFIELD(TupleDesc, rd_att);
-		if (keep_rules)
-		{
-			SWAPFIELD(RuleLock *, rd_rules);
-			SWAPFIELD(MemoryContext, rd_rulescxt);
-		}
-		if (keep_policies)
-			SWAPFIELD(RowSecurityDesc *, rd_rsdesc);
-		/* toast OID override must be preserved */
-		SWAPFIELD(Oid, rd_toastoid);
 		/* pgstat_info / enabled must be preserved */
 		SWAPFIELD(struct PgStat_RelationStatus *, pgstat_info);
 		SWAPFIELD(bool, pgstat_enabled);
-		/* preserve old partition key if we have one */
-		if (keep_partkey)
-		{
-			SWAPFIELD(PartitionKey, rd_partkey);
-			SWAPFIELD(MemoryContext, rd_partkeycxt);
-		}
-		if (newrel->rd_pdcxt != NULL || newrel->rd_pddcxt != NULL)
+
+		if (!is_index)
 		{
-			/*
-			 * We are rebuilding a partitioned relation with a non-zero
-			 * reference count, so we must keep the old partition descriptor
-			 * around, in case there's a PartitionDirectory with a pointer to
-			 * it.  This means we can't free the old rd_pdcxt yet.  (This is
-			 * necessary because RelationGetPartitionDesc hands out direct
-			 * pointers to the relcache's data structure, unlike our usual
-			 * practice which is to hand out copies.  We'd have the same
-			 * problem with rd_partkey, except that we always preserve that
-			 * once created.)
-			 *
-			 * To ensure that it's not leaked completely, re-attach it to the
-			 * new reldesc, or make it a child of the new reldesc's rd_pdcxt
-			 * in the unlikely event that there is one already.  (Compare hack
-			 * in RelationBuildPartitionDesc.)  RelationClose will clean up
-			 * any such contexts once the reference count reaches zero.
-			 *
-			 * In the case where the reference count is zero, this code is not
-			 * reached, which should be OK because in that case there should
-			 * be no PartitionDirectory with a pointer to the old entry.
-			 *
-			 * Note that newrel and relation have already been swapped, so the
-			 * "old" partition descriptor is actually the one hanging off of
-			 * newrel.
-			 */
-			relation->rd_partdesc = NULL;	/* ensure rd_partdesc is invalid */
-			relation->rd_partdesc_nodetached = NULL;
-			relation->rd_partdesc_nodetached_xmin = InvalidTransactionId;
-			if (relation->rd_pdcxt != NULL) /* probably never happens */
-				MemoryContextSetParent(newrel->rd_pdcxt, relation->rd_pdcxt);
-			else
-				relation->rd_pdcxt = newrel->rd_pdcxt;
-			if (relation->rd_pddcxt != NULL)
-				MemoryContextSetParent(newrel->rd_pddcxt, relation->rd_pddcxt);
-			else
-				relation->rd_pddcxt = newrel->rd_pddcxt;
-			/* drop newrel's pointers so we don't destroy it below */
-			newrel->rd_partdesc = NULL;
-			newrel->rd_partdesc_nodetached = NULL;
-			newrel->rd_partdesc_nodetached_xmin = InvalidTransactionId;
-			newrel->rd_pdcxt = NULL;
-			newrel->rd_pddcxt = NULL;
+			/* preserve old rules and policies if there was no logical change */
+			if (keep_rules)
+			{
+				SWAPFIELD(RuleLock *, rd_rules);
+				SWAPFIELD(MemoryContext, rd_rulescxt);
+			}
+			if (keep_policies)
+				SWAPFIELD(RowSecurityDesc *, rd_rsdesc);
+
+			/* toast OID override must be preserved */
+			SWAPFIELD(Oid, rd_toastoid);
+
+			/* preserve old partition key if we have one */
+			if (keep_partkey)
+			{
+				SWAPFIELD(PartitionKey, rd_partkey);
+				SWAPFIELD(MemoryContext, rd_partkeycxt);
+			}
+			if (newrel->rd_pdcxt != NULL || newrel->rd_pddcxt != NULL)
+			{
+				/*
+				 * We are rebuilding a partitioned relation with a non-zero
+				 * reference count, so we must keep the old partition descriptor
+				 * around, in case there's a PartitionDirectory with a pointer to
+				 * it.  This means we can't free the old rd_pdcxt yet.  (This is
+				 * necessary because RelationGetPartitionDesc hands out direct
+				 * pointers to the relcache's data structure, unlike our usual
+				 * practice which is to hand out copies.  We'd have the same
+				 * problem with rd_partkey, except that we always preserve that
+				 * once created.)
+				 *
+				 * To ensure that it's not leaked completely, re-attach it to the
+				 * new reldesc, or make it a child of the new reldesc's rd_pdcxt
+				 * in the unlikely event that there is one already.  (Compare hack
+				 * in RelationBuildPartitionDesc.)  RelationClose will clean up
+				 * any such contexts once the reference count reaches zero.
+				 *
+				 * In the case where the reference count is zero, this code is not
+				 * reached, which should be OK because in that case there should
+				 * be no PartitionDirectory with a pointer to the old entry.
+				 *
+				 * Note that newrel and relation have already been swapped, so the
+				 * "old" partition descriptor is actually the one hanging off of
+				 * newrel.
+				 */
+				relation->rd_partdesc = NULL;	/* ensure rd_partdesc is invalid */
+				relation->rd_partdesc_nodetached = NULL;
+				relation->rd_partdesc_nodetached_xmin = InvalidTransactionId;
+				if (relation->rd_pdcxt != NULL) /* probably never happens */
+					MemoryContextSetParent(newrel->rd_pdcxt, relation->rd_pdcxt);
+				else
+					relation->rd_pdcxt = newrel->rd_pdcxt;
+				if (relation->rd_pddcxt != NULL)
+					MemoryContextSetParent(newrel->rd_pddcxt, relation->rd_pddcxt);
+				else
+					relation->rd_pddcxt = newrel->rd_pddcxt;
+				/* drop newrel's pointers so we don't destroy it below */
+				newrel->rd_partdesc = NULL;
+				newrel->rd_partdesc_nodetached = NULL;
+				newrel->rd_partdesc_nodetached_xmin = InvalidTransactionId;
+				newrel->rd_pdcxt = NULL;
+				newrel->rd_pddcxt = NULL;
+			}
 		}
 
 #undef SWAPFIELD
@@ -4365,8 +4389,8 @@ RelationCacheInitializePhase3(void)
 		}
 
 		/* Reload tableam data if needed */
-		if (relation->rd_tableam == NULL &&
-			(RELKIND_HAS_TABLE_AM(relation->rd_rel->relkind) || relation->rd_rel->relkind == RELKIND_SEQUENCE))
+		if ((RELKIND_HAS_TABLE_AM(relation->rd_rel->relkind) || relation->rd_rel->relkind == RELKIND_SEQUENCE) &&
+			relation->rd_tableam == NULL)
 		{
 			RelationInitTableAccessMethod(relation);
 			Assert(relation->rd_tableam != NULL);
@@ -5164,6 +5188,9 @@ RelationGetIndexExpressions(Relation relation)
 	char	   *exprsString;
 	MemoryContext oldcxt;
 
+	if (!RelationIsIndex(relation))
+		return NIL;
+
 	/* Quick exit if we already computed the result. */
 	if (relation->rd_indexprs)
 		return copyObject(relation->rd_indexprs);
@@ -5224,6 +5251,9 @@ RelationGetDummyIndexExpressions(Relation relation)
 	List	   *rawExprs;
 	ListCell   *lc;
 
+	if (!RelationIsIndex(relation))
+		return NIL;
+
 	/* Quick exit if there is nothing to do. */
 	if (relation->rd_indextuple == NULL ||
 		heap_attisnull(relation->rd_indextuple, Anum_pg_index_indexprs, NULL))
@@ -5277,6 +5307,9 @@ RelationGetIndexPredicate(Relation relation)
 	char	   *predString;
 	MemoryContext oldcxt;
 
+	if (!RelationIsIndex(relation))
+		return NIL;
+
 	/* Quick exit if we already computed the result. */
 	if (relation->rd_indpred)
 		return copyObject(relation->rd_indpred);
@@ -6522,18 +6555,6 @@ load_relcache_init_file(bool shared)
 			/* Load table AM data */
 			if (RELKIND_HAS_TABLE_AM(rel->rd_rel->relkind) || rel->rd_rel->relkind == RELKIND_SEQUENCE)
 				RelationInitTableAccessMethod(rel);
-
-			Assert(rel->rd_index == NULL);
-			Assert(rel->rd_indextuple == NULL);
-			Assert(rel->rd_indexcxt == NULL);
-			Assert(rel->rd_indam == NULL);
-			Assert(rel->rd_opfamily == NULL);
-			Assert(rel->rd_opcintype == NULL);
-			Assert(rel->rd_support == NULL);
-			Assert(rel->rd_supportinfo == NULL);
-			Assert(rel->rd_indoption == NULL);
-			Assert(rel->rd_indcollation == NULL);
-			Assert(rel->rd_opcoptions == NULL);
 		}
 
 		/*
@@ -6543,55 +6564,69 @@ load_relcache_init_file(bool shared)
 		 * be a big performance hit since few system catalogs have such. Ditto
 		 * for RLS policy data, partition info, index expressions, predicates,
 		 * exclusion info, and FDW info.
+		 *
+		 * These fields are overlaid in a union with the index-only fields
+		 * that were just set up above (see RelationData in rel_internal.h),
+		 * so this must be skipped for index relations to avoid clobbering
+		 * that data.
 		 */
-		rel->rd_rules = NULL;
-		rel->rd_rulescxt = NULL;
-		rel->trigdesc = NULL;
-		rel->rd_rsdesc = NULL;
-		rel->rd_partkey = NULL;
-		rel->rd_partkeycxt = NULL;
-		rel->rd_partdesc = NULL;
-		rel->rd_partdesc_nodetached = NULL;
-		rel->rd_partdesc_nodetached_xmin = InvalidTransactionId;
-		rel->rd_pdcxt = NULL;
-		rel->rd_pddcxt = NULL;
-		rel->rd_partcheck = NIL;
-		rel->rd_partcheckvalid = false;
-		rel->rd_partcheckcxt = NULL;
-		rel->rd_indexprs = NIL;
-		rel->rd_indpred = NIL;
-		rel->rd_exclops = NULL;
-		rel->rd_exclprocs = NULL;
-		rel->rd_exclstrats = NULL;
-		rel->rd_fdwroutine = NULL;
+		if (!RelationIsIndex(rel))
+		{
+			rel->rd_rules = NULL;
+			rel->rd_rulescxt = NULL;
+			rel->trigdesc = NULL;
+			rel->rd_rsdesc = NULL;
+			rel->rd_partkey = NULL;
+			rel->rd_partkeycxt = NULL;
+			rel->rd_partdesc = NULL;
+			rel->rd_partdesc_nodetached = NULL;
+			rel->rd_partdesc_nodetached_xmin = InvalidTransactionId;
+			rel->rd_pdcxt = NULL;
+			rel->rd_pddcxt = NULL;
+			rel->rd_keyattr = NULL;
+			rel->rd_pkattr = NULL;
+			rel->rd_idattr = NULL;
+			rel->rd_hotblockingattr = NULL;
+			rel->rd_summarizedattr = NULL;
+			rel->rd_pubdesc = NULL;
+			rel->rd_fdwroutine = NULL;
+			rel->rd_fkeyvalid = false;
+			rel->rd_fkeylist = NIL;
+			rel->rd_indexvalid = false;
+			rel->rd_indexlist = NIL;
+			rel->rd_pkindex = InvalidOid;
+			rel->rd_replidindex = InvalidOid;
+			rel->rd_attrsvalid = false;
+			rel->rd_statvalid = false;
+			rel->rd_statlist = NIL;
+			rel->rd_toastchunkidtype = InvalidOid;
+		}
+		else
+		{
+			/* These lazily built fields are not stored in the init file. */
+			rel->rd_indexprs = NIL;
+			rel->rd_indpred = NIL;
+			rel->rd_exclops = NULL;
+			rel->rd_exclprocs = NULL;
+			rel->rd_exclstrats = NULL;
+		}
 
 		/*
 		 * Reset transient-state fields in the relcache entry
 		 */
 		rel->rd_smgr = NULL;
+		rel->rd_partcheck = NIL;
+		rel->rd_partcheckvalid = false;
+		rel->rd_partcheckcxt = NULL;
 		if (rel->rd_isnailed)
 			rel->rd_refcnt = 1;
 		else
 			rel->rd_refcnt = 0;
-		rel->rd_indexvalid = false;
-		rel->rd_indexlist = NIL;
-		rel->rd_pkindex = InvalidOid;
-		rel->rd_replidindex = InvalidOid;
-		rel->rd_attrsvalid = false;
-		rel->rd_keyattr = NULL;
-		rel->rd_pkattr = NULL;
-		rel->rd_idattr = NULL;
-		rel->rd_pubdesc = NULL;
-		rel->rd_statvalid = false;
-		rel->rd_statlist = NIL;
-		rel->rd_fkeyvalid = false;
-		rel->rd_fkeylist = NIL;
 		rel->rd_createSubid = InvalidSubTransactionId;
 		rel->rd_newRelfilelocatorSubid = InvalidSubTransactionId;
 		rel->rd_firstRelfilelocatorSubid = InvalidSubTransactionId;
 		rel->rd_droppedSubid = InvalidSubTransactionId;
 		rel->rd_amcache = NULL;
-		rel->rd_toastchunkidtype = InvalidOid;
 		rel->pgstat_info = NULL;
 
 		/*
diff --git a/src/include/utils/rel.h b/src/include/utils/rel.h
index 7b8c2b1e362..9777dd46a53 100644
--- a/src/include/utils/rel.h
+++ b/src/include/utils/rel.h
@@ -54,6 +54,134 @@ typedef LockInfoData *LockInfo;
 
 typedef struct RelationData
 {
+	union
+	{
+		/* fields used only for a non-index (table-like) relation */
+		struct
+		{
+			RuleLock   *rd_rules;		/* rewrite rules */
+			MemoryContext rd_rulescxt;	/* private memory cxt for rd_rules, if any */
+			TriggerDesc *trigdesc;		/* Trigger info, or NULL if rel has none */
+			/* use "struct" here to avoid needing to include rowsecurity.h: */
+			struct RowSecurityDesc *rd_rsdesc;	/* row security policies, or NULL */
+
+			/* data managed by RelationGetFKeyList: */
+			List	   *rd_fkeylist;	/* list of ForeignKeyCacheInfo (see below) */
+			bool		rd_fkeyvalid;	/* true if rd_fkeylist has been computed */
+
+			/* data managed by RelationGetPartitionKey: */
+			PartitionKey rd_partkey;	/* partition key, or NULL */
+			MemoryContext rd_partkeycxt;	/* private context for rd_partkey, if any */
+
+			/* data managed by RelationGetPartitionDesc: */
+			PartitionDesc rd_partdesc;	/* partition descriptor, or NULL */
+			MemoryContext rd_pdcxt;		/* private context for rd_partdesc, if any */
+
+			/* Same as above, for partdescs that omit detached partitions */
+			PartitionDesc rd_partdesc_nodetached;	/* partdesc w/o detached parts */
+			MemoryContext rd_pddcxt;	/* for rd_partdesc_nodetached, if any */
+
+			/*
+			 * pg_inherits.xmin of the partition that was excluded in
+			 * rd_partdesc_nodetached.  This informs a future user of that partdesc:
+			 * if this value is not in progress for the active snapshot, then the
+			 * partdesc can be used, otherwise they have to build a new one.  (This
+			 * matches what find_inheritance_children_extended would do).
+			 */
+			TransactionId rd_partdesc_nodetached_xmin;
+
+			/* data managed by RelationGetIndexList: */
+			List	   *rd_indexlist;	/* list of OIDs of indexes on relation */
+			Oid			rd_pkindex;		/* OID of (deferrable?) primary key, if any */
+			bool		rd_ispkdeferrable;	/* is rd_pkindex a deferrable PK? */
+			bool		rd_indexvalid;	/* is rd_indexlist valid? (also rd_pkindex and
+									 * rd_replidindex) */
+			Oid			rd_replidindex; /* OID of replica identity index, if any */
+
+			/* data managed by RelationGetIndexAttrBitmap: */
+			bool		rd_attrsvalid;	/* are bitmaps of attrs valid? (see
+									 * RelationGetIndexAttrBitmap) */
+			Bitmapset  *rd_keyattr;		/* cols that can be ref'd by foreign keys */
+			Bitmapset  *rd_pkattr;		/* cols included in primary key */
+			Bitmapset  *rd_idattr;		/* included in replica identity index */
+			Bitmapset  *rd_hotblockingattr; /* cols blocking HOT update */
+			Bitmapset  *rd_summarizedattr;	/* cols indexed by summarizing indexes */
+
+			/* data managed by RelationGetStatExtList: */
+			List	   *rd_statlist;	/* list of OIDs of extended stats */
+			bool		rd_statvalid;	/* is rd_statlist valid? */
+
+			/*
+			 * Table access method.
+			 */
+			const struct TableAmRoutine *rd_tableam;
+
+			/*
+			 * Hack for CLUSTER, rewriting ALTER TABLE, etc: when writing a new
+			 * version of a table, we need to make any toast pointers inserted into it
+			 * have the existing toast table's OID, not the OID of the transient toast
+			 * table.  If rd_toastoid isn't InvalidOid, it is the OID to place in
+			 * toast pointers inserted into this rel.  (Note it's set on the new
+			 * version of the main heap, not the toast table itself.)  This also
+			 * causes toast_save_datum() to try to preserve toast value OIDs.
+			 */
+			Oid			rd_toastoid;	/* Real TOAST table's OID, or InvalidOid */
+
+			/*
+			 * Type OID of the "chunk_id" column of this relation's TOAST table, i.e.
+			 * OIDOID or OID8OID.
+			 *
+			 * This data is filled on demand by RelationGetToastChunkIdType(), not at
+			 * relcache build time, so as to save in syscache lookups.
+			 */
+			Oid			rd_toastchunkidtype;
+
+			PublicationDesc *rd_pubdesc;	/* publication descriptor, or NULL */
+
+			/*
+			 * foreign-table support
+			 *
+			 * rd_fdwroutine must point to a single memory chunk palloc'd in
+			 * CacheMemoryContext.  It will be freed and reset to NULL on a
+			 * relcache reset.
+			 */
+			/* use "struct" here to avoid needing to include fdwapi.h: */
+			struct FdwRoutine *rd_fdwroutine;	/* cached function pointers, or NULL */
+		};
+
+		/* fields used only for an index relation */
+		struct
+		{
+			Form_pg_index rd_index;		/* pg_index tuple describing this index */
+			/* use "struct" here to avoid needing to include htup.h: */
+			struct HeapTupleData *rd_indextuple;	/* all of pg_index tuple */
+
+			/*
+			 * index access support info (used only for an index relation)
+			 *
+			 * Note: only default support procs for each opclass are cached, namely
+			 * those with lefttype and righttype equal to the opclass's opcintype. The
+			 * arrays are indexed by support function number, which is a sufficient
+			 * identifier given that restriction.
+			 */
+			MemoryContext rd_indexcxt;	/* private memory cxt for this stuff */
+			/* use "struct" here to avoid needing to include amapi.h: */
+			const struct IndexAmRoutine *rd_indam;	/* index AM's API struct */
+			Oid		   *rd_opfamily;	/* OIDs of op families for each index col */
+			Oid		   *rd_opcintype;	/* OIDs of opclass declared input data types */
+			RegProcedure *rd_support;	/* OIDs of support procedures */
+			struct FmgrInfo *rd_supportinfo;	/* lookup info for support procedures */
+			int16	   *rd_indoption;	/* per-column AM-specific flags */
+			List	   *rd_indexprs;	/* index expression trees, if any */
+			List	   *rd_indpred;		/* index predicate tree, if any */
+			Oid		   *rd_exclops;		/* OIDs of exclusion operators, if any */
+			Oid		   *rd_exclprocs;	/* OIDs of exclusion ops' procs, if any */
+			uint16	   *rd_exclstrats;	/* exclusion ops' strategy numbers, if any */
+			Oid		   *rd_indcollation;	/* OIDs of index collations */
+			bytea	  **rd_opcoptions;	/* parsed opclass-specific options */
+		};
+	};
+
 	RelFileLocator rd_locator;	/* relation physical identifier */
 	SMgrRelation rd_smgr;		/* cached file handle, or NULL */
 	int			rd_refcnt;		/* reference count */
@@ -61,9 +189,6 @@ typedef struct RelationData
 	bool		rd_islocaltemp; /* rel is a temp rel of this session */
 	bool		rd_isnailed;	/* rel is nailed in cache */
 	bool		rd_isvalid;		/* relcache entry is valid */
-	bool		rd_indexvalid;	/* is rd_indexlist valid? (also rd_pkindex and
-								 * rd_replidindex) */
-	bool		rd_statvalid;	/* is rd_statlist valid? */
 
 	/*----------
 	 * rd_createSubid is the ID of the highest subtransaction the rel has
@@ -112,61 +237,12 @@ typedef struct RelationData
 	TupleDesc	rd_att;			/* tuple descriptor */
 	Oid			rd_id;			/* relation's object id */
 	LockInfoData rd_lockInfo;	/* lock mgr's info for locking relation */
-	RuleLock   *rd_rules;		/* rewrite rules */
-	MemoryContext rd_rulescxt;	/* private memory cxt for rd_rules, if any */
-	TriggerDesc *trigdesc;		/* Trigger info, or NULL if rel has none */
-	/* use "struct" here to avoid needing to include rowsecurity.h: */
-	struct RowSecurityDesc *rd_rsdesc;	/* row security policies, or NULL */
-
-	/* data managed by RelationGetFKeyList: */
-	List	   *rd_fkeylist;	/* list of ForeignKeyCacheInfo (see below) */
-	bool		rd_fkeyvalid;	/* true if list has been computed */
-
-	/* data managed by RelationGetPartitionKey: */
-	PartitionKey rd_partkey;	/* partition key, or NULL */
-	MemoryContext rd_partkeycxt;	/* private context for rd_partkey, if any */
-
-	/* data managed by RelationGetPartitionDesc: */
-	PartitionDesc rd_partdesc;	/* partition descriptor, or NULL */
-	MemoryContext rd_pdcxt;		/* private context for rd_partdesc, if any */
-
-	/* Same as above, for partdescs that omit detached partitions */
-	PartitionDesc rd_partdesc_nodetached;	/* partdesc w/o detached parts */
-	MemoryContext rd_pddcxt;	/* for rd_partdesc_nodetached, if any */
-
-	/*
-	 * pg_inherits.xmin of the partition that was excluded in
-	 * rd_partdesc_nodetached.  This informs a future user of that partdesc:
-	 * if this value is not in progress for the active snapshot, then the
-	 * partdesc can be used, otherwise they have to build a new one.  (This
-	 * matches what find_inheritance_children_extended would do).
-	 */
-	TransactionId rd_partdesc_nodetached_xmin;
 
 	/* data managed by RelationGetPartitionQual: */
 	List	   *rd_partcheck;	/* partition CHECK quals */
 	bool		rd_partcheckvalid;	/* true if list has been computed */
 	MemoryContext rd_partcheckcxt;	/* private cxt for rd_partcheck, if any */
 
-	/* data managed by RelationGetIndexList: */
-	List	   *rd_indexlist;	/* list of OIDs of indexes on relation */
-	Oid			rd_pkindex;		/* OID of (deferrable?) primary key, if any */
-	bool		rd_ispkdeferrable;	/* is rd_pkindex a deferrable PK? */
-	Oid			rd_replidindex; /* OID of replica identity index, if any */
-
-	/* data managed by RelationGetStatExtList: */
-	List	   *rd_statlist;	/* list of OIDs of extended stats */
-
-	/* data managed by RelationGetIndexAttrBitmap: */
-	bool		rd_attrsvalid;	/* are bitmaps of attrs valid? */
-	Bitmapset  *rd_keyattr;		/* cols that can be ref'd by foreign keys */
-	Bitmapset  *rd_pkattr;		/* cols included in primary key */
-	Bitmapset  *rd_idattr;		/* included in replica identity index */
-	Bitmapset  *rd_hotblockingattr; /* cols blocking HOT update */
-	Bitmapset  *rd_summarizedattr;	/* cols indexed by summarizing indexes */
-
-	PublicationDesc *rd_pubdesc;	/* publication descriptor, or NULL */
-
 	/*
 	 * rd_options is set whenever rd_rel is loaded into the relcache entry.
 	 * Note that you can NOT look into rd_rel for this data.  NULL means "use
@@ -183,40 +259,6 @@ typedef struct RelationData
 	 */
 	Oid			rd_amhandler;	/* OID of index AM's handler function */
 
-	/*
-	 * Table access method.
-	 */
-	const struct TableAmRoutine *rd_tableam;
-
-	/* These are non-NULL only for an index relation: */
-	Form_pg_index rd_index;		/* pg_index tuple describing this index */
-	/* use "struct" here to avoid needing to include htup.h: */
-	struct HeapTupleData *rd_indextuple;	/* all of pg_index tuple */
-
-	/*
-	 * index access support info (used only for an index relation)
-	 *
-	 * Note: only default support procs for each opclass are cached, namely
-	 * those with lefttype and righttype equal to the opclass's opcintype. The
-	 * arrays are indexed by support function number, which is a sufficient
-	 * identifier given that restriction.
-	 */
-	MemoryContext rd_indexcxt;	/* private memory cxt for this stuff */
-	/* use "struct" here to avoid needing to include amapi.h: */
-	const struct IndexAmRoutine *rd_indam;	/* index AM's API struct */
-	Oid		   *rd_opfamily;	/* OIDs of op families for each index col */
-	Oid		   *rd_opcintype;	/* OIDs of opclass declared input data types */
-	RegProcedure *rd_support;	/* OIDs of support procedures */
-	struct FmgrInfo *rd_supportinfo;	/* lookup info for support procedures */
-	int16	   *rd_indoption;	/* per-column AM-specific flags */
-	List	   *rd_indexprs;	/* index expression trees, if any */
-	List	   *rd_indpred;		/* index predicate tree, if any */
-	Oid		   *rd_exclops;		/* OIDs of exclusion operators, if any */
-	Oid		   *rd_exclprocs;	/* OIDs of exclusion ops' procs, if any */
-	uint16	   *rd_exclstrats;	/* exclusion ops' strategy numbers, if any */
-	Oid		   *rd_indcollation;	/* OIDs of index collations */
-	bytea	  **rd_opcoptions;	/* parsed opclass-specific options */
-
 	/*
 	 * rd_amcache is available for index and table AMs to cache private data
 	 * about the relation.  This must be just a cache since it may get reset
@@ -228,37 +270,6 @@ typedef struct RelationData
 	 */
 	void	   *rd_amcache;		/* available for use by index/table AM */
 
-	/*
-	 * foreign-table support
-	 *
-	 * rd_fdwroutine must point to a single memory chunk palloc'd in
-	 * CacheMemoryContext.  It will be freed and reset to NULL on a relcache
-	 * reset.
-	 */
-
-	/* use "struct" here to avoid needing to include fdwapi.h: */
-	struct FdwRoutine *rd_fdwroutine;	/* cached function pointers, or NULL */
-
-	/*
-	 * Hack for CLUSTER, rewriting ALTER TABLE, etc: when writing a new
-	 * version of a table, we need to make any toast pointers inserted into it
-	 * have the existing toast table's OID, not the OID of the transient toast
-	 * table.  If rd_toastoid isn't InvalidOid, it is the OID to place in
-	 * toast pointers inserted into this rel.  (Note it's set on the new
-	 * version of the main heap, not the toast table itself.)  This also
-	 * causes toast_save_datum() to try to preserve toast value OIDs.
-	 */
-	Oid			rd_toastoid;	/* Real TOAST table's OID, or InvalidOid */
-
-	/*
-	 * Type OID of the "chunk_id" column of this relation's TOAST table, i.e.
-	 * OIDOID or OID8OID.
-	 *
-	 * This data is filled on demand by RelationGetToastChunkIdType(), not at
-	 * relcache build time, so as to save on syscache lookups.
-	 */
-	Oid			rd_toastchunkidtype;
-
 	bool		pgstat_enabled; /* should relation stats be counted */
 	/* use "struct" here to avoid needing to include pgstat.h: */
 	struct PgStat_RelationStatus *pgstat_info;	/* statistics collection area */
@@ -543,6 +554,14 @@ typedef struct ViewOptions
  */
 #define RelationGetRelid(relation) ((relation)->rd_id)
 
+/*
+ * RelationIsIndex
+ * 		True for both, ordinary and partitioned index relations.
+ */
+#define RelationIsIndex(relation) \
+	((relation)->rd_rel->relkind == RELKIND_INDEX || \
+	 (relation)->rd_rel->relkind == RELKIND_PARTITIONED_INDEX)
+
 /*
  * RelationGetNumberOfAttributes
  *		Returns the total number of attributes in a relation.
-- 
2.53.0

From e18a7a015d02df17fbbdd77747bc7f2dcc70843e Mon Sep 17 00:00:00 2001
From: David Geier <[email protected]>
Date: Thu, 15 Oct 2026 21:32:14 +0200
Subject: [PATCH v7 5/7] Allocate partition cache data lazily

Most relations never cache partition keys, descriptors, or partition quals.
Collect that state in RelationPartitionInfo and allocate it only when one of
the partition cache APIs needs it.

sizeof(RelationData): 296 bytes
---
 src/backend/partitioning/partdesc.c |  41 +++++----
 src/backend/utils/cache/partcache.c |  43 ++++++---
 src/backend/utils/cache/relcache.c  | 131 +++++++++++++++-------------
 src/include/utils/rel.h             |  70 +++++++++------
 4 files changed, 170 insertions(+), 115 deletions(-)

diff --git a/src/backend/partitioning/partdesc.c b/src/backend/partitioning/partdesc.c
index 4399fe9a3a0..951e708c5d1 100644
--- a/src/backend/partitioning/partdesc.c
+++ b/src/backend/partitioning/partdesc.c
@@ -70,6 +70,8 @@ static PartitionDesc RelationBuildPartitionDesc(Relation rel,
 PartitionDesc
 RelationGetPartitionDesc(Relation rel, bool omit_detached)
 {
+	RelationPartitionInfo *partinfo = rel->rd_partinfo;
+
 	Assert(rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE);
 
 	/*
@@ -80,10 +82,10 @@ RelationGetPartitionDesc(Relation rel, bool omit_detached)
 	 * If there is no active snapshot, detached partitions aren't omitted
 	 * either, so we can use the cached descriptor too in that case.
 	 */
-	if (likely(rel->rd_partdesc &&
-			   (!rel->rd_partdesc->detached_exist || !omit_detached ||
+	if (likely(partinfo && partinfo->partdesc &&
+			   (!partinfo->partdesc->detached_exist || !omit_detached ||
 				!ActiveSnapshotSet())))
-		return rel->rd_partdesc;
+		return partinfo->partdesc;
 
 	/*
 	 * If we're asked to omit detached partitions, we may be able to use a
@@ -94,16 +96,17 @@ RelationGetPartitionDesc(Relation rel, bool omit_detached)
 	 * scratch.
 	 */
 	if (omit_detached &&
-		rel->rd_partdesc_nodetached &&
+		partinfo &&
+		partinfo->partdesc_nodetached &&
 		ActiveSnapshotSet())
 	{
 		Snapshot	activesnap;
 
-		Assert(TransactionIdIsValid(rel->rd_partdesc_nodetached_xmin));
+		Assert(TransactionIdIsValid(partinfo->partdesc_nodetached_xmin));
 		activesnap = GetActiveSnapshot();
 
-		if (!XidInMVCCSnapshot(rel->rd_partdesc_nodetached_xmin, activesnap))
-			return rel->rd_partdesc_nodetached;
+		if (!XidInMVCCSnapshot(partinfo->partdesc_nodetached_xmin, activesnap))
+			return partinfo->partdesc_nodetached;
 	}
 
 	return RelationBuildPartitionDesc(rel, omit_detached);
@@ -147,6 +150,7 @@ RelationBuildPartitionDesc(Relation rel, bool omit_detached)
 				nparts;
 	bool		retried = false;
 	PartitionKey partkey = RelationGetPartitionKey(rel);
+	RelationPartitionInfo *partinfo;
 	MemoryContext new_pdcxt;
 	MemoryContext oldcxt;
 	int		   *mapping;
@@ -385,12 +389,17 @@ retry:
 	 * the regular partdesc in rd_pdcxt, and the partdesc-excluding-
 	 * detached-partitions in rd_pddcxt.)
 	 */
+	if (rel->rd_partinfo == NULL)
+		rel->rd_partinfo = MemoryContextAllocZero(CacheMemoryContext,
+												  sizeof(RelationPartitionInfo));
+	partinfo = rel->rd_partinfo;
+
 	if (is_omit)
 	{
-		if (rel->rd_pddcxt != NULL)
-			MemoryContextSetParent(rel->rd_pddcxt, new_pdcxt);
-		rel->rd_pddcxt = new_pdcxt;
-		rel->rd_partdesc_nodetached = partdesc;
+		if (partinfo->pddcxt != NULL)
+			MemoryContextSetParent(partinfo->pddcxt, new_pdcxt);
+		partinfo->pddcxt = new_pdcxt;
+		partinfo->partdesc_nodetached = partdesc;
 
 		/*
 		 * For partdescs built excluding detached partitions, which we save
@@ -401,14 +410,14 @@ retry:
 		 * with.
 		 */
 		Assert(TransactionIdIsValid(detached_xmin));
-		rel->rd_partdesc_nodetached_xmin = detached_xmin;
+		partinfo->partdesc_nodetached_xmin = detached_xmin;
 	}
 	else
 	{
-		if (rel->rd_pdcxt != NULL)
-			MemoryContextSetParent(rel->rd_pdcxt, new_pdcxt);
-		rel->rd_pdcxt = new_pdcxt;
-		rel->rd_partdesc = partdesc;
+		if (partinfo->pdcxt != NULL)
+			MemoryContextSetParent(partinfo->pdcxt, new_pdcxt);
+		partinfo->pdcxt = new_pdcxt;
+		partinfo->partdesc = partdesc;
 	}
 
 	return partdesc;
diff --git a/src/backend/utils/cache/partcache.c b/src/backend/utils/cache/partcache.c
index a0982674884..e7c563eaca3 100644
--- a/src/backend/utils/cache/partcache.c
+++ b/src/backend/utils/cache/partcache.c
@@ -53,10 +53,10 @@ RelationGetPartitionKey(Relation rel)
 	if (rel->rd_rel->relkind != RELKIND_PARTITIONED_TABLE)
 		return NULL;
 
-	if (unlikely(rel->rd_partkey == NULL))
+	if (unlikely(rel->rd_partinfo == NULL || rel->rd_partinfo->partkey == NULL))
 		RelationBuildPartitionKey(rel);
 
-	return rel->rd_partkey;
+	return rel->rd_partinfo->partkey;
 }
 
 /*
@@ -90,6 +90,7 @@ RelationBuildPartitionKey(Relation relation)
 	MemoryContext partkeycxt,
 				oldcxt;
 	int16		procnum;
+	RelationPartitionInfo *partinfo;
 
 	tuple = SearchSysCache1(PARTRELID,
 							ObjectIdGetDatum(RelationGetRelid(relation)));
@@ -255,17 +256,23 @@ RelationBuildPartitionKey(Relation relation)
 
 	ReleaseSysCache(tuple);
 
+	partinfo = relation->rd_partinfo;
+
 	/* Assert that we're not leaking any old data during assignments below */
-	Assert(relation->rd_partkeycxt == NULL);
-	Assert(relation->rd_partkey == NULL);
+	Assert(partinfo == NULL || partinfo->partkeycxt == NULL);
+	Assert(partinfo == NULL || partinfo->partkey == NULL);
 
 	/*
 	 * Success --- reparent our context and make the relcache point to the
 	 * newly constructed key
 	 */
+	if (partinfo == NULL)
+		relation->rd_partinfo = partinfo =
+			MemoryContextAllocZero(CacheMemoryContext,
+								   sizeof(RelationPartitionInfo));
 	MemoryContextSetParent(partkeycxt, CacheMemoryContext);
-	relation->rd_partkeycxt = partkeycxt;
-	relation->rd_partkey = key;
+	partinfo->partkeycxt = partkeycxt;
+	partinfo->partkey = key;
 }
 
 /*
@@ -344,13 +351,14 @@ generate_partition_qual(Relation rel)
 			   *result = NIL;
 	Oid			parentrelid;
 	Relation	parent;
+	RelationPartitionInfo *partinfo;
 
 	/* Guard against stack overflow due to overly deep partition tree */
 	check_stack_depth();
 
 	/* If we already cached the result, just return a copy */
-	if (rel->rd_partcheckvalid)
-		return copyObject(rel->rd_partcheck);
+	if (rel->rd_partinfo && rel->rd_partinfo->partcheckvalid)
+		return copyObject(rel->rd_partinfo->partcheck);
 
 	/*
 	 * Grab at least an AccessShareLock on the parent table.  Must do this
@@ -397,9 +405,16 @@ generate_partition_qual(Relation rel)
 	 */
 	result = map_partition_varattnos(result, 1, rel, parent);
 
+	partinfo = rel->rd_partinfo;
+
 	/* Assert that we're not leaking any old data during assignments below */
-	Assert(rel->rd_partcheckcxt == NULL);
-	Assert(rel->rd_partcheck == NIL);
+	Assert(partinfo == NULL || partinfo->partcheckcxt == NULL);
+	Assert(partinfo == NULL || partinfo->partcheck == NIL);
+
+	if (partinfo == NULL)
+		rel->rd_partinfo = partinfo =
+			MemoryContextAllocZero(CacheMemoryContext,
+								   sizeof(RelationPartitionInfo));
 
 	/*
 	 * Save a copy in the relcache.  The order of these operations is fairly
@@ -434,12 +449,12 @@ generate_partition_qual(Relation rel)
 		/* finally, link the allocations and memctx into the right places */
 		MemoryContextSetParent(partctx, CacheMemoryContext);
 
-		rel->rd_partcheckcxt = partctx;
-		rel->rd_partcheck = partcheck;
+		partinfo->partcheckcxt = partctx;
+		partinfo->partcheck = partcheck;
 	}
 	else
-		rel->rd_partcheck = NIL;
-	rel->rd_partcheckvalid = true;
+		partinfo->partcheck = NIL;
+	partinfo->partcheckvalid = true;
 
 	/* Keep the parent locked until commit */
 	relation_close(parent, NoLock);
diff --git a/src/backend/utils/cache/relcache.c b/src/backend/utils/cache/relcache.c
index a9b7568951d..ad715bae3c0 100644
--- a/src/backend/utils/cache/relcache.c
+++ b/src/backend/utils/cache/relcache.c
@@ -93,7 +93,7 @@
 #include "utils/snapmgr.h"
 #include "utils/syscache.h"
 
-#define RELCACHE_INIT_FILEMAGIC		0x573267	/* version ID value */
+#define RELCACHE_INIT_FILEMAGIC		0x573268	/* version ID value */
 
 /*
  * Whether to bother checking if relation cache memory needs to be freed
@@ -1214,9 +1214,7 @@ retry:
 	 */
 	RelationBuildTupleDesc(relation);
 
-	relation->rd_partcheck = NIL;
-	relation->rd_partcheckvalid = false;
-	relation->rd_partcheckcxt = NULL;
+	relation->rd_partinfo = NULL;
 
 	/*
 	 * initialize the relation lock manager information
@@ -1240,15 +1238,6 @@ retry:
 	}
 	else
 	{
-		/* partitioning data is not loaded till asked for */
-		relation->rd_partkey = NULL;
-		relation->rd_partkeycxt = NULL;
-		relation->rd_partdesc = NULL;
-		relation->rd_partdesc_nodetached = NULL;
-		relation->rd_partdesc_nodetached_xmin = InvalidTransactionId;
-		relation->rd_pdcxt = NULL;
-		relation->rd_pddcxt = NULL;
-
 		/*
 		 * initialize access method information
 		 */
@@ -2248,15 +2237,16 @@ RelationCloseCleanup(Relation relation)
 	 * stale partition descriptors it has.  This is unlikely, so check to see
 	 * if there are child contexts before expending a call to mcxt.c.
 	 */
-	if (RelationHasReferenceCountZero(relation) && !RelationIsIndex(relation))
+	if (RelationHasReferenceCountZero(relation) &&
+	    !RelationIsIndex(relation) && relation->rd_partinfo != NULL)
 	{
-		if (relation->rd_pdcxt != NULL &&
-			relation->rd_pdcxt->firstchild != NULL)
-			MemoryContextDeleteChildren(relation->rd_pdcxt);
+		RelationPartitionInfo *partinfo = relation->rd_partinfo;
+
+		if (partinfo->pdcxt != NULL && partinfo->pdcxt->firstchild != NULL)
+			MemoryContextDeleteChildren(partinfo->pdcxt);
 
-		if (relation->rd_pddcxt != NULL &&
-			relation->rd_pddcxt->firstchild != NULL)
-			MemoryContextDeleteChildren(relation->rd_pddcxt);
+		if (partinfo->pddcxt != NULL && partinfo->pddcxt->firstchild != NULL)
+			MemoryContextDeleteChildren(partinfo->pddcxt);
 	}
 
 #ifdef RELCACHE_FORCE_RELEASE
@@ -2493,8 +2483,20 @@ RelationDestroyRelation(Relation relation, bool remember_tupdesc)
 		pfree(relation->rd_options);
 	if (relation->rd_amcache)
 		pfree(relation->rd_amcache);
-	if (relation->rd_partcheckcxt)
-		MemoryContextDelete(relation->rd_partcheckcxt);
+	if (relation->rd_partinfo)
+	{
+		RelationPartitionInfo *partinfo = relation->rd_partinfo;
+
+		if (partinfo->partkeycxt)
+			MemoryContextDelete(partinfo->partkeycxt);
+		if (partinfo->pdcxt)
+			MemoryContextDelete(partinfo->pdcxt);
+		if (partinfo->pddcxt)
+			MemoryContextDelete(partinfo->pddcxt);
+		if (partinfo->partcheckcxt)
+			MemoryContextDelete(partinfo->partcheckcxt);
+		pfree(partinfo);
+	}
 	if (!is_index)
 	{
 		list_free(relation->rd_indexlist);
@@ -2514,12 +2516,6 @@ RelationDestroyRelation(Relation relation, bool remember_tupdesc)
 			MemoryContextDelete(relation->rd_rulescxt);
 		if (relation->rd_rsdesc)
 			MemoryContextDelete(relation->rd_rsdesc->rscxt);
-		if (relation->rd_partkeycxt)
-			MemoryContextDelete(relation->rd_partkeycxt);
-		if (relation->rd_pdcxt)
-			MemoryContextDelete(relation->rd_pdcxt);
-		if (relation->rd_pddcxt)
-			MemoryContextDelete(relation->rd_pddcxt);
 	}
 	else
 	{
@@ -2724,9 +2720,23 @@ RelationRebuildRelation(Relation relation)
 			keep_rules = equalRuleLocks(relation->rd_rules, newrel->rd_rules);
 			keep_policies = equalRSDesc(relation->rd_rsdesc, newrel->rd_rsdesc);
 			/* partkey is immutable once set up, so we can always keep it */
-			keep_partkey = (relation->rd_partkey != NULL);
+			keep_partkey = (relation->rd_partinfo != NULL &&
+							relation->rd_partinfo->partkey != NULL);
 		}
 
+		/*
+		 * Ensure that the destination has storage for partition metadata
+		 * before starting the descriptor swap.  Nothing in the swap region
+		 * may fail, because relation is transiently inconsistent there.
+		 */
+		if (!is_index && newrel->rd_partinfo == NULL &&
+			(keep_partkey ||
+			 (relation->rd_partinfo != NULL &&
+			  (relation->rd_partinfo->pdcxt != NULL ||
+			   relation->rd_partinfo->pddcxt != NULL))))
+			newrel->rd_partinfo = MemoryContextAllocZero(CacheMemoryContext,
+														 sizeof(RelationPartitionInfo));
+
 		/*
 		 * Perform swapping of the relcache entry contents.  Within this
 		 * process the old entry is momentarily invalid, so there *must* be no
@@ -2789,27 +2799,36 @@ RelationRebuildRelation(Relation relation)
 			/* toast OID override must be preserved */
 			SWAPFIELD(Oid, rd_toastoid);
 
-			/* preserve old partition key if we have one */
+			/*
+			 * preserve old partition key if we have one; rd_partinfo as a whole
+			 * has already been swapped above along with the rest of the struct,
+			 * so at this point "relation" holds the freshly-built (usually NULL)
+			 * rd_partinfo and "newrel" holds the old one.
+			 */
 			if (keep_partkey)
 			{
-				SWAPFIELD(PartitionKey, rd_partkey);
-				SWAPFIELD(MemoryContext, rd_partkeycxt);
+				SWAPFIELD(PartitionKey, rd_partinfo->partkey);
+				SWAPFIELD(MemoryContext, rd_partinfo->partkeycxt);
 			}
-			if (newrel->rd_pdcxt != NULL || newrel->rd_pddcxt != NULL)
+			if (newrel->rd_partinfo != NULL &&
+				(newrel->rd_partinfo->pdcxt != NULL || newrel->rd_partinfo->pddcxt != NULL))
 			{
+				RelationPartitionInfo *old_partinfo = newrel->rd_partinfo;
+				RelationPartitionInfo *partinfo = relation->rd_partinfo;
+
 				/*
 				 * We are rebuilding a partitioned relation with a non-zero
 				 * reference count, so we must keep the old partition descriptor
 				 * around, in case there's a PartitionDirectory with a pointer to
-				 * it.  This means we can't free the old rd_pdcxt yet.  (This is
+				 * it.  This means we can't free the old pdcxt yet.  (This is
 				 * necessary because RelationGetPartitionDesc hands out direct
 				 * pointers to the relcache's data structure, unlike our usual
 				 * practice which is to hand out copies.  We'd have the same
-				 * problem with rd_partkey, except that we always preserve that
+				 * problem with partkey, except that we always preserve that
 				 * once created.)
 				 *
 				 * To ensure that it's not leaked completely, re-attach it to the
-				 * new reldesc, or make it a child of the new reldesc's rd_pdcxt
+				 * new reldesc, or make it a child of the new reldesc's pdcxt
 				 * in the unlikely event that there is one already.  (Compare hack
 				 * in RelationBuildPartitionDesc.)  RelationClose will clean up
 				 * any such contexts once the reference count reaches zero.
@@ -2822,23 +2841,24 @@ RelationRebuildRelation(Relation relation)
 				 * "old" partition descriptor is actually the one hanging off of
 				 * newrel.
 				 */
-				relation->rd_partdesc = NULL;	/* ensure rd_partdesc is invalid */
-				relation->rd_partdesc_nodetached = NULL;
-				relation->rd_partdesc_nodetached_xmin = InvalidTransactionId;
-				if (relation->rd_pdcxt != NULL) /* probably never happens */
-					MemoryContextSetParent(newrel->rd_pdcxt, relation->rd_pdcxt);
+				Assert(partinfo != NULL);
+				partinfo->partdesc = NULL;	/* ensure partdesc is invalid */
+				partinfo->partdesc_nodetached = NULL;
+				partinfo->partdesc_nodetached_xmin = InvalidTransactionId;
+				if (partinfo->pdcxt != NULL)	/* probably never happens */
+					MemoryContextSetParent(old_partinfo->pdcxt, partinfo->pdcxt);
 				else
-					relation->rd_pdcxt = newrel->rd_pdcxt;
-				if (relation->rd_pddcxt != NULL)
-					MemoryContextSetParent(newrel->rd_pddcxt, relation->rd_pddcxt);
+					partinfo->pdcxt = old_partinfo->pdcxt;
+				if (partinfo->pddcxt != NULL)
+					MemoryContextSetParent(old_partinfo->pddcxt, partinfo->pddcxt);
 				else
-					relation->rd_pddcxt = newrel->rd_pddcxt;
+					partinfo->pddcxt = old_partinfo->pddcxt;
 				/* drop newrel's pointers so we don't destroy it below */
-				newrel->rd_partdesc = NULL;
-				newrel->rd_partdesc_nodetached = NULL;
-				newrel->rd_partdesc_nodetached_xmin = InvalidTransactionId;
-				newrel->rd_pdcxt = NULL;
-				newrel->rd_pddcxt = NULL;
+				old_partinfo->partdesc = NULL;
+				old_partinfo->partdesc_nodetached = NULL;
+				old_partinfo->partdesc_nodetached_xmin = InvalidTransactionId;
+				old_partinfo->pdcxt = NULL;
+				old_partinfo->pddcxt = NULL;
 			}
 		}
 
@@ -6576,13 +6596,6 @@ load_relcache_init_file(bool shared)
 			rel->rd_rulescxt = NULL;
 			rel->trigdesc = NULL;
 			rel->rd_rsdesc = NULL;
-			rel->rd_partkey = NULL;
-			rel->rd_partkeycxt = NULL;
-			rel->rd_partdesc = NULL;
-			rel->rd_partdesc_nodetached = NULL;
-			rel->rd_partdesc_nodetached_xmin = InvalidTransactionId;
-			rel->rd_pdcxt = NULL;
-			rel->rd_pddcxt = NULL;
 			rel->rd_keyattr = NULL;
 			rel->rd_pkattr = NULL;
 			rel->rd_idattr = NULL;
@@ -6615,9 +6628,7 @@ load_relcache_init_file(bool shared)
 		 * Reset transient-state fields in the relcache entry
 		 */
 		rel->rd_smgr = NULL;
-		rel->rd_partcheck = NIL;
-		rel->rd_partcheckvalid = false;
-		rel->rd_partcheckcxt = NULL;
+		rel->rd_partinfo = NULL;
 		if (rel->rd_isnailed)
 			rel->rd_refcnt = 1;
 		else
diff --git a/src/include/utils/rel.h b/src/include/utils/rel.h
index 9777dd46a53..af82ce99fd9 100644
--- a/src/include/utils/rel.h
+++ b/src/include/utils/rel.h
@@ -48,6 +48,45 @@ typedef struct LockInfoData
 
 typedef LockInfoData *LockInfo;
 
+/*
+ * RelationPartitionInfo
+ *		Partition-related data cached for a relation, allocated lazily on
+ *		first use.  Only ever populated for partitioned tables (partkey and
+ *		the partdesc fields) and/or partitions (partcheck fields); most
+ *		relations need none of this, hence it's a separate lazily-allocated
+ *		struct rather than a set of fields embedded directly in
+ *		RelationData.
+ */
+typedef struct RelationPartitionInfo
+{
+	/* data managed by RelationGetPartitionKey: */
+	PartitionKey partkey;		/* partition key, or NULL */
+	MemoryContext partkeycxt;	/* private context for partkey, if any */
+
+	/* data managed by RelationGetPartitionDesc: */
+	PartitionDesc partdesc;		/* partition descriptor, or NULL */
+	MemoryContext pdcxt;		/* private context for partdesc, if any */
+
+	/* Same as above, for partdescs that omit detached partitions */
+	PartitionDesc partdesc_nodetached; /* partdesc w/o detached parts */
+	MemoryContext pddcxt;		/* for partdesc_nodetached, if any */
+
+	/* data managed by RelationGetPartitionQual: */
+	List	   *partcheck;		/* partition CHECK quals */
+	MemoryContext partcheckcxt; /* private cxt for partcheck, if any */
+
+	/*
+	 * pg_inherits.xmin of the partition that was excluded in
+	 * partdesc_nodetached.  This informs a future user of that partdesc: if
+	 * this value is not in progress for the active snapshot, then the
+	 * partdesc can be used, otherwise they have to build a new one.  (This
+	 * matches what find_inheritance_children_extended would do).
+	 */
+	TransactionId partdesc_nodetached_xmin;
+
+	bool		partcheckvalid; /* true if partcheck has been computed */
+} RelationPartitionInfo;
+
 /*
  * Here are the contents of a relation cache entry.
  */
@@ -69,27 +108,6 @@ typedef struct RelationData
 			List	   *rd_fkeylist;	/* list of ForeignKeyCacheInfo (see below) */
 			bool		rd_fkeyvalid;	/* true if rd_fkeylist has been computed */
 
-			/* data managed by RelationGetPartitionKey: */
-			PartitionKey rd_partkey;	/* partition key, or NULL */
-			MemoryContext rd_partkeycxt;	/* private context for rd_partkey, if any */
-
-			/* data managed by RelationGetPartitionDesc: */
-			PartitionDesc rd_partdesc;	/* partition descriptor, or NULL */
-			MemoryContext rd_pdcxt;		/* private context for rd_partdesc, if any */
-
-			/* Same as above, for partdescs that omit detached partitions */
-			PartitionDesc rd_partdesc_nodetached;	/* partdesc w/o detached parts */
-			MemoryContext rd_pddcxt;	/* for rd_partdesc_nodetached, if any */
-
-			/*
-			 * pg_inherits.xmin of the partition that was excluded in
-			 * rd_partdesc_nodetached.  This informs a future user of that partdesc:
-			 * if this value is not in progress for the active snapshot, then the
-			 * partdesc can be used, otherwise they have to build a new one.  (This
-			 * matches what find_inheritance_children_extended would do).
-			 */
-			TransactionId rd_partdesc_nodetached_xmin;
-
 			/* data managed by RelationGetIndexList: */
 			List	   *rd_indexlist;	/* list of OIDs of indexes on relation */
 			Oid			rd_pkindex;		/* OID of (deferrable?) primary key, if any */
@@ -238,10 +256,12 @@ typedef struct RelationData
 	Oid			rd_id;			/* relation's object id */
 	LockInfoData rd_lockInfo;	/* lock mgr's info for locking relation */
 
-	/* data managed by RelationGetPartitionQual: */
-	List	   *rd_partcheck;	/* partition CHECK quals */
-	bool		rd_partcheckvalid;	/* true if list has been computed */
-	MemoryContext rd_partcheckcxt;	/* private cxt for rd_partcheck, if any */
+	/*
+	 * Data managed by RelationGetPartitionKey(), RelationGetPartitionDesc(),
+	 * and RelationGetPartitionQual(); NULL if none of these has been
+	 * called for this relation.  See RelationPartitionInfo above.
+	 */
+	RelationPartitionInfo *rd_partinfo;
 
 	/*
 	 * rd_options is set whenever rd_rel is loaded into the relcache entry.
-- 
2.53.0

From 78071a7de9d47c28c6cf4aaf8dc70f682474bbb3 Mon Sep 17 00:00:00 2001
From: David Geier <[email protected]>
Date: Thu, 15 Oct 2026 21:37:37 +0200
Subject: [PATCH v7 6/7] Pack RelationData to eliminate padding

Reorder a small number of members to fill alignment gaps while retaining the
existing logical groups where they do not introduce padding.

sizeof(RelationData): 256 bytes
---
 src/backend/utils/cache/relcache.c |  2 +-
 src/include/utils/rel.h            | 31 +++++++++++++++---------------
 2 files changed, 17 insertions(+), 16 deletions(-)

diff --git a/src/backend/utils/cache/relcache.c b/src/backend/utils/cache/relcache.c
index ad715bae3c0..30355a405be 100644
--- a/src/backend/utils/cache/relcache.c
+++ b/src/backend/utils/cache/relcache.c
@@ -93,7 +93,7 @@
 #include "utils/snapmgr.h"
 #include "utils/syscache.h"
 
-#define RELCACHE_INIT_FILEMAGIC		0x573268	/* version ID value */
+#define RELCACHE_INIT_FILEMAGIC		0x573269	/* version ID value */
 
 /*
  * Whether to bother checking if relation cache memory needs to be freed
diff --git a/src/include/utils/rel.h b/src/include/utils/rel.h
index af82ce99fd9..ea9fd919ed3 100644
--- a/src/include/utils/rel.h
+++ b/src/include/utils/rel.h
@@ -106,7 +106,6 @@ typedef struct RelationData
 
 			/* data managed by RelationGetFKeyList: */
 			List	   *rd_fkeylist;	/* list of ForeignKeyCacheInfo (see below) */
-			bool		rd_fkeyvalid;	/* true if rd_fkeylist has been computed */
 
 			/* data managed by RelationGetIndexList: */
 			List	   *rd_indexlist;	/* list of OIDs of indexes on relation */
@@ -114,11 +113,13 @@ typedef struct RelationData
 			bool		rd_ispkdeferrable;	/* is rd_pkindex a deferrable PK? */
 			bool		rd_indexvalid;	/* is rd_indexlist valid? (also rd_pkindex and
 									 * rd_replidindex) */
+			bool		rd_fkeyvalid;	/* true if rd_fkeylist has been computed */
+			bool		rd_attrsvalid;	/* are bitmaps of attrs valid? (see
+									 * RelationGetIndexAttrBitmap) */
+			bool		rd_statvalid;	/* is rd_statlist valid? */
 			Oid			rd_replidindex; /* OID of replica identity index, if any */
 
 			/* data managed by RelationGetIndexAttrBitmap: */
-			bool		rd_attrsvalid;	/* are bitmaps of attrs valid? (see
-									 * RelationGetIndexAttrBitmap) */
 			Bitmapset  *rd_keyattr;		/* cols that can be ref'd by foreign keys */
 			Bitmapset  *rd_pkattr;		/* cols included in primary key */
 			Bitmapset  *rd_idattr;		/* included in replica identity index */
@@ -127,7 +128,6 @@ typedef struct RelationData
 
 			/* data managed by RelationGetStatExtList: */
 			List	   *rd_statlist;	/* list of OIDs of extended stats */
-			bool		rd_statvalid;	/* is rd_statlist valid? */
 
 			/*
 			 * Table access method.
@@ -200,13 +200,14 @@ typedef struct RelationData
 		};
 	};
 
-	RelFileLocator rd_locator;	/* relation physical identifier */
 	SMgrRelation rd_smgr;		/* cached file handle, or NULL */
+	RelFileLocator rd_locator;	/* relation physical identifier */
 	int			rd_refcnt;		/* reference count */
 	ProcNumber	rd_backend;		/* owning backend's proc number, if temp rel */
 	bool		rd_islocaltemp; /* rel is a temp rel of this session */
 	bool		rd_isnailed;	/* rel is nailed in cache */
 	bool		rd_isvalid;		/* relcache entry is valid */
+	bool		pgstat_enabled; /* should relation stats be counted */
 
 	/*----------
 	 * rd_createSubid is the ID of the highest subtransaction the rel has
@@ -254,6 +255,16 @@ typedef struct RelationData
 	Form_pg_class rd_rel;		/* RELATION tuple */
 	TupleDesc	rd_att;			/* tuple descriptor */
 	Oid			rd_id;			/* relation's object id */
+
+	/*
+	 * Oid of the handler for this relation. For an index this is a function
+	 * returning IndexAmRoutine, for table like relations a function returning
+	 * TableAmRoutine.  This is stored separately from rd_indam, rd_tableam as
+	 * its lookup requires syscache access, but during relcache bootstrap we
+	 * need to be able to initialize rd_tableam without syscache lookups.
+	 */
+	Oid			rd_amhandler;	/* OID of index AM's handler function */
+
 	LockInfoData rd_lockInfo;	/* lock mgr's info for locking relation */
 
 	/*
@@ -270,15 +281,6 @@ typedef struct RelationData
 	 */
 	bytea	   *rd_options;		/* parsed pg_class.reloptions */
 
-	/*
-	 * Oid of the handler for this relation. For an index this is a function
-	 * returning IndexAmRoutine, for table like relations a function returning
-	 * TableAmRoutine.  This is stored separately from rd_indam, rd_tableam as
-	 * its lookup requires syscache access, but during relcache bootstrap we
-	 * need to be able to initialize rd_tableam without syscache lookups.
-	 */
-	Oid			rd_amhandler;	/* OID of index AM's handler function */
-
 	/*
 	 * rd_amcache is available for index and table AMs to cache private data
 	 * about the relation.  This must be just a cache since it may get reset
@@ -290,7 +292,6 @@ typedef struct RelationData
 	 */
 	void	   *rd_amcache;		/* available for use by index/table AM */
 
-	bool		pgstat_enabled; /* should relation stats be counted */
 	/* use "struct" here to avoid needing to include pgstat.h: */
 	struct PgStat_RelationStatus *pgstat_info;	/* statistics collection area */
 } RelationData;
-- 
2.53.0

From 458454fe56fa364284c57f16f5eeb50c1e1c3046 Mon Sep 17 00:00:00 2001
From: David Geier <[email protected]>
Date: Thu, 15 Oct 2026 21:32:27 +0200
Subject: [PATCH v7 7/7] Compute relation lock identifiers on demand

A relation lock identifier is fully determined by the relation OID, shared
status, and current database.  Compute it when needed instead of caching
rd_lockInfo in every relcache entry.

sizeof(RelationData): 248 bytes
---
 src/backend/access/common/relation.c   |  2 +-
 src/backend/access/heap/heapam.c       |  4 +-
 src/backend/access/index/indexam.c     |  2 +-
 src/backend/access/nbtree/nbtutils.c   | 14 ++---
 src/backend/access/transam/xlogutils.c | 25 +++++---
 src/backend/catalog/index.c            |  4 +-
 src/backend/commands/indexcmds.c       |  8 +--
 src/backend/commands/vacuum.c          |  2 +-
 src/backend/storage/lmgr/lmgr.c        | 80 ++++++++++----------------
 src/backend/utils/cache/relcache.c     | 21 ++-----
 src/include/storage/lmgr.h             |  2 -
 src/include/utils/rel.h                | 32 ++++++++---
 12 files changed, 93 insertions(+), 103 deletions(-)

diff --git a/src/backend/access/common/relation.c b/src/backend/access/common/relation.c
index 38b356b8239..2d0fed50a9e 100644
--- a/src/backend/access/common/relation.c
+++ b/src/backend/access/common/relation.c
@@ -205,7 +205,7 @@ relation_openrv_extended(const RangeVar *relation, LOCKMODE lockmode,
 void
 relation_close(Relation relation, LOCKMODE lockmode)
 {
-	LockRelId	relid = relation->rd_lockInfo.lockRelId;
+	LockRelId	relid = RelationGetLockRelId(relation);
 
 	Assert(lockmode >= NoLock && lockmode < MAX_LOCKMODES);
 
diff --git a/src/backend/access/heap/heapam.c b/src/backend/access/heap/heapam.c
index 6a09a1a1517..e283fecdc5b 100644
--- a/src/backend/access/heap/heapam.c
+++ b/src/backend/access/heap/heapam.c
@@ -4404,8 +4404,8 @@ check_lock_if_inplace_updateable_rel(Relation relation,
 				LOCKTAG		tuptag;
 
 				SET_LOCKTAG_TUPLE(tuptag,
-								  relation->rd_lockInfo.lockRelId.dbId,
-								  relation->rd_lockInfo.lockRelId.relId,
+								  RelationGetLockRelId(relation).dbId,
+								  RelationGetLockRelId(relation).relId,
 								  ItemPointerGetBlockNumber(otid),
 								  ItemPointerGetOffsetNumber(otid));
 				if (LockHeldByMe(&tuptag, InplaceUpdateTupleLock, false))
diff --git a/src/backend/access/index/indexam.c b/src/backend/access/index/indexam.c
index db811056991..04c97f0c7b2 100644
--- a/src/backend/access/index/indexam.c
+++ b/src/backend/access/index/indexam.c
@@ -181,7 +181,7 @@ try_index_open(Oid relationId, LOCKMODE lockmode)
 void
 index_close(Relation relation, LOCKMODE lockmode)
 {
-	LockRelId	relid = relation->rd_lockInfo.lockRelId;
+	LockRelId	relid = RelationGetLockRelId(relation);
 
 	Assert(lockmode >= NoLock && lockmode < MAX_LOCKMODES);
 
diff --git a/src/backend/access/nbtree/nbtutils.c b/src/backend/access/nbtree/nbtutils.c
index 85c1b632522..204d8de11e2 100644
--- a/src/backend/access/nbtree/nbtutils.c
+++ b/src/backend/access/nbtree/nbtutils.c
@@ -448,8 +448,8 @@ _bt_vacuum_cycleid(Relation rel)
 	{
 		BTOneVacInfo *vac = &btvacinfo->vacuums[i];
 
-		if (vac->relid.relId == rel->rd_lockInfo.lockRelId.relId &&
-			vac->relid.dbId == rel->rd_lockInfo.lockRelId.dbId)
+		if (vac->relid.relId == RelationGetLockRelId(rel).relId &&
+			vac->relid.dbId == RelationGetLockRelId(rel).dbId)
 		{
 			result = vac->cycleid;
 			break;
@@ -490,8 +490,8 @@ _bt_start_vacuum(Relation rel)
 	for (i = 0; i < btvacinfo->num_vacuums; i++)
 	{
 		vac = &btvacinfo->vacuums[i];
-		if (vac->relid.relId == rel->rd_lockInfo.lockRelId.relId &&
-			vac->relid.dbId == rel->rd_lockInfo.lockRelId.dbId)
+		if (vac->relid.relId == RelationGetLockRelId(rel).relId &&
+			vac->relid.dbId == RelationGetLockRelId(rel).dbId)
 		{
 			/*
 			 * Unlike most places in the backend, we have to explicitly
@@ -512,7 +512,7 @@ _bt_start_vacuum(Relation rel)
 		elog(ERROR, "out of btvacinfo slots");
 	}
 	vac = &btvacinfo->vacuums[btvacinfo->num_vacuums];
-	vac->relid = rel->rd_lockInfo.lockRelId;
+	vac->relid = RelationGetLockRelId(rel);
 	vac->cycleid = result;
 	btvacinfo->num_vacuums++;
 
@@ -538,8 +538,8 @@ _bt_end_vacuum(Relation rel)
 	{
 		BTOneVacInfo *vac = &btvacinfo->vacuums[i];
 
-		if (vac->relid.relId == rel->rd_lockInfo.lockRelId.relId &&
-			vac->relid.dbId == rel->rd_lockInfo.lockRelId.dbId)
+		if (vac->relid.relId == RelationGetLockRelId(rel).relId &&
+			vac->relid.dbId == RelationGetLockRelId(rel).dbId)
 		{
 			/* Remove it by shifting down the last entry */
 			*vac = btvacinfo->vacuums[btvacinfo->num_vacuums - 1];
diff --git a/src/backend/access/transam/xlogutils.c b/src/backend/access/transam/xlogutils.c
index ff71e14015d..c86f872b51e 100644
--- a/src/backend/access/transam/xlogutils.c
+++ b/src/backend/access/transam/xlogutils.c
@@ -23,6 +23,7 @@
 #include "access/xlogrecovery.h"
 #include "access/xlog_internal.h"
 #include "access/xlogutils.h"
+#include "catalog/pg_tablespace_d.h"
 #include "miscadmin.h"
 #include "storage/fd.h"
 #include "storage/smgr.h"
@@ -617,14 +618,24 @@ CreateFakeRelcacheEntry(RelFileLocator rlocator)
 	sprintf(RelationGetRelationName(rel), "%u", rlocator.relNumber);
 
 	/*
-	 * We set up the lockRelId in case anything tries to lock the dummy
-	 * relation.  Note that this is fairly bogus since relNumber may be
-	 * different from the relation's OID.  It shouldn't really matter though.
-	 * In recovery, we are running by ourselves and can't have any lock
-	 * conflicts.  While syncing, we already hold AccessExclusiveLock.
+	 * RelationGetLockRelId() derives the LockRelId to use for locking the
+	 * relation from rd_id and rd_rel->relisshared, in case anything tries
+	 * to lock the dummy relation.  We don't have a real OID for this fake
+	 * entry, so use relNumber instead.  Note that this is fairly bogus
+	 * since relNumber may be different from the relation's real OID.  It
+	 * shouldn't really matter though.  In recovery, we are running by
+	 * ourselves and can't have any lock conflicts.  While syncing, we
+	 * already hold AccessExclusiveLock.  Set relisshared to match rlocator
+	 * so that RelationGetLockRelId() derives the correct dbId for shared
+	 * relations (InvalidOid); for non-shared relations it'll derive
+	 * MyDatabaseId, which is correct whenever this is called from a real
+	 * backend (e.g. while syncing) and simply irrelevant during recovery.
 	 */
-	rel->rd_lockInfo.lockRelId.dbId = rlocator.dbOid;
-	rel->rd_lockInfo.lockRelId.relId = rlocator.relNumber;
+	Assert((rlocator.dbOid == InvalidOid) ==
+		   (rlocator.spcOid == GLOBALTABLESPACE_OID));
+
+	rel->rd_id = rlocator.relNumber;
+	rel->rd_rel->relisshared = (rlocator.dbOid == InvalidOid);
 
 	/*
 	 * Set up a non-pinned SMgrRelation reference, so that we don't need to
diff --git a/src/backend/catalog/index.c b/src/backend/catalog/index.c
index 99413556572..6764bb8f487 100644
--- a/src/backend/catalog/index.c
+++ b/src/backend/catalog/index.c
@@ -2267,9 +2267,9 @@ index_drop(Oid indexId, bool concurrent, bool concurrent_lock_mode)
 		CacheInvalidateRelcache(userHeapRelation);
 
 		/* save lockrelid and locktag for below, then close but keep locks */
-		heaprelid = userHeapRelation->rd_lockInfo.lockRelId;
+		heaprelid = RelationGetLockRelId(userHeapRelation);
 		SET_LOCKTAG_RELATION(heaplocktag, heaprelid.dbId, heaprelid.relId);
-		indexrelid = userIndexRelation->rd_lockInfo.lockRelId;
+		indexrelid = RelationGetLockRelId(userIndexRelation);
 
 		table_close(userHeapRelation, NoLock);
 		index_close(userIndexRelation, NoLock);
diff --git a/src/backend/commands/indexcmds.c b/src/backend/commands/indexcmds.c
index 5a0312fe772..b8a0c908637 100644
--- a/src/backend/commands/indexcmds.c
+++ b/src/backend/commands/indexcmds.c
@@ -1650,7 +1650,7 @@ DefineIndex(ParseState *pstate,
 	}
 
 	/* save lockrelid and locktag for below, then close rel */
-	heaprelid = rel->rd_lockInfo.lockRelId;
+	heaprelid = RelationGetLockRelId(rel);
 	SET_LOCKTAG_RELATION(heaplocktag, heaprelid.dbId, heaprelid.relId);
 	table_close(rel, NoLock);
 
@@ -4177,10 +4177,10 @@ ReindexRelationConcurrently(const ReindexStmt *stmt, Oid relationOid, const Rein
 		 * parentRelationIds built earlier.
 		 */
 		lockrelid = palloc_object(LockRelId);
-		*lockrelid = indexRel->rd_lockInfo.lockRelId;
+		*lockrelid = RelationGetLockRelId(indexRel);
 		relationLocks = lappend(relationLocks, lockrelid);
 		lockrelid = palloc_object(LockRelId);
-		*lockrelid = newIndexRel->rd_lockInfo.lockRelId;
+		*lockrelid = RelationGetLockRelId(newIndexRel);
 		relationLocks = lappend(relationLocks, lockrelid);
 
 		MemoryContextSwitchTo(oldcontext);
@@ -4226,7 +4226,7 @@ ReindexRelationConcurrently(const ReindexStmt *stmt, Oid relationOid, const Rein
 
 		/* Add lockrelid of heap relation to the list of locked relations */
 		lockrelid = palloc_object(LockRelId);
-		*lockrelid = heapRelation->rd_lockInfo.lockRelId;
+		*lockrelid = RelationGetLockRelId(heapRelation);
 		relationLocks = lappend(relationLocks, lockrelid);
 
 		heaplocktag = palloc_object(LOCKTAG);
diff --git a/src/backend/commands/vacuum.c b/src/backend/commands/vacuum.c
index 3a5c1efd6ac..63849d7fc19 100644
--- a/src/backend/commands/vacuum.c
+++ b/src/backend/commands/vacuum.c
@@ -2205,7 +2205,7 @@ vacuum_rel(Oid relid, RangeVar *relation, VacuumParams params,
 	 * because the lock manager knows that both lock requests are from the
 	 * same process.
 	 */
-	lockrelid = rel->rd_lockInfo.lockRelId;
+	lockrelid = RelationGetLockRelId(rel);
 	LockRelationIdForSession(&lockrelid, lmode);
 
 	/*
diff --git a/src/backend/storage/lmgr/lmgr.c b/src/backend/storage/lmgr/lmgr.c
index 2ccf7237fee..c9b6e9f04e1 100644
--- a/src/backend/storage/lmgr/lmgr.c
+++ b/src/backend/storage/lmgr/lmgr.c
@@ -60,26 +60,6 @@ typedef struct XactLockTableWaitInfo
 
 static void XactLockTableWaitErrorCb(void *arg);
 
-/*
- * RelationInitLockInfo
- *		Initializes the lock information in a relation descriptor.
- *
- *		relcache.c must call this during creation of any reldesc.
- */
-void
-RelationInitLockInfo(Relation relation)
-{
-	Assert(RelationIsValid(relation));
-	Assert(OidIsValid(RelationGetRelid(relation)));
-
-	relation->rd_lockInfo.lockRelId.relId = RelationGetRelid(relation);
-
-	if (relation->rd_rel->relisshared)
-		relation->rd_lockInfo.lockRelId.dbId = InvalidOid;
-	else
-		relation->rd_lockInfo.lockRelId.dbId = MyDatabaseId;
-}
-
 /*
  * SetLocktagRelationOid
  *		Set up a locktag for a relation, given only relation OID
@@ -250,8 +230,8 @@ LockRelation(Relation relation, LOCKMODE lockmode)
 	LockAcquireResult res;
 
 	SET_LOCKTAG_RELATION(tag,
-						 relation->rd_lockInfo.lockRelId.dbId,
-						 relation->rd_lockInfo.lockRelId.relId);
+						 RelationGetLockRelId(relation).dbId,
+						 RelationGetLockRelId(relation).relId);
 
 	res = LockAcquireExtended(&tag, lockmode, false, false, true, &locallock,
 							  false);
@@ -282,8 +262,8 @@ ConditionalLockRelation(Relation relation, LOCKMODE lockmode)
 	LockAcquireResult res;
 
 	SET_LOCKTAG_RELATION(tag,
-						 relation->rd_lockInfo.lockRelId.dbId,
-						 relation->rd_lockInfo.lockRelId.relId);
+						 RelationGetLockRelId(relation).dbId,
+						 RelationGetLockRelId(relation).relId);
 
 	res = LockAcquireExtended(&tag, lockmode, false, true, true, &locallock,
 							  false);
@@ -316,8 +296,8 @@ UnlockRelation(Relation relation, LOCKMODE lockmode)
 	LOCKTAG		tag;
 
 	SET_LOCKTAG_RELATION(tag,
-						 relation->rd_lockInfo.lockRelId.dbId,
-						 relation->rd_lockInfo.lockRelId.relId);
+						 RelationGetLockRelId(relation).dbId,
+						 RelationGetLockRelId(relation).relId);
 
 	LockRelease(&tag, lockmode, false);
 }
@@ -336,8 +316,8 @@ CheckRelationLockedByMe(Relation relation, LOCKMODE lockmode, bool orstronger)
 	LOCKTAG		tag;
 
 	SET_LOCKTAG_RELATION(tag,
-						 relation->rd_lockInfo.lockRelId.dbId,
-						 relation->rd_lockInfo.lockRelId.relId);
+						 RelationGetLockRelId(relation).dbId,
+						 RelationGetLockRelId(relation).relId);
 
 	return LockHeldByMe(&tag, lockmode, orstronger);
 }
@@ -369,8 +349,8 @@ LockHasWaitersRelation(Relation relation, LOCKMODE lockmode)
 	LOCKTAG		tag;
 
 	SET_LOCKTAG_RELATION(tag,
-						 relation->rd_lockInfo.lockRelId.dbId,
-						 relation->rd_lockInfo.lockRelId.relId);
+						 RelationGetLockRelId(relation).dbId,
+						 RelationGetLockRelId(relation).relId);
 
 	return LockHasWaiters(&tag, lockmode, false);
 }
@@ -426,8 +406,8 @@ LockRelationForExtension(Relation relation, LOCKMODE lockmode)
 	LOCKTAG		tag;
 
 	SET_LOCKTAG_RELATION_EXTEND(tag,
-								relation->rd_lockInfo.lockRelId.dbId,
-								relation->rd_lockInfo.lockRelId.relId);
+								RelationGetLockRelId(relation).dbId,
+								RelationGetLockRelId(relation).relId);
 
 	(void) LockAcquire(&tag, lockmode, false, false);
 }
@@ -444,8 +424,8 @@ ConditionalLockRelationForExtension(Relation relation, LOCKMODE lockmode)
 	LOCKTAG		tag;
 
 	SET_LOCKTAG_RELATION_EXTEND(tag,
-								relation->rd_lockInfo.lockRelId.dbId,
-								relation->rd_lockInfo.lockRelId.relId);
+								RelationGetLockRelId(relation).dbId,
+								RelationGetLockRelId(relation).relId);
 
 	return (LockAcquire(&tag, lockmode, false, true) != LOCKACQUIRE_NOT_AVAIL);
 }
@@ -461,8 +441,8 @@ RelationExtensionLockWaiterCount(Relation relation)
 	LOCKTAG		tag;
 
 	SET_LOCKTAG_RELATION_EXTEND(tag,
-								relation->rd_lockInfo.lockRelId.dbId,
-								relation->rd_lockInfo.lockRelId.relId);
+								RelationGetLockRelId(relation).dbId,
+								RelationGetLockRelId(relation).relId);
 
 	return LockWaiterCount(&tag);
 }
@@ -476,8 +456,8 @@ UnlockRelationForExtension(Relation relation, LOCKMODE lockmode)
 	LOCKTAG		tag;
 
 	SET_LOCKTAG_RELATION_EXTEND(tag,
-								relation->rd_lockInfo.lockRelId.dbId,
-								relation->rd_lockInfo.lockRelId.relId);
+								RelationGetLockRelId(relation).dbId,
+								RelationGetLockRelId(relation).relId);
 
 	LockRelease(&tag, lockmode, false);
 }
@@ -509,8 +489,8 @@ LockPage(Relation relation, BlockNumber blkno, LOCKMODE lockmode)
 	LOCKTAG		tag;
 
 	SET_LOCKTAG_PAGE(tag,
-					 relation->rd_lockInfo.lockRelId.dbId,
-					 relation->rd_lockInfo.lockRelId.relId,
+					 RelationGetLockRelId(relation).dbId,
+					 RelationGetLockRelId(relation).relId,
 					 blkno);
 
 	(void) LockAcquire(&tag, lockmode, false, false);
@@ -528,8 +508,8 @@ ConditionalLockPage(Relation relation, BlockNumber blkno, LOCKMODE lockmode)
 	LOCKTAG		tag;
 
 	SET_LOCKTAG_PAGE(tag,
-					 relation->rd_lockInfo.lockRelId.dbId,
-					 relation->rd_lockInfo.lockRelId.relId,
+					 RelationGetLockRelId(relation).dbId,
+					 RelationGetLockRelId(relation).relId,
 					 blkno);
 
 	return (LockAcquire(&tag, lockmode, false, true) != LOCKACQUIRE_NOT_AVAIL);
@@ -544,8 +524,8 @@ UnlockPage(Relation relation, BlockNumber blkno, LOCKMODE lockmode)
 	LOCKTAG		tag;
 
 	SET_LOCKTAG_PAGE(tag,
-					 relation->rd_lockInfo.lockRelId.dbId,
-					 relation->rd_lockInfo.lockRelId.relId,
+					 RelationGetLockRelId(relation).dbId,
+					 RelationGetLockRelId(relation).relId,
 					 blkno);
 
 	LockRelease(&tag, lockmode, false);
@@ -564,8 +544,8 @@ LockTuple(Relation relation, const ItemPointerData *tid, LOCKMODE lockmode)
 	LOCKTAG		tag;
 
 	SET_LOCKTAG_TUPLE(tag,
-					  relation->rd_lockInfo.lockRelId.dbId,
-					  relation->rd_lockInfo.lockRelId.relId,
+					  RelationGetLockRelId(relation).dbId,
+					  RelationGetLockRelId(relation).relId,
 					  ItemPointerGetBlockNumber(tid),
 					  ItemPointerGetOffsetNumber(tid));
 
@@ -585,8 +565,8 @@ ConditionalLockTuple(Relation relation, const ItemPointerData *tid, LOCKMODE loc
 	LOCKTAG		tag;
 
 	SET_LOCKTAG_TUPLE(tag,
-					  relation->rd_lockInfo.lockRelId.dbId,
-					  relation->rd_lockInfo.lockRelId.relId,
+					  RelationGetLockRelId(relation).dbId,
+					  RelationGetLockRelId(relation).relId,
 					  ItemPointerGetBlockNumber(tid),
 					  ItemPointerGetOffsetNumber(tid));
 
@@ -603,8 +583,8 @@ UnlockTuple(Relation relation, const ItemPointerData *tid, LOCKMODE lockmode)
 	LOCKTAG		tag;
 
 	SET_LOCKTAG_TUPLE(tag,
-					  relation->rd_lockInfo.lockRelId.dbId,
-					  relation->rd_lockInfo.lockRelId.relId,
+					  RelationGetLockRelId(relation).dbId,
+					  RelationGetLockRelId(relation).relId,
 					  ItemPointerGetBlockNumber(tid),
 					  ItemPointerGetOffsetNumber(tid));
 
diff --git a/src/backend/utils/cache/relcache.c b/src/backend/utils/cache/relcache.c
index 30355a405be..72fc8474e73 100644
--- a/src/backend/utils/cache/relcache.c
+++ b/src/backend/utils/cache/relcache.c
@@ -93,7 +93,7 @@
 #include "utils/snapmgr.h"
 #include "utils/syscache.h"
 
-#define RELCACHE_INIT_FILEMAGIC		0x573269	/* version ID value */
+#define RELCACHE_INIT_FILEMAGIC		0x57326A	/* version ID value */
 
 /*
  * Whether to bother checking if relation cache memory needs to be freed
@@ -1216,11 +1216,6 @@ retry:
 
 	relation->rd_partinfo = NULL;
 
-	/*
-	 * initialize the relation lock manager information
-	 */
-	RelationInitLockInfo(relation); /* see lmgr.c */
-
 	/*
 	 * initialize physical addressing information for the relation
 	 */
@@ -2021,11 +2016,6 @@ formrdesc(const char *relationName, Oid relationReltype,
 							 RelationGetRelid(relation),
 							 isshared, true);
 
-	/*
-	 * initialize the relation lock manager information
-	 */
-	RelationInitLockInfo(relation); /* see lmgr.c */
-
 	/*
 	 * initialize physical addressing information for the relation
 	 */
@@ -3756,8 +3746,6 @@ RelationBuildLocalRelation(const char *relname,
 	else
 		rel->rd_rel->relfilenode = relfilenumber;
 
-	RelationInitLockInfo(rel);	/* see lmgr.c */
-
 	RelationInitPhysicalAddr(rel);
 
 	rel->rd_rel->relam = accessmtd;
@@ -6641,11 +6629,10 @@ load_relcache_init_file(bool shared)
 		rel->pgstat_info = NULL;
 
 		/*
-		 * Recompute lock and physical addressing info.  This is needed in
-		 * case the pg_internal.init file was copied from some other database
-		 * by CREATE DATABASE.
+		 * Recompute physical addressing info.  This is needed in case the
+		 * pg_internal.init file was copied from some other database by
+		 * CREATE DATABASE.
 		 */
-		RelationInitLockInfo(rel);
 		RelationInitPhysicalAddr(rel);
 	}
 
diff --git a/src/include/storage/lmgr.h b/src/include/storage/lmgr.h
index 2a985ce5e15..64cc69c410d 100644
--- a/src/include/storage/lmgr.h
+++ b/src/include/storage/lmgr.h
@@ -34,8 +34,6 @@ typedef enum XLTW_Oper
 	XLTW_RecheckExclusionConstr,
 } XLTW_Oper;
 
-extern void RelationInitLockInfo(Relation relation);
-
 /* Lock a relation */
 extern void LockRelationOid(Oid relid, LOCKMODE lockmode);
 extern void LockRelationId(LockRelId *relid, LOCKMODE lockmode);
diff --git a/src/include/utils/rel.h b/src/include/utils/rel.h
index ea9fd919ed3..dbbaf67c565 100644
--- a/src/include/utils/rel.h
+++ b/src/include/utils/rel.h
@@ -20,6 +20,7 @@
 #include "catalog/pg_class.h"
 #include "catalog/pg_index.h"
 #include "catalog/pg_publication.h"
+#include "miscadmin.h"
 #include "nodes/bitmapset.h"
 #include "partitioning/partdefs.h"
 #include "rewrite/prs2lock.h"
@@ -41,13 +42,6 @@ typedef struct LockRelId
 	Oid			dbId;			/* a database identifier */
 } LockRelId;
 
-typedef struct LockInfoData
-{
-	LockRelId	lockRelId;
-} LockInfoData;
-
-typedef LockInfoData *LockInfo;
-
 /*
  * RelationPartitionInfo
  *		Partition-related data cached for a relation, allocated lazily on
@@ -265,8 +259,6 @@ typedef struct RelationData
 	 */
 	Oid			rd_amhandler;	/* OID of index AM's handler function */
 
-	LockInfoData rd_lockInfo;	/* lock mgr's info for locking relation */
-
 	/*
 	 * Data managed by RelationGetPartitionKey(), RelationGetPartitionDesc(),
 	 * and RelationGetPartitionQual(); NULL if none of these has been
@@ -583,6 +575,28 @@ typedef struct ViewOptions
 	((relation)->rd_rel->relkind == RELKIND_INDEX || \
 	 (relation)->rd_rel->relkind == RELKIND_PARTITIONED_INDEX)
 
+/*
+ * RelationGetLockRelId
+ *		Returns the LockRelId to use for locking the relation.
+ *
+ * This used to be a field cached in the relation descriptor
+ * (rd_lockInfo.lockRelId), populated once by RelationInitLockInfo().  It's
+ * cheap enough to compute on the fly instead, which lets us avoid storing
+ * it.  Note that we can't derive dbId from rd_locator.dbOid: relation kinds
+ * without storage (e.g. partitioned tables/indexes, views) never have
+ * rd_locator populated, so we replicate the original relisshared-based
+ * computation instead.
+ */
+static inline LockRelId
+RelationGetLockRelId(Relation relation)
+{
+	LockRelId	lockRelId;
+
+	lockRelId.relId = RelationGetRelid(relation);
+	lockRelId.dbId = relation->rd_rel->relisshared ? InvalidOid : MyDatabaseId;
+	return lockRelId;
+}
+
 /*
  * RelationGetNumberOfAttributes
  *		Returns the total number of attributes in a relation.
-- 
2.53.0

Reply via email to