From 6b69e19bdae8b282a75ebf373573cdb96adeef06 Mon Sep 17 00:00:00 2001
From: Kyotaro Horiguchi <horikyoga.ntt@gmail.com>
Date: Wed, 27 Nov 2019 07:38:46 -0500
Subject: [PATCH v26 2/6] change swap_relation_files

The current patch doesn't adjust the new relation in
swap_relation_files. This inhibits the relcache from
invalidated. Adjust relache of the new relfilenode.
Change lock level for relcache adjusting.
---
 src/backend/commands/cluster.c | 28 ++++++++++++++++++++++++----
 1 file changed, 24 insertions(+), 4 deletions(-)

diff --git a/src/backend/commands/cluster.c b/src/backend/commands/cluster.c
index 093fff8c5c..af7733eef4 100644
--- a/src/backend/commands/cluster.c
+++ b/src/backend/commands/cluster.c
@@ -1015,6 +1015,7 @@ swap_relation_files(Oid r1, Oid r2, bool target_is_pg_class,
 	Oid			swaptemp;
 	char		swptmpchr;
 	Relation	rel1;
+	Relation	rel2;
 
 	/* We need writable copies of both pg_class tuples. */
 	relRelation = table_open(RelationRelationId, RowExclusiveLock);
@@ -1177,12 +1178,31 @@ swap_relation_files(Oid r1, Oid r2, bool target_is_pg_class,
 
 	/*
 	 * Recognize that rel1's relfilenode (swapped from rel2) is new in this
-	 * subtransaction. Since the next step for rel2 is deletion, don't bother
-	 * recording the newness of its relfilenode.
+	 * subtransaction. However the next step for rel2 is deletion, we need to
+	 * turn off the newness of its relfilenode, that allows the relcache to be
+	 * flushed. Requried lock must be held before getting here so we take
+	 * AccessShareLock in case no lock is acquired. Since command counter is
+	 * not advanced the relcache entries has the contens before the above
+	 * updates. We don't bother incrementing it and swap their contents
+	 * directly.
+	 */
+	rel1 = relation_open(r1, AccessShareLock);
+	rel2 = relation_open(r2, AccessShareLock);
+
+	/* swap relfilenodes */
+	rel1->rd_node.relNode = relfilenode2;
+	rel2->rd_node.relNode = relfilenode1;
+
+	/*
+	 * Adjust newness flags. relfilenode2 is already added to EOXact array so
+	 * we don't need to do that again here. We assume the new file is created
+	 * in the current subtransaction.
 	 */
-	rel1 = relation_open(r1, AccessExclusiveLock);
 	RelationAssumeNewRelfilenode(rel1);
-	relation_close(rel1, NoLock);
+	rel2->rd_createSubid = InvalidSubTransactionId;
+
+	relation_close(rel1, AccessShareLock);
+	relation_close(rel2, AccessShareLock);
 
 	/*
 	 * Post alter hook for modified relations. The change to r2 is always
-- 
2.23.0

