From d8081ae9410811a69b139d6fa314959369cb1463 Mon Sep 17 00:00:00 2001
From: Marcus Gartner <magartner@gmail.com>
Date: Thu, 30 Oct 2025 10:28:08 -0400
Subject: [PATCH] Fix LTREE subpath with negative offset

subpath(ltree,offset,len) now correctly errors when given an offset less
than -n where n is the number of labels in the given ltree. A duplicate
block of code has been removed which allowed an offset as low as -2n.
---
 contrib/ltree/expected/ltree.out | 2 ++
 contrib/ltree/ltree_op.c         | 5 -----
 contrib/ltree/sql/ltree.sql      | 1 +
 3 files changed, 3 insertions(+), 5 deletions(-)

diff --git a/contrib/ltree/expected/ltree.out b/contrib/ltree/expected/ltree.out
index c8eac3f6b21..aa53b970c6b 100644
--- a/contrib/ltree/expected/ltree.out
+++ b/contrib/ltree/expected/ltree.out
@@ -128,6 +128,8 @@ SELECT subpath('Top.Child1.Child2',1);
  Child1.Child2
 (1 row)
 
+SELECT subpath('Top.Child1.Child2',-4);
+ERROR:  invalid positions
 SELECT index('1.2.3.4.5.6','1.2');
  index 
 -------
diff --git a/contrib/ltree/ltree_op.c b/contrib/ltree/ltree_op.c
index ce9f4caad4f..167662b4749 100644
--- a/contrib/ltree/ltree_op.c
+++ b/contrib/ltree/ltree_op.c
@@ -323,11 +323,6 @@ subpath(PG_FUNCTION_ARGS)
 		start = t->numlevel + start;
 		end = start + len;
 	}
-	if (start < 0)
-	{							/* start > t->numlevel */
-		start = t->numlevel + start;
-		end = start + len;
-	}
 
 	if (len < 0)
 		end = t->numlevel + len;
diff --git a/contrib/ltree/sql/ltree.sql b/contrib/ltree/sql/ltree.sql
index dd705d9d7ca..108cfecad6f 100644
--- a/contrib/ltree/sql/ltree.sql
+++ b/contrib/ltree/sql/ltree.sql
@@ -34,6 +34,7 @@ SELECT subpath('Top.Child1.Child2',0,0);
 SELECT subpath('Top.Child1.Child2',1,0);
 SELECT subpath('Top.Child1.Child2',0);
 SELECT subpath('Top.Child1.Child2',1);
+SELECT subpath('Top.Child1.Child2',-4);
 
 
 SELECT index('1.2.3.4.5.6','1.2');
-- 
2.39.0

