From 908b70280f7d6a1140bbbda8f9ac87e9e4ac75db Mon Sep 17 00:00:00 2001
From: "Chao Li (Evan)" <lic@highgo.com>
Date: Sat, 13 Dec 2025 10:25:07 +0800
Subject: [PATCH v3] pageinspect: clean up StringInfo usage in
 gist_page_items()

Reuse a single StringInfo across iterations, initializing it once and
resetting it as needed, and free it at function exit. This clarifies
lifetime management and avoids unnecessary allocations.

Author: Chao Li <lic@highgo.com>
Discussion: https://postgr.es/m/CAEoWx2=bL41WWcD-4Fxx-buS2Y2G5=9PjkxZbHeFMR6Uy2WNvw@mail.gmail.com
---
 contrib/pageinspect/gistfuncs.c | 16 ++++++++++++++--
 1 file changed, 14 insertions(+), 2 deletions(-)

diff --git a/contrib/pageinspect/gistfuncs.c b/contrib/pageinspect/gistfuncs.c
index 414513c395b..d6c888dde57 100644
--- a/contrib/pageinspect/gistfuncs.c
+++ b/contrib/pageinspect/gistfuncs.c
@@ -205,6 +205,8 @@ gist_page_items(PG_FUNCTION_ARGS)
 	OffsetNumber offset;
 	OffsetNumber maxoff = InvalidOffsetNumber;
 	char	   *index_columns;
+	StringInfoData buf;
+	bool		buf_initialized = false;
 
 	if (!superuser())
 		ereport(ERROR,
@@ -267,7 +269,6 @@ gist_page_items(PG_FUNCTION_ARGS)
 		IndexTuple	itup;
 		Datum		itup_values[INDEX_MAX_KEYS];
 		bool		itup_isnull[INDEX_MAX_KEYS];
-		StringInfoData buf;
 		int			i;
 
 		id = PageGetItemId(page, offset);
@@ -289,7 +290,15 @@ gist_page_items(PG_FUNCTION_ARGS)
 
 		if (index_columns)
 		{
-			initStringInfo(&buf);
+			if (!buf_initialized)
+			{
+				initStringInfo(&buf);
+				buf_initialized = true;
+			}
+			else
+			{
+				resetStringInfo(&buf);
+			}
 			appendStringInfo(&buf, "(%s)=(", index_columns);
 
 			/* Most of this is copied from record_out(). */
@@ -363,5 +372,8 @@ gist_page_items(PG_FUNCTION_ARGS)
 
 	index_close(indexRel, AccessShareLock);
 
+	if (buf.data)
+		pfree(buf.data);
+
 	return (Datum) 0;
 }
-- 
2.39.5 (Apple Git-154)

