From cd9cc6411270e2d99727b8cc31046dd781854ef2 Mon Sep 17 00:00:00 2001
From: Jim Jones <jim.jones@uni-muenster.de>
Date: Fri, 27 Nov 2026 10:05:51 +0100
Subject: [PATCH v4 2/3] 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.  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.

Author: Jim Jones <jim.jones@uni-muenster.de>
Discussion: https://postgr.es/m/7581277e-e089-417d-867f-8ffd54b9e4c6@uni-muenster.de
---
 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

