From b92679dc82f6e30b44cea2fc5601d639a9e765b5 Mon Sep 17 00:00:00 2001
From: Manu <manuelreyesbravo@gmail.com>
Date: Sun, 6 Dec 2026 01:35:45 -0300
Subject: [PATCH v4 2/3] Sort only the new partition bounds into the previous
 ones

With 0001, the bounds of the partitions taken from the previous
descriptor are already in order, but partition_bounds_create() still
sorts all of them, which for text keys means O(N log N) strcoll()
calls on every rebuild.  Sort only the new bounds and insert each into
the known ones with a binary search.  Bounds of different partitions
never compare equal, so the result is the same; assert-enabled builds
check that the known part is in order.
---
 src/backend/partitioning/partbounds.c | 106 +++++++++++++++++++++++---
 1 file changed, 97 insertions(+), 9 deletions(-)

diff --git a/src/backend/partitioning/partbounds.c b/src/backend/partitioning/partbounds.c
index a386b117738..51b5d34a689 100644
--- a/src/backend/partitioning/partbounds.c
+++ b/src/backend/partitioning/partbounds.c
@@ -107,6 +107,11 @@ static PartitionBoundInfo create_range_bounds(PartitionBoundSpec **boundspecs,
 											  int nparts, PartitionBoundsHint *hint,
 											  PartitionKey key, int **mapping);
 static int *hint_new_index(PartitionBoundsHint *hint, int *size);
