From c8f88cc7be57821ea9eb28bf6280ac980fed3519 Mon Sep 17 00:00:00 2001
From: Sami Imseih <simseih@amazon.com>
Date: Fri, 25 Apr 2025 16:59:50 -0500
Subject: [PATCH 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, and creating a
new unnamed portal requires dropping the previous one. This behavior
is problematic for several reasons, not least because it delays the
execution of the ExecutorEnd hook. This patch addresses the issue by
ensuring that the portal is dropped only after it has been fully
fetched to completion.
---
 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..cb4c4854078 100644
--- a/src/backend/tcop/postgres.c
+++ b/src/backend/tcop/postgres.c
@@ -2327,6 +2327,10 @@ exec_execute_message(const char *portal_name, long max_rows)
 
 		/* Send appropriate CommandComplete to client */
 		EndCommand(&qc, dest, false);
+
+		/* close the portal, if not pinned */
+		if (!portal->portalPinned)
+			PortalDrop(portal, false);
 	}
 	else
 	{
-- 
2.39.5 (Apple Git-154)

