From 38f432898131270e5b64245786cb67f322538bae Mon Sep 17 00:00:00 2001
From: Fujii Masao <fujii@postgresql.org>
Date: Thu, 21 Nov 2013 21:52:03 +0900
Subject: [PATCH] Fix pg_isready to handle -d option properly.
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit

Previously, -d option for pg_isready was broken. When the name of the
database was specified by -d option, pg_isready failed with an error.
When the conninfo specified by -d option contained the setting of the
host name but not Numeric IP address (i.e., hostaddr), pg_isready
displayed wrong connection message. -d option could not handle a valid
URI prefix at all. This commit fixes these bugs of pg_isready.

Backpatch to 9.3, where pg_isready was introduced.

Per report from Josh Berkus and Robert Haas.
Original patch by Fabrízio de Royes Mello, heavily modified by me.
---
 src/bin/scripts/pg_isready.c | 20 ++++++++++++++++----
 1 file changed, 16 insertions(+), 4 deletions(-)

diff --git a/src/bin/scripts/pg_isready.c b/src/bin/scripts/pg_isready.c
index d27ccea70fb..33b9ff7ffe1 100644
--- a/src/bin/scripts/pg_isready.c
+++ b/src/bin/scripts/pg_isready.c
@@ -31,6 +31,7 @@ main(int argc, char **argv)
 	const char *connect_timeout = DEFAULT_CONNECT_TIMEOUT;
 
 	const char *pghost_str = NULL;
+	const char *pghostaddr_str = NULL;
 	const char *pgport_str = NULL;
 
 #define PARAMS_ARRAY_SIZE	7
@@ -130,7 +131,10 @@ main(int argc, char **argv)
 	/*
 	 * Get the host and port so we can display them in our output
 	 */
-	if (pgdbname)
+	if (pgdbname &&
+		(strncmp(pgdbname, "postgresql://", 13) == 0 ||
+		 strncmp(pgdbname, "postgres://", 11) == 0 ||
+		 strchr(pgdbname, '=') != NULL))
 	{
 		opts = PQconninfoParse(pgdbname, &errmsg);
 		if (opts == NULL)
@@ -149,8 +153,7 @@ main(int argc, char **argv)
 
 	for (opt = opts, def = defs; def->keyword; def++)
 	{
-		if (strcmp(def->keyword, "hostaddr") == 0 ||
-			strcmp(def->keyword, "host") == 0)
+		if (strcmp(def->keyword, "host") == 0)
 		{
 			if (opt && opt->val)
 				pghost_str = opt->val;
@@ -161,6 +164,13 @@ main(int argc, char **argv)
 			else
 				pghost_str = DEFAULT_PGSOCKET_DIR;
 		}
+		else if (strcmp(def->keyword, "hostaddr") == 0)
+		{
+			if (opt && opt->val)
+				pghostaddr_str = opt->val;
+			else if (def->val)
+				pghostaddr_str = def->val;
+		}
 		else if (strcmp(def->keyword, "port") == 0)
 		{
 			if (opt && opt->val)
@@ -179,7 +189,9 @@ main(int argc, char **argv)
 
 	if (!quiet)
 	{
-		printf("%s:%s - ", pghost_str, pgport_str);
+		printf("%s:%s - ",
+			   pghostaddr_str != NULL ? pghostaddr_str : pghost_str,
+			   pgport_str);
 
 		switch (rv)
 		{
-- 
GitLab