From 755bacaea00010895c2737a925fb28a2fa58bc1f Mon Sep 17 00:00:00 2001
From: "Chao Li (Evan)" <lic@highgo.com>
Date: Mon, 16 Nov 2026 20:38:27 +0800
Subject: [PATCH v1 1/2] Add a table AM method to check whether a relation is
 empty

Introduce relation_is_empty with conservative fast and exact modes.
Require AccessExclusiveLock and SnapshotSelf semantics, and
implement both modes for heap tables.

Add regression coverage for empty tables, live tuples, committed
and aborted changes, and truncation.

Author: Chao Li <lic@highgo.com>
Reviewed-by:
Discussion: https://postgr.es/m/...
---
 src/backend/access/heap/heapam_handler.c   | 34 ++++++++++
 src/backend/access/table/tableamapi.c      |  1 +
 src/include/access/tableam.h               | 23 +++++++
 src/test/regress/expected/fast_default.out | 77 ++++++++++++++++++++++
 src/test/regress/regress.c                 | 22 +++++++
 src/test/regress/sql/fast_default.sql      | 38 +++++++++++
 6 files changed, 195 insertions(+)

diff --git a/src/backend/access/heap/heapam_handler.c b/src/backend/access/heap/heapam_handler.c
index 05a81e4557a..e0e0ddd9d6b 100644
--- a/src/backend/access/heap/heapam_handler.c
+++ b/src/backend/access/heap/heapam_handler.c
@@ -46,6 +46,7 @@
 #include "storage/smgr.h"
 #include "utils/builtins.h"
 #include "utils/rel.h"
