From c3df92e4435861eb24a3ea2d11861f3f44b5bba4 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 v2 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 | 35 +++++++++++++++++++++++++++++++++++
 1 file changed, 35 insertions(+)

diff --git a/src/backend/utils/adt/xml.c b/src/backend/utils/adt/xml.c
index 3fa050987fa..8687e3c2aed 100644
--- a/src/backend/utils/adt/xml.c
+++ b/src/backend/utils/adt/xml.c
@@ -2994,6 +2994,7 @@ cursor_to_xml(PG_FUNCTION_ARGS)
 
 	StringInfoData result;
 	Portal		portal;
+	MemoryContext rowcxt;
 	uint64		i;
 
 	initStringInfo(&result);
@@ -3012,9 +3013,26 @@ 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);
+
 	for (i = 0; i < SPI_processed; i++)
+	{
+		MemoryContext oldcxt;
+
+		CHECK_FOR_INTERRUPTS();
+
+		oldcxt = MemoryContextSwitchTo(rowcxt);
 		SPI_sql_row_to_xmlelement(i, &result, NULL, nulls,
 								  tableforest, targetns, true);
+		MemoryContextSwitchTo(oldcxt);
+
+		MemoryContextReset(rowcxt);
+	}
+
+	MemoryContextDelete(rowcxt);
 
 	SPI_finish();
 
@@ -3078,6 +3096,7 @@ query_to_xml_internal(const char *query, char *tablename,
 {
 	StringInfo	result;
 	char	   *xmltn;
+	MemoryContext rowcxt;
 	uint64		i;
 
 	if (tablename)
@@ -3103,9 +3122,25 @@ 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);
+
 	for (i = 0; i < SPI_processed; i++)
+	{
+		MemoryContext oldcxt;
+
+		CHECK_FOR_INTERRUPTS();
+
+		oldcxt = MemoryContextSwitchTo(rowcxt);
 		SPI_sql_row_to_xmlelement(i, result, tablename, nulls,
 								  tableforest, targetns, top_level);
+		MemoryContextSwitchTo(oldcxt);
+
+		MemoryContextReset(rowcxt);
+	}
+
+	MemoryContextDelete(rowcxt);
 
 	if (!tableforest)
 		xmldata_root_element_end(result, xmltn);
-- 
2.56.1

