From b5b337ed772999e03d6a4d4391f4631b6af19d59 Mon Sep 17 00:00:00 2001
From: Heikki Linnakangas <heikki.linnakangas@iki.fi>
Date: Thu, 29 Jan 2015 15:48:02 +0200
Subject: [PATCH 1/1] Fix bug where GIN scan keys were not initialized with
 gin_fuzzy_search_limit.

In 9.4, startScanKey() does a lot of stuff, setting up the requiredEntries
array, and you readily get a segfault if it's not initialized. In earlier
versions it was harder to trigger incorrect behaviour, because it just set
a few flags which were initialized in ginNewScanKey() already. But even on
on earlier versions, you would get an assertion failure or missing result
rows if the query involved a re-scan of the GIN scan.

Reported by Olaf Gawenda, bug #12694, Backpatch to 9.1 and above, 9.0 didn't
have the early return in startScan().
---
 src/backend/access/gin/ginget.c | 21 ++++++++++++++++-----
 1 file changed, 16 insertions(+), 5 deletions(-)

diff --git a/src/backend/access/gin/ginget.c b/src/backend/access/gin/ginget.c
index 3494d6b..306a3ce 100644
--- a/src/backend/access/gin/ginget.c
+++ b/src/backend/access/gin/ginget.c
@@ -540,17 +540,28 @@ startScan(IndexScanDesc scan)
 		 * supposition isn't true), that total result will not more than
 		 * minimal predictNumberResult.
 		 */
+		bool		reduce = true;
 
 		for (i = 0; i < so->totalentries; i++)
+		{
 			if (so->entries[i]->predictNumberResult <= so->totalentries * GinFuzzySearchLimit)
-				return;
+			{
+				reduce = false;
+				break;
+			}
+		}
 
-		for (i = 0; i < so->totalentries; i++)
-			if (so->entries[i]->predictNumberResult > so->totalentries * GinFuzzySearchLimit)
+		if (reduce)
+		{
+			for (i = 0; i < so->totalentries; i++)
 			{
-				so->entries[i]->predictNumberResult /= so->totalentries;
-				so->entries[i]->reduceResult = TRUE;
+				if (so->entries[i]->predictNumberResult > so->totalentries * GinFuzzySearchLimit)
+				{
+					so->entries[i]->predictNumberResult /= so->totalentries;
+					so->entries[i]->reduceResult = TRUE;
+				}
 			}
+		}
 	}
 
 	for (i = 0; i < so->nkeys; i++)
-- 
2.1.4

