From 3e99153f940bdda4850f1c7b6aca77dfb84d28e5 Mon Sep 17 00:00:00 2001
From: Sai Pranav <rajasaipranav0@gmail.com>
Date: Mon, 30 Nov 2026 16:36:50 +0530
Subject: [PATCH v2] pg_dump: Restore a child's NOT VALID not-null constraint
 before its parent's

NOT VALID not-null constraints are dumped as separate ALTER TABLE ... ADD
CONSTRAINT commands.  Adding one to a table also adds it to the table's
inheritance children, and a child with no not-null constraint on the
column yet gets one with the parent's constraint name.  So if a child has
its own NOT VALID not-null constraint with a different name, and the
parent's is restored first, the child's own command then fails with
"cannot create not-null constraint ... A not-null constraint named ...
already exists for this column".  This breaks pg_dump/restore and
pg_upgrade.

Fix by making, in flagInhAttrs(), the NOT VALID not-null constraints of
each ancestor on the same column depend on the child's own, so the
child's is restored first and the ancestors' then merge into it, as in
the original database.  To find a column's constraint object there,
getTableAttrs() now records it per column.

Add a table pair to the constraints regression test that is left in
place, so that the pg_upgrade test covers this.

Reported-by: Alexander Lakhin <exclusion@gmail.com>
---
 src/bin/pg_dump/common.c                  | 51 +++++++++++++++++++++++
 src/bin/pg_dump/pg_dump.c                 | 15 ++++++-
 src/bin/pg_dump/pg_dump.h                 |  3 ++
 src/test/regress/expected/constraints.out | 13 ++++++
 src/test/regress/sql/constraints.sql      |  7 ++++
 5 files changed, 88 insertions(+), 1 deletion(-)

diff --git a/src/bin/pg_dump/common.c b/src/bin/pg_dump/common.c
index cda9d73a9d..50698f7796 100644
--- a/src/bin/pg_dump/common.c
+++ b/src/bin/pg_dump/common.c
@@ -86,6 +86,9 @@ static void flagInhTables(Archive *fout, TableInfo *tblinfo, int numTables,
 static void flagInhIndexes(Archive *fout, TableInfo *tblinfo, int numTables);
 static void flagInhAttrs(Archive *fout, DumpOptions *dopt, TableInfo *tblinfo,
 						 int numTables);
+static void addInvalidNotNullDependencies(TableInfo *tbinfo,
+										  const char *attname,
+										  ConstraintInfo *childcon);
 static int	strInArray(const char *pattern, char **arr, int arr_size);
 static IndxInfo *findIndexByOid(Oid oid);
 
@@ -580,6 +583,16 @@ flagInhAttrs(Archive *fout, DumpOptions *dopt, TableInfo *tblinfo, int numTables
 				}
 			}
 
