From 0c3c1bb44ea532db7d06952a79b48efd5e3f034e Mon Sep 17 00:00:00 2001
From: Aidar Imamov <imamovaj22@gmail.com>
Date: Wed, 25 Nov 2026 19:18:45 +0300
Subject: [PATCH] Use the table AM relation_size callback in the SQL size
 functions

pg_relation_size() and pg_table_size() measure a relation by summing up
its files.  That works for heap, but a table AM can add files next to
the standard forks, named after the relation's relfilenode, and then the
functions report 0 while pg_database_size() sees the files just fine.

Ask a custom table AM for the main fork instead, in pg_relation_size(),
pg_table_size() and pg_total_relation_size(), and do the same for the
toast table's main fork, since relation_toast_am() can point to a
different AM.  Heap keeps the file-based measurement: heapam's callback
goes through smgr, which raises an error where the size functions have
always returned zero, as with an unlogged table on a standby.  Other
forks, indexes and relations without a table AM are left alone.

The callback is user-visible now, so document what it should return: the
physical footprint of the relation's own storage for MAIN_FORKNUM,
without the toast table and its indexes, the overall footprint for
InvalidForkNumber, and file sizes for the other forks.  There is a
sentence about it in the docs as well.

Add src/test/modules/dummy_table_am, a copy of heapam whose
relation_size() returns half of the heap footprint, with a test that
checks the size functions return that number and count it once instead
of adding it to the file sizes.
---
 doc/src/sgml/func/func-admin.sgml             | 10 ++-
 src/backend/utils/adt/dbsize.c                | 69 ++++++++++++++++--
 src/include/access/tableam.h                  |  8 ++
 src/test/modules/Makefile                     |  1 +
 src/test/modules/dummy_table_am/Makefile      | 20 +++++
 src/test/modules/dummy_table_am/README        | 13 ++++
 .../dummy_table_am/dummy_table_am--1.0.sql    | 12 +++
 .../modules/dummy_table_am/dummy_table_am.c   | 57 +++++++++++++++
 .../dummy_table_am/dummy_table_am.control     |  5 ++
 .../expected/dummy_table_am.out               | 73 +++++++++++++++++++
 src/test/modules/dummy_table_am/meson.build   | 33 +++++++++
 .../dummy_table_am/sql/dummy_table_am.sql     | 44 +++++++++++
 src/test/modules/meson.build                  |  1 +
 13 files changed, 337 insertions(+), 9 deletions(-)
 create mode 100644 src/test/modules/dummy_table_am/Makefile
 create mode 100644 src/test/modules/dummy_table_am/README
 create mode 100644 src/test/modules/dummy_table_am/dummy_table_am--1.0.sql
 create mode 100644 src/test/modules/dummy_table_am/dummy_table_am.c
 create mode 100644 src/test/modules/dummy_table_am/dummy_table_am.control
 create mode 100644 src/test/modules/dummy_table_am/expected/dummy_table_am.out
 create mode 100644 src/test/modules/dummy_table_am/meson.build
 create mode 100644 src/test/modules/dummy_table_am/sql/dummy_table_am.sql

diff --git a/doc/src/sgml/func/func-admin.sgml b/doc/src/sgml/func/func-admin.sgml
index ed872264f02..c6268245d09 100644
--- a/doc/src/sgml/func/func-admin.sgml
+++ b/doc/src/sgml/func/func-admin.sgml
@@ -1682,6 +1682,12 @@ postgres=# SELECT '0/0'::pg_lsn + pd.segment_number * ps.setting::int + :offset
           </para>
          </listitem>
         </itemizedlist>
+       </para>
+       <para>
+        The size of the main fork is reported by the relation's table access
+        method, which may keep its data somewhere other than the relation's
+        main fork; the other forks are measured from the size of their files
+        on disk.
        </para></entry>
       </row>
 
@@ -1733,7 +1739,9 @@ postgres=# SELECT '0/0'::pg_lsn + pd.segment_number * ps.setting::int + :offset
        <para>
         Computes the disk space used by the specified table, excluding indexes
         (but including its TOAST table if any, free space map, and visibility
-        map).
+        map).  The size of the table itself is reported by its table access
+        method; the TOAST table, free space map and visibility map are added
+        to that.
        </para></entry>
       </row>
 
