From c650b3025c622bd98436ca5ca33ab8912f833bd0 Mon Sep 17 00:00:00 2001
From: Yongtao Huang <yongtah2022@gmail.com>
Date: Fri, 19 Jan 2024 22:35:00 +0800
Subject: [PATCH] Optimize duplicate code and fix memory leak in tablesync.c

---
 src/backend/replication/logical/tablesync.c | 44 ++++++++++++++---------------
 1 file changed, 21 insertions(+), 23 deletions(-)

diff --git a/src/backend/replication/logical/tablesync.c b/src/backend/replication/logical/tablesync.c
index 06d5b3d..29b97f9 100644
--- a/src/backend/replication/logical/tablesync.c
+++ b/src/backend/replication/logical/tablesync.c
@@ -777,6 +777,23 @@ copy_read_data(void *outbuf, int minread, int maxread)
 	return bytesread;
 }
 
+/* Build the publications name list. */
+static StringInfoData
+make_pubname_list(List* publications)
+{
+	StringInfoData	pub_names;
+	initStringInfo(&pub_names);
+
+	foreach_node(String, pubstr, publications)
+	{
+		if (foreach_current_index(pubstr) > 0)
+			appendStringInfoString(&pub_names, ", ");
+			
+		appendStringInfoString(&pub_names, quote_literal_cstr(strVal(pubstr)));
+	}
+
+	return pub_names;
+}
 
 /*
  * Get information about remote relation in similar fashion the RELATION
@@ -795,7 +812,6 @@ fetch_remote_table_info(char *nspname, char *relname,
 	Oid			qualRow[] = {TEXTOID};
 	bool		isnull;
 	int			natt;
-	ListCell   *lc;
 	Bitmapset  *included_cols = NULL;
 
 	lrel->nspname = nspname;
@@ -849,15 +865,7 @@ fetch_remote_table_info(char *nspname, char *relname,
 		WalRcvExecResult *pubres;
 		TupleTableSlot *tslot;
 		Oid			attrsRow[] = {INT2VECTOROID};
-		StringInfoData pub_names;
-
-		initStringInfo(&pub_names);
-		foreach(lc, MySubscription->publications)
-		{
-			if (foreach_current_index(lc) > 0)
-				appendStringInfoString(&pub_names, ", ");
-			appendStringInfoString(&pub_names, quote_literal_cstr(strVal(lfirst(lc))));
-		}
+		StringInfoData pub_names = make_pubname_list(MySubscription->publications);
 
 		/*
 		 * Fetch info about column lists for the relation (from all the
@@ -1032,19 +1040,7 @@ fetch_remote_table_info(char *nspname, char *relname,
 	 */
 	if (walrcv_server_version(LogRepWorkerWalRcvConn) >= 150000)
 	{
-		StringInfoData pub_names;
-
-		/* Build the pubname list. */
-		initStringInfo(&pub_names);
-		foreach_node(String, pubstr, MySubscription->publications)
-		{
-			char	   *pubname = strVal(pubstr);
-
-			if (foreach_current_index(pubstr) > 0)
-				appendStringInfoString(&pub_names, ", ");
-
-			appendStringInfoString(&pub_names, quote_literal_cstr(pubname));
-		}
+		StringInfoData pub_names = make_pubname_list(MySubscription->publications);
 
 		/* Check for row filters. */
 		resetStringInfo(&cmd);
@@ -1094,6 +1090,8 @@ fetch_remote_table_info(char *nspname, char *relname,
 		ExecDropSingleTupleTableSlot(slot);
 
 		walrcv_clear_result(res);
+
+		pfree(pub_names.data);
 	}
 
 	pfree(cmd.data);
-- 
1.8.3.1

