From ea1497b5033f1c229dd6156251cf8adc1bb1f91a Mon Sep 17 00:00:00 2001
From: Kyotaro Horiguchi <horikyota.ntt@gmail.com>
Date: Tue, 27 Aug 2024 16:09:29 +0900
Subject: [PATCH v34 09/16] Prevent PREPARE for transactions with in-place
 relation persistence changes

Allowing a transaction to be prepared when an in-place relation
persistence change has occurred within the transaction can
significantly complicate crash recovery behavior. Since the benefits
of allowing this are minimal, prohibit such behavior.
---
 src/backend/access/transam/xact.c   |  6 ++++++
 src/backend/storage/buffer/bufmgr.c | 13 +++++++++++++
 src/include/storage/bufmgr.h        |  1 +
 3 files changed, 20 insertions(+)

diff --git a/src/backend/access/transam/xact.c b/src/backend/access/transam/xact.c
index 17a8fd0e20..1e1f86e578 100644
--- a/src/backend/access/transam/xact.c
+++ b/src/backend/access/transam/xact.c
@@ -2534,6 +2534,12 @@ PrepareTransaction(void)
 			 TransStateAsString(s->state));
 	Assert(s->parent == NULL);
 
+
+	/* Check if any relation persistence flips have been performed. */
+	if (CheckIfPersistenceChanged())
+		ereport(ERROR,
+				errmsg("cannot prepare transaction if persistence change has been made to any relation"));
+
 	/*
 	 * Do pre-commit processing that involves calling user-defined code, such
 	 * as triggers.  Since closing cursors could queue trigger actions,
diff --git a/src/backend/storage/buffer/bufmgr.c b/src/backend/storage/buffer/bufmgr.c
index 14360f69b7..6de8e00bdc 100644
--- a/src/backend/storage/buffer/bufmgr.c
+++ b/src/backend/storage/buffer/bufmgr.c
@@ -4479,6 +4479,19 @@ SetRelationBuffersPersistenceRedo(SMgrRelation srel, bool permanent,
 	cleanups = cu;
 }
 
+/*
+ *	CheckIfPersistenceChanged
+ *
+ *		Returns true if any relation's persistence change has occurred in the
+ *		current transaction.
+ *		--------------------------------------------------------------------
+ */
+bool
+CheckIfPersistenceChanged(void)
+{
+	return cleanups != NULL;
+}
+
 /* ---------------------------------------------------------------------
  *		DropRelationsAllBuffers
  *
diff --git a/src/include/storage/bufmgr.h b/src/include/storage/bufmgr.h
index 4267098080..df881ea86c 100644
--- a/src/include/storage/bufmgr.h
+++ b/src/include/storage/bufmgr.h
@@ -279,6 +279,7 @@ extern void DropRelationsAllBuffers(struct SMgrRelationData **smgr_reln,
 extern void DropDatabaseBuffers(Oid dbid);
 extern void SetRelationBuffersPersistence(struct SMgrRelationData *srel,
 										  bool permanent);
+extern bool CheckIfPersistenceChanged(void);
 
 #define RelationGetNumberOfBlocks(reln) \
 	RelationGetNumberOfBlocksInFork(reln, MAIN_FORKNUM)
-- 
2.43.5

