From 4d4e5d35e3ed7abb46387269fff98530f2dee24e Mon Sep 17 00:00:00 2001
From: shihao zhong <zhong950419@gmail.com>
Date: Sat, 5 Dec 2026 10:38:50 -0500
Subject: [PATCH v1] Fix stuck DETACH of a re-attached partitioned table with
 identity

Since 17, ATTACH PARTITION sets the identity property only on the
attached table.  Its own partitions do not get it.  This happens for a
table that was detached earlier, and for one that was never in the
tree.  Inserting into such a partition directly then fails to get the
default.  A later DETACH recurses with DROP IDENTITY and errors out on
those partitions.  DETACH CONCURRENTLY then stays pending, and FINALIZE
fails the same way.

Fix this in two parts.  ATTACH PARTITION now sets identity in the
partitions at every level.  DROP IDENTITY now warns and skips a
partition without identity when it recurses, instead of failing.

A database that is already stuck can now run DETACH ... FINALIZE.
Detaching and attaching the table again then restores identity in
its partitions.

Reported-by: Oleg Ivanov <o15611@gmail.com>
Discussion: https://postgr.es/m/19580-4baeeaaf5407a60d@postgresql.org
Backpatch-through: 17
---
 src/backend/commands/tablecmds.c       | 82 ++++++++++++++++++++++++++
 src/test/regress/expected/identity.out | 44 ++++++++++++++
 src/test/regress/sql/identity.sql      | 21 +++++++
 3 files changed, 147 insertions(+)

