From fd8c79cf387c1d2ce767314865e4f471a4eea81c Mon Sep 17 00:00:00 2001
From: Robins Tharakan <tharakan@gmail.com>
Date: Sat, 15 Feb 2025 21:09:17 +1030
Subject: [PATCH v1] Add tab completion for ALTER DATABASE RESET

Currently tab completion for ALTER DATABASE RESET shows a list
of all vars that could be set on a database, which is only
partially helpful. This patch allows tab completion to see which
vars are currently set for the database and only show those
options.
---
 src/bin/psql/tab-complete.in.c | 20 +++++++++++++++++++-
 1 file changed, 19 insertions(+), 1 deletion(-)

diff --git a/src/bin/psql/tab-complete.in.c b/src/bin/psql/tab-complete.in.c
index a9a81ab3c14..18fecd32807 100644
--- a/src/bin/psql/tab-complete.in.c
+++ b/src/bin/psql/tab-complete.in.c
@@ -1000,6 +1000,15 @@ static const SchemaQuery Query_for_trigger_of_table = {
 "SELECT datname FROM pg_catalog.pg_database "\
 " WHERE datname LIKE '%s'"
 
+#define Query_for_list_of_database_vars \
+"SELECT conf FROM ("\
+"       SELECT setdatabase, pg_catalog.split_part(unnest(setconfig),'=',1) conf"\
+"         FROM pg_db_role_setting "\
+"       ) s, pg_database d "\
+" WHERE s.setdatabase = d.oid "\
+"   AND conf LIKE '%s'"\
+"   AND d.datname LIKE '%s'"
+
 #define Query_for_list_of_tablespaces \
 "SELECT spcname FROM pg_catalog.pg_tablespace "\
 " WHERE spcname LIKE '%s'"
@@ -2320,6 +2329,13 @@ match_previous_words(int pattern_id,
 					  "IS_TEMPLATE", "ALLOW_CONNECTIONS",
 					  "CONNECTION LIMIT");
 
+	/* ALTER DATABASE <name> RESET */
+	else if (Matches("ALTER", "DATABASE", MatchAny, "RESET"))
+	{
+		set_completion_reference(prev2_wd);
+		COMPLETE_WITH_QUERY_PLUS(Query_for_list_of_database_vars, "ALL");
+	}
+
 	/* ALTER DATABASE <name> SET TABLESPACE */
 	else if (Matches("ALTER", "DATABASE", MatchAny, "SET", "TABLESPACE"))
 		COMPLETE_WITH_QUERY(Query_for_list_of_tablespaces);
@@ -4906,7 +4922,9 @@ match_previous_words(int pattern_id,
 
 /* SET, RESET, SHOW */
 	/* Complete with a variable name */
-	else if (TailMatches("SET|RESET") && !TailMatches("UPDATE", MatchAny, "SET"))
+	else if (TailMatches("SET|RESET") &&
+			 !TailMatches("UPDATE", MatchAny, "SET") &&
+			 !TailMatches("ALTER", "DATABASE", MatchAny, "RESET"))
 		COMPLETE_WITH_QUERY_VERBATIM_PLUS(Query_for_list_of_set_vars,
 										  "CONSTRAINTS",
 										  "TRANSACTION",
-- 
2.43.0

