From 574e5864ef586a7f39860e9b265b58f2b900af99 Mon Sep 17 00:00:00 2001
From: James Coleman <jtc331@gmail.com>
Date: Wed, 25 Mar 2020 08:36:36 -0400
Subject: [PATCH v42 04/12] better rescan sort state reset

---
 src/backend/executor/nodeIncrementalSort.c | 10 ++++++++--
 1 file changed, 8 insertions(+), 2 deletions(-)

diff --git a/src/backend/executor/nodeIncrementalSort.c b/src/backend/executor/nodeIncrementalSort.c
index 53dccf3450..4cb7679f10 100644
--- a/src/backend/executor/nodeIncrementalSort.c
+++ b/src/backend/executor/nodeIncrementalSort.c
@@ -1154,14 +1154,20 @@ ExecReScanIncrementalSort(IncrementalSortState *node)
 
 	node->execution_status = INCSORT_LOADFULLSORT;
 
+	/*
+	 * If we've set up either of the sort states yet, we need to reset them.
+	 * We could end them and null out the pointers, but there's no reason to
+	 * repay the setup cost, and because guard setting up pivot comparator
+	 * state similarly, doing so might actually cause a leak.
+	 */
 	if (node->fullsort_state != NULL)
 	{
-		tuplesort_end(node->fullsort_state);
+		tuplesort_reset(node->fullsort_state);
 		node->fullsort_state = NULL;
 	}
 	if (node->prefixsort_state != NULL)
 	{
-		tuplesort_end(node->prefixsort_state);
+		tuplesort_reset(node->prefixsort_state);
 		node->prefixsort_state = NULL;
 	}
 
-- 
2.17.1

