From 749d05cbbcb6f3e67648e36a048acdb86cbdeb25 Mon Sep 17 00:00:00 2001
From: Karina Litskevich <litskevichkarina@gmail.com>
Date: Mon, 13 Jul 2026 16:39:04 +0300
Subject: [PATCH] pg_stat_statements: explicitly convert number of entries to
 int32

hash_get_num_entries returns long before PG19 (int64 since 13b935cd).
Technically assigning it to int32 is wrong. In practice number of entries
should not exceed pgss_max. While pgss_max fits int32 we should be okay.
Add the corresponding check for safety's sake.

We do this instead of changing num_entries type to avoid changing the file
header format.

Also fix the definition of pgver according to its usage while we are here.
---
 contrib/pg_stat_statements/pg_stat_statements.c | 10 ++++++++--
 1 file changed, 8 insertions(+), 2 deletions(-)

diff --git a/contrib/pg_stat_statements/pg_stat_statements.c b/contrib/pg_stat_statements/pg_stat_statements.c
index 92315627916..6f4d172d9ab 100644
--- a/contrib/pg_stat_statements/pg_stat_statements.c
+++ b/contrib/pg_stat_statements/pg_stat_statements.c
@@ -534,7 +534,7 @@ pgss_shmem_init(void *arg)
 	FILE	   *qfile = NULL;
 	uint32		header;
 	int32		num;
-	int32		pgver;
+	uint32		pgver;
 	int32		i;
 	int			buffer_size;
 	char	   *buffer = NULL;
@@ -760,7 +760,13 @@ pgss_shmem_shutdown(int code, Datum arg)
 		goto error;
 	if (fwrite(&PGSS_PG_MAJOR_VERSION, sizeof(uint32), 1, file) != 1)
 		goto error;
-	num_entries = hash_get_num_entries(pgss_hash);
+
+	/*
+	 * Number of elements in pgss_hash should not exceed pgss_max. And we want
+	 * it to fit into int32.
+	 */
+	StaticAssertStmt(sizeof(pgss_max) <= sizeof(int32), "pgss_max should fit into int32");
+	num_entries = (int32) hash_get_num_entries(pgss_hash);
 	if (fwrite(&num_entries, sizeof(int32), 1, file) != 1)
 		goto error;
 
-- 
2.51.0

