Thank you for the testing!

v3 is a trivial rebase.
From 90d0a39deace2fc9a26c2e06b20b29aa750507f6 Mon Sep 17 00:00:00 2001
From: Zsolt Parragi <[email protected]>
Date: Tue, 11 Aug 2026 21:59:44 +0000
Subject: [PATCH v3 1/2] Preserve statistics target of extended statistics
 rebuilt by ALTER TABLE

When ALTER TABLE ALTER COLUMN TYPE (or SET EXPRESSION) recreates the
extended statistics objects that depend on the altered column, it does
so by capturing each object's definition string and replaying it
through CREATE STATISTICS.  A statistics target set with ALTER
STATISTICS ... SET STATISTICS is not part of that definition string,
and CreateStatistics() always stored a null stxstattarget, so the
target silently reverted to the default after the rebuild.

This is the same class of problem as the statistics owner reset that
commit 6713a6e04cb fixed, and the fix follows the same pattern: have
RememberStatisticsForRebuilding() capture stxstattarget along with the
owner, thread it through ATPostAlterTypeParse() into the recreated
CreateStatsStmt, and make CreateStatistics() store it.  CreateStatsStmt
gains a stxstattarget field, with -1 meaning the default (null) target.
---
 src/backend/commands/statscmds.c        |  6 +++-
 src/backend/commands/tablecmds.c        | 37 +++++++++++++++++--------
 src/backend/parser/gram.y               |  2 ++
 src/backend/parser/parse_utilcmd.c      |  1 +
 src/include/nodes/parsenodes.h          |  1 +
 src/test/regress/expected/stats_ext.out | 20 +++++++------
 src/test/regress/sql/stats_ext.sql      |  8 ++++--
 7 files changed, 51 insertions(+), 24 deletions(-)

diff --git a/src/backend/commands/statscmds.c b/src/backend/commands/statscmds.c
index 4aaf41855ce..db5945c0493 100644
--- a/src/backend/commands/statscmds.c
+++ b/src/backend/commands/statscmds.c
@@ -572,7 +572,11 @@ CreateStatistics(List *relids, CreateStatsStmt *stmt, bool check_rights)
 	values[Anum_pg_statistic_ext_stxnamespace - 1] = ObjectIdGetDatum(namespaceId);
 	values[Anum_pg_statistic_ext_stxowner - 1] = ObjectIdGetDatum(stxowner);
 	values[Anum_pg_statistic_ext_stxkeys - 1] = PointerGetDatum(stxkeys);
-	nulls[Anum_pg_statistic_ext_stxstattarget - 1] = true;
+	if (stmt->stxstattarget >= 0)
+		values[Anum_pg_statistic_ext_stxstattarget - 1] =
+			Int16GetDatum(stmt->stxstattarget);
+	else
+		nulls[Anum_pg_statistic_ext_stxstattarget - 1] = true;
 	values[Anum_pg_statistic_ext_stxkind - 1] = PointerGetDatum(stxkind);
 
 	values[Anum_pg_statistic_ext_stxexprs - 1] = exprsDatum;
diff --git a/src/backend/commands/tablecmds.c b/src/backend/commands/tablecmds.c
index 9786a5af58a..4a5679a1728 100644
--- a/src/backend/commands/tablecmds.c
+++ b/src/backend/commands/tablecmds.c
@@ -213,6 +213,7 @@ typedef struct AlteredTableInfo
 	List	   *changedStatisticsOids;	/* OIDs of statistics to rebuild */
 	List	   *changedStatisticsDefs;	/* string definitions of same */
 	List	   *changedStatisticsOwners;	/* owners of same */
+	List	   *changedStatisticsTargets;	/* stxstattarget of same, or -1 */
 } AlteredTableInfo;
 
 /* Struct describing one new constraint to check in Phase 3 scan */