diff --git a/src/backend/utils/adt/dbsize.c b/src/backend/utils/adt/dbsize.c
index cccc4a24c84..e98146eb8de 100644
--- a/src/backend/utils/adt/dbsize.c
+++ b/src/backend/utils/adt/dbsize.c
@@ -15,6 +15,7 @@
 
 #include "access/htup_details.h"
 #include "access/relation.h"
+#include "access/tableam.h"
 #include "catalog/namespace.h"
 #include "catalog/pg_authid.h"
 #include "catalog/pg_database.h"
@@ -319,6 +320,10 @@ pg_tablespace_size_name(PG_FUNCTION_ARGS)
 /*
  * calculate size of (one fork of) a relation
  *
+ * This measures the fork's files directly.  It is used for relations that
+ * have no table access method (indexes, partitioned tables) and for the
+ * forks that are not the main one.
+ *
  * Note: we can safely apply this to temp tables of other sessions, so there
  * is no check here or at the call sites for that.
  */
@@ -360,12 +365,40 @@ calculate_relation_size(RelFileLocator *rfn, ProcNumber backend, ForkNumber fork
 	return totalsize;
 }
 
+/*
+ * Calculate the size of the main fork of a relation.
+ *
+ * For a custom table AM the size of the main fork is provided by the AM.
+ * A table AM may store its data outside the standard main fork (for
+ * example, in additional files of its own), so only the AM itself can
+ * account for all of it.  Relations without a table access method (e.g.
+ * indexes, partitioned tables) are measured by summing up the sizes of
+ * their main fork files on disk.
+ *
+ * The built-in heap AM keeps that file-based measurement as well.  Its
+ * relation_size callback goes through smgr, which raises an error when the
+ * main fork file does not exist, while the size functions have always
+ * reported zero in that case -- an unlogged table on a standby being the
+ * typical example.
+ */
+static int64
+calculate_main_relation_size(Relation rel)
+{
+	if (rel->rd_tableam == NULL ||
+		rel->rd_tableam == GetHeapamTableAmRoutine())
+		return calculate_relation_size(&(rel->rd_locator), rel->rd_backend,
+									   MAIN_FORKNUM);
+
+	return (int64) table_relation_size(rel, MAIN_FORKNUM);
+}
+
 Datum
 pg_relation_size(PG_FUNCTION_ARGS)
 {
 	Oid			relOid = PG_GETARG_OID(0);
 	text	   *forkName = PG_GETARG_TEXT_PP(1);
 	Relation	rel;
+	ForkNumber	forknum;
 	int64		size;
 
 	rel = try_relation_open(relOid, AccessShareLock);
@@ -380,8 +413,13 @@ pg_relation_size(PG_FUNCTION_ARGS)
 	if (rel == NULL)
 		PG_RETURN_NULL();
 
-	size = calculate_relation_size(&(rel->rd_locator), rel->rd_backend,
-								   forkname_to_number(text_to_cstring(forkName)));
+	forknum = forkname_to_number(text_to_cstring(forkName));
+
+	if (forknum == MAIN_FORKNUM)
+		size = calculate_main_relation_size(rel);
+	else
+		size = calculate_relation_size(&(rel->rd_locator), rel->rd_backend,
+									   forknum);
 
 	relation_close(rel, AccessShareLock);
 
@@ -403,10 +441,15 @@ calculate_toast_table_size(Oid toastrelid)
 
 	toastRel = relation_open(toastrelid, AccessShareLock);
 
-	/* toast heap size, including FSM and VM size */
+	/* toast table size, including FSM and VM size */
 	for (forkNum = 0; forkNum <= MAX_FORKNUM; forkNum++)
-		size += calculate_relation_size(&(toastRel->rd_locator),
-										toastRel->rd_backend, forkNum);
+	{
+		if (forkNum == MAIN_FORKNUM)
+			size += calculate_main_relation_size(toastRel);
+		else
+			size += calculate_relation_size(&(toastRel->rd_locator),
+											toastRel->rd_backend, forkNum);
+	}
 
 	/* toast index size, including FSM and VM size */
 	indexlist = RelationGetIndexList(toastRel);
@@ -445,11 +488,21 @@ calculate_table_size(Relation rel)
 	ForkNumber	forkNum;
 
 	/*
-	 * heap size, including FSM and VM
+	 * relation size, including FSM and VM.  The main fork comes from the
+	 * relation's table access method, the other forks are measured from
+	 * their files.  This deliberately does not ask the AM for the overall
+	 * size: an AM's answer for that need not be the sum of the per-fork
+	 * sizes (table_block_relation_size() leaves out the init fork, for
+	 * instance), and pg_table_size() has always added up the forks.
 	 */
 	for (forkNum = 0; forkNum <= MAX_FORKNUM; forkNum++)
-		size += calculate_relation_size(&(rel->rd_locator), rel->rd_backend,
-										forkNum);
+	{
+		if (forkNum == MAIN_FORKNUM)
+			size += calculate_main_relation_size(rel);
+		else
+			size += calculate_relation_size(&(rel->rd_locator),
+											rel->rd_backend, forkNum);
+	}
 
 	/*
 	 * Size of toast relation
diff --git a/src/include/access/tableam.h b/src/include/access/tableam.h
index 9d2fc7f9acb..3359a9c03a2 100644
--- a/src/include/access/tableam.h
+++ b/src/include/access/tableam.h
@@ -754,6 +754,14 @@ typedef struct TableAmRoutine
 	/*
 	 * See table_relation_size().
 	 *
+	 * For MAIN_FORKNUM the callback reports the physical footprint of the
+	 * relation's own storage, including whatever the AM keeps outside the
+	 * main fork -- this is what pg_relation_size() returns to the user.  It
+	 * must not include the relation's TOAST table or its indexes; the
+	 * SQL-level size functions add those separately.  For InvalidForkNumber
+	 * it reports the relation's overall footprint.  For the other forks a
+	 * block-oriented AM reports the size of the corresponding files.
+	 *
 	 * Note that currently a few callers use the MAIN_FORKNUM size to figure
 	 * out the range of potentially interesting blocks (brin, analyze). It's
 	 * probable that we'll need to revise the interface for those at some
diff --git a/src/test/modules/Makefile b/src/test/modules/Makefile
index 6c1504ac932..77d4e016411 100644
--- a/src/test/modules/Makefile
+++ b/src/test/modules/Makefile
@@ -10,6 +10,7 @@ SUBDIRS = \
 		  delay_execution \
 		  dummy_index_am \
 		  dummy_seclabel \
+		  dummy_table_am \
 		  index \
 		  libpq_pipeline \
 		  oauth_validator \
diff --git a/src/test/modules/dummy_table_am/Makefile b/src/test/modules/dummy_table_am/Makefile
new file mode 100644
index 00000000000..9ea4a590c67
--- /dev/null
+++ b/src/test/modules/dummy_table_am/Makefile
@@ -0,0 +1,20 @@
+# src/test/modules/dummy_table_am/Makefile
+
+MODULES = dummy_table_am
+
+EXTENSION = dummy_table_am
+DATA = dummy_table_am--1.0.sql
+PGFILEDESC = "dummy_table_am - table access method template"
+
+REGRESS = dummy_table_am
+
+ifdef USE_PGXS
+PG_CONFIG = pg_config
+PGXS := $(shell $(PG_CONFIG) --pgxs)
+include $(PGXS)
+else
+subdir = src/test/modules/dummy_table_am
+top_builddir = ../../../..
+include $(top_builddir)/src/Makefile.global
+include $(top_srcdir)/contrib/contrib-global.mk
+endif
diff --git a/src/test/modules/dummy_table_am/README b/src/test/modules/dummy_table_am/README
new file mode 100644
index 00000000000..a5a971d0374
--- /dev/null
+++ b/src/test/modules/dummy_table_am/README
@@ -0,0 +1,13 @@
+Dummy Table AM
+==============
+
+Dummy table AM is a module for testing any facility usable by a table access
+method.  The routine is a copy of the heap one with a few callbacks replaced,
+so that a table created with this access method has real storage while the
+answers the core gets from the AM are easy to predict.
+
+Currently it only overrides relation_size(), which reports half of the heap
+footprint for the main fork.  The number tracks the relation's real size but
+is never equal to it, so the SQL-level size functions can be told apart from
+plain file measurement, while RelationGetNumberOfBlocks() still stays within
+the relation.
diff --git a/src/test/modules/dummy_table_am/dummy_table_am--1.0.sql b/src/test/modules/dummy_table_am/dummy_table_am--1.0.sql
new file mode 100644
index 00000000000..8f6b526b563
--- /dev/null
+++ b/src/test/modules/dummy_table_am/dummy_table_am--1.0.sql
@@ -0,0 +1,12 @@
+/* src/test/modules/dummy_table_am/dummy_table_am--1.0.sql */
+
+-- complain if script is sourced in psql, rather than via CREATE EXTENSION
+\echo Use "CREATE EXTENSION dummy_table_am" to load this file. \quit
+
+CREATE FUNCTION dummy_table_am_handler(internal)
+RETURNS table_am_handler
+AS 'MODULE_PATHNAME'
+LANGUAGE C;
+
+-- Access method
+CREATE ACCESS METHOD dummy_table_am TYPE TABLE HANDLER dummy_table_am_handler;
diff --git a/src/test/modules/dummy_table_am/dummy_table_am.c b/src/test/modules/dummy_table_am/dummy_table_am.c
new file mode 100644
index 00000000000..8016a07dd73
--- /dev/null
+++ b/src/test/modules/dummy_table_am/dummy_table_am.c
@@ -0,0 +1,57 @@
+/*-------------------------------------------------------------------------
+ *
+ * dummy_table_am.c
+ *		A dummy table access method for testing.
+ *
+ * The routine is the heap one with a few callbacks replaced, so that a table
+ * created with this access method has real storage while the answers the
+ * core gets from the AM are trivial to predict.
+ *
+ * Portions Copyright (c) 1996-2026, PostgreSQL Global Development Group
+ * Portions Copyright (c) 1994, Regents of the University of California
+ *
+ * IDENTIFICATION
+ *		src/test/modules/dummy_table_am/dummy_table_am.c
+ *
+ *-------------------------------------------------------------------------
+ */
+#include "postgres.h"
+
+#include "access/tableam.h"
+#include "fmgr.h"
+
+PG_MODULE_MAGIC;
+
+/*
+ * Report half of the heap footprint for the main fork.  The number tracks
+ * the relation's real size but is never equal to it, so the SQL-level size
+ * functions can be told apart from plain file measurement.  Reporting more
+ * than the heap size would make RelationGetNumberOfBlocks() point past the
+ * end of the relation, so it is capped at the real size.
+ */
+static uint64
+dummy_relation_size(Relation rel, ForkNumber forknum)
+{
+	if (forknum == MAIN_FORKNUM || forknum == InvalidForkNumber)
+		return table_block_relation_size(rel, MAIN_FORKNUM) / 2;
+
+	return table_block_relation_size(rel, forknum);
+}
+
+PG_FUNCTION_INFO_V1(dummy_table_am_handler);
+
+Datum
+dummy_table_am_handler(PG_FUNCTION_ARGS)
+{
+	static TableAmRoutine routine;
+	static bool initialized = false;
+
+	if (!initialized)
+	{
+		memcpy(&routine, GetHeapamTableAmRoutine(), sizeof(TableAmRoutine));
+		routine.relation_size = dummy_relation_size;
+		initialized = true;
+	}
+
+	PG_RETURN_POINTER(&routine);
+}
diff --git a/src/test/modules/dummy_table_am/dummy_table_am.control b/src/test/modules/dummy_table_am/dummy_table_am.control
new file mode 100644
index 00000000000..08f2f868d49
--- /dev/null
+++ b/src/test/modules/dummy_table_am/dummy_table_am.control
@@ -0,0 +1,5 @@
+# dummy_table_am extension
+comment = 'dummy_table_am - table access method template'
+default_version = '1.0'
+module_pathname = '$libdir/dummy_table_am'
+relocatable = true
diff --git a/src/test/modules/dummy_table_am/expected/dummy_table_am.out b/src/test/modules/dummy_table_am/expected/dummy_table_am.out
new file mode 100644
index 00000000000..327f71283ab
--- /dev/null
+++ b/src/test/modules/dummy_table_am/expected/dummy_table_am.out
@@ -0,0 +1,73 @@
+-- Tests for the SQL-level size functions with a table AM
+CREATE EXTENSION dummy_table_am;
+-- The AM reports half of the heap footprint for the main fork, so the size
+-- functions must not report the relation's file sizes.
+CREATE TABLE dummy_table_am_tab (a int) USING dummy_table_am;
+CREATE TABLE dummy_table_am_heap (a int);
+INSERT INTO dummy_table_am_tab SELECT generate_series(1, 1000);
+INSERT INTO dummy_table_am_heap SELECT generate_series(1, 1000);
+-- Both tables use the same amount of storage, and the AM reports half of it.
+SELECT pg_relation_size('dummy_table_am_tab') =
+       pg_relation_size('dummy_table_am_heap') / 2 AS half_of_heap;
+ half_of_heap 
+--------------
+ t
+(1 row)
+
+SELECT pg_relation_size('dummy_table_am_tab') <>
+       pg_relation_size('dummy_table_am_heap') AS differs_from_heap;
+ differs_from_heap 
+-------------------
+ t
+(1 row)
+
+-- The other forks are still measured from their files; the inserts above
+-- already created the fsm fork.
+SELECT pg_relation_size('dummy_table_am_tab', 'fsm') > 0 AS fsm_exists,
+       pg_relation_size('dummy_table_am_tab', 'vm') = 0 AS no_vm_yet;
+ fsm_exists | no_vm_yet 
+------------+-----------
+ t          | t
+(1 row)
+
+-- The AM's answer is counted exactly once, not added to the file sizes:
+-- pg_table_size() is the AM's answer plus the other forks.
+SELECT pg_table_size('dummy_table_am_tab') =
+       pg_relation_size('dummy_table_am_tab')
+       + pg_relation_size('dummy_table_am_tab', 'fsm')
+       + pg_relation_size('dummy_table_am_tab', 'vm')
+       + pg_relation_size('dummy_table_am_tab', 'init')
+       AS table_size_counts_forks;
+ table_size_counts_forks 
+-------------------------
+ t
+(1 row)
+
+SELECT pg_total_relation_size('dummy_table_am_tab') =
+       pg_table_size('dummy_table_am_tab') AS total_size_exact;
+ total_size_exact 
+------------------
+ t
+(1 row)
+
+-- After VACUUM the vm fork appears as well, and the same identity holds.
+VACUUM dummy_table_am_tab;
+SELECT pg_relation_size('dummy_table_am_tab', 'vm') > 0 AS vm_exists;
+ vm_exists 
+-----------
+ t
+(1 row)
+
+SELECT pg_table_size('dummy_table_am_tab') =
+       pg_relation_size('dummy_table_am_tab')
+       + pg_relation_size('dummy_table_am_tab', 'fsm')
+       + pg_relation_size('dummy_table_am_tab', 'vm')
+       + pg_relation_size('dummy_table_am_tab', 'init')
+       AS table_size_counts_forks;
+ table_size_counts_forks 
+-------------------------
+ t
+(1 row)
+
+DROP TABLE dummy_table_am_tab, dummy_table_am_heap;
+DROP EXTENSION dummy_table_am;
diff --git a/src/test/modules/dummy_table_am/meson.build b/src/test/modules/dummy_table_am/meson.build
new file mode 100644
index 00000000000..299c451890b
--- /dev/null
+++ b/src/test/modules/dummy_table_am/meson.build
@@ -0,0 +1,33 @@
+# Copyright (c) 2022-2026, PostgreSQL Global Development Group
+
+dummy_table_am_sources = files(
+  'dummy_table_am.c',
+)
+
+if host_system == 'windows'
+  dummy_table_am_sources += rc_lib_gen.process(win32ver_rc, extra_args: [
+    '--NAME', 'dummy_table_am',
+    '--FILEDESC', 'dummy_table_am - table access method template',])
+endif
+
+dummy_table_am = shared_module('dummy_table_am',
+  dummy_table_am_sources,
+  kwargs: pg_test_mod_args,
+)
+test_install_libs += dummy_table_am
+
+test_install_data += files(
+  'dummy_table_am.control',
+  'dummy_table_am--1.0.sql',
+)
+
+tests += {
+  'name': 'dummy_table_am',
+  'sd': meson.current_source_dir(),
+  'bd': meson.current_build_dir(),
+  'regress': {
+    'sql': [
+      'dummy_table_am',
+    ],
+  },
+}
diff --git a/src/test/modules/dummy_table_am/sql/dummy_table_am.sql b/src/test/modules/dummy_table_am/sql/dummy_table_am.sql
new file mode 100644
index 00000000000..75dc59f9a0c
--- /dev/null
+++ b/src/test/modules/dummy_table_am/sql/dummy_table_am.sql
@@ -0,0 +1,44 @@
+-- Tests for the SQL-level size functions with a table AM
+CREATE EXTENSION dummy_table_am;
+
+-- The AM reports half of the heap footprint for the main fork, so the size
+-- functions must not report the relation's file sizes.
+CREATE TABLE dummy_table_am_tab (a int) USING dummy_table_am;
+CREATE TABLE dummy_table_am_heap (a int);
+INSERT INTO dummy_table_am_tab SELECT generate_series(1, 1000);
+INSERT INTO dummy_table_am_heap SELECT generate_series(1, 1000);
+
+-- Both tables use the same amount of storage, and the AM reports half of it.
+SELECT pg_relation_size('dummy_table_am_tab') =
+       pg_relation_size('dummy_table_am_heap') / 2 AS half_of_heap;
+SELECT pg_relation_size('dummy_table_am_tab') <>
+       pg_relation_size('dummy_table_am_heap') AS differs_from_heap;
+
+-- The other forks are still measured from their files; the inserts above
+-- already created the fsm fork.
+SELECT pg_relation_size('dummy_table_am_tab', 'fsm') > 0 AS fsm_exists,
+       pg_relation_size('dummy_table_am_tab', 'vm') = 0 AS no_vm_yet;
+
+-- The AM's answer is counted exactly once, not added to the file sizes:
+-- pg_table_size() is the AM's answer plus the other forks.
+SELECT pg_table_size('dummy_table_am_tab') =
+       pg_relation_size('dummy_table_am_tab')
+       + pg_relation_size('dummy_table_am_tab', 'fsm')
+       + pg_relation_size('dummy_table_am_tab', 'vm')
+       + pg_relation_size('dummy_table_am_tab', 'init')
+       AS table_size_counts_forks;
+SELECT pg_total_relation_size('dummy_table_am_tab') =
+       pg_table_size('dummy_table_am_tab') AS total_size_exact;
+
+-- After VACUUM the vm fork appears as well, and the same identity holds.
+VACUUM dummy_table_am_tab;
+SELECT pg_relation_size('dummy_table_am_tab', 'vm') > 0 AS vm_exists;
+SELECT pg_table_size('dummy_table_am_tab') =
+       pg_relation_size('dummy_table_am_tab')
+       + pg_relation_size('dummy_table_am_tab', 'fsm')
+       + pg_relation_size('dummy_table_am_tab', 'vm')
+       + pg_relation_size('dummy_table_am_tab', 'init')
+       AS table_size_counts_forks;
+
+DROP TABLE dummy_table_am_tab, dummy_table_am_heap;
+DROP EXTENSION dummy_table_am;
diff --git a/src/test/modules/meson.build b/src/test/modules/meson.build
index ef3cdb8faf9..0a9f6a23d78 100644
--- a/src/test/modules/meson.build
+++ b/src/test/modules/meson.build
@@ -5,6 +5,7 @@ subdir('commit_ts')
 subdir('delay_execution')
 subdir('dummy_index_am')
 subdir('dummy_seclabel')
+subdir('dummy_table_am')
 subdir('gin')
 subdir('hash')
 subdir('index')
-- 
2.47.1

