From be743cccfae542dec9ee07918b88be61073ab6ec Mon Sep 17 00:00:00 2001
From: Julien Tachoires <julmon@gmail.com>
Date: Wed, 15 Apr 2026 12:46:46 +0200
Subject: [PATCH 2/2] Fix attnum remapping in generateClonedExtStatsStmt()

When cloning extended statistics via CREATE TABLE ... LIKE ... INCLUDING
STATISTICS, stxkeys holds attribute numbers from the source (parent) table,
but get_attname() was being called with the child relation's OID.  If the
parent has dropped columns, the child's attribute numbers are renumbered
sequentially and no longer match, so the lookup either returns the wrong
column name or errors out when the attnum does not exist in the child.

Fix it by remapping the parent attnum through attmap before the lookup,
consistent with how expression statistics are already handled a few lines
below.
---
 src/backend/parser/parse_utilcmd.c | 3 ++-
 1 file changed, 2 insertions(+), 1 deletion(-)

diff --git a/src/backend/parser/parse_utilcmd.c b/src/backend/parser/parse_utilcmd.c
index 37071502a9f..131f33962b5 100644
--- a/src/backend/parser/parse_utilcmd.c
+++ b/src/backend/parser/parse_utilcmd.c
@@ -2100,7 +2100,8 @@ generateClonedExtStatsStmt(RangeVar *heapRel, Oid heapRelid,
 		StatsElem  *selem = makeNode(StatsElem);
 		AttrNumber	attnum = statsrec->stxkeys.values[i];
 
-		selem->name = get_attname(heapRelid, attnum, false);
+		selem->name =
+			get_attname(heapRelid, attmap->attnums[attnum - 1], false);
 		selem->expr = NULL;
 
 		def_names = lappend(def_names, selem);
-- 
2.51.2

