From 7ffe657225ad38b912688769ffb58e3d450ef17d Mon Sep 17 00:00:00 2001
From: Heikki Linnakangas <heikki.linnakangas@iki.fi>
Date: Tue, 6 Jan 2009 14:55:37 +0000
Subject: [PATCH] Fix logic in lazy vacuum to decide if it's worth trying to
 truncate the heap. If the table was smaller than REL_TRUNCATE_FRACTION (= 16)
 pages, we always tried to acquire AccessExclusiveLock on it even if there was
 no empty pages at the end.

Report by Simon Riggs. Back-patch all the way to 7.4.
---
 src/backend/commands/vacuumlazy.c | 7 ++++---
 1 file changed, 4 insertions(+), 3 deletions(-)

diff --git a/src/backend/commands/vacuumlazy.c b/src/backend/commands/vacuumlazy.c
index 9856ee9d6e..4a009a62e7 100644
--- a/src/backend/commands/vacuumlazy.c
+++ b/src/backend/commands/vacuumlazy.c
@@ -29,7 +29,7 @@
  *
  *
  * IDENTIFICATION
- *	  $PostgreSQL: pgsql/src/backend/commands/vacuumlazy.c,v 1.115 2009/01/01 17:23:40 momjian Exp $
+ *	  $PostgreSQL: pgsql/src/backend/commands/vacuumlazy.c,v 1.116 2009/01/06 14:55:37 heikki Exp $
  *
  *-------------------------------------------------------------------------
  */
@@ -183,8 +183,9 @@ lazy_vacuum_rel(Relation onerel, VacuumStmt *vacstmt,
 	 * number of pages.  Otherwise, the time taken isn't worth it.
 	 */
 	possibly_freeable = vacrelstats->rel_pages - vacrelstats->nonempty_pages;
-	if (possibly_freeable >= REL_TRUNCATE_MINIMUM ||
-		possibly_freeable >= vacrelstats->rel_pages / REL_TRUNCATE_FRACTION)
+	if (possibly_freeable > 0 &&
+		(possibly_freeable >= REL_TRUNCATE_MINIMUM ||
+		 possibly_freeable >= vacrelstats->rel_pages / REL_TRUNCATE_FRACTION))
 		lazy_truncate_heap(onerel, vacrelstats);
 
 	/* Vacuum the Free Space Map */