From 6c734c6288ff00bcb43ec240d8c481888ad930e1 Mon Sep 17 00:00:00 2001
From: Jelte Fennema-Nio <postgres@jeltef.nl>
Date: Thu, 4 Dec 2025 15:35:08 +0100
Subject: [PATCH v1 2/6] Add hash_make macros

This adds the hash_make, hashset_make and ShmemRequestHashMake macros as
wrappers around hash_create and ShmemRequestHashWithOpts. They take the
entry type and the name of its key member, which has these benefits:

1. Key and entry sizes are derived from the types.
2. The key member is referenced in the code, so it cannot be removed
   without the compiler noticing.
3. A static assertion checks that the key is the first member.
4. HASH_STRINGS or HASH_BLOBS is chosen based on the key type.
5. The other HASH_* flags are derived from the options that are set,
   and the always required HASH_ELEM is no longer needed.
6. The memory context defaults to CurrentMemoryContext instead of
   TopMemoryContext, like for all other functions that allocate.
7. Creating a hash table becomes a single statement.

Options are passed as named arguments, e.g. ".mcxt = TopMemoryContext",
like for ShmemRequestHash.

Co-Authored-By: Bertrand Drouvot <bertranddrouvot.pg@gmail.com>
---
 doc/src/sgml/system-views.sgml       |   5 +-
 doc/src/sgml/xfunc.sgml              |  17 +++
 src/backend/storage/ipc/shmem_hash.c |  34 +++++-
 src/backend/utils/hash/dynahash.c    |  87 ++++++++++++++
 src/include/storage/shmem.h          |  47 +++++++-
 src/include/utils/hsearch.h          | 169 ++++++++++++++++++++++++++-
 src/tools/pgindent/typedefs.list     |   1 +
 7 files changed, 351 insertions(+), 9 deletions(-)

diff --git a/doc/src/sgml/system-views.sgml b/doc/src/sgml/system-views.sgml
index 77202e2c765..63e4f3bd16b 100644
--- a/doc/src/sgml/system-views.sgml
+++ b/doc/src/sgml/system-views.sgml
@@ -4255,8 +4255,9 @@ SELECT * FROM pg_locks pl LEFT JOIN pg_prepared_xacts ppx
   <para>
    Anonymous allocations are allocations that have been made
    with <literal>ShmemAlloc()</literal> directly, rather than via
-   <literal>ShmemRequestStruct()</literal> or
-   <literal>ShmemRequestHash()</literal>.
+   <literal>ShmemRequestStruct()</literal>,
+   <literal>ShmemRequestHash()</literal> or
+   <literal>ShmemRequestHashMake()</literal>.
   </para>
 
   <para>
diff --git a/doc/src/sgml/xfunc.sgml b/doc/src/sgml/xfunc.sgml
index bc04d9dfc13..30d1fe116be 100644
--- a/doc/src/sgml/xfunc.sgml
+++ b/doc/src/sgml/xfunc.sgml
@@ -3702,6 +3702,23 @@ my_shmem_init(void *arg)
       to zero, but before any other processes are running, and thus no locking
       is required.
      </para>
+     <para>
+      A hash table in shared memory can be requested in the same way, by
+      calling <function>ShmemRequestHashMake()</function> from the
+      <function>request_fn</function> callback.  Its first two arguments are
+      the entry type and the name of its key member, which must be the first
+      member:
+<programlisting>
+    ShmemRequestHashMake(MyHashEntry, key,
+                         .name = "My hash table",
+                         .nelems = 1024,
+                         .ptr = &amp;MyHash);
+</programlisting>
+      <literal>.nelems</literal> is the maximum number of entries.  The hash
+      table does no locking of its own, so access to it has to be protected
+      with a lock, such as an
+      <link linkend="xfunc-addin-lwlocks">LWLock</link>.
+     </para>
      <para>
       On Windows, the <function>attach_fn</function> callback, if any, is
       additionally called at every backend startup.  It can be used to
