From fccf6783936dc7293d847ede008185e236f27d0a Mon Sep 17 00:00:00 2001
From: "houzj.fnst" <houzj.fnst@fujitsu.com>
Date: Thu, 11 Nov 2021 13:43:51 +0800
Subject: [PATCH] fix duplicate table in pg_publication_tables

if publish_via_partition_root is false, and both child and parent
table were added to the publication. Then there could be duplicate child
table in the view pg_publication_tables. The reason is that the function
GetPublicationRelations doesn't de-duplicate the output Oid List.

Fix it by de-duplicating the relation oid in GetPublicationRelations.

---
 src/backend/catalog/pg_publication.c      | 5 ++++-
 src/test/regress/expected/publication.out | 8 ++++++++
 src/test/regress/sql/publication.sql      | 4 ++++
 3 files changed, 16 insertions(+), 1 deletion(-)

diff --git a/src/backend/catalog/pg_publication.c b/src/backend/catalog/pg_publication.c
index fed83b89a9..933456cfd0 100644
--- a/src/backend/catalog/pg_publication.c
+++ b/src/backend/catalog/pg_publication.c
@@ -472,10 +472,13 @@ GetPublicationRelations(Oid pubid, PublicationPartOpt pub_partopt)
 	while (HeapTupleIsValid(tup = systable_getnext(scan)))
 	{
 		Form_pg_publication_rel pubrel;
+		List	*relids = NIL;
 
 		pubrel = (Form_pg_publication_rel) GETSTRUCT(tup);
-		result = GetPubPartitionOptionRelations(result, pub_partopt,
+		relids = GetPubPartitionOptionRelations(relids, pub_partopt,
 												pubrel->prrelid);
+
+		result = list_concat_unique_oid(result, relids);
 	}
 
 	systable_endscan(scan);
diff --git a/src/test/regress/expected/publication.out b/src/test/regress/expected/publication.out
index 2ff21a7543..af3da0a855 100644
--- a/src/test/regress/expected/publication.out
+++ b/src/test/regress/expected/publication.out
@@ -816,6 +816,14 @@ SELECT * FROM pg_publication_tables;
  pub     | sch2       | tbl1_part1
 (1 row)
 
+-- Table publication that includes both the parent table and the child table
+ALTER PUBLICATION pub ADD TABLE sch1.tbl1;
+SELECT * FROM pg_publication_tables;
+ pubname | schemaname | tablename  
+---------+------------+------------
+ pub     | sch2       | tbl1_part1
+(1 row)
+
 DROP PUBLICATION pub;
 DROP TABLE sch2.tbl1_part1;
 DROP TABLE sch1.tbl1;
diff --git a/src/test/regress/sql/publication.sql b/src/test/regress/sql/publication.sql
index 85a5302a74..829407aea3 100644
--- a/src/test/regress/sql/publication.sql
+++ b/src/test/regress/sql/publication.sql
@@ -455,6 +455,10 @@ DROP PUBLICATION pub;
 CREATE PUBLICATION pub FOR TABLE sch2.tbl1_part1 WITH (PUBLISH_VIA_PARTITION_ROOT=0);
 SELECT * FROM pg_publication_tables;
 
+-- Table publication that includes both the parent table and the child table
+ALTER PUBLICATION pub ADD TABLE sch1.tbl1;
+SELECT * FROM pg_publication_tables;
+
 DROP PUBLICATION pub;
 DROP TABLE sch2.tbl1_part1;
 DROP TABLE sch1.tbl1;
-- 
2.18.4

