From 7b278ea5c48d386e1c6f277f3d94520505205cd2 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Dagfinn=20Ilmari=20Manns=C3=A5ker?= <ilmari@ilmari.org>
Date: Mon, 31 Jan 2022 00:42:00 +0000
Subject: [PATCH 1/2] Respect COMP_KEYWORD_CASE for additional keywords

When tacking on keywords to the result of a completion query, use
pg_strdup_keyword_case().
---
 src/bin/psql/t/010_tab_completion.pl | 26 ++++++++++++++++++++------
 src/bin/psql/tab-complete.c          |  4 ++--
 2 files changed, 22 insertions(+), 8 deletions(-)

diff --git a/src/bin/psql/t/010_tab_completion.pl b/src/bin/psql/t/010_tab_completion.pl
index c4f6552ac9..c4a1d5e1bc 100644
--- a/src/bin/psql/t/010_tab_completion.pl
+++ b/src/bin/psql/t/010_tab_completion.pl
@@ -317,12 +317,26 @@ sub clear_line
 
 clear_line();
 
-# check completion of a keyword offered in addition to object names
-# (that code path currently doesn't preserve case of what's typed)
-check_completion(
-	"comment on constraint foo on dom\t",
-	qr|DOMAIN|,
-	"offer keyword in addition to query result");
+foreach (
+	['lower', 'DOM', 'domain'],
+	['upper', 'dom', 'DOMAIN'],
+	['preserve-lower', 'dom', 'domain'],
+	['preserve-upper', 'DOM', 'DOMAIN'],
+) {
+	my ($case, $in, $out) = @$_;
+
+	# check completion of a keyword offered in addition to object names
+	# and obeys COMP_KEYWORD_CASE
+	check_completion(
+		"\\set COMP_KEYWORD_CASE $case\n",
+		qr/postgres=#/,
+		"set completion case to '$case'");
+	check_completion(
+		"comment on constraint foo on $in\t",
+		qr|$out|,
+		"offer keyword in addition to query result (COMP_KEYWORD_CASE=$case)");
+	clear_line();
+}
 
 clear_query();
 
diff --git a/src/bin/psql/tab-complete.c b/src/bin/psql/tab-complete.c
index b2ec50b4f2..0c7a99be0a 100644
--- a/src/bin/psql/tab-complete.c
+++ b/src/bin/psql/tab-complete.c
@@ -5032,7 +5032,7 @@ _complete_from_query(const char *simple_query,
 				if (pg_strncasecmp(text, item, strlen(text)) == 0)
 				{
 					num_other++;
-					return pg_strdup(item);
+					return pg_strdup_keyword_case(item, text);
 				}
 			}
 		}
@@ -5050,7 +5050,7 @@ _complete_from_query(const char *simple_query,
 				if (pg_strncasecmp(text, item, strlen(text)) == 0)
 				{
 					num_other++;
-					return pg_strdup(item);
+					return pg_strdup_keyword_case(item, text);
 				}
 			}
 		}
-- 
2.30.2