diff --git a/src/backend/storage/ipc/shmem_hash.c b/src/backend/storage/ipc/shmem_hash.c
index c28d673cbd2..5967025b69e 100644
--- a/src/backend/storage/ipc/shmem_hash.c
+++ b/src/backend/storage/ipc/shmem_hash.c
@@ -39,6 +39,9 @@ static void *ShmemHashAlloc(Size size, void *alloc_arg);
  *
  * Similar to ShmemRequestStruct(), but requests a hash table instead of an
  * opaque area.
+ *
+ * This is the function behind both the ShmemRequestHash() and the
+ * ShmemRequestHashMake() macro, see shmem.h for how they differ.
  */
 void
 ShmemRequestHashWithOpts(const ShmemHashOpts *options)
@@ -51,6 +54,35 @@ ShmemRequestHashWithOpts(const ShmemHashOpts *options)
 									  sizeof(ShmemHashOpts));
 	memcpy(options_copy, options, sizeof(ShmemHashOpts));
 
+	/*
+	 * Translate a ShmemRequestHashMake() request to hash_info and hash_flags
+	 * right away, so that everything else only has to deal with the one
+	 * representation.
+	 */
+	if (options->keysize != 0)
+	{
+		HASHOPTS	hash_opts = {HASH_COMMON_OPTS_COPY(options)};
+
+		Assert(options->hash_flags == 0);
+
+		hash_opts_init(&options_copy->hash_info, &options_copy->hash_flags,
+					   options->keysize, options->entrysize,
+					   options->string_key, &hash_opts);
+	}
+	else
+	{
+		/*
+		 * Catch plain ShmemRequestHash() callers that set e.g. .hash where
+		 * .hash_info.hash was meant, which would otherwise be silently
+		 * ignored.
+		 */
+		Assert(options->hash == NULL);
+		Assert(options->match == NULL);
+		Assert(options->keycopy == NULL);
+		Assert(options->num_partitions == 0);
+		Assert(!options->force_blobs);
+	}
+
 	/* Set options for the fixed-size area holding the hash table */
 	options_copy->base.name = options->name;
 	options_copy->base.size = hash_estimate_size(options_copy->nelems,
@@ -111,7 +143,7 @@ shmem_hash_attach(void *location, ShmemStructOpts *base_options)
  * choose to specify HASH_PARTITION.
  *
  * Note: This is a legacy interface, kept for backwards compatibility with
- * extensions.  Use ShmemRequestHash() in new code!
+ * extensions.  Use ShmemRequestHashMake() in new code!
  */
 HTAB *
 ShmemInitHash(const char *name,		/* table string name for shmem index */
diff --git a/src/backend/utils/hash/dynahash.c b/src/backend/utils/hash/dynahash.c
index 47d3cacc532..1fefdaae3bc 100644
--- a/src/backend/utils/hash/dynahash.c
+++ b/src/backend/utils/hash/dynahash.c
@@ -618,6 +618,93 @@ hash_create(const char *tabname, int64 nelem, const HASHCTL *info, int flags)
 	return hashp;
 }
 
+/*
+ * hash_opts_init -- initialize HASHCTL and flags from HASHOPTS
+ *
+ * For code that takes HASHOPTS but needs to call hash_create() itself.
+ */
+void
+hash_opts_init(HASHCTL *ctl, int *flags,
+			   Size keysize, Size entrysize, bool string_key,
+			   const HASHOPTS *opts)
+{
+	MemSet(ctl, 0, sizeof(*ctl));
+	ctl->keysize = keysize;
+	ctl->entrysize = entrysize;
+
+	*flags = HASH_ELEM;
+
+	if (opts == NULL)
+	{
+		*flags |= string_key ? HASH_STRINGS : HASH_BLOBS;
+		return;
+	}
+
+	if (opts->hash != NULL)
+	{
+		/* force_blobs only affects default hash selection, not custom hash */
+		Assert(!opts->force_blobs);
+		ctl->hash = opts->hash;
+		*flags |= HASH_FUNCTION;
+	}
+	else if (opts->force_blobs)
+	{
+		*flags |= HASH_BLOBS;
+	}
+	else
+	{
+		*flags |= string_key ? HASH_STRINGS : HASH_BLOBS;
+	}
+
+	if (opts->match != NULL)
+	{
+		ctl->match = opts->match;
+		*flags |= HASH_COMPARE;
+	}
+
+	if (opts->keycopy != NULL)
+	{
+		ctl->keycopy = opts->keycopy;
+		*flags |= HASH_KEYCOPY;
+	}
+
+	if (opts->alloc != NULL)
+	{
+		ctl->alloc = opts->alloc;
+		*flags |= HASH_ALLOC;
+	}
+
+	if (opts->num_partitions > 0)
+	{
+		ctl->num_partitions = opts->num_partitions;
+		*flags |= HASH_PARTITION;
+	}
+
+	if (opts->fixed_size)
+		*flags |= HASH_FIXED_SIZE;
+}
+
+/*
+ * hash_make_impl -- implementation of the hash_make() and hashset_make()
+ * macros, see hsearch.h.
+ */
+HTAB *
+hash_make_impl(const char *tabname, int64 nelem,
+			   Size keysize, Size entrysize,
+			   bool string_key,
+			   HASHOPTS opts)
+{
+	HASHCTL		ctl;
+	int			flags;
+
+	hash_opts_init(&ctl, &flags, keysize, entrysize, string_key, &opts);
+
+	ctl.hcxt = opts.mcxt ? opts.mcxt : CurrentMemoryContext;
+	flags |= HASH_CONTEXT;
+
+	return hash_create(tabname, nelem, &ctl, flags);
+}
+
 /*
  * Set default HASHHDR parameters.
  */
diff --git a/src/include/storage/shmem.h b/src/include/storage/shmem.h
index 43b636868c7..8f93ece2253 100644
--- a/src/include/storage/shmem.h
+++ b/src/include/storage/shmem.h
@@ -69,7 +69,7 @@ typedef struct ShmemStructOpts
 #define SHMEM_ATTACH_UNKNOWN_SIZE (-1)
 
 /*
- * Options for ShmemRequestHash()
+ * Options for ShmemRequestHash() and ShmemRequestHashMake()
  *
  * Each hash table is backed by a contiguous shmem area.
  */
@@ -101,6 +101,20 @@ typedef struct ShmemHashOpts
 	HASHCTL		hash_info;
 	int			hash_flags;
 
+	/*
+	 * Set by ShmemRequestHashMake() instead of hash_info and hash_flags; do
+	 * not touch directly.
+	 */
+	Size		keysize;
+	Size		entrysize;
+	bool		string_key;
+
+	/*
+	 * Options for ShmemRequestHashMake(): the hash_make() options that work
+	 * for shared memory hash tables, see HASH_COMMON_OPTS_FIELDS.
+	 */
+				HASH_COMMON_OPTS_FIELDS;
+
 	/*
 	 * When the hash table is initialized or attached to, pointer to its
 	 * backend-private handle is stored in *ptr.  It usually points to a
@@ -172,6 +186,27 @@ extern bool ShmemAddrIsValid(const void *addr);
 /*
  * These macros provide syntactic sugar for calling the underlying functions
  * with named arguments -like syntax.
+ *
+ * ShmemRequestHashMake() is the preferred way to request a hash table.  It is
+ * to ShmemRequestHash() what hash_make() is to hash_create(): it takes the
+ * entry type and the name of the key member as its first two arguments, and
+ * uses those to derive the key and entry sizes and to automatically choose
+ * HASH_STRINGS vs HASH_BLOBS based on the key type (char arrays and NameData
+ * are treated as strings).
+ *
+ * Example:
+ *   ShmemRequestHashMake(MyEntry, key,
+ *                        .name = "my hash",
+ *                        .nelems = 64,
+ *                        .ptr = &MyHash);
+ *
+ * For partitioned tables, custom hash functions, etc., use the same options
+ * as for hash_make(), instead of .hash_info and .hash_flags:
+ *   ShmemRequestHashMake(LOCK, tag,
+ *                        .name = "LOCK hash",
+ *                        .nelems = max_table_size,
+ *                        .ptr = &LockMethodLockHash,
+ *                        .num_partitions = NUM_LOCK_PARTITIONS);
  */
 #define ShmemRequestStruct(...)  \
 	ShmemRequestStructWithOpts(&(ShmemStructOpts){__VA_ARGS__})
@@ -179,6 +214,16 @@ extern bool ShmemAddrIsValid(const void *addr);
 #define ShmemRequestHash(...)  \
 	ShmemRequestHashWithOpts(&(ShmemHashOpts){__VA_ARGS__})
 
+#define ShmemRequestHashMake(entrytype, keymember, ...) \
+	(StaticAssertExpr(offsetof(entrytype, keymember) == 0, \
+					  #keymember " must be first member in " #entrytype), \
+	 ShmemRequestHashWithOpts(&(ShmemHashOpts){ \
+		 .keysize = sizeof(((entrytype *)0)->keymember), \
+		 .entrysize = sizeof(entrytype), \
+		 .string_key = HASH_KEY_AS_STRING(entrytype, keymember), \
+		 __VA_ARGS__ \
+	 }))
+
 extern void ShmemRequestStructWithOpts(const ShmemStructOpts *options);
 extern void ShmemRequestHashWithOpts(const ShmemHashOpts *options);
 
diff --git a/src/include/utils/hsearch.h b/src/include/utils/hsearch.h
index 9d9064c45a3..4e4ec34c9bf 100644
--- a/src/include/utils/hsearch.h
+++ b/src/include/utils/hsearch.h
@@ -15,6 +15,9 @@
 #define HSEARCH_H
 
 
+/* Hash table control struct is an opaque type known only within dynahash.c */
+typedef struct HTAB HTAB;
+
 /*
  * Hash functions must have this signature.
  */
@@ -42,6 +45,159 @@ typedef void *(*HashCopyFunc) (void *dest, const void *src, Size keysize);
  */
 typedef void *(*HashAllocFunc) (Size request, void *alloc_arg);
 
+/*
+ * The hash options that work for both backend-local and shared memory hash
+ * tables.  These are in a macro so that ShmemHashOpts can include the same
+ * fields, without the options that cannot work in shared memory.
+ *
+ * hash				custom hash function (NULL for default)
+ * match			custom comparison function (NULL for default)
+ * keycopy			custom key copy function (NULL for default)
+ * num_partitions	partition count (0 for none)
+ * force_blobs		if true, use HASH_BLOBS even for string types
+ *
+ * HASH_COMMON_OPTS_COPY(src) expands to the designated initializers that copy
+ * these fields from *src.  It must be kept in sync with the field list.
+ */
+#define HASH_COMMON_OPTS_FIELDS \
+	HashValueFunc hash; \
+	HashCompareFunc match; \
+	HashCopyFunc keycopy; \
+	int64		num_partitions; \
+	bool		force_blobs
+
+#define HASH_COMMON_OPTS_COPY(src) \
+	.hash = (src)->hash, \
+	.match = (src)->match, \
+	.keycopy = (src)->keycopy, \
+	.num_partitions = (src)->num_partitions, \
+	.force_blobs = (src)->force_blobs
+
+/*
+ * Hash options for the hash_make() macros.
+ *
+ * All fields are optional: zero-initialized fields use the appropriate
+ * default behavior.
+ */
+typedef struct HASHOPTS
+{
+	HASH_COMMON_OPTS_FIELDS;
+	HashAllocFunc alloc;		/* custom allocator (NULL for default) */
+	MemoryContext mcxt;			/* memory context (NULL for
+								 * CurrentMemoryContext) */
+	bool		fixed_size;		/* if true, hash table cannot grow */
+} HASHOPTS;
+
+/*
+ * Helpers to detect if a type should be hashed as a string.
+ *
+ * String types include: char arrays and NameData.
+ * Everything else is treated as a binary blob (HASH_BLOBS).
+ *
+ * HASH_PTR_AS_STRING(ptr, size) checks whether the key pointer points to a
+ * char array of the given size or to a NameData.  The C version uses _Generic,
+ * which applies lvalue conversion (so a "char[size]" member decays to
+ * "char (*)[size]" here), and the C++ version reproduces that behavior with
+ * std::is_same over std::decay.
+ *
+ * HASH_TYPE_AS_STRING(type) does the same for a bare type by forming a null
+ * pointer to it.  In C that is "(type *) NULL", but that spelling fails in C++
+ * for types containing brackets (e.g. char[64]), so C++ uses std::add_pointer_t
+ * instead.
+ */
+#ifdef __cplusplus
+#define HASH_PTR_AS_STRING(ptr, size) \
+	(std::is_same<typename std::decay<decltype(ptr)>::type, char (*)[size]>::value || \
+	 std::is_same<typename std::decay<decltype(ptr)>::type, NameData *>::value)
+#define HASH_TYPE_AS_STRING(type) \
+	HASH_PTR_AS_STRING(static_cast<std::add_pointer_t<type>>(nullptr), sizeof(type))
+#else
+#define HASH_PTR_AS_STRING(ptr, size) \
+	_Generic((ptr), char (*)[size]: 1, NameData *: 1, default: 0)
+#define HASH_TYPE_AS_STRING(type) \
+	HASH_PTR_AS_STRING((type *) NULL, sizeof(type))
+#endif
+#define HASH_KEY_AS_STRING(entrytype, keymember) \
+	HASH_PTR_AS_STRING(&((entrytype *)0)->keymember, \
+					   sizeof(((entrytype *)0)->keymember))
+
+/*
+ * Spelling of a HASHOPTS compound literal for the hash_make macros.
+ *
+ * C spells this as the compound literal (HASHOPTS){...}.  GCC and Clang accept
+ * that spelling in C++ too, but MSVC's C++ compiler rejects it (error C4576),
+ * so in C++ we use aggregate brace-initialization instead, which relies on
+ * C++20 designated initializers for the optional fields.
+ */
+#ifdef __cplusplus
+#define HASH_MAKE_OPTS(...) HASHOPTS{__VA_ARGS__}
+#else
+#define HASH_MAKE_OPTS(...) (HASHOPTS){__VA_ARGS__}
+#endif
+
+/*
+ * Create a hash table with minimal boilerplate.
+ *
+ * This is the simplest way to create a hash table. It:
+ * - Derives keysize from the keymember's actual type
+ * - Derives entrysize from the entrytype
+ * - Automatically chooses HASH_STRINGS or HASH_BLOBS based on key type
+ *   (char arrays and NameData are treated as strings)
+ * - Uses CurrentMemoryContext by default
+ * - Validates that keymember is at offset 0
+ *
+ * Optional behavior is specified via designated initializers in the
+ * trailing varargs, which initialize a HASHOPTS struct.  See HASHOPTS for
+ * available fields.
+ *
+ * NOTE: If you use char[N] to store binary data that might contain null bytes
+ * and/or is not null terminated, the automatic detection will incorrectly
+ * treat it as a string and use string comparison.  In such cases, pass
+ * .force_blobs = true to override the automatic detection.
+ *
+ * Usage:
+ *   typedef struct { Oid oid; char *data; } MyEntry;
+ *   HTAB *h = hash_make(MyEntry, oid, "my table", 64);
+ *
+ *   HTAB *h = hash_make(MyEntry, oid, "my table", 64,
+ *                       .mcxt = TopMemoryContext,
+ *                       .num_partitions = 16);
+ *
+ *   HTAB *h = hash_make(MyEntry, key, "my table", 64,
+ *                       .hash = my_hash_func,
+ *                       .match = my_match_func);
+ */
+#define hash_make(entrytype, keymember, tabname, nelem, ...) \
+	(StaticAssertExpr(offsetof(entrytype, keymember) == 0, \
+					  #keymember " must be first member in " #entrytype), \
+	 hash_make_impl((tabname), (nelem), \
+					sizeof(((entrytype *)0)->keymember), \
+					sizeof(entrytype), \
+					HASH_KEY_AS_STRING(entrytype, keymember), \
+					HASH_MAKE_OPTS(__VA_ARGS__)))
+
+/*
+ * Create a hash set where the entire entry is the key.
+ *
+ * Like hash_make, but the key is the entire entry.  Same designated
+ * initializer syntax in the varargs for optional HASHOPTS fields.
+ */
+#define hashset_make(entrytype, tabname, nelem, ...) \
+	hash_make_impl((tabname), (nelem), sizeof(entrytype), sizeof(entrytype), \
+				   HASH_TYPE_AS_STRING(entrytype), \
+				   HASH_MAKE_OPTS(__VA_ARGS__))
+
+/*
+ * Implementation function for hash_make/hashset_make macros.  Not meant to
+ * be called directly.
+ *
+ * If string_key is true, the key is treated as a null-terminated string.
+ */
+extern HTAB *hash_make_impl(const char *tabname, int64 nelem,
+							Size keysize, Size entrysize,
+							bool string_key,
+							HASHOPTS opts);
+
 /*
  * HASHELEMENT is the private part of a hashtable entry.  The caller's data
  * follows the HASHELEMENT structure (on a MAXALIGN'd boundary).  The hash key
@@ -56,11 +212,11 @@ typedef struct HASHELEMENT
 /* Hash table header struct is an opaque type known only within dynahash.c */
 typedef struct HASHHDR HASHHDR;
 
-/* Hash table control struct is an opaque type known only within dynahash.c */
-typedef struct HTAB HTAB;
-
-/* Parameter data structure for hash_create */
-/* Only those fields indicated by hash_flags need be set */
+/*
+ * Parameter data structure for hash_create (which is the low-level method of
+ * initializing hash tables, hash_make macros are preferred)
+ * Only those fields indicated by hash_flags need be set
+ */
 typedef struct HASHCTL
 {
 	/* Used if HASH_PARTITION flag is set: */
@@ -197,6 +353,9 @@ foreach_hash_start(HTAB *hashp)
  */
 extern HTAB *hash_create(const char *tabname, int64 nelem,
 						 const HASHCTL *info, int flags);
+extern void hash_opts_init(HASHCTL *ctl, int *flags,
+						   Size keysize, Size entrysize, bool string_key,
+						   const HASHOPTS *opts);
 extern void hash_destroy(HTAB *hashp);
 extern void hash_stats(const char *caller, HTAB *hashp);
 extern void *hash_search(HTAB *hashp, const void *keyPtr, HASHACTION action,
diff --git a/src/tools/pgindent/typedefs.list b/src/tools/pgindent/typedefs.list
index f10eb469266..adfb8d3ba80 100644
--- a/src/tools/pgindent/typedefs.list
+++ b/src/tools/pgindent/typedefs.list
@@ -1192,6 +1192,7 @@ HASHBUCKET
 HASHCTL
 HASHELEMENT
 HASHHDR
+HASHOPTS
 HASHSEGMENT
 HASH_SEQ_STATUS
 HE
-- 
2.56.1