+			/*
+			 * If this table has its own NOT VALID not-null constraint on the
+			 * column, it must be restored before those of its ancestors.
+			 */
+			if (tbinfo->notnull_invalidcon &&
+				tbinfo->notnull_invalidcon[j] &&
+				tbinfo->notnull_invalidcon[j]->conislocal)
+				addInvalidNotNullDependencies(tbinfo, tbinfo->attnames[j],
+											  tbinfo->notnull_invalidcon[j]);
+
 			/*
 			 * In versions < 18, for lack of a better system, we arbitrarily
 			 * decide that a not-null constraint is not locally defined if at
@@ -647,6 +660,44 @@ flagInhAttrs(Archive *fout, DumpOptions *dopt, TableInfo *tblinfo, int numTables
 	}
 }
 
+/*
+ * addInvalidNotNullDependencies
+ *	  Make the NOT VALID not-null constraints on column attname of all of
+ *	  tbinfo's ancestors depend on childcon, a NOT VALID not-null constraint
+ *	  that a descendant of theirs defines locally on that column.
+ *
+ * Adding a NOT VALID not-null constraint to a table also adds it to its
+ * inheritance children, and a child that has no not-null constraint on the
+ * column yet gets one with the parent's name.  If the child has its own
+ * constraint with a different name and the parent's is restored first,
+ * creating the child's then fails.  Restoring the child's first lets the
+ * parent's merge into it, as in the original database.
+ *
+ * Tables in between that have no constraint of their own are walked through
+ * too, since adding a constraint to a table recurses to all its descendants.
+ */
+static void
+addInvalidNotNullDependencies(TableInfo *tbinfo, const char *attname,
+							  ConstraintInfo *childcon)
+{
+	for (int k = 0; k < tbinfo->numParents; k++)
+	{
+		TableInfo  *parent = tbinfo->parents[k];
+		int			inhAttrInd;
+
+		inhAttrInd = strInArray(attname, parent->attnames, parent->numatts);
+		if (inhAttrInd < 0)
+			continue;
+
+		if (parent->notnull_invalidcon &&
+			parent->notnull_invalidcon[inhAttrInd])
+			addObjectDependency(&parent->notnull_invalidcon[inhAttrInd]->dobj,
+								childcon->dobj.dumpId);
+
+		addInvalidNotNullDependencies(parent, attname, childcon);
+	}
+}
+
 /*
  * AssignDumpId
  *		Given a newly-created dumpable object, assign a dump ID,
diff --git a/src/bin/pg_dump/pg_dump.c b/src/bin/pg_dump/pg_dump.c
index 24517805b0..3f015ab508 100644
--- a/src/bin/pg_dump/pg_dump.c
+++ b/src/bin/pg_dump/pg_dump.c
@@ -9752,6 +9752,7 @@ getTableAttrs(Archive *fout, TableInfo *tblinfo, int numTables)
 		int			i_conname;
 		int			i_consrc;
 		int			i_conislocal;
+		int			i_conattnum;
 
 		pg_log_info("finding invalid not-null constraints");
 
@@ -9759,7 +9760,7 @@ getTableAttrs(Archive *fout, TableInfo *tblinfo, int numTables)
 		appendPQExpBuffer(q,
 						  "SELECT c.tableoid, c.oid, conrelid, conname, "
 						  "pg_catalog.pg_get_constraintdef(c.oid) AS consrc, "
-						  "conislocal, convalidated "
+						  "conislocal, convalidated, conkey[1] AS conattnum "
 						  "FROM unnest('%s'::pg_catalog.oid[]) AS src(conoid)\n"
 						  "JOIN pg_catalog.pg_constraint c ON (src.conoid = c.oid)\n"
 						  "ORDER BY c.conrelid, c.conname",
@@ -9776,6 +9777,7 @@ getTableAttrs(Archive *fout, TableInfo *tblinfo, int numTables)
 		i_conname = PQfnumber(res, "conname");
 		i_consrc = PQfnumber(res, "consrc");
 		i_conislocal = PQfnumber(res, "conislocal");
+		i_conattnum = PQfnumber(res, "conattnum");
 
 		/* As above, this loop iterates once per table, not once per row */
 		curtblindx = -1;
@@ -9803,8 +9805,19 @@ getTableAttrs(Archive *fout, TableInfo *tblinfo, int numTables)
 			if (curtblindx >= numTables)
 				pg_fatal("unrecognized table OID %u", conrelid);
 
