From 21c504144f378e9c24198476c14a32a3021cd95c Mon Sep 17 00:00:00 2001
From: Justin Pryzby <justin@telsasoft.com>
Date: Sat, 9 Feb 2019 19:20:43 -0500
Subject: [PATCH] Conditionally re-log prepared statement during execution

Now controlled by log_error_verbosity>=PGERROR_VERBOSE.
---
 src/backend/tcop/postgres.c | 23 ++++++++++++++++++-----
 1 file changed, 18 insertions(+), 5 deletions(-)

diff --git a/src/backend/tcop/postgres.c b/src/backend/tcop/postgres.c
index 36cfd507b2..622e780d3d 100644
--- a/src/backend/tcop/postgres.c
+++ b/src/backend/tcop/postgres.c
@@ -1042,7 +1042,7 @@ exec_simple_query(const char *query_string)
 		ereport(LOG,
 				(errmsg("statement: %s", query_string),
 				 errhidestmt(true),
-				 errdetail_execute(parsetree_list)));
+				 Log_error_verbosity>=PGERROR_VERBOSE ? errdetail_execute(parsetree_list) : 0));
 		was_logged = true;
 	}
 
@@ -1966,6 +1966,7 @@ exec_execute_message(const char *portal_name, long max_rows)
 	bool		is_xact_command;
 	bool		execute_is_fetch;
 	bool		was_logged = false;
+	bool		log_prepared;
 	char		msec_str[32];
 
 	/* Adjust destination to tell printtup.c what to do */
@@ -2058,18 +2059,29 @@ exec_execute_message(const char *portal_name, long max_rows)
 	 */
 	execute_is_fetch = !portal->atStart;
 
+	/*
+	 * Log "execute <unnamed>: ..." rather than just "execute <unnamed>"
+	 * when using the unnamed portal and unamed perpared statements, which
+	 * are used behind the scenes by PQexecParams.
+	 * XXX: if anything else uses unnamed portal+unnamed prepared, then the
+	 * prepared statement will be logged on every EXECUTE.
+	 */
+	log_prepared = (!*portal_name && !portal->prepStmtName) ||
+		Log_error_verbosity>=PGERROR_VERBOSE;
+
 	/* Log immediately if dictated by log_statement */
 	if (check_log_statement(portal->stmts))
 	{
 		ereport(LOG,
-				(errmsg("%s %s%s%s: %s",
+				(errmsg("%s %s%s%s%s%s",
 						execute_is_fetch ?
 						_("execute fetch from") :
 						_("execute"),
 						prepStmtName,
 						*portal_name ? "/" : "",
 						*portal_name ? portal_name : "",
-						sourceText),
+						log_prepared ? ": " : "",
+						log_prepared ? sourceText : ""),
 				 errhidestmt(true),
 				 errdetail_params(portalParams)));
 		was_logged = true;
@@ -2150,7 +2162,7 @@ exec_execute_message(const char *portal_name, long max_rows)
 			break;
 		case 2:
 			ereport(LOG,
-					(errmsg("duration: %s ms  %s %s%s%s: %s",
+					(errmsg("duration: %s ms  %s %s%s%s%s%s",
 							msec_str,
 							execute_is_fetch ?
 							_("execute fetch from") :
@@ -2158,7 +2170,8 @@ exec_execute_message(const char *portal_name, long max_rows)
 							prepStmtName,
 							*portal_name ? "/" : "",
 							*portal_name ? portal_name : "",
-							sourceText),
+							log_prepared ? ": " : "",
+							log_prepared ? sourceText : ""),
 					 errhidestmt(true),
 					 errdetail_params(portalParams)));
 			break;
-- 
2.12.2

