From f7b13e48375a5a8ea2a8b157622a9310512f4e27 Mon Sep 17 00:00:00 2001
From: Andrew Dunstan <andrew@dunslane.net>
Date: Wed, 5 Sep 2012 17:49:30 -0400
Subject: [PATCH] Fix line end mishandling in pg_upgrade on Windows.

pg_upgrade opened the output from pg_dumpall in text mode and
wrote the split files in text mode. This caused unwanted eating
of intended carriage returns on input and production of spurious
carriage returns on output. To avoid this, open all these files
in binary mode. On non-Windows platforms, this change has no
effect.

Backpatch to 9.0. On 9.0 and 9.1, we also switch from redirecting
pg_dumpall's output to using pg_dumpall's -f switch, for the same
reason.
---
 contrib/pg_upgrade/dump.c | 13 +++++++++----
 1 file changed, 9 insertions(+), 4 deletions(-)

diff --git a/contrib/pg_upgrade/dump.c b/contrib/pg_upgrade/dump.c
index 3a2ded629c..c2b300addd 100644
--- a/contrib/pg_upgrade/dump.c
+++ b/contrib/pg_upgrade/dump.c
@@ -23,7 +23,7 @@ generate_old_dump(migratorContext *ctx)
 	 */
 	exec_prog(ctx, true,
 			  SYSTEMQUOTE "\"%s/pg_dumpall\" --port %d --username \"%s\" "
-			  "--schema-only --binary-upgrade > \"%s/" ALL_DUMP_FILE "\""
+			  "--schema-only --binary-upgrade -f \"%s/" ALL_DUMP_FILE "\""
 		   SYSTEMQUOTE, ctx->new.bindir, ctx->old.port, ctx->user, ctx->cwd);
 	check_ok(ctx);
 }
@@ -55,14 +55,19 @@ split_old_dump(migratorContext *ctx)
 	char		filename[MAXPGPATH];
 	bool		suppressed_username = false;
 
+	/* 
+	 * Open all files in binary mode to avoid line end translation on Windows,
+	 * both for input and output.
+	 */
+
 	snprintf(filename, sizeof(filename), "%s/%s", ctx->cwd, ALL_DUMP_FILE);
-	if ((all_dump = fopen(filename, "r")) == NULL)
+	if ((all_dump = fopen(filename, PG_BINARY_R)) == NULL)
 		pg_log(ctx, PG_FATAL, "Cannot open dump file %s\n", filename);
 	snprintf(filename, sizeof(filename), "%s/%s", ctx->cwd, GLOBALS_DUMP_FILE);
-	if ((globals_dump = fopen(filename, "w")) == NULL)
+	if ((globals_dump = fopen(filename, PG_BINARY_W)) == NULL)
 		pg_log(ctx, PG_FATAL, "Cannot write to dump file %s\n", filename);
 	snprintf(filename, sizeof(filename), "%s/%s", ctx->cwd, DB_DUMP_FILE);
-	if ((db_dump = fopen(filename, "w")) == NULL)
+	if ((db_dump = fopen(filename, PG_BINARY_W)) == NULL)
 		pg_log(ctx, PG_FATAL, "Cannot write to dump file %s\n", filename);
 	current_output = globals_dump;
 
-- 
2.49.0