From 2a4ffc1ded47a508030f6ef098cf6da44b6f785a Mon Sep 17 00:00:00 2001
From: Jim Jones <jim.jones@uni-muenster.de>
Date: Wed, 25 Nov 2026 14:07:56 +0100
Subject: [PATCH v3 2/2] Fix memory growth in the *_to_xml() functions

query_to_xml(), table_to_xml(), cursor_to_xml() and the functions built
on them convert every row of the query result in the same memory
context, so the intermediate data produced for each row accumulates
until all rows have been processed.  For large results this can use far
more memory than the result itself.  The row loop also does not check
for interrupts.

Convert each row in a temporary memory context that is reset after
every iteration, and add CHECK_FOR_INTERRUPTS() to the loop.
---
 src/backend/utils/adt/xml.c | 33 +++++++++++++++++++++++++++++++++
 1 file changed, 33 insertions(+)

diff --git a/src/backend/utils/adt/xml.c b/src/backend/utils/adt/xml.c
index 80a8e4c54d0..e19ab446e6d 100644
--- a/src/backend/utils/adt/xml.c
+++ b/src/backend/utils/adt/xml.c
@@ -2990,6 +2990,8 @@ cursor_to_xml(PG_FUNCTION_ARGS)
 
 	StringInfoData result;
 	Portal		portal;
+	MemoryContext rowcxt;
+	MemoryContext oldcxt;
 	uint64		i;
 
 	initStringInfo(&result);
@@ -3008,10 +3010,25 @@ cursor_to_xml(PG_FUNCTION_ARGS)
 				 errmsg("cursor \"%s\" does not exist", name)));
 
 	SPI_cursor_fetch(portal, true, count);
+
+	rowcxt = AllocSetContextCreate(CurrentMemoryContext,
+								   "cursor_to_xml temporary cxt",
+								   ALLOCSET_DEFAULT_SIZES);
+	oldcxt = MemoryContextSwitchTo(rowcxt);
+
 	for (i = 0; i < SPI_processed; i++)
+	{
+		CHECK_FOR_INTERRUPTS();
+
 		SPI_sql_row_to_xmlelement(i, &result, NULL, nulls,
 								  tableforest, targetns, true);
 
+		MemoryContextReset(rowcxt);
+	}
+
+	MemoryContextSwitchTo(oldcxt);
+	MemoryContextDelete(rowcxt);
+
 	SPI_finish();
 
 	if (!tableforest)
@@ -3074,6 +3091,8 @@ query_to_xml_internal(const char *query, char *tablename,
 {
 	StringInfo	result;
 	char	   *xmltn;
+	MemoryContext rowcxt;
+	MemoryContext oldcxt;
 	uint64		i;
 
 	if (tablename)
@@ -3099,10 +3118,24 @@ query_to_xml_internal(const char *query, char *tablename,
 	if (xmlschema)
 		appendStringInfo(result, "%s\n\n", xmlschema);
 
+	rowcxt = AllocSetContextCreate(CurrentMemoryContext,
+								   "query_to_xml_internal temporary cxt",
+								   ALLOCSET_DEFAULT_SIZES);
+	oldcxt = MemoryContextSwitchTo(rowcxt);
+
 	for (i = 0; i < SPI_processed; i++)
+	{
+		CHECK_FOR_INTERRUPTS();
+
 		SPI_sql_row_to_xmlelement(i, result, tablename, nulls,
 								  tableforest, targetns, top_level);
 
+		MemoryContextReset(rowcxt);
+	}
+
+	MemoryContextSwitchTo(oldcxt);
+	MemoryContextDelete(rowcxt);
+
 	if (!tableforest)
 		xmldata_root_element_end(result, xmltn);
 
-- 
2.56.1

