From 643551a193dc4c98ee525eca94931fb0d7b03635 Mon Sep 17 00:00:00 2001
From: Mahendra Singh Thalor <mahi6run@gmail.com>
Date: Fri, 6 Aug 2021 11:34:04 -0700
Subject: [PATCH] pg_stat_reset and pg_stat_reset_single_table_counters don't
 work for shared objects.

This patch will reset the stats for shared tables also.
Code changes are done in pgstat_recv_resetcounter and
pgstat_recv_resetsinglecounter for dbentry with 'InvaidOid'.
---
 src/backend/postmaster/pgstat.c | 26 +++++++++++++++++++++++---
 1 file changed, 23 insertions(+), 3 deletions(-)

diff --git a/src/backend/postmaster/pgstat.c b/src/backend/postmaster/pgstat.c
index 56755cb92b..1194e02e07 100644
--- a/src/backend/postmaster/pgstat.c
+++ b/src/backend/postmaster/pgstat.c
@@ -38,6 +38,7 @@
 #include "access/transam.h"
 #include "access/twophase_rmgr.h"
 #include "access/xact.h"
+#include "catalog/catalog.h"
 #include "catalog/partition.h"
 #include "catalog/pg_database.h"
 #include "catalog/pg_proc.h"
@@ -339,6 +340,7 @@ static void pgstat_recv_tabstat(PgStat_MsgTabstat *msg, int len);
 static void pgstat_recv_tabpurge(PgStat_MsgTabpurge *msg, int len);
 static void pgstat_recv_dropdb(PgStat_MsgDropdb *msg, int len);
 static void pgstat_recv_resetcounter(PgStat_MsgResetcounter *msg, int len);
+static void reset_dbentry(PgStat_StatDBEntry *dbentry);
 static void pgstat_recv_resetsharedcounter(PgStat_MsgResetsharedcounter *msg, int len);
 static void pgstat_recv_resetsinglecounter(PgStat_MsgResetsinglecounter *msg, int len);
 static void pgstat_recv_resetslrucounter(PgStat_MsgResetslrucounter *msg, int len);
@@ -5080,7 +5082,8 @@ pgstat_recv_dropdb(PgStat_MsgDropdb *msg, int len)
 /* ----------
  * pgstat_recv_resetcounter() -
  *
- *	Reset the statistics for the specified database.
+ *	Reset the statistics for the specified database and also resets for all
+ *	the shared tables
  * ----------
  */
 static void
@@ -5089,10 +5092,24 @@ pgstat_recv_resetcounter(PgStat_MsgResetcounter *msg, int len)
 	PgStat_StatDBEntry *dbentry;
 
 	/*
-	 * Lookup the database in the hashtable.  Nothing to do if not there.
+	 * Lookup the database in the hashtable.
 	 */
 	dbentry = pgstat_get_db_entry(msg->m_databaseid, false);
 
+	reset_dbentry(dbentry);
+
+	/*
+	 * Lookup for the shared tables also to reset the stats
+	 */
+	dbentry = pgstat_get_db_entry(InvalidOid, false);
+
+	reset_dbentry(dbentry);
+}
+
+static void
+reset_dbentry(PgStat_StatDBEntry *dbentry)
+{
+	/* Nothing to do if not there. */
 	if (!dbentry)
 		return;
 
@@ -5160,7 +5177,10 @@ pgstat_recv_resetsinglecounter(PgStat_MsgResetsinglecounter *msg, int len)
 {
 	PgStat_StatDBEntry *dbentry;
 
-	dbentry = pgstat_get_db_entry(msg->m_databaseid, false);
+	if (IsSharedRelation(msg->m_objectid))
+		dbentry = pgstat_get_db_entry(InvalidOid, false);
+	else
+		dbentry = pgstat_get_db_entry(msg->m_databaseid, false);
 
 	if (!dbentry)
 		return;
-- 
2.17.1

