From 07f75c6220297bb2fba7c80b666445f9207cffbe Mon Sep 17 00:00:00 2001
From: David Christensen <david.christensen@crunchydata.com>
Date: Thu, 1 Feb 2024 14:58:34 -0600
Subject: [PATCH] Add output of the command that got us here to the QUERY
 output

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

diff --git a/src/bin/psql/command.c b/src/bin/psql/command.c
index 5c906e4806..6e55f81b0f 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 = 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..7749656f5f 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,7 @@ PGresult *
 PSQLexec(const char *query)
 {
 	PGresult   *res;
+	char *label = "";
 
 	if (!pset.db)
 	{
@@ -588,21 +590,27 @@ PSQLexec(const char *query)
 		return NULL;
 	}
 
+	if (curcmd)
+		label = psprintf(" (\\%s)", curcmd);
+
 	if (pset.echo_hidden != PSQL_ECHO_HIDDEN_OFF)
 	{
-		printf(_("/******** QUERY *********/\n"
+		printf(_("/******** QUERY%s *********/\n"
 				 "%s\n"
-				 "/************************/\n\n"), query);
+				 "/************************/\n\n"), label, query);
 		fflush(stdout);
 		if (pset.logfile)
 		{
 			fprintf(pset.logfile,
-					_("/******** QUERY *********/\n"
+					_("/******** QUERY%s *********/\n"
 					  "%s\n"
-					  "/************************/\n\n"), query);
+					  "/************************/\n\n"), label, query);
 			fflush(pset.logfile);
 		}
 
+		if (curcmd)
+			pfree(label);
+
 		if (pset.echo_hidden == PSQL_ECHO_HIDDEN_NOEXEC)
 			return NULL;
 	}
-- 
2.39.3 (Apple Git-145)