+#include "utils/snapmgr.h"
 #include "utils/tuplesort.h"
 
 static void reform_and_rewrite_tuple(HeapTuple tuple,
@@ -1991,6 +1992,38 @@ heapam_scan_get_blocks_done(HeapScanDesc hscan)
  * ------------------------------------------------------------------------
  */
 
+/*
+ * Check whether the heap contains no live tuples.  In fast mode, only a heap
+ * with no blocks is considered empty; otherwise, scan for a live tuple if
+ * necessary.  The caller must hold AccessExclusiveLock on the relation.
+ */
+static bool
+heapam_relation_is_empty(Relation rel, bool fast_decision)
+{
+	TableScanDesc scan;
+	bool		is_empty;
+
+	Assert(CheckRelationLockedByMe(rel, AccessExclusiveLock, true));
+
+	/* A relation with no blocks is certainly empty. */
+	if (RelationGetNumberOfBlocks(rel) == 0)
+		return true;
+
+	if (fast_decision)
+		return false;
+
+	/*
+	 * Look for a live tuple, including our own changes and any commits made
+	 * since the caller's snapshot was taken.  AccessExclusiveLock ensures
+	 * there are no concurrent modifications to consider.
+	 */
+	scan = table_beginscan_strat(rel, SnapshotSelf, 0, NULL, true, false);
+	is_empty = (heap_getnext(scan, ForwardScanDirection) == NULL);
+	table_endscan(scan);
+
+	return is_empty;
+}
+
 /*
  * Check to see whether the table needs a TOAST table.  It does only if
  * (1) there are any toastable attributes, and (2) the maximum length
@@ -2700,6 +2733,7 @@ static const TableAmRoutine heapam_methods = {
 	.index_validate_scan = heapam_index_validate_scan,
 
 	.relation_size = table_block_relation_size,
+	.relation_is_empty = heapam_relation_is_empty,
 	.relation_needs_toast_table = heapam_relation_needs_toast_table,
 	.relation_toast_am = heapam_relation_toast_am,
 	.relation_fetch_toast_slice = heap_fetch_toast_slice,
diff --git a/src/backend/access/table/tableamapi.c b/src/backend/access/table/tableamapi.c
index 72d2c662bf2..ab3be4d8aa0 100644
--- a/src/backend/access/table/tableamapi.c
+++ b/src/backend/access/table/tableamapi.c
@@ -86,6 +86,7 @@ GetTableAmRoutine(Oid amhandler)
 	Assert(routine->index_validate_scan != NULL);
 
 	Assert(routine->relation_size != NULL);
+	Assert(routine->relation_is_empty != NULL);
 	Assert(routine->relation_needs_toast_table != NULL);
 
 	Assert(routine->relation_estimate_size != NULL);
diff --git a/src/include/access/tableam.h b/src/include/access/tableam.h
index 9d2fc7f9acb..ac587df4deb 100644
--- a/src/include/access/tableam.h
+++ b/src/include/access/tableam.h
@@ -761,6 +761,9 @@ typedef struct TableAmRoutine
 	 */
 	uint64		(*relation_size) (Relation rel, ForkNumber forkNumber);
 
+	/* See table_relation_is_empty(). */
+	bool		(*relation_is_empty) (Relation rel, bool fast_decision);
+
 
 	/*
 	 * This callback should return true if the relation requires a TOAST table
@@ -1962,6 +1965,26 @@ table_relation_size(Relation rel, ForkNumber forkNumber)
 	return rel->rd_tableam->relation_size(rel, forkNumber);
 }
 
+/*
+ * Return true if the relation contains no live tuples.
+ *
+ * If fast_decision is true, the AM may use a conservative, inexpensive check
+ * rather than scanning the relation.  In that case, false means that the
+ * relation might not be empty.  Otherwise, the result must be exact, scanning
+ * the relation if necessary.
+ *
+ * The caller must hold AccessExclusiveLock on the relation, so that it cannot
+ * become nonempty while the result is being used.  The check must consider all
+ * committed changes and the current transaction's changes, including those
+ * made by the current command (SnapshotSelf semantics).  It must not depend on
+ * the caller's MVCC snapshot, which might not see recently committed tuples.
+ */
+static inline bool
+table_relation_is_empty(Relation rel, bool fast_decision)
+{
+	return rel->rd_tableam->relation_is_empty(rel, fast_decision);
+}
+
 /*
  * table_relation_needs_toast_table - does this relation need a toast table?
  */
diff --git a/src/test/regress/expected/fast_default.out b/src/test/regress/expected/fast_default.out
index e586abd0262..23f539f9086 100644
--- a/src/test/regress/expected/fast_default.out
+++ b/src/test/regress/expected/fast_default.out
@@ -323,6 +323,83 @@ DROP DOMAIN domain2;
 DROP DOMAIN domain3;
 DROP DOMAIN domain4;
 DROP FUNCTION foo(INT);
+-- The fast emptiness check is conservative; the exact check ignores tuples
+-- deleted by us or by committed transactions, and ignores aborted inserts.
+\getenv libdir PG_LIBDIR
+\getenv dlsuffix PG_DLSUFFIX
+\set regresslib :libdir '/regress' :dlsuffix
+CREATE FUNCTION test_table_is_empty(regclass, boolean) RETURNS boolean
+  AS :'regresslib', 'test_table_is_empty' LANGUAGE C STRICT;
+CREATE TABLE check_empty (a int) WITH (autovacuum_enabled = false);
+SELECT test_table_is_empty('check_empty', true) AS fast,
+       test_table_is_empty('check_empty', false) AS exact;
+ fast | exact 
+------+-------
+ t    | t
+(1 row)
+
+BEGIN;
+INSERT INTO check_empty VALUES (1);
+SELECT test_table_is_empty('check_empty', true) AS fast,
+       test_table_is_empty('check_empty', false) AS exact;
+ fast | exact 
+------+-------
+ f    | f
+(1 row)
+
+DELETE FROM check_empty;
+SELECT test_table_is_empty('check_empty', true) AS fast,
+       test_table_is_empty('check_empty', false) AS exact;
+ fast | exact 
+------+-------
+ f    | t
+(1 row)
+
+ROLLBACK;
+SELECT test_table_is_empty('check_empty', true) AS fast,
+       test_table_is_empty('check_empty', false) AS exact;
+ fast | exact 
+------+-------
+ f    | t
+(1 row)
+
+INSERT INTO check_empty VALUES (1);
+BEGIN;
+DELETE FROM check_empty;
+SELECT test_table_is_empty('check_empty', true) AS fast,
+       test_table_is_empty('check_empty', false) AS exact;
+ fast | exact 
+------+-------
+ f    | t
+(1 row)
+
+ROLLBACK;
+-- An aborted delete must not hide the live tuple.
+SELECT test_table_is_empty('check_empty', true) AS fast,
+       test_table_is_empty('check_empty', false) AS exact;
+ fast | exact 
+------+-------
+ f    | f
+(1 row)
+
+DELETE FROM check_empty;
+SELECT test_table_is_empty('check_empty', true) AS fast,
+       test_table_is_empty('check_empty', false) AS exact;
+ fast | exact 
+------+-------
+ f    | t
+(1 row)
+
+TRUNCATE check_empty;
+SELECT test_table_is_empty('check_empty', true) AS fast,
+       test_table_is_empty('check_empty', false) AS exact;
+ fast | exact 
+------+-------
+ t    | t
+(1 row)
+
+DROP TABLE check_empty;
+DROP FUNCTION test_table_is_empty(regclass, boolean);
 -- Fall back to full rewrite for volatile expressions
 CREATE TABLE T(pk INT NOT NULL PRIMARY KEY);
 INSERT INTO T VALUES (1);
diff --git a/src/test/regress/regress.c b/src/test/regress/regress.c
index 6e61c0d201b..9a8d090d6e5 100644
--- a/src/test/regress/regress.c
+++ b/src/test/regress/regress.c
@@ -21,6 +21,8 @@
 
 #include "access/detoast.h"
 #include "access/htup_details.h"
+#include "access/table.h"
+#include "access/tableam.h"
 #include "catalog/catalog.h"
 #include "catalog/namespace.h"
 #include "catalog/pg_operator.h"
@@ -1744,3 +1746,23 @@ test_pg_locale_apis(PG_FUNCTION_ARGS)
 
 	PG_RETURN_VOID();
 }
