From ef3409cd7a6935606b32053e4d8afec86de66b9d Mon Sep 17 00:00:00 2001
From: Sai Pranav <rajasaipranav0@gmail.com>
Date: Mon, 30 Nov 2026 16:36:50 +0530
Subject: [PATCH v4 1/2] 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.

The walk goes through every ancestor once, so an inheritance cycle ends
it; it also goes through ancestors whose columns were not loaded, since
their own ancestors may be dumped.  A NO INHERIT constraint does not
reach the descendants, so it is left out; for that, getTableAttrs() now
records NO INHERIT for invalid not-null constraints too.

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                  | 83 +++++++++++++++++++++++
 src/bin/pg_dump/pg_dump.c                 | 26 +++++--
 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, 128 insertions(+), 4 deletions(-)

diff --git a/src/bin/pg_dump/common.c b/src/bin/pg_dump/common.c
index cda9d73a9d..b66a85769f 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,76 @@ 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.
+ * So are ancestors whose columns were not loaded (only direct parents of
+ * dumped tables get them), since their ancestors may still be dumped.  A
+ * NO INHERIT constraint does not reach the descendants, so it needs no
+ * ordering.  Each ancestor is visited once, which also copes with an
+ * inheritance cycle.
+ */
+static void
+addInvalidNotNullDependencies(TableInfo *tbinfo, const char *attname,
+							  ConstraintInfo *childcon)
+{
+	TableInfo **visited;
+	int			nvisited = 0;
+	int			maxvisited = 8;
+
+	visited = pg_malloc_array(TableInfo *, maxvisited);
+	visited[nvisited++] = tbinfo;
+
+	/* visited[] doubles as the queue of tables whose parents to look at */
+	for (int i = 0; i < nvisited; i++)
+	{
+		TableInfo  *tab = visited[i];
+
+		for (int k = 0; k < tab->numParents; k++)
+		{
+			TableInfo  *parent = tab->parents[k];
+			int			inhAttrInd;
+			bool		seen = false;
+
+			for (int m = 0; m < nvisited && !seen; m++)
+				seen = (visited[m] == parent);
+			if (seen)
+				continue;
+
+			if (nvisited == maxvisited)
+			{
+				maxvisited *= 2;
+				visited = pg_realloc_array(visited, TableInfo *, maxvisited);
+			}
+			visited[nvisited++] = parent;
+
+			inhAttrInd = strInArray(attname, parent->attnames, parent->numatts);
+			if (inhAttrInd < 0)
+				continue;
+
+			if (parent->notnull_invalidcon &&
+				parent->notnull_invalidcon[inhAttrInd] &&
+				!parent->notnull_noinh[inhAttrInd])
+				addObjectDependency(&parent->notnull_invalidcon[inhAttrInd]->dobj,
+									childcon->dobj.dumpId);
+		}
+	}
+
+	free(visited);
+}
+
 /*
  * 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..77cca591f8 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));
@@ -10031,6 +10044,12 @@ determineNotNullFlags(Archive *fout, PGresult *res, int r,
 {
 	DumpOptions *dopt = fout->dopt;
 
+	/*
+	 * notnull_noinh is straight from the query result.  It is set for invalid
+	 * constraints too, as flagInhAttrs needs it for them.
+	 */
+	tbinfo->notnull_noinh[j] = PQgetvalue(res, r, i_notnull_noinherit)[0] == 't';
+
 	/*
 	 * If this not-null constraint is not valid, list its OID in
 	 * invalidnotnulloids and do nothing further.  It'll be processed
@@ -10065,10 +10084,9 @@ determineNotNullFlags(Archive *fout, PGresult *res, int r,
 	}
 
 	/*
-	 * notnull_noinh is straight from the query result. notnull_islocal also,
-	 * though flagInhAttrs may change that one later.
+	 * notnull_islocal is straight from the query result too, though
+	 * flagInhAttrs may change it later.
 	 */
-	tbinfo->notnull_noinh[j] = PQgetvalue(res, r, i_notnull_noinherit)[0] == 't';
 	tbinfo->notnull_islocal[j] = PQgetvalue(res, r, i_notnull_islocal)[0] == 't';
 	tbinfo->notnull_invalid[j] = false;
 
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)

