From 5e7ee4427856aa5dde4445a62337889a926c6bcb Mon Sep 17 00:00:00 2001
From: "Anton A. Melnikov" <a.melnikov@postgrespro.ru>
Date: Sun, 31 Dec 2023 14:34:57 +0300
Subject: [PATCH 2/5] Allow ordering by operator in ordered indexes

Currently the only ordered index access method is btree, which doesn't support
ordering by operator.  So, optimizer has an assumption that ordered index access
method can't support ordering by operator.  Upcoming knn-btree is going to
break this assumption.  This commit prepares optimizer for that.  Now we assume
following.

 * Index scan ordered by operator doesn't support backward scan independently
   on amcanbackward.
 * If index native ordering matches query needs then we don't consider possible
   operator ordering.

Discussion: https://postgr.es/m/ce35e97b-cf34-3f5d-6b99-2c25bae49999%40postgrespro.ru
Author: Nikita Glukhov
Reviewed-by: Robert Haas, Tom Lane, Anastasia Lubennikova, Alexander Korotkov
---
 src/backend/executor/execAmi.c        |  6 ++++++
 src/backend/executor/nodeIndexscan.c  |  6 ++----
 src/backend/optimizer/path/indxpath.c | 19 ++++++++++---------
 3 files changed, 18 insertions(+), 13 deletions(-)

diff --git a/src/backend/executor/execAmi.c b/src/backend/executor/execAmi.c
index 3289e3e0219..a6545d90046 100644
--- a/src/backend/executor/execAmi.c
+++ b/src/backend/executor/execAmi.c
@@ -553,9 +553,15 @@ ExecSupportsBackwardScan(Plan *node)
 			return false;
 
 		case T_IndexScan:
+			/* Backward ORDER BY operator scans are not supported. */
+			if (((IndexScan *) node)->indexorderby)
+				return false;
 			return IndexSupportsBackwardScan(((IndexScan *) node)->indexid);
 
 		case T_IndexOnlyScan:
+			/* Backward ORDER BY operator scans are not supported. */
+			if (((IndexOnlyScan *) node)->indexorderby)
+				return false;
 			return IndexSupportsBackwardScan(((IndexOnlyScan *) node)->indexid);
 
 		case T_SubqueryScan:
diff --git a/src/backend/executor/nodeIndexscan.c b/src/backend/executor/nodeIndexscan.c
index 8000feff4c9..b2332c03dd9 100644
--- a/src/backend/executor/nodeIndexscan.c
+++ b/src/backend/executor/nodeIndexscan.c
@@ -183,10 +183,8 @@ IndexNextWithReorder(IndexScanState *node)
 	 * Only forward scan is supported with reordering.  Note: we can get away
 	 * with just Asserting here because the system will not try to run the
 	 * plan backwards if ExecSupportsBackwardScan() says it won't work.
-	 * Currently, that is guaranteed because no index AMs support both
-	 * amcanorderbyop and amcanbackward; if any ever do,
-	 * ExecSupportsBackwardScan() will need to consider indexorderbys
-	 * explicitly.
+	 * Currently, ExecSupportsBackwardScan() simply returns false for index
+	 * plans with indexorderbys.
 	 */
 	Assert(!ScanDirectionIsBackward(((IndexScan *) node->ss.ps.plan)->indexorderdir));
 	Assert(ScanDirectionIsForward(estate->es_direction));
diff --git a/src/backend/optimizer/path/indxpath.c b/src/backend/optimizer/path/indxpath.c
index c9685a86196..36bfaab77fc 100644
--- a/src/backend/optimizer/path/indxpath.c
+++ b/src/backend/optimizer/path/indxpath.c
@@ -907,6 +907,10 @@ build_index_paths(PlannerInfo *root, RelOptInfo *rel,
 	 * many of them are actually useful for this query.  This is not relevant
 	 * if we are only trying to build bitmap indexscans.
 	 */
+	useful_pathkeys = NIL;
+	orderbyclauses = NIL;
+	orderbyclausecols = NIL;
+
 	pathkeys_possibly_useful = (scantype != ST_BITMAPSCAN &&
 								has_useful_pathkeys(root, rel));
 	index_is_ordered = (index->sortopfamily != NULL);
@@ -916,16 +920,19 @@ build_index_paths(PlannerInfo *root, RelOptInfo *rel,
 											  ForwardScanDirection);
 		useful_pathkeys = truncate_useless_pathkeys(root, rel,
 													index_pathkeys);
-		orderbyclauses = NIL;
-		orderbyclausecols = NIL;
 	}
-	else if (index->amcanorderbyop && pathkeys_possibly_useful)
+
+	if (useful_pathkeys == NIL &&
+		index->amcanorderbyop && pathkeys_possibly_useful)
 	{
 		/*
 		 * See if we can generate ordering operators for query_pathkeys or at
 		 * least some prefix thereof.  Matching to just a prefix of the
 		 * query_pathkeys will allow an incremental sort to be considered on
 		 * the index's partially sorted results.
+		 * Index  access method can be both ordered and supporting ordering by
+		 * operator.  We're looking for ordering by operator only when native
+		 * ordering doesn't match.
 		 */
 		match_pathkeys_to_index(index, root->query_pathkeys,
 								&orderbyclauses,
@@ -936,12 +943,6 @@ build_index_paths(PlannerInfo *root, RelOptInfo *rel,
 			useful_pathkeys = list_copy_head(root->query_pathkeys,
 											 list_length(orderbyclauses));
 	}
-	else
-	{
-		useful_pathkeys = NIL;
-		orderbyclauses = NIL;
-		orderbyclausecols = NIL;
-	}
 
 	/*
 	 * 3. Check if an index-only scan is possible.  If we're not building
-- 
2.45.2

