From d6d73fbbccd76920e09643ca46b097addb45fba8 Mon Sep 17 00:00:00 2001 From: Peter Geoghegan Date: Thu, 4 Jul 2024 16:11:04 -0400 Subject: [PATCH v1] Avoid unneeded nbtree backwards scan buffer lock. Author: Peter Geoghegan --- src/backend/access/nbtree/nbtsearch.c | 21 +++++++++++++++++---- 1 file changed, 17 insertions(+), 4 deletions(-) diff --git a/src/backend/access/nbtree/nbtsearch.c b/src/backend/access/nbtree/nbtsearch.c index 57bcfc7e4..56089bd53 100644 --- a/src/backend/access/nbtree/nbtsearch.c +++ b/src/backend/access/nbtree/nbtsearch.c @@ -1916,16 +1916,20 @@ _bt_readpage(IndexScanDesc scan, ScanDirection dir, OffsetNumber offnum, } } } + /* When !continuescan, there can't be any more matches, so stop */ if (!pstate.continuescan) - { - /* there can't be any more matches, so stop */ - so->currPos.moreLeft = false; break; - } offnum = OffsetNumberPrev(offnum); } + /* + * We don't need to visit page to the left when no more matches will + * be found there + */ + if (!pstate.continuescan || P_LEFTMOST(opaque)) + so->currPos.moreLeft = false; + Assert(itemIndex >= 0); so->currPos.firstItem = itemIndex; so->currPos.lastItem = MaxTIDsPerBTreePage - 1; @@ -2230,6 +2234,15 @@ _bt_readnextpage(IndexScanDesc scan, BlockNumber blkno, ScanDirection dir) } else { + /* Precheck: done if we know there are no matching keys to the left */ + if (!so->currPos.moreLeft) + { + _bt_parallel_done(scan); + BTScanPosUnpinIfPinned(so->currPos); + BTScanPosInvalidate(so->currPos); + return false; + } + /* * Should only happen in parallel cases, when some other backend * advanced the scan. -- 2.45.2