From 6692a2faa87c8829189baf55dc40527882abf09f Mon Sep 17 00:00:00 2001
From: Sergey Tatarintsev <s.tatarintsev@postgrespro.ru>
Date: Wed, 29 Jan 2025 20:40:16 +0700
Subject: [PATCH] Restrict publishing of foreign tables and partitioned tables
 with a foreign table as partition

Added foreign table checking, creating foreign paritions + some fixes
---
 src/backend/catalog/pg_publication.c | 19 ++++++++------
 src/backend/commands/foreigncmds.c   | 37 ++++++++++++++++++++++++++++
 src/backend/commands/tablecmds.c     | 30 +++++++++++++++-------
 src/test/regress/sql/publication.sql | 14 +++++++++++
 4 files changed, 84 insertions(+), 16 deletions(-)

diff --git a/src/backend/catalog/pg_publication.c b/src/backend/catalog/pg_publication.c
index ef8a392077..583248c48e 100644
--- a/src/backend/catalog/pg_publication.c
+++ b/src/backend/catalog/pg_publication.c
@@ -1349,6 +1349,7 @@ check_partrel_has_foreign_table(Form_pg_class relform, Oid *foreign_tbl_relid)
 {
 	bool		has_foreign_tbl = false;
 
+	*foreign_tbl_relid = InvalidOid;
 	if (relform->relkind == RELKIND_PARTITIONED_TABLE)
 	{
 		List	   *relids = NIL;
@@ -1384,7 +1385,7 @@ void
 check_foreign_tables_in_schema(Oid schemaid)
 {
 	Relation	classRel;
-	ScanKeyData key[2];
+	ScanKeyData key[1];
 	TableScanDesc scan;
 	HeapTuple	tuple;
 
@@ -1394,18 +1395,15 @@ check_foreign_tables_in_schema(Oid schemaid)
 				Anum_pg_class_relnamespace,
 				BTEqualStrategyNumber, F_OIDEQ,
 				schemaid);
-	ScanKeyInit(&key[1],
-				Anum_pg_class_relkind,
-				BTEqualStrategyNumber, F_CHAREQ,
-				CharGetDatum(RELKIND_PARTITIONED_TABLE));
 
-	scan = table_beginscan_catalog(classRel, 2, key);
+	scan = table_beginscan_catalog(classRel, 1, key);
 	while ((tuple = heap_getnext(scan, ForwardScanDirection)) != NULL)
 	{
 		Form_pg_class relForm = (Form_pg_class) GETSTRUCT(tuple);
 		Oid			foreign_tbl_relid;
 
-		if (check_partrel_has_foreign_table(relForm, &foreign_tbl_relid))
+		if (relForm->relkind == RELKIND_PARTITIONED_TABLE &&
+			check_partrel_has_foreign_table(relForm, &foreign_tbl_relid))
 		{
 			List	   *ancestors = get_partition_ancestors(relForm->oid);
 			Oid			parent_oid = relForm->oid;
@@ -1419,6 +1417,7 @@ check_foreign_tables_in_schema(Oid schemaid)
 					parent_oid = ancestor;
 			}
 
+			list_free(ancestors);
 			parent_name = get_rel_name(parent_oid);
 
 			ereport(ERROR,
@@ -1428,6 +1427,12 @@ check_foreign_tables_in_schema(Oid schemaid)
 					 errdetail("foreign table \"%s\" is a partition of partitioned table \"%s\"",
 							   get_rel_name(foreign_tbl_relid), parent_name)));
 		}
+		else if (relForm->relkind == RELKIND_FOREIGN_TABLE)
+			ereport(ERROR,
+					(errcode(ERRCODE_INVALID_PARAMETER_VALUE),
+					 errmsg("cannot add relation \"%s\" to publication",
+							get_rel_name(relForm->oid)),
+					 errdetail_relkind_not_supported(RELKIND_FOREIGN_TABLE)));
 	}
 
 	table_endscan(scan);
diff --git a/src/backend/commands/foreigncmds.c b/src/backend/commands/foreigncmds.c
index c14e038d54..f1c27ab352 100644
--- a/src/backend/commands/foreigncmds.c
+++ b/src/backend/commands/foreigncmds.c
@@ -21,6 +21,7 @@
 #include "catalog/dependency.h"
 #include "catalog/indexing.h"
 #include "catalog/objectaccess.h"
+#include "catalog/partition.h"
 #include "catalog/pg_foreign_data_wrapper.h"
 #include "catalog/pg_foreign_server.h"
 #include "catalog/pg_foreign_table.h"
@@ -1423,6 +1424,42 @@ CreateForeignTable(CreateForeignTableStmt *stmt, Oid relid)
 
 	ftrel = table_open(ForeignTableRelationId, RowExclusiveLock);
 
