From b10c8f62e436a52b77e3df2ea59f313112e2466a Mon Sep 17 00:00:00 2001
From: Marti Raudsepp <marti@juffo.org>
Date: Fri, 19 Jun 2015 18:58:17 +0300
Subject: [PATCH] Fix pg_upgrade when postgres/template1 aren't in default
 tablespace

In order to move these databases to the correct tablespace in the new
cluster, pg_dumpall needs to generate \connect commands to switch
databases during restore.

This oversight caused the error:
error while copying relation "pg_catalog.pg_largeobject"
("/tablespace/PG_9.3_201306121/1/12023" to "/PG_9.4_201409291/1/12130"):
No such file or directory
---
 src/bin/pg_dump/pg_dumpall.c | 18 ++++++++++++++++++
 1 file changed, 18 insertions(+)

diff --git a/src/bin/pg_dump/pg_dumpall.c b/src/bin/pg_dump/pg_dumpall.c
index d98c83e..75226f1 100644
--- a/src/bin/pg_dump/pg_dumpall.c
+++ b/src/bin/pg_dump/pg_dumpall.c
@@ -1412,6 +1412,24 @@ dumpCreateDB(PGconn *conn)
 
 			appendPQExpBufferStr(buf, ";\n");
 		}
+		else if (binary_upgrade)
+		{
+			if (strcmp(dbtablespace, "pg_default") != 0 && !no_tablespaces)
+			{
+				/*
+				 * Cannot change tablespace of the database we're connected to.
+				 * To move "postgres" to another tablespace, we connect to
+				 * "template1" and vice versa.
+				 */
+				if (strcmp(dbname, "postgres") == 0)
+					fprintf(OPF, "\\connect %s\n", fmtId("template1"));
+				else
+					fprintf(OPF, "\\connect %s\n", fmtId("postgres"));
+
+				appendPQExpBuffer(buf, "ALTER DATABASE %s SET TABLESPACE %s;\n",
+								  fdbname, fmtId(dbtablespace));
+			}
+		}
 
 		if (binary_upgrade)
 		{
-- 
2.4.4

