From: Andrey Rachitskiy <pl0h0yp1@gmail.com>
Date: Thu, 26 Nov 2026 01:39:55 +0500
Subject: [PATCH] Render large arrays in a temporary context

array_out() and array_to_text_internal() keep every element string
until the result is built. Output functions can return a buffer much
larger than that text, so a large array holds one such buffer per
element.

At or above 65536 elements, render each element in a temporary context.
array_out() copies out the text. array_to_text_internal() appends it
to its result buffer and resets the context. Smaller arrays keep the
direct path.
---
 src/backend/utils/adt/arrayfuncs.c | 23 ++++++++++++++++++++++-
 src/backend/utils/adt/varlena.c    | 20 ++++++++++++++++++++
 src/include/utils/array.h          |  6 ++++++
 3 files changed, 48 insertions(+), 1 deletion(-)
diff --git a/src/backend/utils/adt/arrayfuncs.c b/src/backend/utils/adt/arrayfuncs.c
index c9c2689e77f..4c8bc66383d 100644
--- a/src/backend/utils/adt/arrayfuncs.c
+++ b/src/backend/utils/adt/arrayfuncs.c
@@ -1045,6 +1045,7 @@ array_out(PG_FUNCTION_ARGS)
 			   *lb;
 	array_iter	iter;
 	ArrayMetaState *my_extra;
+	MemoryContext elemcxt = NULL;
 
 	/*
 	 * We arrange to look up info about element type, including its output
@@ -1111,6 +1112,11 @@ array_out(PG_FUNCTION_ARGS)
 	needquotes = palloc_array(bool, nitems);
 	overall_length = 0;
 
+	if (nitems >= MinArrayElemsForTempCxt)
+		elemcxt = AllocSetContextCreate(CurrentMemoryContext,
+										"array_out temporary cxt",
+										ALLOCSET_DEFAULT_SIZES);
+
 	array_iter_setup(&iter, v, typlen, typbyval, typalign);
 
 	for (i = 0; i < nitems; i++)
@@ -1130,7 +1136,19 @@ array_out(PG_FUNCTION_ARGS)
 		}
 		else
 		{
-			values[i] = OutputFunctionCall(&my_extra->proc, itemvalue);
+			if (elemcxt != NULL)
+			{
+				char	   *elemstr;
+				MemoryContext oldcxt;
+
+				oldcxt = MemoryContextSwitchTo(elemcxt);
+				elemstr = OutputFunctionCall(&my_extra->proc, itemvalue);
+				MemoryContextSwitchTo(oldcxt);
+				values[i] = pstrdup(elemstr);
+				MemoryContextReset(elemcxt);
+			}
+			else
+				values[i] = OutputFunctionCall(&my_extra->proc, itemvalue);
 
 			/* count data plus backslashes; detect chars needing quotes */
 			if (values[i][0] == '\0')
@@ -1165,6 +1183,9 @@ array_out(PG_FUNCTION_ARGS)
 		overall_length += 1;
 	}
 
+	if (elemcxt != NULL)
+		MemoryContextDelete(elemcxt);
+
 	/*
 	 * The very last array element doesn't have a typdelim delimiter after it,
 	 * but that's OK; that space is needed for the trailing '\0'.
diff --git a/src/backend/utils/adt/varlena.c b/src/backend/utils/adt/varlena.c
index 74d863e3ff2..3ce4d410b10 100644
--- a/src/backend/utils/adt/varlena.c
+++ b/src/backend/utils/adt/varlena.c
@@ -35,6 +35,7 @@
 #include "parser/scansup.h"
 #include "port/pg_bswap.h"
 #include "regex/regex.h"
+#include "utils/array.h"
 #include "utils/builtins.h"
 #include "utils/guc.h"
 #include "utils/lsyscache.h"
@@ -3963,6 +3964,8 @@ array_to_text_internal(FunctionCallInfo fcinfo, ArrayType *v,
 	int			bitmask;
 	int			i;
 	ArrayMetaState *my_extra;
+	MemoryContext elemcxt = NULL;
+	MemoryContext oldcxt = CurrentMemoryContext;
 
 	ndims = ARR_NDIM(v);
 	dims = ARR_DIMS(v);
@@ -4011,6 +4014,14 @@ array_to_text_internal(FunctionCallInfo fcinfo, ArrayType *v,
 	bitmap = ARR_NULLBITMAP(v);
 	bitmask = 1;
 
+	if (nitems >= MinArrayElemsForTempCxt)
+	{
+		elemcxt = AllocSetContextCreate(CurrentMemoryContext,
+										"array_to_text temporary cxt",
+										ALLOCSET_DEFAULT_SIZES);
+		oldcxt = MemoryContextSwitchTo(elemcxt);
+	}
+
 	for (i = 0; i < nitems; i++)
 	{
 		Datum		itemvalue;
@@ -4041,6 +4052,9 @@ array_to_text_internal(FunctionCallInfo fcinfo, ArrayType *v,
 				appendStringInfoString(&buf, value);
 			printed = true;
 
+			if (elemcxt != NULL)
+				MemoryContextReset(elemcxt);
+
 			p = att_addlength_pointer(p, typlen, p);
 			p = (char *) att_nominal_alignby(p, typalignby);
 		}
@@ -4057,6 +4071,12 @@ array_to_text_internal(FunctionCallInfo fcinfo, ArrayType *v,
 		}
 	}
 
+	if (elemcxt != NULL)
+	{
+		MemoryContextSwitchTo(oldcxt);
+		MemoryContextDelete(elemcxt);
+	}
+
 	result = cstring_to_text_with_len(buf.data, buf.len);
 	pfree(buf.data);
 
diff --git a/src/include/utils/array.h b/src/include/utils/array.h
index e7ee184034e..e126b3f271e 100644
--- a/src/include/utils/array.h
+++ b/src/include/utils/array.h
@@ -81,6 +81,12 @@ typedef struct ExprContext ExprContext;
  */
 #define MaxArraySize ((Size) (MaxAllocSize / sizeof(Datum)))
 
+/*
+ * array_out and array_to_text use a temporary context for arrays of
+ * at least this many elements.
+ */
+#define MinArrayElemsForTempCxt 65536
+
 /*
  * Arrays are varlena objects, so must meet the varlena convention that
  * the first int32 of the object contains the total object size in bytes.
