Skip to content

Commit 7632ef5

Browse files
committed
Fix hypothetical bug in heap backward scans
Both heapgettup() and heapgettup_pagemode() incorrectly set the first page to scan in a backward scan in which the number of pages to scan was specified by heap_setscanlimits(). The code incorrectly started the scan at the end of the relation when startBlk was 0, or otherwise at startBlk - 1, neither of which is correct when only scanning a subset of pages. The fix here checks if heap_setscanlimits() has changed the number of pages to scan and if so we set the first page to scan as the final page in the specified range during backward scans. Proper adjustment of this code was forgotten when heap_setscanlimits() was added in 7516f52 back in 9.5. However, practice, nowhere in core code performs backward scans after having used heap_setscanlimits(), yet, it is possible an extension uses the heap functions in this way, hence backpatch. An upcoming patch does use heap_setscanlimits() with backward scans, so this must be fixed before that can go in. Author: David Rowley Discussion: https://postgr.es/m/CAApHDvpGc9h0_oVD2CtgBcxCS1N-qDYZSeBRnUh+0CWJA9cMaA@mail.gmail.com Backpatch-through: 9.5, all supported versions
1 parent 58a5453 commit 7632ef5

File tree

1 file changed

+16
-4
lines changed

1 file changed

+16
-4
lines changed

src/backend/access/heap/heapam.c

Lines changed: 16 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -582,8 +582,14 @@ heapgettup(HeapScanDesc scan,
582582
* forward scanners.
583583
*/
584584
scan->rs_base.rs_flags &= ~SO_ALLOW_SYNC;
585-
/* start from last page of the scan */
586-
if (scan->rs_startblock > 0)
585+
586+
/*
587+
* Start from last page of the scan. Ensure we take into account
588+
* rs_numblocks if it's been adjusted by heap_setscanlimits().
589+
*/
590+
if (scan->rs_numblocks != InvalidBlockNumber)
591+
page = (scan->rs_startblock + scan->rs_numblocks - 1) % scan->rs_nblocks;
592+
else if (scan->rs_startblock > 0)
587593
page = scan->rs_startblock - 1;
588594
else
589595
page = scan->rs_nblocks - 1;
@@ -893,8 +899,14 @@ heapgettup_pagemode(HeapScanDesc scan,
893899
* forward scanners.
894900
*/
895901
scan->rs_base.rs_flags &= ~SO_ALLOW_SYNC;
896-
/* start from last page of the scan */
897-
if (scan->rs_startblock > 0)
902+
903+
/*
904+
* Start from last page of the scan. Ensure we take into account
905+
* rs_numblocks if it's been adjusted by heap_setscanlimits().
906+
*/
907+
if (scan->rs_numblocks != InvalidBlockNumber)
908+
page = (scan->rs_startblock + scan->rs_numblocks - 1) % scan->rs_nblocks;
909+
else if (scan->rs_startblock > 0)
898910
page = scan->rs_startblock - 1;
899911
else
900912
page = scan->rs_nblocks - 1;

0 commit comments

Comments
 (0)