From a34e6c334a9e7b51527404954417bd545bf998c6 Mon Sep 17 00:00:00 2001
From: vegebird <privacyservice@icloud.com>
Date: Wed, 26 Jan 2022 18:10:16 +0800
Subject: [PATCH 1/2] remove additional and useless loop for each relation file
 when do ptrack_get_pagemapset query reported by
 https://github.com/postgrespro/ptrack/issues/12

---
 ptrack.c | 19 ++++++++++++-------
 1 file changed, 12 insertions(+), 7 deletions(-)

diff --git a/ptrack.c b/ptrack.c
index 66f5676..e59ca2a 100644
--- a/ptrack.c
+++ b/ptrack.c
@@ -368,6 +368,14 @@ ptrack_filelist_getnext(PtScanCtx * ctx)
 		return ptrack_filelist_getnext(ctx);
 	}
 
+	if (fst.st_size == 0)
+	{
+		elog(WARNING, "ptrack: skip empty file %s", fullpath);
+
+		/* But try the next one */
+		return ptrack_filelist_getnext(ctx);
+	}
+
 	if (pfl->segno > 0)
 	{
 		ctx->relsize = pfl->segno * RELSEG_SIZE + fst.st_size / BLCKSZ;
@@ -494,7 +502,7 @@ ptrack_get_pagemapset(PG_FUNCTION_ARGS)
 		XLogRecPtr	update_lsn2;
 
 		/* Stop traversal if there are no more segments */
-		if (ctx->bid.blocknum > ctx->relsize)
+		if (ctx->bid.blocknum + 1 > ctx->relsize)
 		{
 			/* We completed a segment and there is a bitmap to return */
 			if (pagemap.bitmap != NULL)
@@ -526,12 +534,9 @@ ptrack_get_pagemapset(PG_FUNCTION_ARGS)
 				if (htup)
 					SRF_RETURN_NEXT(funcctx, HeapTupleGetDatum(htup));
 			}
-			else
-			{
-				/* We have just processed unchanged file, let's pick next */
-				if (ptrack_filelist_getnext(ctx) < 0)
-					SRF_RETURN_DONE(funcctx);
-			}
+
+			if (ptrack_filelist_getnext(ctx) < 0)
+				SRF_RETURN_DONE(funcctx);
 		}
 
 		hash = BID_HASH_FUNC(ctx->bid);

From 820380ae477bd5567872bde01984dcf84879ca66 Mon Sep 17 00:00:00 2001
From: vegebird <vegebird@users.noreply.github.com>
Date: Mon, 27 Jun 2022 19:38:44 +0800
Subject: [PATCH 2/2] Update ptrack.c

Co-authored-by: Sokolov Yura <funny.falcon@gmail.com>
---
 ptrack.c | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)

diff --git a/ptrack.c b/ptrack.c
index e59ca2a..0911339 100644
--- a/ptrack.c
+++ b/ptrack.c
@@ -502,7 +502,7 @@ ptrack_get_pagemapset(PG_FUNCTION_ARGS)
 		XLogRecPtr	update_lsn2;
 
 		/* Stop traversal if there are no more segments */
-		if (ctx->bid.blocknum + 1 > ctx->relsize)
+		if (ctx->bid.blocknum >= ctx->relsize)
 		{
 			/* We completed a segment and there is a bitmap to return */
 			if (pagemap.bitmap != NULL)