@@ -685,8 +686,8 @@ static void RememberStatisticsForRebuilding(Oid stxoid, AlteredTableInfo *tab);
 static void ATPostAlterTypeCleanup(List **wqueue, AlteredTableInfo *tab,
 								   LOCKMODE lockmode);
 static void ATPostAlterTypeParse(Oid oldId, Oid oldRelId, Oid refRelId, Oid ownerId,
-								 const char *cmdstring, List **wqueue,
-								 LOCKMODE lockmode, bool rewrite);
+								 int stxstattarget, const char *cmdstring,
+								 List **wqueue, LOCKMODE lockmode, bool rewrite);
 static void RebuildConstraintComment(AlteredTableInfo *tab, AlterTablePass pass,
 									 Oid objid, Relation rel, List *domname,
 									 const char *conname);
@@ -16756,6 +16757,8 @@ RememberStatisticsForRebuilding(Oid stxoid, AlteredTableInfo *tab)
 		char	   *defstring = pg_get_statisticsobjdef_string(stxoid);
 		HeapTuple	tup;
 		Form_pg_statistic_ext statext;
+		Datum		target;
+		bool		targetisnull;
 
 		tup = SearchSysCache1(STATEXTOID, ObjectIdGetDatum(stxoid));
 
@@ -16764,6 +16767,10 @@ RememberStatisticsForRebuilding(Oid stxoid, AlteredTableInfo *tab)
 
 		statext = (Form_pg_statistic_ext) GETSTRUCT(tup);
 
+		target = SysCacheGetAttr(STATEXTOID, tup,
+								 Anum_pg_statistic_ext_stxstattarget,
+								 &targetisnull);
+
 		tab->changedStatisticsOids = lappend_oid(tab->changedStatisticsOids,
 												 stxoid);
 		tab->changedStatisticsDefs = lappend(tab->changedStatisticsDefs,
@@ -16772,6 +16779,10 @@ RememberStatisticsForRebuilding(Oid stxoid, AlteredTableInfo *tab)
 		tab->changedStatisticsOwners = lappend_oid(tab->changedStatisticsOwners,
 												   statext->stxowner);
 
+		tab->changedStatisticsTargets =
+			lappend_int(tab->changedStatisticsTargets,
+						targetisnull ? -1 : (int) DatumGetInt16(target));
+
 		ReleaseSysCache(tup);
 	}
 }
@@ -16791,6 +16802,7 @@ ATPostAlterTypeCleanup(List **wqueue, AlteredTableInfo *tab, LOCKMODE lockmode)
 	ListCell   *def_item;
 	ListCell   *oid_item;
 	ListCell   *owner_item;
+	ListCell   *target_item;
 
 	/*
 	 * Collect all the constraints and indexes to drop so we can process them
@@ -16864,7 +16876,7 @@ ATPostAlterTypeCleanup(List **wqueue, AlteredTableInfo *tab, LOCKMODE lockmode)
 		if (relid != tab->relid)
 			LockRelationOid(relid, AccessExclusiveLock);
 
-		ATPostAlterTypeParse(oldId, relid, confrelid, InvalidOid,
+		ATPostAlterTypeParse(oldId, relid, confrelid, InvalidOid, -1,
 							 (char *) lfirst(def_item),
 							 wqueue, lockmode, tab->rewrite);
 	}
@@ -16883,7 +16895,7 @@ ATPostAlterTypeCleanup(List **wqueue, AlteredTableInfo *tab, LOCKMODE lockmode)
 		if (relid != tab->relid)
 			LockRelationOid(relid, AccessExclusiveLock);
 
-		ATPostAlterTypeParse(oldId, relid, InvalidOid, InvalidOid,
+		ATPostAlterTypeParse(oldId, relid, InvalidOid, InvalidOid, -1,
 							 (char *) lfirst(def_item),
 							 wqueue, lockmode, tab->rewrite);
 
@@ -16892,9 +16904,10 @@ ATPostAlterTypeCleanup(List **wqueue, AlteredTableInfo *tab, LOCKMODE lockmode)
 	}
 
 	/* add dependencies for new statistics */