+			/* flagInhAttrs needs each column's constraint object */
+			tbinfo->notnull_invalidcon = pg_malloc0_array(ConstraintInfo *,
+														  tbinfo->numatts);
+
 			for (int c = 0; c < numcons; c++, j++)
 			{
+				int			attnum = atoi(PQgetvalue(res, j, i_conattnum));
+
+				if (attnum < 1 || attnum > tbinfo->numatts)
+					pg_fatal("invalid column number %d for table \"%s\"",
+							 attnum, tbinfo->dobj.name);
+				tbinfo->notnull_invalidcon[attnum - 1] = &constrs[j];
+
 				constrs[j].dobj.objType = DO_CONSTRAINT;
 				constrs[j].dobj.catId.tableoid = atooid(PQgetvalue(res, j, i_tableoid));
 				constrs[j].dobj.catId.oid = atooid(PQgetvalue(res, j, i_oid));
diff --git a/src/bin/pg_dump/pg_dump.h b/src/bin/pg_dump/pg_dump.h
index 41d932f003..7d727bf1f7 100644
--- a/src/bin/pg_dump/pg_dump.h
+++ b/src/bin/pg_dump/pg_dump.h
@@ -378,6 +378,9 @@ typedef struct _tableInfo
 	bool	   *notnull_invalid;	/* true for NOT NULL NOT VALID */
 	bool	   *notnull_noinh;	/* NOT NULL is NO INHERIT */
 	bool	   *notnull_islocal;	/* true if NOT NULL has local definition */
+	struct _constraintInfo **notnull_invalidcon;	/* NOT NULL NOT VALID
+													 * constraint objects;
+													 * NULL if there are none */
 	struct _attrDefInfo **attrdefs; /* DEFAULT expressions */
 	struct _constraintInfo *checkexprs; /* CHECK constraints */
 	struct _relStatsInfo *stats;	/* only set for matviews */
diff --git a/src/test/regress/expected/constraints.out b/src/test/regress/expected/constraints.out
index dede6106a4..6de42f626b 100644
--- a/src/test/regress/expected/constraints.out
+++ b/src/test/regress/expected/constraints.out
@@ -1745,6 +1745,19 @@ ORDER BY 1;
  notnull_child_upg  | n       | t            | t
 (2 rows)
 
+-- Child with its own NOT VALID constraint, differently named, for pg_upgrade
+CREATE TABLE notnull_parent2_upg (a int);
+ALTER TABLE notnull_parent2_upg ADD CONSTRAINT nn NOT NULL a NOT VALID;
+CREATE TABLE notnull_child2_upg (a int);
+ALTER TABLE notnull_child2_upg ADD NOT NULL a NOT VALID;
+ALTER TABLE notnull_child2_upg INHERIT notnull_parent2_upg;
+EXECUTE get_nnconstraint_info('{notnull_parent2_upg, notnull_child2_upg}');
+       tabname       |            conname            | convalidated | conislocal | coninhcount 
+---------------------+-------------------------------+--------------+------------+-------------
+ notnull_child2_upg  | notnull_child2_upg_a_not_null | f            | t          |           1
+ notnull_parent2_upg | nn                            | f            | t          |           0
+(2 rows)
+
 -- Partition table test, for pg_upgrade
 CREATE TABLE notnull_part1_upg (a int, b int) PARTITION BY LIST (a);
 ALTER TABLE notnull_part1_upg ADD CONSTRAINT notnull_con NOT NULL a NOT VALID; --ok
diff --git a/src/test/regress/sql/constraints.sql b/src/test/regress/sql/constraints.sql
index adb55040c7..f3eaca30f2 100644
--- a/src/test/regress/sql/constraints.sql
+++ b/src/test/regress/sql/constraints.sql
@@ -1045,6 +1045,13 @@ SELECT conrelid::regclass, contype, convalidated, conislocal
 FROM pg_catalog.pg_constraint
 WHERE conrelid in ('notnull_parent_upg'::regclass, 'notnull_child_upg'::regclass)
 ORDER BY 1;
+-- Child with its own NOT VALID constraint, differently named, for pg_upgrade
+CREATE TABLE notnull_parent2_upg (a int);
+ALTER TABLE notnull_parent2_upg ADD CONSTRAINT nn NOT NULL a NOT VALID;
+CREATE TABLE notnull_child2_upg (a int);
+ALTER TABLE notnull_child2_upg ADD NOT NULL a NOT VALID;
+ALTER TABLE notnull_child2_upg INHERIT notnull_parent2_upg;
+EXECUTE get_nnconstraint_info('{notnull_parent2_upg, notnull_child2_upg}');
 
 -- Partition table test, for pg_upgrade
 CREATE TABLE notnull_part1_upg (a int, b int) PARTITION BY LIST (a);
-- 
2.50.1 (Apple Git-155)

