v2-0001-Adjust-password-to-use-current-user-instead-of-au.patch

application/octet-stream

Filename: v2-0001-Adjust-password-to-use-current-user-instead-of-au.patch
Type: application/octet-stream
Part: 0
Message: Re: Improving psql's \password command

Patch

Format: format-patch
Series: patch v2-0001
Subject: Adjust \password to use current user instead of authenticated user by default.
File+
src/bin/psql/command.c 16 9
From 02459bbd107d7bf04e97184a00d823c860688a51 Mon Sep 17 00:00:00 2001
From: Nathan Bossart <bossartn@amazon.com>
Date: Fri, 12 Nov 2021 16:57:36 +0000
Subject: [PATCH v2 1/2] Adjust \password to use current user instead of
 authenticated user by default.

---
 src/bin/psql/command.c | 25 ++++++++++++++++---------
 1 file changed, 16 insertions(+), 9 deletions(-)

diff --git a/src/bin/psql/command.c b/src/bin/psql/command.c
index 49d4c0e3ce..5619ed685a 100644
--- a/src/bin/psql/command.c
+++ b/src/bin/psql/command.c
@@ -2023,11 +2023,24 @@ exec_command_password(PsqlScanState scan_state, bool active_branch)
 
 	if (active_branch)
 	{
-		char	   *opt0 = psql_scan_slash_option(scan_state,
+		char	   *user = psql_scan_slash_option(scan_state,
 												  OT_SQLID, NULL, true);
 		char	   *pw1;
 		char	   *pw2;
 
+		if (user == NULL)
+		{
+			/* Fetch current user so we can report whose PW will be changed */
+			PGresult   *res;
+
+			res = PSQLexec("SELECT CURRENT_USER");
+			if (!res)
+				return PSQL_CMD_ERROR;
+
+			user = pg_strdup(PQgetvalue(res, 0, 0));
+			PQclear(res);
+		}
+
 		pw1 = simple_prompt("Enter new password: ", false);
 		pw2 = simple_prompt("Enter it again: ", false);
 
@@ -2038,14 +2051,8 @@ exec_command_password(PsqlScanState scan_state, bool active_branch)
 		}
 		else
 		{
-			char	   *user;
 			char	   *encrypted_password;
 
-			if (opt0)
-				user = opt0;
-			else
-				user = PQuser(pset.db);
-
 			encrypted_password = PQencryptPasswordConn(pset.db, pw1, user, NULL);
 
 			if (!encrypted_password)
@@ -2072,8 +2079,8 @@ exec_command_password(PsqlScanState scan_state, bool active_branch)
 			}
 		}
 
-		if (opt0)
-			free(opt0);
+		if (user)
+			free(user);
 		free(pw1);
 		free(pw2);
 	}
-- 
2.16.6