From 63f7586af41225d3abf4612dc74c6fcbd5f78cc7 Mon Sep 17 00:00:00 2001
From: Richard Guo <guofenglinux@gmail.com>
Date: Fri, 15 Dec 2023 15:07:08 +0800
Subject: [PATCH v1] Adjust tuples estimate for appendrel

---
 src/backend/optimizer/path/allpaths.c | 9 ++++++---
 1 file changed, 6 insertions(+), 3 deletions(-)

diff --git a/src/backend/optimizer/path/allpaths.c b/src/backend/optimizer/path/allpaths.c
index 67921a0826..290e0344a6 100644
--- a/src/backend/optimizer/path/allpaths.c
+++ b/src/backend/optimizer/path/allpaths.c
@@ -949,6 +949,7 @@ set_append_rel_size(PlannerInfo *root, RelOptInfo *rel,
 {
 	int			parentRTindex = rti;
 	bool		has_live_children;
+	double		parent_tuples;
 	double		parent_rows;
 	double		parent_size;
 	double	   *parent_attrsizes;
@@ -986,6 +987,7 @@ set_append_rel_size(PlannerInfo *root, RelOptInfo *rel,
 	 * have zero rows and/or width, if they were excluded by constraints.
 	 */
 	has_live_children = false;
+	parent_tuples = 0;
 	parent_rows = 0;
 	parent_size = 0;
 	nattrs = rel->max_attr - rel->min_attr + 1;
@@ -1152,6 +1154,7 @@ set_append_rel_size(PlannerInfo *root, RelOptInfo *rel,
 		 */
 		Assert(childrel->rows > 0);
 
+		parent_tuples += childrel->tuples;
 		parent_rows += childrel->rows;
 		parent_size += childrel->reltarget->width * childrel->rows;
 
@@ -1204,10 +1207,10 @@ set_append_rel_size(PlannerInfo *root, RelOptInfo *rel,
 			rel->attr_widths[i] = rint(parent_attrsizes[i] / parent_rows);
 
 		/*
-		 * Set "raw tuples" count equal to "rows" for the appendrel; needed
-		 * because some places assume rel->tuples is valid for any baserel.
+		 * Set "raw tuples" count for the appendrel; needed because some places
+		 * assume rel->tuples is valid for any baserel.
 		 */
-		rel->tuples = parent_rows;
+		rel->tuples = parent_tuples;
 
 		/*
 		 * Note that we leave rel->pages as zero; this is important to avoid
-- 
2.31.0

