From 5e2f354f495731b97b41c44f1391f34a2fe7a839 Mon Sep 17 00:00:00 2001
From: Sami Imseih <samimseih@gmail.com>
Date: Tue, 23 Jul 2024 17:52:14 +0000
Subject: [PATCH 1/1] Fix queryId reporting in Extended Query Protocol

---
 src/backend/tcop/postgres.c         | 6 ++++++
 src/backend/utils/cache/plancache.c | 8 ++++++++
 2 files changed, 14 insertions(+)

diff --git a/src/backend/tcop/postgres.c b/src/backend/tcop/postgres.c
index ea517f4b9b..021d48e9fa 100644
--- a/src/backend/tcop/postgres.c
+++ b/src/backend/tcop/postgres.c
@@ -1679,6 +1679,9 @@ exec_bind_message(StringInfo input_message)
 
 	pgstat_report_activity(STATE_RUNNING, psrc->query_string);
 
+	if (list_length(psrc->query_list) > 0)
+		pgstat_report_query_id(linitial_node(Query, psrc->query_list)->queryId, false);
+
 	set_ps_display("BIND");
 
 	if (save_log_statement_stats)
@@ -2147,6 +2150,9 @@ exec_execute_message(const char *portal_name, long max_rows)
 
 	pgstat_report_activity(STATE_RUNNING, sourceText);
 
+	if (list_length(portal->stmts) > 0)
+		pgstat_report_query_id(linitial_node(PlannedStmt, portal->stmts)->queryId, false);
+
 	cmdtagname = GetCommandTagNameAndLen(portal->commandTag, &cmdtaglen);
 
 	set_ps_display_with_len(cmdtagname, cmdtaglen);
diff --git a/src/backend/utils/cache/plancache.c b/src/backend/utils/cache/plancache.c
index 5af1a168ec..762ff0a8ad 100644
--- a/src/backend/utils/cache/plancache.c
+++ b/src/backend/utils/cache/plancache.c
@@ -66,6 +66,7 @@
 #include "storage/lmgr.h"
 #include "tcop/pquery.h"
 #include "tcop/utility.h"
+#include "utils/backend_status.h"
 #include "utils/inval.h"
 #include "utils/memutils.h"
 #include "utils/resowner.h"
@@ -1182,6 +1183,13 @@ GetCachedPlan(CachedPlanSource *plansource, ParamListInfo boundParams,
 	/* Make sure the querytree list is valid and we have parse-time locks */
 	qlist = RevalidateCachedQuery(plansource, queryEnv);
 
+	/*
+	 * In case the query tree underwent re-analysis, we may have a new
+	 * queryId to report.
+	 */
+	if (qlist)
+		pgstat_report_query_id(linitial_node(Query, qlist)->queryId, false);
+
 	/* Decide whether to use a custom plan */
 	customplan = choose_custom_plan(plansource, boundParams);
 
-- 
2.43.0

