From 26691863e461a8c0beee498254f1c18093dfac4a 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 v2 2/2] 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 | 14 ++++++++++++--
 1 file changed, 12 insertions(+), 2 deletions(-)

diff --git a/contrib/pageinspect/gistfuncs.c b/contrib/pageinspect/gistfuncs.c
index 414513c395b..a946647b469 100644
--- a/contrib/pageinspect/gistfuncs.c
+++ b/contrib/pageinspect/gistfuncs.c
@@ -205,6 +205,7 @@ gist_page_items(PG_FUNCTION_ARGS)
 	OffsetNumber offset;
 	OffsetNumber maxoff = InvalidOffsetNumber;
 	char	   *index_columns;
+	StringInfoData buf = {0};	/* mark as uninitialized */
 
 	if (!superuser())
 		ereport(ERROR,
@@ -267,7 +268,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 +289,14 @@ gist_page_items(PG_FUNCTION_ARGS)
 
 		if (index_columns)
 		{
-			initStringInfo(&buf);
+			if (buf.maxlen == 0)
+			{
+				initStringInfo(&buf);
+			}
+			else
+			{
+				resetStringInfo(&buf);
+			}
 			appendStringInfo(&buf, "(%s)=(", index_columns);
 
 			/* Most of this is copied from record_out(). */
@@ -363,5 +370,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)