diff --git a/src/backend/commands/tablecmds.c b/src/backend/commands/tablecmds.c
index 9755943f110..5dc310c3565 100644
--- a/src/backend/commands/tablecmds.c
+++ b/src/backend/commands/tablecmds.c
@@ -384,6 +384,8 @@ static void MergeChildAttribute(List *inh_columns, int exist_attno, int newcol_a
 static ColumnDef *MergeInheritedAttribute(List *inh_columns, int exist_attno, const ColumnDef *newdef);
 static void MergeAttributesIntoExisting(Relation child_rel, Relation parent_rel, bool ispartition);
 static void MergeConstraintsIntoExisting(Relation child_rel, Relation parent_rel);
+static void SetIdentityInPartitions(Relation rel, const char *colName,
+									char identity);
 static void StoreCatalogInheritance(Oid relationId, List *supers,
 									bool child_is_partition);
 static void StoreCatalogInheritance1(Oid relationId, Oid parentOid,
@@ -9159,6 +9161,24 @@ ATExecDropIdentity(Relation rel, const char *colName, bool missing_ok, LOCKMODE
 
 	if (!attTup->attidentity)
 	{
+		/*
+		 * A partition reached by recursion may lack the identity property.
+		 * Older versions of ATTACH PARTITION set it only on the attached
+		 * table, not in its partitions.  This applies to a partitioned table
+		 * attached back after a detach, and to one that was never in the
+		 * tree.  Warn and skip, as an error here would leave a concurrent
+		 * detach unable to finish.
+		 */
+		if (recursing)
+		{
+			ereport(WARNING,
+					(errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
+					 errmsg("column \"%s\" of relation \"%s\" is not an identity column, skipping",
+							colName, RelationGetRelationName(rel))));
+			heap_freetuple(tuple);
+			table_close(attrelation, RowExclusiveLock);
+			return InvalidObjectAddress;
+		}
 		if (!missing_ok)
 			ereport(ERROR,
 					(errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
@@ -18942,6 +18962,19 @@ MergeAttributesIntoExisting(Relation child_rel, Relation parent_rel, bool ispart
 			}
 
 			CatalogTupleUpdate(attrrel, &tuple->t_self, tuple);
+
+			/*
+			 * If the child is itself partitioned, its partitions must have
+			 * the identity property too.  They may lack it because the child
+			 * was detached earlier, which drops identity in the whole
+			 * subtree, or because the child never was in this tree.  Set it
+			 * at every level.
+			 */
+			if (ispartition && parent_att->attidentity &&
+				child_rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE)
+				SetIdentityInPartitions(child_rel, parent_attname,
+										parent_att->attidentity);
+
 			heap_freetuple(tuple);
 		}
 		else
@@ -18955,6 +18988,55 @@ MergeAttributesIntoExisting(Relation child_rel, Relation parent_rel, bool ispart
 	table_close(attrrel, RowExclusiveLock);
 }
 
+/*
+ * Set the identity property of column colName in all partitions of the
+ * partitioned table rel, at every level.
+ *
+ * The caller has set the property on rel itself.  Its partitions may lack
+ * it, either because detaching dropped it from the whole subtree, or because
+ * rel was never part of this tree.
+ */
+static void
+SetIdentityInPartitions(Relation rel, const char *colName, char identity)
+{
+	Relation	attrrel;
+	List	   *children;
+
+	attrrel = table_open(AttributeRelationId, RowExclusiveLock);
+	children = find_inheritance_children(RelationGetRelid(rel),
+										 AccessExclusiveLock);
+
+	foreach_oid(childoid, children)
+	{
+		Relation	childrel;
+		HeapTuple	tuple;
+		Form_pg_attribute att;
+
+		childrel = table_open(childoid, NoLock);
+
+		tuple = SearchSysCacheCopyAttName(childoid, colName);
+		if (!HeapTupleIsValid(tuple))
+			elog(ERROR, "cache lookup failed for column \"%s\" of relation %u",
+				 colName, childoid);
+		att = (Form_pg_attribute) GETSTRUCT(tuple);
+
+		if (att->attidentity != identity)
+		{
+			att->attidentity = identity;
+			CatalogTupleUpdate(attrrel, &tuple->t_self, tuple);
+		}
+		heap_freetuple(tuple);
+
+		if (childrel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE)
+			SetIdentityInPartitions(childrel, colName, identity);
+
+		table_close(childrel, NoLock);
+	}
+
+	list_free(children);
+	table_close(attrrel, RowExclusiveLock);
+}
+
 /*
  * Check constraints in child table match up with constraints in parent,
  * and increment their coninhcount.
diff --git a/src/test/regress/expected/identity.out b/src/test/regress/expected/identity.out
index 0398a19484f..1cd59c335a9 100644
--- a/src/test/regress/expected/identity.out
+++ b/src/test/regress/expected/identity.out
@@ -747,6 +747,50 @@ SELECT tableoid::regclass, f1, f2, f3 FROM pitest2_p1;
 (6 rows)
 
 DROP TABLE pitest2_p1;
+-- reattaching a detached subtree restores identity at every level
+CREATE TABLE pitest2a (f1 date NOT NULL, f2 int GENERATED BY DEFAULT AS IDENTITY)
+  PARTITION BY RANGE (f1);
+CREATE TABLE pitest2a_p1 PARTITION OF pitest2a
+  FOR VALUES FROM ('2016-01-01') TO ('2017-01-01') PARTITION BY RANGE (f1);
+CREATE TABLE pitest2a_p11 PARTITION OF pitest2a_p1
+  FOR VALUES FROM ('2016-01-01') TO ('2016-07-01') PARTITION BY RANGE (f1);
+CREATE TABLE pitest2a_p111 PARTITION OF pitest2a_p11
+  FOR VALUES FROM ('2016-01-01') TO ('2016-04-01');
+ALTER TABLE pitest2a DETACH PARTITION pitest2a_p1;
+SELECT attrelid::regclass, attidentity FROM pg_attribute
+  WHERE attrelid::regclass::text LIKE 'pitest2a%' AND attname = 'f2' ORDER BY 1;
+   attrelid    | attidentity 
+---------------+-------------
+ pitest2a      | d
+ pitest2a_p1   | 
+ pitest2a_p11  | 
+ pitest2a_p111 | 
+(4 rows)
+
+ALTER TABLE pitest2a ATTACH PARTITION pitest2a_p1
+  FOR VALUES FROM ('2016-01-01') TO ('2017-01-01');
+SELECT attrelid::regclass, attidentity FROM pg_attribute
+  WHERE attrelid::regclass::text LIKE 'pitest2a%' AND attname = 'f2' ORDER BY 1;
+   attrelid    | attidentity 
+---------------+-------------
+ pitest2a      | d
+ pitest2a_p1   | d
+ pitest2a_p11  | d
+ pitest2a_p111 | d
+(4 rows)
+
+ALTER TABLE pitest2a DETACH PARTITION pitest2a_p1 CONCURRENTLY;
+SELECT attrelid::regclass, attidentity FROM pg_attribute
+  WHERE attrelid::regclass::text LIKE 'pitest2a%' AND attname = 'f2' ORDER BY 1;
+   attrelid    | attidentity 
+---------------+-------------
+ pitest2a      | d
+ pitest2a_p1   | 
+ pitest2a_p11  | 
+ pitest2a_p111 | 
+(4 rows)
+
+DROP TABLE pitest2a, pitest2a_p1;
 -- changing a regular column to identity column in a partitioned table
 CREATE TABLE pitest3 (f1 date NOT NULL, f2 text, f3 int) PARTITION BY RANGE (f1);
 CREATE TABLE pitest3_p1 PARTITION OF pitest3 FOR VALUES FROM ('2016-07-01') TO ('2016-08-01');
diff --git a/src/test/regress/sql/identity.sql b/src/test/regress/sql/identity.sql
index 45992a3d894..3b228e920f8 100644
--- a/src/test/regress/sql/identity.sql
+++ b/src/test/regress/sql/identity.sql
@@ -409,6 +409,27 @@ SELECT tableoid::regclass, f1, f2, f3 FROM pitest2_p1;
 
 DROP TABLE pitest2_p1;
 
+-- reattaching a detached subtree restores identity at every level
+CREATE TABLE pitest2a (f1 date NOT NULL, f2 int GENERATED BY DEFAULT AS IDENTITY)
+  PARTITION BY RANGE (f1);
+CREATE TABLE pitest2a_p1 PARTITION OF pitest2a
+  FOR VALUES FROM ('2016-01-01') TO ('2017-01-01') PARTITION BY RANGE (f1);
+CREATE TABLE pitest2a_p11 PARTITION OF pitest2a_p1
+  FOR VALUES FROM ('2016-01-01') TO ('2016-07-01') PARTITION BY RANGE (f1);
+CREATE TABLE pitest2a_p111 PARTITION OF pitest2a_p11
+  FOR VALUES FROM ('2016-01-01') TO ('2016-04-01');
+ALTER TABLE pitest2a DETACH PARTITION pitest2a_p1;
+SELECT attrelid::regclass, attidentity FROM pg_attribute
+  WHERE attrelid::regclass::text LIKE 'pitest2a%' AND attname = 'f2' ORDER BY 1;
+ALTER TABLE pitest2a ATTACH PARTITION pitest2a_p1
+  FOR VALUES FROM ('2016-01-01') TO ('2017-01-01');
+SELECT attrelid::regclass, attidentity FROM pg_attribute
+  WHERE attrelid::regclass::text LIKE 'pitest2a%' AND attname = 'f2' ORDER BY 1;
+ALTER TABLE pitest2a DETACH PARTITION pitest2a_p1 CONCURRENTLY;
+SELECT attrelid::regclass, attidentity FROM pg_attribute
+  WHERE attrelid::regclass::text LIKE 'pitest2a%' AND attname = 'f2' ORDER BY 1;
+DROP TABLE pitest2a, pitest2a_p1;
+
 -- changing a regular column to identity column in a partitioned table
 CREATE TABLE pitest3 (f1 date NOT NULL, f2 text, f3 int) PARTITION BY RANGE (f1);
 CREATE TABLE pitest3_p1 PARTITION OF pitest3 FOR VALUES FROM ('2016-07-01') TO ('2016-08-01');
-- 
2.37.1 (Apple Git-137.1)

