From 8b9f720854c8c4f9be7fb0e7ff186ddf1cfdcbf1 Mon Sep 17 00:00:00 2001
From: Michael Banck <michael.banck@credativ.de>
Date: Fri, 17 Oct 2025 10:22:20 +0200
Subject: [PATCH] pg_checksums: Use new routine to retrieve data of PG_VERSION

pg_checksums currently refuses to work with clusters of a different version.
Until this limitation is lifted, running it on a cluster with a different major
version errors out either with a "pg_control CRC value is incorrect" message,
or, if that works, with a "cluster is not compatible with this version of
pg_checksums" message in case the control file is different.

The former is confusing as the control file is correct: only the expected
version does not match.  This commit integrates pg_checksums with the facility
added by cd0be131ba6f, where the contents of PG_VERSION are read and compared
with the value of PG_MAJORVERSION_NUM expected by the tool.
---
 src/bin/pg_checksums/pg_checksums.c | 17 +++++++++++++++++
 1 file changed, 17 insertions(+)

diff --git a/src/bin/pg_checksums/pg_checksums.c b/src/bin/pg_checksums/pg_checksums.c
index f20be82862a..46cb2f36efa 100644
--- a/src/bin/pg_checksums/pg_checksums.c
+++ b/src/bin/pg_checksums/pg_checksums.c
@@ -25,6 +25,7 @@
 #include "common/logging.h"
 #include "common/relpath.h"
 #include "fe_utils/option_utils.h"
+#include "fe_utils/version.h"
 #include "getopt_long.h"
 #include "pg_getopt.h"
 #include "storage/bufpage.h"
@@ -448,6 +449,8 @@ main(int argc, char *argv[])
 	int			c;
 	int			option_index;
 	bool		crc_ok;
+	uint32		major_version;
+	char	   *version_str;
 
 	pg_logging_init(argv[0]);
 	set_pglocale_pgservice(argv[0], PG_TEXTDOMAIN("pg_checksums"));
@@ -543,6 +546,20 @@ main(int argc, char *argv[])
 		exit(1);
 	}
 
+	/*
+	 * Retrieve the contents of this cluster's PG_VERSION.  We require
+	 * compatibility with the same major version as the one this tool is
+	 * compiled with.
+	 */
+	major_version = GET_PG_MAJORVERSION_NUM(get_pg_version(DataDir, &version_str));
+	if (major_version != PG_MAJORVERSION_NUM)
+	{
+		pg_log_error("data directory is of wrong version");
+		pg_log_error_detail("File \"%s\" contains \"%s\", which is not compatible with this program's version \"%s\".",
+							"PG_VERSION", version_str, PG_MAJORVERSION);
+		exit(1);
+	}
+
 	/* Read the control file and check compatibility */
 	ControlFile = get_controlfile(DataDir, &crc_ok);
 	if (!crc_ok)
-- 
2.39.5

