From 94c85baed46e1a8330af7d664c44289d97d6df26 Mon Sep 17 00:00:00 2001
From: Kyotaro Horiguchi <horiguchi.kyotaro@lab.ntt.co.jp>
Date: Mon, 12 Mar 2018 17:31:43 +0900
Subject: [PATCH 3/4] Apply purning to relcache

---
 src/backend/utils/cache/relcache.c | 28 +++++++++++++++++++++++++++-
 1 file changed, 27 insertions(+), 1 deletion(-)

diff --git a/src/backend/utils/cache/relcache.c b/src/backend/utils/cache/relcache.c
index 9ee78f885f..da9ecee15b 100644
--- a/src/backend/utils/cache/relcache.c
+++ b/src/backend/utils/cache/relcache.c
@@ -3503,6 +3503,29 @@ RelationSetNewRelfilenode(Relation relation, char persistence,
 
 #define INITRELCACHESIZE		400
 
+/* callback function for hash pruning */
+static bool
+relcache_prune_cb(HTAB *hashp, void *ent)
+{
+	RelIdCacheEnt  *relent = (RelIdCacheEnt *) ent;
+	Relation		relation;
+
+	/* this relation is requested to be removed.  */
+	RelationIdCacheLookup(relent->reloid, relation);
+
+	/* but cannot remove cache entries currently in use */
+	if (!RelationHasReferenceCountZero(relation))
+		return false;
+
+	/*
+	 * Otherwise we are allowd to forget it unconditionally. see
+	 * RelationForgetRelation
+	 */
+	RelationClearRelation(relation, false);
+
+	return true;
+}
+
 void
 RelationCacheInitialize(void)
 {
@@ -3520,8 +3543,11 @@ RelationCacheInitialize(void)
 	MemSet(&ctl, 0, sizeof(ctl));
 	ctl.keysize = sizeof(Oid);
 	ctl.entrysize = sizeof(RelIdCacheEnt);
+
+	/* use the same setting with syscache */
+	ctl.prune_cb = relcache_prune_cb;
 	RelationIdCache = hash_create("Relcache by OID", INITRELCACHESIZE,
-								  &ctl, HASH_ELEM | HASH_BLOBS);
+								  &ctl, HASH_ELEM | HASH_BLOBS | HASH_PRUNABLE);
 
 	/*
 	 * relation mapper needs to be initialized too
-- 
2.16.2

