From 00e662f9ade2cb1bec60483427f46d07c1485e15 Mon Sep 17 00:00:00 2001
From: Peter Geoghegan <pg@bowt.ie>
Date: Fri, 24 Apr 2020 16:29:58 -0700
Subject: [PATCH v1 3/4] Fix second page deletion bug.

---
 src/backend/access/nbtree/nbtpage.c | 17 +++++++++--------
 1 file changed, 9 insertions(+), 8 deletions(-)

diff --git a/src/backend/access/nbtree/nbtpage.c b/src/backend/access/nbtree/nbtpage.c
index aa163cb493..a2e39a6712 100644
--- a/src/backend/access/nbtree/nbtpage.c
+++ b/src/backend/access/nbtree/nbtpage.c
@@ -2030,6 +2030,14 @@ _bt_unlink_halfdead_page(Relation rel, Buffer leafbuf, bool *rightsib_empty)
 	leafleftsib = opaque->btpo_prev;
 	leafrightsib = opaque->btpo_next;
 
+	/*
+	 * If the leaf page still has a parent pointing to it (or a chain of
+	 * parents), we don't unlink the leaf page yet, but the topmost remaining
+	 * parent in the branch.  Set 'target' to reference the page actually
+	 * being unlinked.
+	 */
+	target = BTreeTupleGetTopParent(leafhikey);
+
 	_bt_unlockbuf(rel, leafbuf);
 
 	/*
@@ -2038,16 +2046,9 @@ _bt_unlink_halfdead_page(Relation rel, Buffer leafbuf, bool *rightsib_empty)
 	 */
 	CHECK_FOR_INTERRUPTS();
 
-	/*
-	 * If the leaf page still has a parent pointing to it (or a chain of
-	 * parents), we don't unlink the leaf page yet, but the topmost remaining
-	 * parent in the branch.  Set 'target' and 'buf' to reference the page
-	 * actually being unlinked.
-	 */
-	target = BTreeTupleGetTopParent(leafhikey);
-
 	if (target != InvalidBlockNumber)
 	{
+		/* Set 'buf' to reference the page actually being unlinked */
 		Assert(target != leafblkno);
 
 		/* fetch the block number of the topmost parent's left sibling */
-- 
2.25.1

