From 7e86930ede6ccc9294c14c748adba068e6e88ecf Mon Sep 17 00:00:00 2001
From: Yugo Nagata <nagata@sraoss.co.jp>
Date: Mon, 25 Aug 2025 06:18:04 +0900
Subject: [PATCH v5 2/2] vacuumdb: check SELECT privilege on pg_statitis or
 pg_statistic_ext_data

---
 src/bin/scripts/vacuumdb.c | 24 ++++++++++++++++++++++++
 1 file changed, 24 insertions(+)

diff --git a/src/bin/scripts/vacuumdb.c b/src/bin/scripts/vacuumdb.c
index fd236087e90..2087b4131a2 100644
--- a/src/bin/scripts/vacuumdb.c
+++ b/src/bin/scripts/vacuumdb.c
@@ -801,6 +801,30 @@ retrieve_objects(PGconn *conn, vacuumingOptions *vacopts,
 	SimpleStringList *found_objs = palloc0(sizeof(SimpleStringList));
 	bool		objects_listed = false;
 
+	if (vacopts->missing_stats_only)
+	{
+		PQExpBufferData aclcheck;
+
+		initPQExpBuffer(&aclcheck);
+		appendPQExpBufferStr(&aclcheck,
+							 "SELECT has_table_privilege('pg_catalog.pg_statistic', 'select'), "
+							 "has_table_privilege('pg_catalog.pg_statistic_ext_data', 'select')");
+		res = executeQuery(conn, aclcheck.data, echo);
+		termPQExpBuffer(&aclcheck);
+		if (strcmp(PQgetvalue(res, 0, 0), "t") != 0)
+		{
+			PQfinish(conn);
+			pg_fatal("--missing-stats-only requires SELECT privileges on pg_statistic");
+		}
+		else if (strcmp(PQgetvalue(res, 0, 1), "t") != 0)
+		{
+			PQfinish(conn);
+			pg_fatal("--missing-stats-only requires SELECT privileges on pg_statistic_ext_data");
+		}
+
+		termPQExpBuffer(&aclcheck);
+	}
+
 	initPQExpBuffer(&catalog_query);
 	for (cell = objects ? objects->head : NULL; cell; cell = cell->next)
 	{
-- 
2.43.0

