From 06bf577b5092a9fa443122bc8eef51284c6aa339 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/3] Apply purning to relcache

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

diff --git a/src/backend/utils/cache/relcache.c b/src/backend/utils/cache/relcache.c
index d85dc92505..dbbf9855b0 100644
--- a/src/backend/utils/cache/relcache.c
+++ b/src/backend/utils/cache/relcache.c
@@ -3442,6 +3442,26 @@ 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);
+
+	/* don't remove if currently in use */
+	if (!RelationHasReferenceCountZero(relation))
+		return false;
+
+	/* otherwise we can forget it unconditionally */
+	RelationClearRelation(relation, false);
+
+	return true;
+}
+
 void
 RelationCacheInitialize(void)
 {
@@ -3459,8 +3479,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.3

