From 47480103c7aca7e66b0f744d7f2fb9d5f9ff64cd Mon Sep 17 00:00:00 2001
From: amit <amitlangote09@gmail.com>
Date: Wed, 26 Apr 2017 16:03:20 +0900
Subject: [PATCH 4/4] Fix a bug in pg_dump's --binary-upgrade code

Said bug caused pg_dump to emit invalid command to attach a partition
to its parent.
---
 src/bin/pg_dump/pg_dump.c | 50 +++++++++++++++++++++++++++++++++--------------
 1 file changed, 35 insertions(+), 15 deletions(-)

diff --git a/src/bin/pg_dump/pg_dump.c b/src/bin/pg_dump/pg_dump.c
index a3a41d4d34..5e6845a495 100644
--- a/src/bin/pg_dump/pg_dump.c
+++ b/src/bin/pg_dump/pg_dump.c
@@ -15427,13 +15427,43 @@ dumpTableSchema(Archive *fout, TableInfo *tbinfo)
 				{
 					TableInfo  *parentRel = parents[k];
 
-					appendPQExpBuffer(q, "ALTER TABLE ONLY %s INHERIT ",
-									  fmtId(tbinfo->dobj.name));
+					/* In the partitioning case, we alter the parent */
+					if (tbinfo->ispartition)
+						appendPQExpBuffer(q, "ALTER TABLE ONLY %s ",
+											fmtId(parentRel->dobj.name));
+					else
+						appendPQExpBuffer(q, "ALTER TABLE ONLY %s ",
+											fmtId(tbinfo->dobj.name));
+
+					if (tbinfo->ispartition)
+						appendPQExpBuffer(q, "ATTACH PARTITION ");
+					else
+						appendPQExpBuffer(q, "INHERIT ");
+
+					/* Add schema-name to the appropriate table */
 					if (parentRel->dobj.namespace != tbinfo->dobj.namespace)
-						appendPQExpBuffer(q, "%s.",
+					{
+						if (tbinfo->ispartition)
+						{
+							/* Partition name */
+							appendPQExpBuffer(q, "%s.",
+								fmtId(tbinfo->dobj.namespace->dobj.name));
+							appendPQExpBuffer(q, "%s",
+								fmtId(tbinfo->dobj.name));
+						}
+						else
+						{
+							/* Inheritance parent name */
+							appendPQExpBuffer(q, "%s.",
 								fmtId(parentRel->dobj.namespace->dobj.name));
-					appendPQExpBuffer(q, "%s;\n",
-									  fmtId(parentRel->dobj.name));
+							appendPQExpBuffer(q, "%s;\n",
+								fmtId(parentRel->dobj.name));
+						}
+					}
+
+					/* Partition needs specifying the bounds */
+					if (tbinfo->ispartition)
+						appendPQExpBuffer(q, " %s;\n", tbinfo->partbound);
 				}
 			}
 
@@ -15445,16 +15475,6 @@ dumpTableSchema(Archive *fout, TableInfo *tbinfo)
 								  tbinfo->reloftype);
 			}
 
-			if (tbinfo->ispartition)
-			{
-				appendPQExpBufferStr(q, "\n-- For binary upgrade, set up partitions this way.\n");
-				appendPQExpBuffer(q, "ALTER TABLE ONLY %s ",
-								  fmtId(tbinfo->parents[0]->dobj.name));
-				appendPQExpBuffer(q, "ATTACH PARTITION %s %s;\n",
-								  fmtId(tbinfo->dobj.name),
-								  tbinfo->partbound);
-			}
-
 			appendPQExpBufferStr(q, "\n-- For binary upgrade, set heap's relfrozenxid and relminmxid\n");
 			appendPQExpBuffer(q, "UPDATE pg_catalog.pg_class\n"
 							  "SET relfrozenxid = '%u', relminmxid = '%u'\n"
-- 
2.11.0

