>From 9ee80028edb112eaa6c1611ac57d8b8eb72baeb8 Mon Sep 17 00:00:00 2001
From: Andres Freund <andres@anarazel.de>
Date: Wed, 1 Oct 2014 12:29:11 +0200
Subject: [PATCH 4/4] Polishing 'pg_basebackup refactoring'.

---
 src/bin/pg_basebackup/pg_recvlogical.c | 30 +++++++---------
 src/bin/pg_basebackup/streamutil.c     | 66 ++++++++++++++++++++--------------
 src/bin/pg_basebackup/streamutil.h     |  7 ++--
 3 files changed, 57 insertions(+), 46 deletions(-)

diff --git a/src/bin/pg_basebackup/pg_recvlogical.c b/src/bin/pg_basebackup/pg_recvlogical.c
index 23ae225..4002296 100644
--- a/src/bin/pg_basebackup/pg_recvlogical.c
+++ b/src/bin/pg_basebackup/pg_recvlogical.c
@@ -56,7 +56,7 @@ static XLogRecPtr output_written_lsn = InvalidXLogRecPtr;
 static XLogRecPtr output_fsync_lsn = InvalidXLogRecPtr;
 
 static void usage(void);
-static void StreamLog();
+static void StreamLogicalLog();
 static void disconnect_and_exit(int code);
 
 static void
@@ -194,7 +194,7 @@ OutputFsync(int64 now)
  * Start the log streaming
  */
 static void
-StreamLog(void)
+StreamLogicalLog(void)
 {
 	PGresult   *res;
 	char	   *copybuf = NULL;
@@ -844,25 +844,21 @@ main(int argc, char **argv)
 		exit(1);
 
 	/*
-	 * Run IDENTIFY_SYSTEM so we can get the timeline and current xlog
-	 * position.
+	 * Run IDENTIFY_SYSTEM to make sure we connected using a database specific
+	 * replication connection.
 	 */
 	if (!RunIdentifySystem(conn, NULL, NULL, NULL, &db_name))
 		disconnect_and_exit(1);
 
-	/*
-	 * Check that there is a database associated with connection, one is
-	 * needed in this context.
-	 */
-	if (!db_name)
+	if (db_name == NULL)
 	{
 		fprintf(stderr,
-				_("%s: no database defined for replication connection \"%s\"\n"),
-				progname, replication_slot);
+				_("%s: failed to establish database specific replication connection\n"),
+				progname);
 		disconnect_and_exit(1);
 	}
 
-	/* Drop a replication slot */
+	/* Drop a replication slot. */
 	if (do_drop_slot)
 	{
 		if (verbose)
@@ -870,12 +866,11 @@ main(int argc, char **argv)
 					_("%s: dropping replication slot \"%s\"\n"),
 					progname, replication_slot);
 
-		if (!DropReplicationSlot(conn, false))
+		if (!DropReplicationSlot(conn, replication_slot))
 			disconnect_and_exit(1);
-		disconnect_and_exit(0);
 	}
 
-	/* Create a replication slot */
+	/* Create a replication slot. */
 	if (do_create_slot)
 	{
 		if (verbose)
@@ -883,7 +878,8 @@ main(int argc, char **argv)
 					_("%s: creating replication slot \"%s\"\n"),
 					progname, replication_slot);
 
-		if (!CreateReplicationSlot(conn, plugin, &startpos, false))
+		if (!CreateReplicationSlot(conn, replication_slot, plugin,
+								   &startpos, false))
 			disconnect_and_exit(1);
 	}
 
