From 3558aba4af7b77ab98464f4d90155c46a2307534 Mon Sep 17 00:00:00 2001
From: "Sami Imseih (AWS)"
 <simseih@dev-dsk-simseih-1d-3940b79e.us-east-1.amazon.com>
Date: Sat, 26 Apr 2025 17:34:09 +0000
Subject: [PATCH v5 1/1] Correct timing of portal drop in an execute message

In the extended query protocol, unnamed portals within a transaction
are dropped whenever the next query execution starts, which at that
point creating a new unnamed portal requires dropping the previous one.
This is problematic for problematic for several reasons, not least because
it delays the execution of the ExecutorEnd hook or delays the logging of
temp file usage ( log_temp_files ). This patch addresses the issue by
ensuring that the portal is dropped only after it has been fully
fetched to completion, in the cases that the portal is not a transaction
control statement or requires to be run outside of a transaction block.
---
 src/backend/tcop/postgres.c | 4 ++++
 1 file changed, 4 insertions(+)

diff --git a/src/backend/tcop/postgres.c b/src/backend/tcop/postgres.c
index dc4c600922d..8c537dfca88 100644
--- a/src/backend/tcop/postgres.c
+++ b/src/backend/tcop/postgres.c
@@ -2323,6 +2323,10 @@ exec_execute_message(const char *portal_name, long max_rows)
 			 * message.  The next protocol message will start a fresh timeout.
 			 */
 			disable_statement_timeout();
+
+			/* unnamed portal executed to completion, so close it */
+			if (portal_name[0] == '\0')
+				PortalDrop(portal, false);
 		}
 
 		/* Send appropriate CommandComplete to client */
-- 
2.47.1

