From 3d8d09033467eaad7fb1922c740f4934bc52ca3e Mon Sep 17 00:00:00 2001
From: "houzj.fnst" <houzj.fnst@cn.fujitsu.com>
Date: Tue, 21 Jun 2022 13:39:54 +0800
Subject: [PATCH] Fix segmentation fault

When building the partition map cache, we didn't update the cached relation if
the partition map is valid. But since the relation is opened and closed by
caller, it caused segmentation violation when we tried to access the cached
relation which was closed.

Fix it by updating the cached relation every time we try to get the partition
map entry.
---
 src/backend/replication/logical/relation.c | 21 +++++++++++++--------
 1 file changed, 13 insertions(+), 8 deletions(-)

diff --git a/src/backend/replication/logical/relation.c b/src/backend/replication/logical/relation.c
index 5f51170..ac2b090 100644
--- a/src/backend/replication/logical/relation.c
+++ b/src/backend/replication/logical/relation.c
@@ -594,20 +594,26 @@ logicalrep_partition_open(LogicalRepRelMapEntry *root,
 														(void *) &partOid,
 														HASH_ENTER, &found);
 
+	if (!found)
+	{
+		memset(part_entry, 0, sizeof(LogicalRepPartMapEntry));
+		part_entry->partoid = partOid;
+	}
+
 	entry = &part_entry->relmapentry;
 
-	if (found && entry->localrelvalid)
+	/*
+	 * Relation is opened and closed by caller, so we need to always update the
+	 * partrel in case the cached relation was closed.
+	 */
+	entry->localrel = partrel;
+
+	if (entry->localrelvalid)
 		return entry;
 
 	/* Switch to longer-lived context. */
 	oldctx = MemoryContextSwitchTo(LogicalRepPartMapContext);
 
-	if (!found)
-	{
-		memset(part_entry, 0, sizeof(LogicalRepPartMapEntry));
-		part_entry->partoid = partOid;
-	}
-
 	if (!entry->remoterel.remoteid)
 	{
 		int			i;
@@ -629,7 +635,6 @@ logicalrep_partition_open(LogicalRepRelMapEntry *root,
 		entry->remoterel.attkeys = bms_copy(remoterel->attkeys);
 	}
 
-	entry->localrel = partrel;
 	entry->localreloid = partOid;
 
 	/*
-- 
2.7.2.windows.1

