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);