On 26/11/2026 10:28, Jim Jones wrote:
>> On Wed, 25 Nov 2026 at 22:43, Tom Lane <[email protected]> wrote:
>>> Another thing I noticed is that we are doing the type-output
>>> function lookup over again for each array element, though
>>> with some refactoring we could do it just once.  Since that
>>> lookup is skipped for "bool" elements, I compared
> 
> +1
> I will take a look at this today or tomorrow and post a separate 0003 patch.


I spent some time with this today. 0003 now moves the body of
map_sql_value_to_xml_value() into map_sql_value_to_xml_value_internal(),
which does the elemnt type lookups once per array and passes the results
down to the conversion of each element -- I added some small regression
tests for that.

here some tests:

(-O2 build without assertions)

== master ==

postgres=# select length(xmlelement(name a, array_fill(''::text,
ARRAY[16000000]))::text);
  length
-----------
 304000007
(1 row)

Time: 6029,250 ms (00:06,029)


== patched (0001, 0002) ==

postgres=# select length(xmlelement(name a, array_fill(''::text,
ARRAY[16000000]))::text);
  length
-----------
 304000007
(1 row)

Time: 2247,771 ms (00:02,248)


== patched (0001, 0002, 0003)==

postgres=# select length(xmlelement(name a, array_fill(''::text,
ARRAY[16000000]))::text);
  length
-----------
 304000007
(1 row)

Time: 1464,118 ms (00:01,464)

0001 and 0002 remain unchanged.

Best, Jim
From 939d349e0f0f8251bb4f8716369a99beb20199bc Mon Sep 17 00:00:00 2001
From: Jim Jones <[email protected]>
Date: Thu, 26 Nov 2026 10:09:23 +0100
Subject: [PATCH v4 1/3] 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 <[email protected]>
Reviewed-by: Jakub Wartak <[email protected]>
Reviewed-by: Daniel Gustafsson <[email protected]>
Reviewed-by: Tom Lane <[email protected]>
Reviewed-by: Kirill Reshke <[email protected]>
Discussion: https://postgr.es/m/[email protected]
---
 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

From cd9cc6411270e2d99727b8cc31046dd781854ef2 Mon Sep 17 00:00:00 2001
From: Jim Jones <[email protected]>
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 <[email protected]>
Discussion: https://postgr.es/m/[email protected]
---
 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

From 39102eed00fc1121773ab1e9cb970a4ae6f759d9 Mon Sep 17 00:00:00 2001
From: Jim Jones <[email protected]>
Date: Fri, 27 Nov 2026 09:25:50 +0100
Subject: [PATCH v4 3/3] Look up element type information once when mapping
 arrays to XML

map_sql_value_to_xml_value() converts each element of an array by
calling itself, and every such call looks up the base type and the
output function of the element type again, although they are the same
for all elements.  Do these lookups once per array instead and pass
the results down to the conversion of each element.

Add tests for arrays of domains, including domains over array types,
whose elements are still converted recursively.

Suggested-by: Tom Lane <[email protected]>
Author: Jim Jones <[email protected]>
Discussion: https://postgr.es/m/[email protected]
---
 src/backend/utils/adt/xml.c       | 61 +++++++++++++++++++++++++++----
 src/test/regress/expected/xml.out | 16 ++++++++
 src/test/regress/sql/xml.sql      |  6 +++
 3 files changed, 76 insertions(+), 7 deletions(-)

