From f5d9437a48a6e42baea722788d298bc82dd0e471 Mon Sep 17 00:00:00 2001
From: Peter Smith <peter.b.smith@fujitsu.com>
Date: Fri, 7 May 2021 17:11:13 +1000
Subject: [PATCH v4] AlterSubscription_refresh - Use stack variable for wrconn.

This patch replaces the global "wrconn" in AlterSubscription_refresh with a local
variable of the same name, making it consistent with other functions in
subscriptioncmds.c (e.g. DropSubscription).

The global wrconn is only meant to be used for logical apply/tablesync worker.

Using the global/incorrect wrconn in AlterSubscription_refresh doesn't normally
cause any problems, but harm is still possible if the apply worker ever manages to
do a subscription refresh. e.g. see [1].

[1] https://www.postgresql.org/message-id/20201111215820.qihhrz7fayu6myfi%40alap3.anarazel.de
---
 src/backend/commands/subscriptioncmds.c | 16 ++++++++--------
 1 file changed, 8 insertions(+), 8 deletions(-)

diff --git a/src/backend/commands/subscriptioncmds.c b/src/backend/commands/subscriptioncmds.c
index 517c8ed..1096aa8 100644
--- a/src/backend/commands/subscriptioncmds.c
+++ b/src/backend/commands/subscriptioncmds.c
@@ -556,18 +556,19 @@ AlterSubscription_refresh(Subscription *sub, bool copy_data)
 		char		state;
 	} SubRemoveRels;
 	SubRemoveRels *sub_remove_rels;
+	WalReceiverConn *wrconn;
 
 	/* Load the library providing us libpq calls. */
 	load_file("libpqwalreceiver", false);
 
+	/* Try to connect to the publisher. */
+	wrconn = walrcv_connect(sub->conninfo, true, sub->name, &err);
+	if (!wrconn)
+		ereport(ERROR,
+				(errmsg("could not connect to the publisher: %s", err)));
+
 	PG_TRY();
 	{
-		/* Try to connect to the publisher. */
-		wrconn = walrcv_connect(sub->conninfo, true, sub->name, &err);
-		if (!wrconn)
-			ereport(ERROR,
-					(errmsg("could not connect to the publisher: %s", err)));
-
 		/* Get the table list from publisher. */
 		pubrel_names = fetch_table_list(wrconn, sub->publications);
 
@@ -737,8 +738,7 @@ AlterSubscription_refresh(Subscription *sub, bool copy_data)
 	}
 	PG_FINALLY();
 	{
-		if (wrconn)
-			walrcv_disconnect(wrconn);
+		walrcv_disconnect(wrconn);
 	}
 	PG_END_TRY();
 
-- 
1.8.3.1