+
+/*
+ * Test both modes of the table AM's emptiness check.
+ */
+PG_FUNCTION_INFO_V1(test_table_is_empty);
+Datum
+test_table_is_empty(PG_FUNCTION_ARGS)
+{
+	Relation	rel;
+	bool		is_empty;
+
+	rel = table_open(PG_GETARG_OID(0), AccessExclusiveLock);
+	if (!RELKIND_HAS_TABLE_AM(rel->rd_rel->relkind))
+		elog(ERROR, "relation \"%s\" does not have a table access method",
+			 RelationGetRelationName(rel));
+	is_empty = table_relation_is_empty(rel, PG_GETARG_BOOL(1));
+	table_close(rel, NoLock);
+
+	PG_RETURN_BOOL(is_empty);
+}
diff --git a/src/test/regress/sql/fast_default.sql b/src/test/regress/sql/fast_default.sql
index fdeb7d147b4..127475b5e42 100644
--- a/src/test/regress/sql/fast_default.sql
+++ b/src/test/regress/sql/fast_default.sql
@@ -294,6 +294,44 @@ DROP DOMAIN domain3;
 DROP DOMAIN domain4;
 DROP FUNCTION foo(INT);
 
+-- The fast emptiness check is conservative; the exact check ignores tuples
+-- deleted by us or by committed transactions, and ignores aborted inserts.
+\getenv libdir PG_LIBDIR
+\getenv dlsuffix PG_DLSUFFIX
+\set regresslib :libdir '/regress' :dlsuffix
+CREATE FUNCTION test_table_is_empty(regclass, boolean) RETURNS boolean
+  AS :'regresslib', 'test_table_is_empty' LANGUAGE C STRICT;
+CREATE TABLE check_empty (a int) WITH (autovacuum_enabled = false);
+SELECT test_table_is_empty('check_empty', true) AS fast,
+       test_table_is_empty('check_empty', false) AS exact;
+BEGIN;
+INSERT INTO check_empty VALUES (1);
+SELECT test_table_is_empty('check_empty', true) AS fast,
+       test_table_is_empty('check_empty', false) AS exact;
+DELETE FROM check_empty;
+SELECT test_table_is_empty('check_empty', true) AS fast,
+       test_table_is_empty('check_empty', false) AS exact;
+ROLLBACK;
+SELECT test_table_is_empty('check_empty', true) AS fast,
+       test_table_is_empty('check_empty', false) AS exact;
+INSERT INTO check_empty VALUES (1);
+BEGIN;
+DELETE FROM check_empty;
+SELECT test_table_is_empty('check_empty', true) AS fast,
+       test_table_is_empty('check_empty', false) AS exact;
+ROLLBACK;
+-- An aborted delete must not hide the live tuple.
+SELECT test_table_is_empty('check_empty', true) AS fast,
+       test_table_is_empty('check_empty', false) AS exact;
+DELETE FROM check_empty;
+SELECT test_table_is_empty('check_empty', true) AS fast,
+       test_table_is_empty('check_empty', false) AS exact;
+TRUNCATE check_empty;
+SELECT test_table_is_empty('check_empty', true) AS fast,
+       test_table_is_empty('check_empty', false) AS exact;
+DROP TABLE check_empty;
+DROP FUNCTION test_table_is_empty(regclass, boolean);
+
 -- Fall back to full rewrite for volatile expressions
 CREATE TABLE T(pk INT NOT NULL PRIMARY KEY);
 
-- 
2.50.1 (Apple Git-155)

