From d45b620515387c531ea1d663b87dac6144b0b41e Mon Sep 17 00:00:00 2001
From: "okbob@github.com" <pavel.stehule@gmail.com>
Date: Fri, 3 Feb 2023 15:53:56 +0100
Subject: [PATCH 2/2] implementation of psql prompt placeholder %N

---
 src/backend/utils/misc/guc_tables.c |  2 +-
 src/bin/psql/common.c               | 25 +++++++++++++++++++++++++
 src/bin/psql/common.h               |  1 +
 src/bin/psql/prompt.c               |  5 +++++
 4 files changed, 32 insertions(+), 1 deletion(-)

diff --git a/src/backend/utils/misc/guc_tables.c b/src/backend/utils/misc/guc_tables.c
index b46e3b8c55..3188fd015d 100644
--- a/src/backend/utils/misc/guc_tables.c
+++ b/src/backend/utils/misc/guc_tables.c
@@ -4144,7 +4144,7 @@ struct config_string ConfigureNamesString[] =
 		{"role", PGC_USERSET, UNGROUPED,
 			gettext_noop("Sets the current role."),
 			NULL,
-			GUC_IS_NAME | GUC_NO_SHOW_ALL | GUC_NO_RESET_ALL | GUC_NOT_IN_SAMPLE | GUC_DISALLOW_IN_FILE | GUC_NOT_WHILE_SEC_REST
+			GUC_IS_NAME | GUC_REPORT | GUC_NO_SHOW_ALL | GUC_NO_RESET_ALL | GUC_NOT_IN_SAMPLE | GUC_DISALLOW_IN_FILE | GUC_NOT_WHILE_SEC_REST
 		},
 		&role_string,
 		"none",
diff --git a/src/bin/psql/common.c b/src/bin/psql/common.c
index f907f5d4e8..9c82b8253b 100644
--- a/src/bin/psql/common.c
+++ b/src/bin/psql/common.c
@@ -2310,6 +2310,31 @@ session_username(void)
 }
 
 
+/*
+ * Return the current user of the current connection.
+ * Replace "none" by session user.
+ */
+const char *
+current_role(void)
+{
+	const char *val;
+
+	if (!pset.db)
+		return NULL;
+
+	val = PQparameterStatus(pset.db, "role");
+	if (val)
+	{
+		if (strncmp(val, "none", 4) == 0 && strlen(val) == 4)
+			return session_username();
+		else
+			return val;
+	}
+	else
+		return PQuser(pset.db);
+}
+
+
 /* expand_tilde
  *
  * substitute '~' with HOME or '~username' with username's home dir
diff --git a/src/bin/psql/common.h b/src/bin/psql/common.h
index cc4c73d097..b7a8182dd2 100644
--- a/src/bin/psql/common.h
+++ b/src/bin/psql/common.h
@@ -37,6 +37,7 @@ extern bool SendQuery(const char *query);
 extern bool is_superuser(void);
 extern bool standard_strings(void);
 extern const char *session_username(void);
+extern const char *current_role(void);
 
 extern void expand_tilde(char **filename);
 
diff --git a/src/bin/psql/prompt.c b/src/bin/psql/prompt.c
index 969cd9908e..91813e1356 100644
--- a/src/bin/psql/prompt.c
+++ b/src/bin/psql/prompt.c
@@ -165,6 +165,11 @@ get_prompt(promptStatus_t status, ConditionalStack cstack)
 					if (pset.db)
 						strlcpy(buf, session_username(), sizeof(buf));
 					break;
+					/* DB server current user name */
+				case 'N':
+					if (pset.db)
+						strlcpy(buf, current_role(), sizeof(buf));
+					break;
 					/* backend pid */
 				case 'p':
 					if (pset.db)
-- 
2.39.1