@@ -893,7 +889,7 @@ main(int argc, char **argv)
 	/* Stream loop */
 	while (true)
 	{
-		StreamLog();
+		StreamLogicalLog();
 		if (time_to_abort)
 		{
 			/*
diff --git a/src/bin/pg_basebackup/streamutil.c b/src/bin/pg_basebackup/streamutil.c
index 2c373b8..2f4bac9 100644
--- a/src/bin/pg_basebackup/streamutil.c
+++ b/src/bin/pg_basebackup/streamutil.c
@@ -27,6 +27,7 @@
 #include "receivelog.h"
 #include "streamutil.h"
 
+#include "pqexpbuffer.h"
 #include "common/fe_memutils.h"
 #include "datatype/timestamp.h"
 
@@ -283,8 +284,17 @@ RunIdentifySystem(PGconn *conn, char **sysid, TimeLineID *starttli,
 
 	/* Get database name, only available in 9.4 and newer versions */
 	if  (db_name != NULL)
-		*db_name = PQnfields(res) > 3 && !PQgetisnull(res, 0, 3) ?
-			pg_strdup(PQgetvalue(res, 0, 3)) : (char *) NULL;
+	{
+		if (PQnfields(res) < 4)
+			fprintf(stderr,
+					_("%s: could not identify system: got %d rows and %d fields, expected %d rows and %d or more fields\n"),
+					progname, PQntuples(res), PQnfields(res), 1, 4);
+
+		if (PQgetisnull(res, 0, 3))
+			*db_name =  NULL;
+		else
+			*db_name = pg_strdup(PQgetvalue(res, 0, 3));
+	}
 
 	PQclear(res);
 	return true;
@@ -296,38 +306,39 @@ RunIdentifySystem(PGconn *conn, char **sysid, TimeLineID *starttli,
  * obtained after the slot creation.
  */
 bool
-CreateReplicationSlot(PGconn *conn, const char *plugin,
+CreateReplicationSlot(PGconn *conn, const char *slot_name, const char *plugin,
 					  XLogRecPtr *startpos, bool is_physical)
 {
-	char		query[256];
+	PQExpBuffer query;
 	PGresult   *res;
-	uint32		hi, lo;
+
+	query = createPQExpBuffer();
 
 	Assert((is_physical && plugin == NULL) ||
 		   (!is_physical && plugin != NULL));
-	Assert(replication_slot != NULL);
+	Assert(slot_name != NULL);
 
 	/* Build query */
 	if (is_physical)
-		snprintf(query, sizeof(query), "CREATE_REPLICATION_SLOT \"%s\" PHYSICAL",
-				 replication_slot);
+		appendPQExpBuffer(query, "CREATE_REPLICATION_SLOT \"%s\" PHYSICAL",
+						  slot_name);
 	else
-		snprintf(query, sizeof(query), "CREATE_REPLICATION_SLOT \"%s\" LOGICAL \"%s\"",
-				 replication_slot, plugin);
+		appendPQExpBuffer(query, "CREATE_REPLICATION_SLOT \"%s\" LOGICAL \"%s\"",
+						  slot_name, plugin);
 
-	res = PQexec(conn, query);
+	res = PQexec(conn, query->data);
 	if (PQresultStatus(res) != PGRES_TUPLES_OK)
 	{
 		fprintf(stderr, _("%s: could not send replication command \"%s\": %s"),
-				progname, query, PQerrorMessage(conn));
+				progname, query->data, PQerrorMessage(conn));
 		return false;
 	}
 
 	if (PQntuples(res) != 1 || PQnfields(res) != 4)
 	{
 		fprintf(stderr,
-				_("%s: could not init %s replication: got %d rows and %d fields, expected %d rows and %d fields\n"),
-				progname, is_physical ? "physical" : "logical",
+				_("%s: could not create replication slot \"%s\": got %d rows and %d fields, expected %d rows and %d fields\n"),
+				progname, slot_name,
 				PQntuples(res), PQnfields(res), 1, 4);
 		return false;
 	}
@@ -335,6 +346,8 @@ CreateReplicationSlot(PGconn *conn, const char *plugin,
 	/* Get LSN start position if necessary */
 	if (startpos != NULL)
 	{
+		uint32		hi, lo;
+
 		if (sscanf(PQgetvalue(res, 0, 1), "%X/%X", &hi, &lo) != 2)
 		{
 			fprintf(stderr,
@@ -345,7 +358,6 @@ CreateReplicationSlot(PGconn *conn, const char *plugin,
 		*startpos = ((uint64) hi) << 32 | lo;
 	}
 
-	replication_slot = strdup(PQgetvalue(res, 0, 0));
 	PQclear(res);
 	return true;
 }
@@ -355,29 +367,31 @@ CreateReplicationSlot(PGconn *conn, const char *plugin,
  * returns true in case of success.
  */
 bool
-DropReplicationSlot(PGconn *conn, bool is_physical)
+DropReplicationSlot(PGconn *conn, const char *slot_name)
 {
-	char        query[256];
+	PQExpBuffer query;
 	PGresult   *res;
 
-	Assert(replication_slot != NULL);
+	Assert(slot_name != NULL);
+
+	query = createPQExpBuffer();
 
 	/* Build query */
-	snprintf(query, sizeof(query), "DROP_REPLICATION_SLOT \"%s\"",
-			 replication_slot);
-	res = PQexec(conn, query);
+	appendPQExpBuffer(query, "DROP_REPLICATION_SLOT \"%s\"",
+					  slot_name);
+	res = PQexec(conn, query->data);
 	if (PQresultStatus(res) != PGRES_COMMAND_OK)
 	{
 		fprintf(stderr, _("%s: could not send replication command \"%s\": %s"),
-				progname, query, PQerrorMessage(conn));
+				progname, query->data, PQerrorMessage(conn));
 		return false;
 	}
 
 	if (PQntuples(res) != 0 || PQnfields(res) != 0)
 	{
 		fprintf(stderr,
-				_("%s: could not stop %s replication: got %d rows and %d fields, expected %d rows and %d fields\n"),
-				progname, is_physical ? "physical" : "logical",
+				_("%s: could not drop replication slot \"%s\": got %d rows and %d fields, expected %d rows and %d fields\n"),
+				progname, slot_name,
 				PQntuples(res), PQnfields(res), 0, 0);
 		return false;
 	}
@@ -389,8 +403,8 @@ DropReplicationSlot(PGconn *conn, bool is_physical)
 
 /*
  * Frontend version of GetCurrentTimestamp(), since we are not linked with
- * backend code. The protocol always uses integer timestamps, regardless of
- * server setting.
+ * backend code. The replication protocol always uses integer timestamps,
+ * regardless of the server setting.
  */
 int64
 feGetCurrentTimestamp(void)
diff --git a/src/bin/pg_basebackup/streamutil.h b/src/bin/pg_basebackup/streamutil.h
index 9067810..ac66145 100644
--- a/src/bin/pg_basebackup/streamutil.h
+++ b/src/bin/pg_basebackup/streamutil.h
@@ -31,9 +31,10 @@ extern PGconn *conn;
 extern PGconn *GetConnection(void);
 
 /* Replication commands */
-extern bool CreateReplicationSlot(PGconn *conn, const char *plugin,
-								  XLogRecPtr *startpos, bool is_physical);
-extern bool DropReplicationSlot(PGconn *conn, bool is_physical);
+extern bool CreateReplicationSlot(PGconn *conn, const char *slot_name,
+								  const char *plugin, XLogRecPtr *startpos,
+								  bool is_physical);
+extern bool DropReplicationSlot(PGconn *conn, const char *slot_name);
 extern bool RunIdentifySystem(PGconn *conn, char **sysid,
 							  TimeLineID *starttli,
 							  XLogRecPtr *startpos,
-- 
1.8.3.251.g1462b67

