From c9000408036903df95ae22d0918a3fffddc7bf48 Mon Sep 17 00:00:00 2001
From: Alvaro Herrera <alvherre@alvh.no-ip.org>
Date: Wed, 13 Nov 2019 15:12:05 -0300
Subject: [PATCH 1/2] build partdesc memcxt

---
 src/backend/partitioning/partdesc.c | 15 +++++++++++++--
 1 file changed, 13 insertions(+), 2 deletions(-)

diff --git a/src/backend/partitioning/partdesc.c b/src/backend/partitioning/partdesc.c
index 6ede084afe..c551df6673 100644
--- a/src/backend/partitioning/partdesc.c
+++ b/src/backend/partitioning/partdesc.c
@@ -71,6 +71,14 @@ RelationBuildPartitionDesc(Relation rel)
 	PartitionKey key = RelationGetPartitionKey(rel);
 	MemoryContext oldcxt;
 	int		   *mapping;
+	static MemoryContext tmpContext = NULL;
+
+	if (tmpContext == NULL)
+		tmpContext = AllocSetContextCreate(TopMemoryContext,
+										   "build part tmp",
+										   ALLOCSET_SMALL_SIZES);
+
+	oldcxt = MemoryContextSwitchTo(tmpContext);
 
 	/*
 	 * Get partition oids from pg_inherits.  This uses a single snapshot to
@@ -205,11 +213,11 @@ RelationBuildPartitionDesc(Relation rel)
 		boundinfo = partition_bounds_create(boundspecs, nparts, key, &mapping);
 
 		/* Now copy all info into relcache's partdesc. */
-		oldcxt = MemoryContextSwitchTo(rel->rd_pdcxt);
+		MemoryContextSwitchTo(rel->rd_pdcxt);
 		partdesc->boundinfo = partition_bounds_copy(boundinfo, key);
 		partdesc->oids = (Oid *) palloc(nparts * sizeof(Oid));
 		partdesc->is_leaf = (bool *) palloc(nparts * sizeof(bool));
-		MemoryContextSwitchTo(oldcxt);
+		MemoryContextSwitchTo(tmpContext);
 
 		/*
 		 * Assign OIDs from the original array into mapped indexes of the
@@ -231,6 +239,9 @@ RelationBuildPartitionDesc(Relation rel)
 		}
 	}
 
+	MemoryContextSwitchTo(oldcxt);
+	MemoryContextResetAndDeleteChildren(tmpContext);
+
 	rel->rd_partdesc = partdesc;
 }
 
-- 
2.20.1

