From 140866a7fbd18044301fc86580ff0602bec681c4 Mon Sep 17 00:00:00 2001
From: amitlan <amitlangote09@gmail.com>
Date: Thu, 18 Mar 2021 21:34:21 +0900
Subject: [PATCH v5 1/2] Mark fully grouped relations partitioned if input
 relation is

When a grouped aggregate is pushed to individual partitions of a
partitioned base/join relation (partitionwise aggregation enabled),
the parent grouping upper rel follows the same partitioning scheme as
the input parent base/join rel in principle, although that isn't
reflected in the former's RelOptInfo.

This commit fixes that situation.  The main benefit is that anything
that relies on using IS_PARTITIONED_REL() macro to apply certain
operations to partitioned relations can now also recognize grouping
rels.
---
 src/backend/optimizer/plan/planner.c | 19 +++++++++++++++++++
 1 file changed, 19 insertions(+)

diff --git a/src/backend/optimizer/plan/planner.c b/src/backend/optimizer/plan/planner.c
index 424d25cbd5..2317231be5 100644
--- a/src/backend/optimizer/plan/planner.c
+++ b/src/backend/optimizer/plan/planner.c
@@ -7620,6 +7620,23 @@ create_partitionwise_grouping_paths(PlannerInfo *root,
 	Assert(patype != PARTITIONWISE_AGGREGATE_PARTIAL ||
 		   partially_grouped_rel != NULL);
 
+	/*
+	 * Make fully grouped rels appear partitioned like the input rel with
+	 * proprties same as the latter.
+	 */
+	Assert(IS_PARTITIONED_REL(input_rel));
+	if (patype == PARTITIONWISE_AGGREGATE_FULL)
+	{
+		grouped_rel->part_scheme = input_rel->part_scheme;
+		grouped_rel->partexprs = input_rel->partexprs;
+		grouped_rel->nullable_partexprs = input_rel->nullable_partexprs;
+		grouped_rel->boundinfo = input_rel->boundinfo;
+		grouped_rel->nparts = nparts;
+		Assert(grouped_rel->part_rels == NULL);
+		grouped_rel->part_rels =
+			(RelOptInfo **) palloc0(sizeof(RelOptInfo *) * nparts);
+	}
+
 	/* Add paths for partitionwise aggregation/grouping. */
 	for (cnt_parts = 0; cnt_parts < nparts; cnt_parts++)
 	{
@@ -7695,6 +7712,8 @@ create_partitionwise_grouping_paths(PlannerInfo *root,
 			set_cheapest(child_grouped_rel);
 			grouped_live_children = lappend(grouped_live_children,
 											child_grouped_rel);
+			Assert(grouped_rel->part_rels[cnt_parts] == NULL);
+			grouped_rel->part_rels[cnt_parts] = child_grouped_rel;
 		}
 
 		pfree(appinfos);
-- 
2.24.1