diff --git a/src/backend/utils/adt/xml.c b/src/backend/utils/adt/xml.c
index e19ab446e6d..c60cb3dc26d 100644
--- a/src/backend/utils/adt/xml.c
+++ b/src/backend/utils/adt/xml.c
@@ -184,6 +184,9 @@ static const char *map_sql_catalog_to_xmlschema_types(List *nspid_list,
 static const char *map_sql_type_to_xml_name(Oid typeoid, int typmod);
 static const char *map_sql_typecoll_to_xmlschema_types(List *tupdesc_list);
 static const char *map_sql_type_to_xmlschema_type(Oid typeoid, int typmod);
+static char *map_sql_value_to_xml_value_internal(Datum value, Oid type,
+												 bool xml_escape_strings,
+												 FmgrInfo *typoutput);
 static void SPI_sql_row_to_xmlelement(uint64 rownum, StringInfo result,
 									  char *tablename, bool nulls, bool tableforest,
 									  const char *targetns, bool top_level);
@@ -2533,7 +2536,23 @@ map_xml_name_to_sql_identifier(const char *name)
 char *
 map_sql_value_to_xml_value(Datum value, Oid type, bool xml_escape_strings)
 {
-	if (type_is_array_domain(type))
+	return map_sql_value_to_xml_value_internal(value, type,
+											   xml_escape_strings, NULL);
+}
+
+/*
+ * Workhorse for map_sql_value_to_xml_value().
+ *
+ * If typoutput is not NULL, "type" must be a non-array base type and
+ * typoutput its output function.  The array case uses this to look them
+ * up only once per array instead of for every element.
+ */
+static char *
+map_sql_value_to_xml_value_internal(Datum value, Oid type,
+									bool xml_escape_strings,
+									FmgrInfo *typoutput)
+{
+	if (typoutput == NULL && type_is_array_domain(type))
 	{
 		ArrayType  *array;
 		Oid			elmtype;
@@ -2546,6 +2565,8 @@ map_sql_value_to_xml_value(Datum value, Oid type, bool xml_escape_strings)
 		StringInfoData buf;
 		MemoryContext elemcxt;
 		MemoryContext oldcxt;
+		FmgrInfo	elmoutput;
+		FmgrInfo   *elmoutputp = NULL;
 		int			i;
 
 		array = DatumGetArrayTypeP(value);
@@ -2557,6 +2578,24 @@ map_sql_value_to_xml_value(Datum value, Oid type, bool xml_escape_strings)
 						  &elem_values, &elem_nulls,
 						  &num_elems);
 
+		/*
+		 * Look up the element type's output function once for all elements,
+		 * unless the elements are themselves arrays (a domain over an array
+		 * type), which are converted recursively.  This must be done before
+		 * switching to the temporary context below, so that whatever the
+		 * output function caches in fn_extra survives each reset.
+		 */
+		if (!type_is_array_domain(elmtype))
+		{
+			Oid			typeOut;
+			bool		isvarlena;
+
+			elmtype = getBaseType(elmtype);
+			getTypeOutputInfo(elmtype, &typeOut, &isvarlena);
+			fmgr_info(typeOut, &elmoutput);
+			elmoutputp = &elmoutput;
+		}
+
 		initStringInfo(&buf);
 
 		/* Free per-element garbage, which can be large, after each element */
@@ -2573,8 +2612,9 @@ map_sql_value_to_xml_value(Datum value, Oid type, bool xml_escape_strings)
 				continue;
 			appendStringInfoString(&buf, "<element>");
 			appendStringInfoString(&buf,
-								   map_sql_value_to_xml_value(elem_values[i],
-															  elmtype, true));
+								   map_sql_value_to_xml_value_internal(elem_values[i],
+																	   elmtype, true,
+																	   elmoutputp));
 			appendStringInfoString(&buf, "</element>");
 
 			MemoryContextReset(elemcxt);
@@ -2597,7 +2637,8 @@ map_sql_value_to_xml_value(Datum value, Oid type, bool xml_escape_strings)
 		 * Flatten domains; the special-case treatments below should apply to,
 		 * eg, domains over boolean not just boolean.
 		 */
-		type = getBaseType(type);
+		if (typoutput == NULL)
+			type = getBaseType(type);
 
 		/*
 		 * Special XSD formatting for some data types
@@ -2741,10 +2782,16 @@ map_sql_value_to_xml_value(Datum value, Oid type, bool xml_escape_strings)
 		}
 
 		/*
-		 * otherwise, just use the type's native text representation
+		 * otherwise, just use the type's native text representation, through
+		 * the output function given by the caller if there is one
 		 */
-		getTypeOutputInfo(type, &typeOut, &isvarlena);
-		str = OidOutputFunctionCall(typeOut, value);
+		if (typoutput)
+			str = OutputFunctionCall(typoutput, value);
+		else
+		{
+			getTypeOutputInfo(type, &typeOut, &isvarlena);
+			str = OidOutputFunctionCall(typeOut, value);
+		}
 
 		/* ... exactly as-is for XML, and when escaping is not wanted */
 		if (type == XMLOID || !xml_escape_strings)
diff --git a/src/test/regress/expected/xml.out b/src/test/regress/expected/xml.out
index 6998745ee03..ee149303fcd 100644
--- a/src/test/regress/expected/xml.out
+++ b/src/test/regress/expected/xml.out
@@ -196,6 +196,22 @@ SELECT xmlelement(name foo, array[1, 2, 3]);
  <foo><element>1</element><element>2</element><element>3</element></foo>
 (1 row)
 
+-- arrays of domains: over a scalar type, and over an array type
+CREATE DOMAIN xmltest_bool AS bool;
+CREATE DOMAIN xmltest_intarr AS int[];
+SELECT xmlelement(name foo, array[true, false]::xmltest_bool[]);
+                         xmlelement                         
+------------------------------------------------------------
+ <foo><element>true</element><element>false</element></foo>
+(1 row)
+
+SELECT xmlelement(name foo, array['{1,2}', '{3}']::xmltest_intarr[]);
+                                                  xmlelement                                                   
+---------------------------------------------------------------------------------------------------------------
+ <foo><element><element>1</element><element>2</element></element><element><element>3</element></element></foo>
+(1 row)
+
+DROP DOMAIN xmltest_bool, xmltest_intarr;
 SET xmlbinary TO base64;
 SELECT xmlelement(name foo, bytea 'bar');
    xmlelement    
diff --git a/src/test/regress/sql/xml.sql b/src/test/regress/sql/xml.sql
index 0581d21b03f..c1c0c9783f0 100644
--- a/src/test/regress/sql/xml.sql
+++ b/src/test/regress/sql/xml.sql
@@ -63,6 +63,12 @@ SELECT xmlelement(name foo, xml 'bar');
 SELECT xmlelement(name foo, text 'b<a/>r');
 SELECT xmlelement(name foo, xml 'b<a/>r');
 SELECT xmlelement(name foo, array[1, 2, 3]);
+-- arrays of domains: over a scalar type, and over an array type
+CREATE DOMAIN xmltest_bool AS bool;
+CREATE DOMAIN xmltest_intarr AS int[];
+SELECT xmlelement(name foo, array[true, false]::xmltest_bool[]);
+SELECT xmlelement(name foo, array['{1,2}', '{3}']::xmltest_intarr[]);
+DROP DOMAIN xmltest_bool, xmltest_intarr;
 SET xmlbinary TO base64;
 SELECT xmlelement(name foo, bytea 'bar');
 SET xmlbinary TO hex;
-- 
2.56.1

Reply via email to