From 83f2586c6a28f237a8e81a9d846b44975998307e Mon Sep 17 00:00:00 2001
From: David Christensen <david.christensen@crunchydata.com>
Date: Thu, 21 Mar 2024 12:27:32 -0500
Subject: [PATCH v3 2/2] Add output of the command that got us here to the
 QUERY output

---
 src/bin/psql/command.c |  5 +++++
 src/bin/psql/common.c  | 24 ++++++++++++++++++++----
 2 files changed, 25 insertions(+), 4 deletions(-)

diff --git a/src/bin/psql/command.c b/src/bin/psql/command.c
index 9b0fa041f7..4cfb91e134 100644
--- a/src/bin/psql/command.c
+++ b/src/bin/psql/command.c
@@ -56,6 +56,8 @@ typedef enum EditableObjectType
 	EditableView,
 } EditableObjectType;
 
+char *curcmd = NULL;
+
 /* local function declarations */
 static backslashResult exec_command(const char *cmd,
 									PsqlScanState scan_state,
@@ -307,6 +309,7 @@ exec_command(const char *cmd,
 					   cmd);
 	}
 
+	curcmd = (char *)cmd;
 	if (strcmp(cmd, "a") == 0)
 		status = exec_command_a(scan_state, active_branch);
 	else if (strcmp(cmd, "bind") == 0)
@@ -423,6 +426,8 @@ exec_command(const char *cmd,
 	else
 		status = PSQL_CMD_UNKNOWN;
 
+	curcmd = NULL;
+
 	/*
 	 * All the commands that return PSQL_CMD_SEND want to execute previous_buf
 	 * if query_buf is empty.  For convenience we implement that here, not in
diff --git a/src/bin/psql/common.c b/src/bin/psql/common.c
index 76e01b02a3..18c8b067ee 100644
--- a/src/bin/psql/common.c
+++ b/src/bin/psql/common.c
@@ -42,6 +42,7 @@ static int	ExecQueryAndProcessResults(const char *query,
 static bool command_no_begin(const char *query);
 static bool is_select_command(const char *query);
 
+extern char *curcmd;
 
 /*
  * openQueryOutputFile --- attempt to open a query output file
@@ -581,6 +582,12 @@ PGresult *
 PSQLexec(const char *query)
 {
 	PGresult   *res;
+	char *label = "";
+	const char *asterisks = "********************"; /* ensure this is as long as the
+											   * longest command that might be
+											   * displayed */
+	int curcmd_length = 0;
+
 
 	if (!pset.db)
 	{
@@ -588,21 +595,30 @@ PSQLexec(const char *query)
 		return NULL;
 	}
 
+	if (curcmd)
+	{
+		label = psprintf(" (\\%s)", curcmd);
+		curcmd_length = strlen(label);
+	}
+
 	if (pset.echo_hidden != PSQL_ECHO_HIDDEN_OFF)
 	{
-		printf(_("/******** QUERY *********/\n"
+		printf(_("/******** QUERY%s *********/\n"
 				 "%s\n"
-				 "/************************/\n\n"), query);
+				 "/************************%.*s/\n\n"), label, query, curcmd_length, asterisks);
 		fflush(stdout);
 		if (pset.logfile)
 		{
 			fprintf(pset.logfile,
-					_("/******** QUERY *********/\n"
+					_("/******** QUERY%s *********/\n"
 					  "%s\n"
-					  "/************************/\n\n"), query);
+					  "/************************%.*s/\n\n"), label, query, curcmd_length, asterisks);
 			fflush(pset.logfile);
 		}
 
+		if (curcmd)
+			pfree(label);
+
 		if (pset.echo_hidden == PSQL_ECHO_HIDDEN_NOEXEC)
 			return NULL;
 	}
-- 
2.39.3 (Apple Git-146)