-	forthree(oid_item, tab->changedStatisticsOids,
-			 def_item, tab->changedStatisticsDefs,
-			 owner_item, tab->changedStatisticsOwners)
+	forfour(oid_item, tab->changedStatisticsOids,
+			def_item, tab->changedStatisticsDefs,
+			owner_item, tab->changedStatisticsOwners,
+			target_item, tab->changedStatisticsTargets)
 	{
 		Oid			oldId = lfirst_oid(oid_item);
 		Oid			relid;
@@ -16915,8 +16928,9 @@ ATPostAlterTypeCleanup(List **wqueue, AlteredTableInfo *tab, LOCKMODE lockmode)
 			LockRelationOid(relid, ShareUpdateExclusiveLock);
 
 		ATPostAlterTypeParse(oldId, relid, InvalidOid, lfirst_oid(owner_item),
-							 (char *) lfirst(def_item),
-							 wqueue, lockmode, tab->rewrite);
+							 lfirst_int(target_item),
+							 (char *) lfirst(def_item), wqueue, lockmode,
+							 tab->rewrite);
 
 		ObjectAddressSet(obj, StatisticExtRelationId, oldId);
 		add_exact_object_address(&obj, objects);
@@ -16979,8 +16993,8 @@ ATPostAlterTypeCleanup(List **wqueue, AlteredTableInfo *tab, LOCKMODE lockmode)
  */
 static void
 ATPostAlterTypeParse(Oid oldId, Oid oldRelId, Oid refRelId, Oid ownerId,
-					 const char *cmdstring, List **wqueue, LOCKMODE lockmode,
-					 bool rewrite)
+					 int stxstattarget, const char *cmdstring, List **wqueue,
+					 LOCKMODE lockmode, bool rewrite)
 {
 	List	   *raw_parsetree_list;
 	List	   *querytree_list;
@@ -17025,6 +17039,7 @@ ATPostAlterTypeParse(Oid oldId, Oid oldRelId, Oid refRelId, Oid ownerId,
 
 			csstmt = transformStatsStmt(oldRelId, (CreateStatsStmt *) stmt, cmdstring);
 			csstmt->owner = ownerId;
+			csstmt->stxstattarget = stxstattarget;
 
 			querytree_list = lappend(querytree_list, csstmt);
 		}
diff --git a/src/backend/parser/gram.y b/src/backend/parser/gram.y
index 0563453fe24..083732021d9 100644
--- a/src/backend/parser/gram.y
+++ b/src/backend/parser/gram.y
@@ -4807,6 +4807,7 @@ CreateStatsStmt:
 					n->relations = $8;
 					n->stxcomment = NULL;
 					n->if_not_exists = false;
+					n->stxstattarget = -1;
 					$$ = (Node *) n;
 				}
 			| CREATE STATISTICS IF_P NOT EXISTS any_name
@@ -4820,6 +4821,7 @@ CreateStatsStmt:
 					n->relations = $11;
 					n->stxcomment = NULL;
 					n->if_not_exists = true;
+					n->stxstattarget = -1;
 					$$ = (Node *) n;
 				}
 			;
