From 273911ac7f202fdc3ade23603349213edc74dc0f Mon Sep 17 00:00:00 2001 From: aykut-bozkurt <51649454+aykut-bozkurt@users.noreply.github.com> Date: Mon, 13 Feb 2023 15:22:13 +0300 Subject: [PATCH] prevent memory leak during ConvertTable with a lot of partitions (#6693) Prevents memory leak during ConvertTable call for a table with a lot of partitions. DESCRIPTION: Fixes memory leak during undistribution and alteration of a table with a lot of partitions. --- src/backend/distributed/commands/alter_table.c | 15 +++++++++++++++ 1 file changed, 15 insertions(+) diff --git a/src/backend/distributed/commands/alter_table.c b/src/backend/distributed/commands/alter_table.c index 7f86509cc..a698fd164 100644 --- a/src/backend/distributed/commands/alter_table.c +++ b/src/backend/distributed/commands/alter_table.c @@ -800,9 +800,21 @@ ConvertTable(TableConversionState *con) ExecuteQueryViaSPI(tableConstructionSQL, SPI_OK_UTILITY); } + /* + * when there are many partitions, each call to ProcessUtilityParseTree + * accumulates used memory. Free context after each call. + */ + MemoryContext citusPerPartitionContext = + AllocSetContextCreate(CurrentMemoryContext, + "citus_per_partition_context", + ALLOCSET_DEFAULT_SIZES); + MemoryContext oldContext = MemoryContextSwitchTo(citusPerPartitionContext); + char *attachPartitionCommand = NULL; foreach_ptr(attachPartitionCommand, attachPartitionCommands) { + MemoryContextReset(citusPerPartitionContext); + Node *parseTree = ParseTreeNode(attachPartitionCommand); ProcessUtilityParseTree(parseTree, attachPartitionCommand, @@ -810,6 +822,9 @@ ConvertTable(TableConversionState *con) NULL, None_Receiver, NULL); } + MemoryContextSwitchTo(oldContext); + MemoryContextDelete(citusPerPartitionContext); + if (isPartitionTable) { ExecuteQueryViaSPI(attachToParentCommand, SPI_OK_UTILITY);