From 76129bcdc918a65f471c6d0860b3d59ac9ca50fb Mon Sep 17 00:00:00 2001
From: Jim Jones <jim.jones@uni-muenster.de>
Date: Wed, 25 Nov 2026 11:52:20 +0100
Subject: [PATCH v1] Fix memory growth when mapping arrays to XML

map_sql_value_to_xml_value() converts each array element in the
caller's memory context, so the intermediate data produced for every
element accumulates until the end of the statement.  For large arrays
this can use far more memory than the result itself.  The loop also
does not check for interrupts.

Convert each element 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 | 25 ++++++++++++++++++++++---
 1 file changed, 22 insertions(+), 3 deletions(-)

diff --git a/src/backend/utils/adt/xml.c b/src/backend/utils/adt/xml.c
index 88a2e358a15..839d444146f 100644
--- a/src/backend/utils/adt/xml.c
+++ b/src/backend/utils/adt/xml.c
@@ -99,6 +99,7 @@
 #include "utils/date.h"
 #include "utils/datetime.h"
 #include "utils/lsyscache.h"
+#include "utils/memutils.h"
 #include "utils/rel.h"
 #include "utils/syscache.h"
 #include "utils/xml.h"
@@ -2543,6 +2544,8 @@ map_sql_value_to_xml_value(Datum value, Oid type, bool xml_escape_strings)
 		Datum	   *elem_values;
 		bool	   *elem_nulls;
 		StringInfoData buf;
+		MemoryContext elemcxt;
+		MemoryContext oldcxt;
 		int			i;
 
 		array = DatumGetArrayTypeP(value);
@@ -2556,17 +2559,33 @@ map_sql_value_to_xml_value(Datum value, Oid type, bool xml_escape_strings)
 
 		initStringInfo(&buf);
 
+		/* Free per-element garbage, which can be large, after each element */
+		elemcxt = AllocSetContextCreate(CurrentMemoryContext,
+										"map_sql_value_to_xml_value temporary cxt",
+										ALLOCSET_DEFAULT_SIZES);
+
 		for (i = 0; i < num_elems; i++)
 		{
+			char	   *elemstr;
+
+			CHECK_FOR_INTERRUPTS();
+
 			if (elem_nulls[i])
 				continue;
+
+			oldcxt = MemoryContextSwitchTo(elemcxt);
+			elemstr = map_sql_value_to_xml_value(elem_values[i],
+												 elmtype, true);
+			MemoryContextSwitchTo(oldcxt);
+
 			appendStringInfoString(&buf, "<element>");
-			appendStringInfoString(&buf,
-								   map_sql_value_to_xml_value(elem_values[i],
-															  elmtype, true));
+			appendStringInfoString(&buf, elemstr);
 			appendStringInfoString(&buf, "</element>");
+
+			MemoryContextReset(elemcxt);
 		}
 
+		MemoryContextDelete(elemcxt);
 		pfree(elem_values);
 		pfree(elem_nulls);
 
-- 
2.56.1

