From 157bd59341f7440fb405b0073bc557487703b61e Mon Sep 17 00:00:00 2001
From: Anthonin Bonnefoy <anthonin.bonnefoy@datadoghq.com>
Date: Thu, 10 Oct 2024 08:52:22 +0200
Subject: Fix psql segfault on word completion without match

When completing a word that has no match, completion would fallback to
check the previous word to search for possible words like TABLE or
INDEX... However, if there's no previous word, it will still try to
compare the unset previous word, leading to a segfault.

This patch fixes by making sure that a previous word exists before
checking it.
---
 src/bin/psql/t/010_tab_completion.pl | 5 +++++
 src/bin/psql/tab-complete.in.c       | 2 +-
 2 files changed, 6 insertions(+), 1 deletion(-)

diff --git a/src/bin/psql/t/010_tab_completion.pl b/src/bin/psql/t/010_tab_completion.pl
index fd645896c97..5c36f014f37 100644
--- a/src/bin/psql/t/010_tab_completion.pl
+++ b/src/bin/psql/t/010_tab_completion.pl
@@ -415,6 +415,11 @@ check_completion("blarg \t\t", qr//, "check completion failure path");
 
 clear_query();
 
+# check word completion without match code path
+check_completion("z\t\t", qr//, "check completion failure path");
+
+clear_query();
+
 # check COPY FROM with DEFAULT option
 check_completion(
 	"COPY foo FROM stdin WITH ( DEF\t)",
diff --git a/src/bin/psql/tab-complete.in.c b/src/bin/psql/tab-complete.in.c
index a9f4d205e14..1be0056af73 100644
--- a/src/bin/psql/tab-complete.in.c
+++ b/src/bin/psql/tab-complete.in.c
@@ -2024,7 +2024,7 @@ psql_completion(const char *text, int start, int end)
 	 * check if that was the previous word. If so, execute the query to get a
 	 * list of them.
 	 */
-	if (matches == NULL)
+	if (matches == NULL && previous_words_count > 0)
 	{
 		const pgsql_thing_t *wac;
 
-- 
2.39.5 (Apple Git-154)

