From aae0a76c609bb83972a4ec7625c567810e2d172e Mon Sep 17 00:00:00 2001
From: Vignesh C <vignesh21@gmail.com>
Date: Wed, 16 Jul 2025 15:31:54 +0530
Subject: [PATCH v3 2/3] Add custom PQsetNoticeProcessor handlers for dblink
 connection

This patch introduces a custom notice processor for libpq-based
connections in dblink connection.  The notice processor captures
messages and routes them through ereport(), making them visible
in local logs with a prefix making it easy for diagnosis.
---
 contrib/dblink/dblink.c | 23 +++++++++++++++++++++++
 1 file changed, 23 insertions(+)

diff --git a/contrib/dblink/dblink.c b/contrib/dblink/dblink.c
index 8a0b112a7ff..42b96c314db 100644
--- a/contrib/dblink/dblink.c
+++ b/contrib/dblink/dblink.c
@@ -177,6 +177,24 @@ xpstrdup(const char *in)
 	return pstrdup(in);
 }
 
+/*
+ * Custom notice processor for libpq connections used by dblink.
+ */
+static void
+notice_processor(void *arg, const char *message)
+{
+	/* Trim trailing newline for cleaner logs */
+	size_t		len = strlen(message);
+
+	if (len > 0 && message[len - 1] == '\n')
+		ereport(LOG,
+				errmsg("received message from remote server: %.*s",
+					   (int) (len - 1), message));
+	else
+		ereport(LOG,
+				errmsg("received message from remote server: %s", message));
+}
+
 pg_noreturn static void
 dblink_res_internalerror(PGconn *conn, PGresult *res, const char *p2)
 {
@@ -240,6 +258,9 @@ dblink_get_conn(char *conname_or_str,
 					 errmsg("could not establish connection"),
 					 errdetail_internal("%s", msg)));
 		}
+
+		PQsetNoticeProcessor(conn, notice_processor, NULL);
+
 		dblink_security_check(conn, NULL, connstr);
 		if (PQclientEncoding(conn) != GetDatabaseEncoding())
 			PQsetClientEncoding(conn, GetDatabaseEncodingName());
@@ -338,6 +359,8 @@ dblink_connect(PG_FUNCTION_ARGS)
 				 errdetail_internal("%s", msg)));
 	}
 
+	PQsetNoticeProcessor(conn, notice_processor, NULL);
+
 	/* check password actually used if not superuser */
 	dblink_security_check(conn, connname, connstr);
 
-- 
2.43.0

