From ae7f7ab7df353044b8b2878253d1bdb8adbcd054 Mon Sep 17 00:00:00 2001
From: Kyotaro Horiguchi <horikyoga.ntt@gmail.com>
Date: Thu, 3 Dec 2020 16:51:07 +0900
Subject: [PATCH 2/2] share param part of riinfo

---
 src/backend/utils/adt/ri_triggers.c | 33 +++++++++++++++++++++++++++++
 1 file changed, 33 insertions(+)

diff --git a/src/backend/utils/adt/ri_triggers.c b/src/backend/utils/adt/ri_triggers.c
index 3f8407c311..080e8af1a5 100644
--- a/src/backend/utils/adt/ri_triggers.c
+++ b/src/backend/utils/adt/ri_triggers.c
@@ -110,6 +110,8 @@ typedef struct RI_ConstraintParam
 	Oid			pf_eq_oprs[RI_MAX_NUMKEYS]; /* equality operators (PK = FK) */
 	Oid			pp_eq_oprs[RI_MAX_NUMKEYS]; /* equality operators (PK = PK) */
 	Oid			ff_eq_oprs[RI_MAX_NUMKEYS]; /* equality operators (FK = FK) */
+
+	/* This should follow the aboves, see ri_LoadConstraintInfo */
 	struct RI_ConstraintInfo *ownerinfo; /* owner info of this param */
 } RI_ConstraintParam;
 
@@ -2111,6 +2113,37 @@ ri_LoadConstraintInfo(Oid constraintOid)
 
 	ReleaseSysCache(tup);
 
+	if (OidIsValid(conForm->conparentid))
+	{
+		Oid pconid = conForm->conparentid;
+		const RI_ConstraintInfo *priinfo = ri_LoadConstraintInfo(pconid);
+		RI_ConstraintParam		*p = riinfo->param;
+		RI_ConstraintParam		*pp = priinfo->param;
+
+		/* share the same parameters if identical */
+		if (memcmp(p, pp, offsetof(RI_ConstraintParam, pk_attnums)) == 0)
+		{
+			int i;
+
+			for (i = 0 ; i < p->nkeys ; i++)
+			{
+				if (p->pk_attnums[i] != pp->pk_attnums[i] ||
+					p->fk_attnums[i] != pp->fk_attnums[i] ||
+					p->pf_eq_oprs[i] != pp->pf_eq_oprs[i] ||
+					p->pp_eq_oprs[i] != pp->pp_eq_oprs[i] ||
+					p->ff_eq_oprs[i] != pp->ff_eq_oprs[i])
+					break;
+			}
+			if (i == p->nkeys)
+			{
+				/* this riinfo can share the parameters with parent */
+				Assert(p->ownerinfo == riinfo);
+				pfree(riinfo->param);
+				riinfo->param = pp;
+			}
+		}
+	}
+
 	/*
 	 * For efficient processing of invalidation messages below, we keep a
 	 * doubly-linked list, and a count, of all currently valid entries.
-- 
2.18.4