+static int	qsort_partition_hbound_cmp_arg(const void *a, const void *b,
+										   void *arg);
+static void partition_bounds_sort(void *base, size_t nel, size_t known,
+								  size_t size, qsort_arg_comparator cmp,
+								  void *arg);
 static PartitionBoundInfo merge_list_bounds(FmgrInfo *partsupfunc,
 											Oid *partcollation,
 											RelOptInfo *outer_rel,
@@ -412,8 +417,9 @@ create_hash_bounds(PartitionBoundSpec **boundspecs, int nparts,
 	}
 
 	/* Sort all the bounds in ascending order */
-	qsort(hbounds, nparts, sizeof(PartitionHashBound),
-		  qsort_partition_hbound_cmp);
+	partition_bounds_sort(hbounds, nparts, hint ? hint->nprev : 0,
+						  sizeof(PartitionHashBound),
+						  qsort_partition_hbound_cmp_arg, NULL);
 
 	/* After sorting, moduli are now stored in ascending order. */
 	greatest_modulus = hbounds[nparts - 1].modulus;
@@ -611,8 +617,9 @@ create_list_bounds(PartitionBoundSpec **boundspecs, int nparts,
 	/* ensure we found a Datum for every slot in the all_values array */
 	Assert(j == ndatums);
 
-	qsort_arg(all_values, ndatums, sizeof(PartitionListValue),
-			  qsort_partition_list_value_cmp, key);
+	partition_bounds_sort(all_values, ndatums, nfromprev,
+						  sizeof(PartitionListValue),
+						  qsort_partition_list_value_cmp, key);
 
 	boundinfo->ndatums = ndatums;
 	boundinfo->datums = palloc0_array(Datum *, ndatums);
@@ -773,6 +780,7 @@ create_range_bounds(PartitionBoundSpec **boundspecs, int nparts,
 	Datum	   *boundDatums;
 	PartitionRangeDatumKind *boundKinds;
 	int			nprev = hint ? hint->nprev : 0;
+	int			nfromprev = 0;
 
 	boundinfo = palloc0_object(PartitionBoundInfoData);
 	boundinfo->strategy = key->strategy;
@@ -788,7 +796,8 @@ create_range_bounds(PartitionBoundSpec **boundspecs, int nparts,
 	 * Take the bounds of the partitions known from the previous bound info
 	 * from there.  A partition's upper bound is the datum whose index entry
 	 * is the partition, and its lower bound is the datum just before that one
-	 * (which may be the upper bound of the partition before it).
+	 * (which may be the upper bound of the partition before it).  In
+	 * canonical order these bounds are sorted already.
 	 */
 	if (nprev > 0)
 	{
@@ -842,6 +851,7 @@ create_range_bounds(PartitionBoundSpec **boundspecs, int nparts,
 			all_bounds[ndatums++] = lower;
 			all_bounds[ndatums++] = upper;
 		}
+		nfromprev = ndatums;
 		pfree(newidx);
 		pfree(upper_at);
 	}
@@ -877,10 +887,10 @@ create_range_bounds(PartitionBoundSpec **boundspecs, int nparts,
 		   (default_index != -1 && ndatums == (nparts - 1) * 2));
 
 	/* Sort all the bounds in ascending order */
-	qsort_arg(all_bounds, ndatums,
-			  sizeof(PartitionRangeBound *),
-			  qsort_partition_rbound_cmp,
-			  key);
+	partition_bounds_sort(all_bounds, ndatums, nfromprev,
+						  sizeof(PartitionRangeBound *),
+						  qsort_partition_rbound_cmp,
+						  key);
 
 	/* Save distinct bounds from all_bounds into rbounds. */
 	rbounds = palloc_array(PartitionRangeBound *, ndatums);
@@ -3930,6 +3940,12 @@ qsort_partition_hbound_cmp(const void *a, const void *b)
 								h2->modulus, h2->remainder);
 }
 
+static int
+qsort_partition_hbound_cmp_arg(const void *a, const void *b, void *arg)
+{
+	return qsort_partition_hbound_cmp(a, b);
+}
+
 /*
  * hint_new_index
  *		Map canonical indexes in hint->prev to indexes in the new boundspecs.
@@ -3954,6 +3970,78 @@ hint_new_index(PartitionBoundsHint *hint, int *size)
 	return newidx;
 }
 
+/*
+ * partition_bounds_sort
+ *		Sort the bounds of all partitions, given that the first known ones are
+ *		sorted already.
+ *
+ * The bounds taken from a previous bound info come first and are in order;
+ * usually only a few new ones follow.  Sort those, and insert each into the
+ * sorted part with a binary search, which costs about nel moves and
+ * (nel - known) * log2(nel) comparisons instead of nel * log2(nel)
+ * comparisons.  Since bounds of different partitions never compare equal,
+ * the result is the same as sorting the whole array.
+ */
+static void
+partition_bounds_sort(void *base, size_t nel, size_t known, size_t size,
+					  qsort_arg_comparator cmp, void *arg)
+{
+	char	   *a = (char *) base;
+	char	   *out;
+	size_t		lo;
+	size_t		nout;
+
+#define ELEM(i) (a + (i) * size)
+
+	if (known == 0 || nel < 2)
+	{
+		qsort_arg(a, nel, size, cmp, arg);
+		return;
+	}
+
+#ifdef USE_ASSERT_CHECKING
+	for (size_t i = 1; i < known; i++)
+		Assert(cmp(ELEM(i - 1), ELEM(i), arg) < 0);
+#endif
+
+	if (known == nel)
+		return;
+
+	qsort_arg(ELEM(known), nel - known, size, cmp, arg);
+
+	out = palloc(nel * size);
+	nout = 0;
+	lo = 0;
+	for (size_t t = known; t < nel; t++)
+	{
+		size_t		l = lo,
+					h = known;
+
+		/* first element of the rest of the sorted part greater than ELEM(t) */
+		while (l < h)
+		{
+			size_t		m = l + (h - l) / 2;
+
+			if (cmp(ELEM(m), ELEM(t), arg) < 0)
+				l = m + 1;
+			else
+				h = m;
+		}
+		memcpy(out + nout * size, ELEM(lo), (l - lo) * size);
+		nout += l - lo;
+		memcpy(out + nout * size, ELEM(t), size);
+		nout++;
+		lo = l;
+	}
+	memcpy(out + nout * size, ELEM(lo), (known - lo) * size);
+	nout += known - lo;
+	Assert(nout == nel);
+	memcpy(a, out, nel * size);
+	pfree(out);
+
+#undef ELEM
+}
+
 /*
  * qsort_partition_list_value_cmp
  *
-- 
2.56.1

