From caa24ca549c01e99b3873860dcffe0d8161345d4 Mon Sep 17 00:00:00 2001
From: jian he <jian.universality@gmail.com>
Date: Tue, 5 Nov 2024 14:34:02 +0800
Subject: [PATCH v12 3/3] array_sort cache ArrayMetaState

---
 src/backend/utils/adt/array_userfuncs.c | 13 ++++++++++++-
 1 file changed, 12 insertions(+), 1 deletion(-)

diff --git a/src/backend/utils/adt/array_userfuncs.c b/src/backend/utils/adt/array_userfuncs.c
index 436f761614..c14ef1ed90 100644
--- a/src/backend/utils/adt/array_userfuncs.c
+++ b/src/backend/utils/adt/array_userfuncs.c
@@ -1804,6 +1804,7 @@ typedef struct ArraySortCachedInfo
 {
 	TypeCacheEntry *typentry;
 	TypeCacheEntry *array_typentry;
+	ArrayMetaState array_meta;
 } ArraySortCachedInfo;
 
 /*
@@ -1848,6 +1849,7 @@ array_sort(PG_FUNCTION_ARGS)
 																sizeof(ArraySortCachedInfo));
 		cache_info->typentry = NULL;
 		cache_info->array_typentry = NULL;
+		memset(&cache_info->array_meta, 0, sizeof(ArrayMetaState));
 		fcinfo->flinfo->fn_extra = (void *) cache_info;
 	}
 
@@ -1864,6 +1866,10 @@ array_sort(PG_FUNCTION_ARGS)
 						 errmsg("could not identify ordering operator for type %s",
 								format_type_be(elmtyp))));
 			cache_info->typentry = typentry;
+			cache_info->array_meta.element_type = elmtyp;
+			cache_info->array_meta.typlen = typentry->typlen;
+			cache_info->array_meta.typbyval = typentry->typbyval;
+			cache_info->array_meta.typalign = typentry->typalign;
 		}
 	}
 	else
@@ -1886,6 +1892,11 @@ array_sort(PG_FUNCTION_ARGS)
 								format_type_be(array_type))));
 			cache_info->array_typentry = typentry;
 		}
+		cache_info->array_meta.element_type = elmtyp;
+		get_typlenbyvalalign(elmtyp,
+							 &cache_info->array_meta.typlen,
+							 &cache_info->array_meta.typbyval,
+							 &cache_info->array_meta.typalign);
 	}
 
 	tuplesortstate = tuplesort_begin_datum(typentry->type_id,
@@ -1893,7 +1904,7 @@ array_sort(PG_FUNCTION_ARGS)
 										   collation,
 										   false, work_mem, NULL, false);
 
-	array_iterator = array_create_iterator(array, ndim - 1, NULL);
+	array_iterator = array_create_iterator(array, ndim - 1, &cache_info->array_meta);
 	while (array_iterate(array_iterator, &value, &isnull))
 	{
 		tuplesort_putdatum(tuplesortstate, value, isnull);
-- 
2.34.1

