From 9830c13742e7584660e61d1ecb70236e063919d5 Mon Sep 17 00:00:00 2001
From: Jim Jones <jim.jones@uni-muenster.de>
Date: Thu, 26 Nov 2026 10:09:23 +0100
Subject: [PATCH v3 1/2] 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.

Author: Jim Jones <jim.jones@uni-muenster.de>
Reviewed-by: Jakub Wartak <jakub.wartak@enterprisedb.com>
Reviewed-by: Daniel Gustafsson <daniel@yesql.se>
Reviewed-by: Tom Lane <tgl@sss.pgh.pa.us>
Reviewed-by: Kirill Reshke <reshkekirill@gmail.com>
---
 src/backend/utils/adt/xml.c | 15 +++++++++++++++
 1 file changed, 15 insertions(+)

diff --git a/src/backend/utils/adt/xml.c b/src/backend/utils/adt/xml.c
index 44a3a21d135..80a8e4c54d0 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,8 +2559,16 @@ 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);
+		oldcxt = MemoryContextSwitchTo(elemcxt);
+
 		for (i = 0; i < num_elems; i++)
 		{
+			CHECK_FOR_INTERRUPTS();
+
 			if (elem_nulls[i])
 				continue;
 			appendStringInfoString(&buf, "<element>");
@@ -2565,8 +2576,12 @@ map_sql_value_to_xml_value(Datum value, Oid type, bool xml_escape_strings)
 								   map_sql_value_to_xml_value(elem_values[i],
 															  elmtype, true));
 			appendStringInfoString(&buf, "</element>");
+
+			MemoryContextReset(elemcxt);
 		}
 
+		MemoryContextSwitchTo(oldcxt);
+		MemoryContextDelete(elemcxt);
 		pfree(elem_values);
 		pfree(elem_nulls);
 
-- 
2.56.1

