From 286861adbf418fa91ce357473f56965b9f919af0 Mon Sep 17 00:00:00 2001
From: Pengzhou Tang <ptang@pivotal.io>
Date: Thu, 12 Mar 2020 01:24:32 -0400
Subject: [PATCH] Set numtrans correctly when building hash aggregate tables

aggstate->numtrans is always zero when building hash aggregate
tables, this seems to be incorrect, fix it by delay the building
until the transitions are initialized.
---
 src/backend/executor/nodeAgg.c | 12 ++++++++----
 1 file changed, 8 insertions(+), 4 deletions(-)

diff --git a/src/backend/executor/nodeAgg.c b/src/backend/executor/nodeAgg.c
index 7aebb247d8..9d7a35d653 100644
--- a/src/backend/executor/nodeAgg.c
+++ b/src/backend/executor/nodeAgg.c
@@ -2520,10 +2520,6 @@ ExecInitAgg(Agg *node, EState *estate, int eflags)
 	{
 		/* this is an array of pointers, not structures */
 		aggstate->hash_pergroup = pergroups;
-
-		find_hash_columns(aggstate);
-		build_hash_tables(aggstate);
-		aggstate->table_filled = false;
 	}
 
 	/*
@@ -2879,6 +2875,14 @@ ExecInitAgg(Agg *node, EState *estate, int eflags)
 				(errcode(ERRCODE_GROUPING_ERROR),
 				 errmsg("aggregate function calls cannot be nested")));
 
+	/* Initialize hash tables for hash aggregates */
+	if (use_hashing)
+	{
+		find_hash_columns(aggstate);
+		build_hash_tables(aggstate);
+		aggstate->table_filled = false;
+	}
+
 	/*
 	 * Build expressions doing all the transition work at once. We build a
 	 * different one for each phase, as the number of transition function
-- 
2.14.1