diff --git a/src/backend/parser/parse_utilcmd.c b/src/backend/parser/parse_utilcmd.c
index 583346bf531..0492229128d 100644
--- a/src/backend/parser/parse_utilcmd.c
+++ b/src/backend/parser/parse_utilcmd.c
@@ -2182,6 +2182,7 @@ generateClonedExtStatsStmt(RangeVar *heapRel, Oid heapRelid,
 	stats->stxcomment = NULL;
 	stats->transformed = true;	/* don't need transformStatsStmt again */
 	stats->if_not_exists = false;
+	stats->stxstattarget = -1;
 
 	/* Clean up */
 	ReleaseSysCache(ht_stats);
diff --git a/src/include/nodes/parsenodes.h b/src/include/nodes/parsenodes.h
index 5be1d4a944b..c34496cbad1 100644
--- a/src/include/nodes/parsenodes.h
+++ b/src/include/nodes/parsenodes.h
@@ -3574,6 +3574,7 @@ typedef struct CreateStatsStmt
 	bool		transformed;	/* true when transformStatsStmt is finished */
 	bool		if_not_exists;	/* do nothing if stats name already exists */
 	Oid			owner;			/* OID of owner, or InvalidOid for default */
+	int			stxstattarget;	/* statistics target, or -1 for default */
 } CreateStatsStmt;
 
 /*
diff --git a/src/test/regress/expected/stats_ext.out b/src/test/regress/expected/stats_ext.out
index 42d6c2777ea..dd8d0585d12 100644
--- a/src/test/regress/expected/stats_ext.out
+++ b/src/test/regress/expected/stats_ext.out
@@ -3611,18 +3611,20 @@ CREATE TABLE stats_ext_tbl (a int, b int);
 ALTER TABLE stats_ext_tbl OWNER TO regress_relowner;
 CREATE STATISTICS tst ON a, b FROM stats_ext_tbl;
 ALTER STATISTICS tst OWNER TO regress_stxowner;
-SELECT stxowner::regrole FROM pg_statistic_ext WHERE stxname = 'tst';
-     stxowner     
-------------------
- regress_stxowner
+ALTER STATISTICS tst SET STATISTICS 1000;
+SELECT stxowner::regrole, stxstattarget FROM pg_statistic_ext WHERE stxname = 'tst';
+     stxowner     | stxstattarget 
+------------------+---------------
+ regress_stxowner |          1000
 (1 row)
 
--- re-creating statistics via ALTER TABLE preserve the statistics owner.
+-- re-creating statistics via ALTER TABLE preserve the statistics owner
+-- and target.
 ALTER TABLE stats_ext_tbl ALTER COLUMN a TYPE bigint;
-SELECT stxowner::regrole FROM pg_statistic_ext WHERE stxname = 'tst';
-     stxowner     
-------------------
- regress_stxowner
+SELECT stxowner::regrole, stxstattarget FROM pg_statistic_ext WHERE stxname = 'tst';
+     stxowner     | stxstattarget 
+------------------+---------------
+ regress_stxowner |          1000
 (1 row)
 
 -- Tidy up
diff --git a/src/test/regress/sql/stats_ext.sql b/src/test/regress/sql/stats_ext.sql
index 6045cfa51e8..9ce5c522124 100644
--- a/src/test/regress/sql/stats_ext.sql
+++ b/src/test/regress/sql/stats_ext.sql
@@ -1855,11 +1855,13 @@ CREATE TABLE stats_ext_tbl (a int, b int);
 ALTER TABLE stats_ext_tbl OWNER TO regress_relowner;
 CREATE STATISTICS tst ON a, b FROM stats_ext_tbl;
 ALTER STATISTICS tst OWNER TO regress_stxowner;
-SELECT stxowner::regrole FROM pg_statistic_ext WHERE stxname = 'tst';
+ALTER STATISTICS tst SET STATISTICS 1000;
+SELECT stxowner::regrole, stxstattarget FROM pg_statistic_ext WHERE stxname = 'tst';
 
--- re-creating statistics via ALTER TABLE preserve the statistics owner.
+-- re-creating statistics via ALTER TABLE preserve the statistics owner
+-- and target.
 ALTER TABLE stats_ext_tbl ALTER COLUMN a TYPE bigint;
-SELECT stxowner::regrole FROM pg_statistic_ext WHERE stxname = 'tst';
+SELECT stxowner::regrole, stxstattarget FROM pg_statistic_ext WHERE stxname = 'tst';
 
 -- Tidy up
 DROP TABLE stats_ext_tbl;
-- 
2.56.1

From c3618d936e964e56345e5c0ad71deb4ad485ae9d Mon Sep 17 00:00:00 2001
From: Zsolt Parragi <[email protected]>
Date: Wed, 12 Aug 2026 16:06:45 +0000
Subject: [PATCH v3 2/2] Preserve statistics targets of indexes rebuilt by
 ALTER TABLE

When ALTER TABLE ALTER COLUMN TYPE (or SET EXPRESSION) recreates the
indexes that depend on the altered column, it replays each index's
definition string through CREATE INDEX.  A statistics target set on an
expression column with ALTER INDEX ... ALTER COLUMN ... SET STATISTICS
is not part of that definition string, so the target silently reverted
to the default after the rebuild.  The index of a rebuilt exclusion
constraint lost its targets the same way.

To fix, capture the per-column targets next to where
ATPostAlterTypeParse() already captures the index's comment, carry them
in a new IndexStmt field, and have DefineIndex() apply them once the
index exists.  DefineIndex() also propagates the targets to the indexes
it creates on partitions, matching the recursion that ALTER INDEX ...
SET STATISTICS performs on partitioned indexes.  Targets set directly
on a partition's index are still not preserved when the rebuild
recurses from the parent, mirroring the pre-existing behavior for such
indexes' comments.
---
 src/backend/commands/indexcmds.c          | 70 +++++++++++++++++++++++
 src/backend/commands/tablecmds.c          | 60 +++++++++++++++++++
 src/include/nodes/parsenodes.h            |  1 +
 src/test/regress/expected/alter_table.out | 36 ++++++++++++
 src/test/regress/sql/alter_table.sql      | 26 +++++++++
 5 files changed, 193 insertions(+)

diff --git a/src/backend/commands/indexcmds.c b/src/backend/commands/indexcmds.c
index 4a0d24afe70..f4aaeacccb3 100644
--- a/src/backend/commands/indexcmds.c
+++ b/src/backend/commands/indexcmds.c
@@ -30,6 +30,7 @@
 #include "catalog/indexing.h"
 #include "catalog/namespace.h"
 #include "catalog/pg_am.h"
+#include "catalog/pg_attribute.h"
 #include "catalog/pg_authid.h"
 #include "catalog/pg_collation.h"
 #include "catalog/pg_constraint.h"
@@ -84,6 +85,7 @@ typedef struct CIEN_context
 /* non-export function prototypes */
 static bool CompareOpclassOptions(const Datum *opts1, const Datum *opts2, int natts);
 static void CheckPredicate(Expr *predicate);