+	if (stmt->base.inhRelations)
+	{
+		Oid			foreign_tbl_relid;
+		RangeVar   *root = castNode(RangeVar, lfirst(list_head(stmt->base.inhRelations)));
+		Relation	rootrel = table_openrv(root, AccessShareLock);
+
+		if (check_partrel_has_foreign_table(RelationGetForm(rootrel), &foreign_tbl_relid))
+		{
+			Oid			schemaid = RelationGetNamespace(rootrel);
+			List	   *puboids = GetRelationPublications(relid);
+			List	   *ancestors;
+
+			puboids = list_concat_unique_oid(puboids, GetAllTablesPublications());
+			puboids = list_concat_unique_oid(puboids, GetSchemaPublications(schemaid));
+			ancestors = get_partition_ancestors(relid);
+
+			foreach_oid(ancestor, ancestors)
+			{
+				puboids = list_concat_unique_oid(puboids,
+												 GetRelationPublications(ancestor));
+				schemaid = get_rel_namespace(ancestor);
+				puboids = list_concat_unique_oid(puboids,
+												 GetSchemaPublications(schemaid));
+			}
+
+			if (puboids)
+				ereport(ERROR,
+						(errcode(ERRCODE_WRONG_OBJECT_TYPE),
+						 errmsg("cannot attach a partitioned table with a foreign table as partition of a published table"),
+						 errdetail("foreign table \"%s\" is a partition of partitioned table \"%s\"",
+								   get_rel_name(foreign_tbl_relid),
+								   RelationGetRelationName(rootrel))));
+		}
+		table_close(rootrel, AccessShareLock);
+	}
+
 	/*
 	 * For now the owner cannot be specified on create. Use effective user ID.
 	 */
diff --git a/src/backend/commands/tablecmds.c b/src/backend/commands/tablecmds.c
index 4cf7b7454d..512028810e 100644
--- a/src/backend/commands/tablecmds.c
+++ b/src/backend/commands/tablecmds.c
@@ -19349,10 +19349,11 @@ ATExecAttachPartition(List **wqueue, Relation rel, PartitionCmd *cmd,
 				 errmsg("cannot attach temporary relation of another session as partition")));
 
 	/*
-	 * If table is a partitioned table and has a foreign table as its
-	 * partition and the parent relation is published.
+	 * In case of foreign table of if table is a partitioned table and has a
+	 * foreign table as its partition and the parent relation is published
 	 */
-	if (check_partrel_has_foreign_table(RelationGetForm(attachrel), &foreign_tbl_relid))
+	if (check_partrel_has_foreign_table(RelationGetForm(attachrel), &foreign_tbl_relid) ||
+		attachrel->rd_rel->relkind == RELKIND_FOREIGN_TABLE)
 	{
 		Oid			schemaid = RelationGetNamespace(rel);
 		List	   *puboids = GetRelationPublications(rel->rd_id);
@@ -19370,14 +19371,25 @@ ATExecAttachPartition(List **wqueue, Relation rel, PartitionCmd *cmd,
 			puboids = list_concat_unique_oid(puboids,
 											 GetSchemaPublications(schemaid));
 		}
+		list_free(ancestors);
 
 		if (puboids)
-			ereport(ERROR,
-					(errcode(ERRCODE_WRONG_OBJECT_TYPE),
-					 errmsg("cannot attach a partitioned table with a foreign table as partition of a published table"),
-					 errdetail("foreign table \"%s\" is a partition of partitioned table \"%s\"",
-							   get_rel_name(foreign_tbl_relid),
-							   RelationGetRelationName(attachrel))));
+		{
+			if (attachrel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE)
+				ereport(ERROR,
+						(errcode(ERRCODE_WRONG_OBJECT_TYPE),
+						 errmsg("cannot attach a partitioned table with a foreign table as partition of a published table"),
+						 errdetail("foreign table \"%s\" is a partition of partitioned table \"%s\"",
+								   get_rel_name(foreign_tbl_relid),
+								   RelationGetRelationName(attachrel))));
+			else
+				ereport(ERROR,
+						(errcode(ERRCODE_INVALID_PARAMETER_VALUE),
+						 errmsg("cannot add relation \"%s\" to publication",
+								get_rel_name(attachrel->rd_rel->oid)),
+						 errdetail_relkind_not_supported(RELKIND_FOREIGN_TABLE)));
+
+		}
 	}
 
 	/*
diff --git a/src/test/regress/sql/publication.sql b/src/test/regress/sql/publication.sql
index d0d5e22949..d142238060 100644
--- a/src/test/regress/sql/publication.sql
+++ b/src/test/regress/sql/publication.sql
@@ -1211,6 +1211,20 @@ ALTER TABLE sch3.tmain DETACH PARTITION sch3.part2;
 CREATE PUBLICATION pub1 FOR TABLE sch3.tmain;
 ALTER TABLE sch3.tmain ATTACH PARTITION sch3.part2 FOR VALUES FROM (5) TO (10);
 
+-- Can't create foreign partition of published table
+CREATE FOREIGN TABLE sch3.part3_1 PARTITION OF sch3.tmain FOR VALUES FROM (10) TO (15) SERVER fdw_server;
+
+-- Can't attach foreign partition to published table
+CREATE FOREIGN TABLE sch3.part3_2(id int) SERVER fdw_server;
+ALTER TABLE sch3.tmain ATTACH PARTITION sch3.part3_2 FOR VALUES FROM (15) TO (20);
+
+-- Can't create publication for schema with foreign tables
+CREATE SCHEMA sch4;
+CREATE FOREIGN TABLE sch4.ftable(id int) SERVER fdw_server;
+CREATE PUBLICATION pub_sch4 FOR TABLES IN SCHEMA sch4;
+
+DROP SCHEMA sch4 CASCADE;
+
 DROP PUBLICATION pub1;
 DROP SCHEMA sch3 CASCADE;
 DROP SERVER fdw_server;
-- 
2.43.0

