From 024b158f20d2c8ea10989e7e5139a771e00338ce Mon Sep 17 00:00:00 2001
From: jian he <jian.universality@gmail.com>
Date: Wed, 2 Jul 2025 10:14:58 +0800
Subject: [PATCH v2 1/1] pg_restore not restore comments when it's object not
 restored

If certain objects are excluded from restoration in pg_restore, then comments
associated with those objects should also not be restored.
So this patch applies to the following pg_restore option:
--no-policies, --no-publications, --no-subscriptions
i manually tested these three options.

I didn't test --no-security-labels option, so no changes for it.

discussion: https://postgr.es/m/18970-a7d1cfe1f8d5d8d9@postgresql.org
---
 src/bin/pg_dump/pg_backup_archiver.c | 17 +++++++++++++++++
 1 file changed, 17 insertions(+)

diff --git a/src/bin/pg_dump/pg_backup_archiver.c b/src/bin/pg_dump/pg_backup_archiver.c
index 197c1295d93..44bcce71712 100644
--- a/src/bin/pg_dump/pg_backup_archiver.c
+++ b/src/bin/pg_dump/pg_backup_archiver.c
@@ -3020,6 +3020,23 @@ _tocEntryRequired(TocEntry *te, teSection curSection, ArchiveHandle *AH)
 		 strcmp(te->desc, "ROW SECURITY") == 0))
 		return 0;
 
+	if (strcmp(te->desc, "COMMENT") == 0)
+	{
+		/*
+		 * If --no-policies, --no-publications, or --no-subscriptions is
+		 * specified, comments related to those objects should also be skipped
+		 * during restore.
+		*/
+		if (ropt->no_policies && strncmp(te->tag, "POLICY", strlen("POLICY")) == 0)
+			return 0;
+
+		if (ropt->no_publications && strncmp(te->tag, "PUBLICATION", strlen("PUBLICATION")) == 0)
+			return 0;
+
+		if (ropt->no_subscriptions && strncmp(te->tag, "SUBSCRIPTION", strlen("SUBSCRIPTION")) == 0)
+			return 0;
+	}
+
 	/*
 	 * If it's a publication or a table part of a publication, maybe ignore
 	 * it.
-- 
2.34.1