+static void SetIndexStatTargets(Oid indexOid, List *stattargets);
 static void ComputeIndexAttrs(ParseState *pstate,
 							  IndexInfo *indexInfo,
 							  Oid *typeOids,
@@ -1327,6 +1329,10 @@ DefineIndex(ParseState *pstate,
 		CreateComments(indexRelationId, RelationRelationId, 0,
 					   stmt->idxcomment);
 
+	/* Apply any requested per-column statistics targets */
+	if (stmt->stattargets != NIL)
+		SetIndexStatTargets(indexRelationId, stmt->stattargets);
+
 	if (partitioned)
 	{
 		PartitionDesc partdesc;
@@ -1549,6 +1555,13 @@ DefineIndex(ParseState *pstate,
 														attmap,
 														NULL);
 
+					/*
+					 * Propagate any per-column statistics targets to the
+					 * child index, matching the recursion that ALTER INDEX
+					 * ... SET STATISTICS performs on partitioned indexes.
+					 */
+					childStmt->stattargets = stmt->stattargets;
+
 					/*
 					 * Recurse as the starting user ID.  Callee will use that
 					 * for permission checks, then switch again.
@@ -1853,6 +1866,63 @@ DefineIndex(ParseState *pstate,
 	return address;
 }
 
+/*
+ * SetIndexStatTargets
+ *		Apply per-column statistics targets to a just-created index.
+ *
+ * The list contains one integer per index column, with -1 meaning the
+ * target is not set for that column.  It is captured from a previous
+ * incarnation of the index by ATPostAlterTypeParse(), so the column
+ * structure is known to match.
+ */
+static void
+SetIndexStatTargets(Oid indexOid, List *stattargets)
+{
+	Relation	attrelation;
+	AttrNumber	attnum = 0;
+	ListCell   *lc;
+
+	attrelation = table_open(AttributeRelationId, RowExclusiveLock);
+
+	foreach(lc, stattargets)
+	{
+		int			target = lfirst_int(lc);
+		HeapTuple	tuple,
+					newtuple;
+		Datum		repl_val[Natts_pg_attribute];
+		bool		repl_null[Natts_pg_attribute];
+		bool		repl_repl[Natts_pg_attribute];
+
+		attnum++;
+
+		if (target < 0)
+			continue;
+
+		tuple = SearchSysCache2(ATTNUM,
+								ObjectIdGetDatum(indexOid),
+								Int16GetDatum(attnum));
+		if (!HeapTupleIsValid(tuple))
+			elog(ERROR, "cache lookup failed for attribute %d of relation %u",
+				 attnum, indexOid);
+
+		memset(repl_val, 0, sizeof(repl_val));
+		memset(repl_null, false, sizeof(repl_null));
+		memset(repl_repl, false, sizeof(repl_repl));
+
+		repl_val[Anum_pg_attribute_attstattarget - 1] = Int16GetDatum(target);
+		repl_repl[Anum_pg_attribute_attstattarget - 1] = true;
+
+		newtuple = heap_modify_tuple(tuple, RelationGetDescr(attrelation),
+									 repl_val, repl_null, repl_repl);
+		CatalogTupleUpdate(attrelation, &tuple->t_self, newtuple);
+
+		heap_freetuple(newtuple);
+		ReleaseSysCache(tuple);
+	}
+
+	table_close(attrelation, RowExclusiveLock);
+}
+
 
 /*
  * CheckPredicate
diff --git a/src/backend/commands/tablecmds.c b/src/backend/commands/tablecmds.c
index 4a5679a1728..b44e89b5657 100644
--- a/src/backend/commands/tablecmds.c
+++ b/src/backend/commands/tablecmds.c
@@ -683,6 +683,7 @@ static void RememberWholeRowDependentForRebuilding(AlteredTableInfo *tab, AlterT
 static void RememberConstraintForRebuilding(Oid conoid, AlteredTableInfo *tab);
 static void RememberIndexForRebuilding(Oid indoid, AlteredTableInfo *tab);
 static void RememberStatisticsForRebuilding(Oid stxoid, AlteredTableInfo *tab);
+static List *GetIndexStatTargets(Oid indexOid);
 static void ATPostAlterTypeCleanup(List **wqueue, AlteredTableInfo *tab,
 								   LOCKMODE lockmode);
 static void ATPostAlterTypeParse(Oid oldId, Oid oldRelId, Oid refRelId, Oid ownerId,
@@ -16983,6 +16984,61 @@ ATPostAlterTypeCleanup(List **wqueue, AlteredTableInfo *tab, LOCKMODE lockmode)
 	 */
 }
 
+/*
+ * Subroutine for ATPostAlterTypeParse().  Fetch the per-column statistics
+ * targets of the given index, as a list of integers with -1 standing for
+ * columns whose target is not set.  Returns NIL if no column has a target,
+ * which is the common case.
+ */
+static List *
+GetIndexStatTargets(Oid indexOid)
+{
+	List	   *result = NIL;
+	bool		found = false;
+	HeapTuple	reltup;
+	int			natts;
+
+	reltup = SearchSysCache1(RELOID, ObjectIdGetDatum(indexOid));
+	if (!HeapTupleIsValid(reltup))
+		elog(ERROR, "cache lookup failed for relation %u", indexOid);
+	natts = ((Form_pg_class) GETSTRUCT(reltup))->relnatts;
+	ReleaseSysCache(reltup);
+
+	for (AttrNumber attnum = 1; attnum <= natts; attnum++)
+	{
+		HeapTuple	tuple;
+		Datum		dat;
+		bool		isnull;
+
+		tuple = SearchSysCache2(ATTNUM,
+								ObjectIdGetDatum(indexOid),
+								Int16GetDatum(attnum));
+		if (!HeapTupleIsValid(tuple))
+			elog(ERROR, "cache lookup failed for attribute %d of relation %u",
+				 attnum, indexOid);
+
+		dat = SysCacheGetAttr(ATTNUM, tuple,
+							  Anum_pg_attribute_attstattarget, &isnull);
+		if (isnull)
+			result = lappend_int(result, -1);
+		else
+		{
+			result = lappend_int(result, (int) DatumGetInt16(dat));
+			found = true;
+		}
+
+		ReleaseSysCache(tuple);
+	}
+
+	if (!found)
+	{
+		list_free(result);
+		return NIL;
+	}
+
+	return result;
+}
+
 /*
  * Parse the previously-saved definition string for a constraint, index or
  * statistics object against the newly-established column data type(s), and
@@ -17075,6 +17131,8 @@ ATPostAlterTypeParse(Oid oldId, Oid oldRelId, Oid refRelId, Oid ownerId,
 			stmt->reset_default_tblspc = true;
 			/* keep the index's comment */
 			stmt->idxcomment = GetComment(oldId, RelationRelationId, 0);
+			/* keep any per-column statistics targets */
+			stmt->stattargets = GetIndexStatTargets(oldId);
 
 			newcmd = makeNode(AlterTableCmd);
 			newcmd->subtype = AT_ReAddIndex;
@@ -17104,6 +17162,8 @@ ATPostAlterTypeParse(Oid oldId, Oid oldRelId, Oid refRelId, Oid ownerId,
 					/* keep any comment on the index */
 					indstmt->idxcomment = GetComment(indoid,
 													 RelationRelationId, 0);
+					/* keep any per-column statistics targets */
+					indstmt->stattargets = GetIndexStatTargets(indoid);
 					indstmt->reset_default_tblspc = true;
 
 					cmd->subtype = AT_ReAddIndex;
diff --git a/src/include/nodes/parsenodes.h b/src/include/nodes/parsenodes.h
index c34496cbad1..bce235c7695 100644
--- a/src/include/nodes/parsenodes.h
+++ b/src/include/nodes/parsenodes.h
@@ -3540,6 +3540,7 @@ typedef struct IndexStmt
 	Node	   *whereClause;	/* qualification (partial-index predicate) */
 	List	   *excludeOpNames; /* exclusion operator names, or NIL if none */
 	char	   *idxcomment;		/* comment to apply to index, or NULL */
+	List	   *stattargets;	/* per-column statistics targets, or NIL */
 	Oid			indexOid;		/* OID of an existing index, if any */
 	RelFileNumber oldNumber;	/* relfilenumber of existing storage, if any */
 	SubTransactionId oldCreateSubid;	/* rd_createSubid of oldNumber */
diff --git a/src/test/regress/expected/alter_table.out b/src/test/regress/expected/alter_table.out
index f99b2b9e663..786818382cd 100644
--- a/src/test/regress/expected/alter_table.out
+++ b/src/test/regress/expected/alter_table.out
@@ -119,6 +119,42 @@ HINT:  Alter statistics on table column instead.
 ALTER INDEX attmp_idx ALTER COLUMN 4 SET STATISTICS 1000;
 ERROR:  column number 4 of relation "attmp_idx" does not exist
 ALTER INDEX attmp_idx ALTER COLUMN 2 SET STATISTICS -1;
+DROP TABLE attmp;
+-- Check that index column statistics targets survive the index rebuilds
+-- caused by ALTER TABLE ... ALTER COLUMN TYPE, including the rebuild of
+-- an exclusion constraint's index and recursion to partitions.
+CREATE TABLE attmp (a int, b int, EXCLUDE ((a + b) WITH =));
+CREATE INDEX attmp_expr_idx ON attmp ((a * b));
+ALTER INDEX attmp_expr_idx ALTER COLUMN 1 SET STATISTICS 100;
+ALTER INDEX attmp_a_b_excl ALTER COLUMN 1 SET STATISTICS 200;
+ALTER TABLE attmp ALTER COLUMN a TYPE bigint;
+SELECT c.relname, a.attstattarget
+  FROM pg_attribute a JOIN pg_class c ON c.oid = a.attrelid
+  WHERE c.relname IN ('attmp_expr_idx', 'attmp_a_b_excl') AND a.attnum = 1
+  ORDER BY c.relname;
+    relname     | attstattarget 
+----------------+---------------
+ attmp_a_b_excl |           200
+ attmp_expr_idx |           100
+(2 rows)
+
+DROP TABLE attmp;
+CREATE TABLE attmp (a int, b int) PARTITION BY RANGE (b);
+CREATE TABLE attmp1 PARTITION OF attmp FOR VALUES FROM (0) TO (100);
+CREATE INDEX attmp_part_idx ON attmp ((a + 1));
+ALTER INDEX attmp_part_idx ALTER COLUMN 1 SET STATISTICS 100;
+ALTER TABLE attmp ALTER COLUMN a TYPE bigint;
+SELECT c.relname, a.attstattarget
+  FROM pg_attribute a JOIN pg_class c ON c.oid = a.attrelid
+  WHERE a.attrelid IN ('attmp_part_idx'::regclass, 'attmp1_a_1_idx'::regclass)
+    AND a.attnum = 1
+  ORDER BY c.relname;
+    relname     | attstattarget 
+----------------+---------------
+ attmp1_a_1_idx |           100
+ attmp_part_idx |           100
+(2 rows)
+
 DROP TABLE attmp;
 --
 -- add attribute when the row type is in use
diff --git a/src/test/regress/sql/alter_table.sql b/src/test/regress/sql/alter_table.sql
index a6b4265b811..cd0cf2ce643 100644
--- a/src/test/regress/sql/alter_table.sql
+++ b/src/test/regress/sql/alter_table.sql
@@ -158,6 +158,32 @@ ALTER INDEX attmp_idx ALTER COLUMN 2 SET STATISTICS -1;
 
 DROP TABLE attmp;
 
+-- Check that index column statistics targets survive the index rebuilds
+-- caused by ALTER TABLE ... ALTER COLUMN TYPE, including the rebuild of
+-- an exclusion constraint's index and recursion to partitions.
+CREATE TABLE attmp (a int, b int, EXCLUDE ((a + b) WITH =));
+CREATE INDEX attmp_expr_idx ON attmp ((a * b));
+ALTER INDEX attmp_expr_idx ALTER COLUMN 1 SET STATISTICS 100;
+ALTER INDEX attmp_a_b_excl ALTER COLUMN 1 SET STATISTICS 200;
+ALTER TABLE attmp ALTER COLUMN a TYPE bigint;
+SELECT c.relname, a.attstattarget
+  FROM pg_attribute a JOIN pg_class c ON c.oid = a.attrelid
+  WHERE c.relname IN ('attmp_expr_idx', 'attmp_a_b_excl') AND a.attnum = 1
+  ORDER BY c.relname;
+DROP TABLE attmp;
+
+CREATE TABLE attmp (a int, b int) PARTITION BY RANGE (b);
+CREATE TABLE attmp1 PARTITION OF attmp FOR VALUES FROM (0) TO (100);
+CREATE INDEX attmp_part_idx ON attmp ((a + 1));
+ALTER INDEX attmp_part_idx ALTER COLUMN 1 SET STATISTICS 100;
+ALTER TABLE attmp ALTER COLUMN a TYPE bigint;
+SELECT c.relname, a.attstattarget
+  FROM pg_attribute a JOIN pg_class c ON c.oid = a.attrelid
+  WHERE a.attrelid IN ('attmp_part_idx'::regclass, 'attmp1_a_1_idx'::regclass)
+    AND a.attnum = 1
+  ORDER BY c.relname;
+DROP TABLE attmp;
+
 --
 -- add attribute when the row type is in use
 --
-- 
2.56.1

Reply via email to