From 19fc3ce6185f9c74d0393ee1bfbd6fe8020131c7 Mon Sep 17 00:00:00 2001
From: Ubuntu <ubuntu@ip-172-31-46-230.ec2.internal>
Date: Fri, 19 Sep 2025 20:06:37 +0000
Subject: [PATCH v13 1/2] Fix temp file logging blame in extended query
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit

With the extended query protocol, temporary files created by unnamed
portals could be blamed on the wrong statement. Because temp file logging
happens when the portal is dropped, this patch ensures that unnamed portals
are dropped before resetting debug_query_string, so that temp files are
blamed on the correct statement.

Author: Sami Imseih <samimseih@gmail.com>
Author: Frédéric Yhuel <frederic.yhuel@dalibo.com>
Reviewed-by: Mircea Cadariu <cadariu.mircea@gmail.com>
Discussion: https://www.postgresql.org/message-id/flat/3d07ee43-8855-42db-97e0-bad5db82d972@dalibo.com
---
 src/backend/utils/mmgr/portalmem.c | 15 +++++++++++++++
 1 file changed, 15 insertions(+)

diff --git a/src/backend/utils/mmgr/portalmem.c b/src/backend/utils/mmgr/portalmem.c
index 0be1c2b0fff..c18d44c3e6a 100644
--- a/src/backend/utils/mmgr/portalmem.c
+++ b/src/backend/utils/mmgr/portalmem.c
@@ -23,6 +23,7 @@
 #include "funcapi.h"
 #include "miscadmin.h"
 #include "storage/ipc.h"
+#include "tcop/tcopprot.h"
 #include "utils/builtins.h"
 #include "utils/memutils.h"
 #include "utils/snapmgr.h"
@@ -467,8 +468,19 @@ MarkPortalFailed(Portal portal)
 void
 PortalDrop(Portal portal, bool isTopCommit)
 {
+	const char *saved_debug_query_string = NULL;
+
 	Assert(PortalIsValid(portal));
 
+	/*
+	 * Save the current debug_query_string and temporarily set it to the
+	 * portal's query while dropping, so log messages are blamed on the
+	 * portal.
+	 */
+	saved_debug_query_string = debug_query_string;
+	if (portal->queryDesc)
+		debug_query_string = portal->queryDesc->sourceText;
+
 	/*
 	 * Don't allow dropping a pinned portal, it's still needed by whoever
 	 * pinned it.
@@ -594,6 +606,9 @@ PortalDrop(Portal portal, bool isTopCommit)
 	/* release subsidiary storage */
 	MemoryContextDelete(portal->portalContext);
 
+	/* reset the debug_query_string */
+	debug_query_string = saved_debug_query_string;
+
 	/* release portal struct (it's in TopPortalContext) */
 	pfree(portal);
 }
-- 
2.43.0

