From 3be161266dd013b8fdd68352dc1c6bd34ed36069 Mon Sep 17 00:00:00 2001
From: Dilip Kumar <dilipkumar@localhost.localdomain>
Date: Mon, 31 May 2021 14:37:26 +0530
Subject: [PATCH v2] Extract unchanged replica identity key if it is stored
 externally

If replica identity is set to key and the key is not modified we don't log
key seperately because it should be logged along with the updated tuple.  But
if the key is stored externally we must have to detoast and log it separately.
---
 src/backend/access/heap/heapam.c | 16 ++++++++++++++--
 1 file changed, 14 insertions(+), 2 deletions(-)

diff --git a/src/backend/access/heap/heapam.c b/src/backend/access/heap/heapam.c
index bd60129..9b53cdc 100644
--- a/src/backend/access/heap/heapam.c
+++ b/src/backend/access/heap/heapam.c
@@ -8407,8 +8407,11 @@ ExtractReplicaIdentity(Relation relation, HeapTuple tp, bool key_changed,
 		return tp;
 	}
 
-	/* if the key hasn't changed and we're only logging the key, we're done */
-	if (!key_changed)
+	/*
+	 * if the key hasn't changed and we're only logging the key, we're done.
+	 * But if tuple has external data then we might have to detoast the key.
+	 */
+	if ((!key_changed) && !HeapTupleHasExternal(tp))
 		return NULL;
 
 	/* find out the replica identity columns */
@@ -8459,6 +8462,15 @@ ExtractReplicaIdentity(Relation relation, HeapTuple tp, bool key_changed,
 		key_tuple = toast_flatten_tuple(oldtup, desc);
 		heap_freetuple(oldtup);
 	}
+	/*
+	 * If key tuple doesn't have any external data and key is not changed then
+	 * just free the key tuple and return NULL.
+	 */
+	else if (!key_changed)
+	{
+		heap_freetuple(key_tuple);
+		return NULL;
+	}
 
 	return key_tuple;
 }
-- 
1.8.3.1

