PostgreSQL Source Code git master
Loading...
Searching...
No Matches
hsearch.h File Reference
This graph shows which files directly or indirectly include this file:

Go to the source code of this file.

Data Structures

struct  HASHELEMENT
 
struct  HASHCTL
 
struct  HASH_SEQ_STATUS
 

Macros

#define HASH_PARTITION   0x0001 /* Hashtable is used w/partitioned locking */
 
#define HASH_ELEM   0x0008 /* Set keysize and entrysize (now required!) */
 
#define HASH_STRINGS   0x0010 /* Select support functions for string keys */
 
#define HASH_BLOBS   0x0020 /* Select support functions for binary keys */
 
#define HASH_FUNCTION   0x0040 /* Set user defined hash function */
 
#define HASH_COMPARE   0x0080 /* Set user defined comparison function */
 
#define HASH_KEYCOPY   0x0100 /* Set user defined key-copying function */
 
#define HASH_ALLOC   0x0200 /* Set memory allocator */
 
#define HASH_CONTEXT   0x0400 /* Set memory allocation context */
 
#define HASH_SHARED_MEM   0x0800 /* Hashtable is in shared memory */
 
#define HASH_ATTACH   0x1000 /* Do not initialize hctl */
 
#define HASH_FIXED_SIZE   0x2000 /* Initial size is a hard limit */
 
#define NO_MAX_DSIZE   (-1)
 

Typedefs

typedef uint32(* HashValueFunc) (const void *key, Size keysize)
 
typedef int(* HashCompareFunc) (const void *key1, const void *key2, Size keysize)
 
typedef void *(* HashCopyFunc) (void *dest, const void *src, Size keysize)
 
typedef void *(* HashAllocFunc) (Size request, void *alloc_arg)
 
typedef struct HASHELEMENT HASHELEMENT
 
typedef struct HASHHDR HASHHDR
 
typedef struct HTAB HTAB
 
typedef struct HASHCTL HASHCTL
 

Enumerations

enum  HASHACTION { HASH_FIND , HASH_ENTER , HASH_REMOVE , HASH_ENTER_NULL }
 

Functions

HTABhash_create (const char *tabname, int64 nelem, const HASHCTL *info, int flags)
 
void hash_destroy (HTAB *hashp)
 
void hash_stats (const char *caller, HTAB *hashp)
 
voidhash_search (HTAB *hashp, const void *keyPtr, HASHACTION action, bool *foundPtr)
 
uint32 get_hash_value (HTAB *hashp, const void *keyPtr)
 
voidhash_search_with_hash_value (HTAB *hashp, const void *keyPtr, uint32 hashvalue, HASHACTION action, bool *foundPtr)
 
bool hash_update_hash_key (HTAB *hashp, void *existingEntry, const void *newKeyPtr)
 
int64 hash_get_num_entries (HTAB *hashp)
 
void hash_seq_init (HASH_SEQ_STATUS *status, HTAB *hashp)
 
void hash_seq_init_with_hash_value (HASH_SEQ_STATUS *status, HTAB *hashp, uint32 hashvalue)
 
voidhash_seq_search (HASH_SEQ_STATUS *status)
 
void hash_seq_term (HASH_SEQ_STATUS *status)
 
void hash_freeze (HTAB *hashp)
 
Size hash_estimate_size (int64 num_entries, Size entrysize)
 
void AtEOXact_HashTables (bool isCommit)
 
void AtEOSubXact_HashTables (bool isCommit, int nestDepth)
 

Macro Definition Documentation

◆ HASH_ALLOC

#define HASH_ALLOC   0x0200 /* Set memory allocator */

Definition at line 96 of file hsearch.h.

◆ HASH_ATTACH

#define HASH_ATTACH   0x1000 /* Do not initialize hctl */

Definition at line 99 of file hsearch.h.

◆ HASH_BLOBS

#define HASH_BLOBS   0x0020 /* Select support functions for binary keys */

Definition at line 92 of file hsearch.h.

◆ HASH_COMPARE

#define HASH_COMPARE   0x0080 /* Set user defined comparison function */

Definition at line 94 of file hsearch.h.

◆ HASH_CONTEXT

#define HASH_CONTEXT   0x0400 /* Set memory allocation context */

Definition at line 97 of file hsearch.h.

◆ HASH_ELEM

#define HASH_ELEM   0x0008 /* Set keysize and entrysize (now required!) */

Definition at line 90 of file hsearch.h.

◆ HASH_FIXED_SIZE

#define HASH_FIXED_SIZE   0x2000 /* Initial size is a hard limit */

Definition at line 100 of file hsearch.h.

◆ HASH_FUNCTION

#define HASH_FUNCTION   0x0040 /* Set user defined hash function */

Definition at line 93 of file hsearch.h.

◆ HASH_KEYCOPY

#define HASH_KEYCOPY   0x0100 /* Set user defined key-copying function */

Definition at line 95 of file hsearch.h.

◆ HASH_PARTITION

#define HASH_PARTITION   0x0001 /* Hashtable is used w/partitioned locking */

Definition at line 87 of file hsearch.h.

◆ HASH_SHARED_MEM

#define HASH_SHARED_MEM   0x0800 /* Hashtable is in shared memory */

Definition at line 98 of file hsearch.h.

◆ HASH_STRINGS

#define HASH_STRINGS   0x0010 /* Select support functions for string keys */

Definition at line 91 of file hsearch.h.

◆ NO_MAX_DSIZE

#define NO_MAX_DSIZE   (-1)

Definition at line 103 of file hsearch.h.

Typedef Documentation

◆ HashAllocFunc

typedef void *(* HashAllocFunc) (Size request, void *alloc_arg)

Definition at line 43 of file hsearch.h.

◆ HashCompareFunc

typedef int(* HashCompareFunc) (const void *key1, const void *key2, Size keysize)

Definition at line 29 of file hsearch.h.

◆ HashCopyFunc

typedef void *(* HashCopyFunc) (void *dest, const void *src, Size keysize)

Definition at line 37 of file hsearch.h.

◆ HASHCTL

◆ HASHELEMENT

◆ HASHHDR

Definition at line 57 of file hsearch.h.

◆ HashValueFunc

typedef uint32(* HashValueFunc) (const void *key, Size keysize)

Definition at line 21 of file hsearch.h.

◆ HTAB

typedef struct HTAB HTAB

Definition at line 60 of file hsearch.h.

Enumeration Type Documentation

◆ HASHACTION

Enumerator
HASH_FIND 
HASH_ENTER 
HASH_REMOVE 
HASH_ENTER_NULL 

Definition at line 106 of file hsearch.h.

107{
108 HASH_FIND,
112} HASHACTION;
HASHACTION
Definition hsearch.h:107
@ HASH_FIND
Definition hsearch.h:108
@ HASH_REMOVE
Definition hsearch.h:110
@ HASH_ENTER
Definition hsearch.h:109
@ HASH_ENTER_NULL
Definition hsearch.h:111

Function Documentation

◆ AtEOSubXact_HashTables()

void AtEOSubXact_HashTables ( bool  isCommit,
int  nestDepth 
)
extern

Definition at line 1890 of file dynahash.c.

1891{
1892 int i;
1893
1894 /*
1895 * Search backward to make cleanup easy. Note we must check all entries,
1896 * not only those at the end of the array, because deletion technique
1897 * doesn't keep them in order.
1898 */
1899 for (i = num_seq_scans - 1; i >= 0; i--)
1900 {
1901 if (seq_scan_level[i] >= nestDepth)
1902 {
1903 if (isCommit)
1904 elog(WARNING, "leaked hash_seq_search scan for hash table %p",
1908 num_seq_scans--;
1909 }
1910 }
1911}
static HTAB * seq_scan_tables[MAX_SEQ_SCANS]
Definition dynahash.c:1810
static int seq_scan_level[MAX_SEQ_SCANS]
Definition dynahash.c:1811
static int num_seq_scans
Definition dynahash.c:1812
#define WARNING
Definition elog.h:37
#define elog(elevel,...)
Definition elog.h:228
int i
Definition isn.c:77
static int fb(int x)

References elog, fb(), i, num_seq_scans, seq_scan_level, seq_scan_tables, and WARNING.

Referenced by AbortSubTransaction(), and CommitSubTransaction().

◆ AtEOXact_HashTables()

void AtEOXact_HashTables ( bool  isCommit)
extern

Definition at line 1864 of file dynahash.c.

1865{
1866 /*
1867 * During abort cleanup, open scans are expected; just silently clean 'em
1868 * out. An open scan at commit means someone forgot a hash_seq_term()
1869 * call, so complain.
1870 *
1871 * Note: it's tempting to try to print the tabname here, but refrain for
1872 * fear of touching deallocated memory. This isn't a user-facing message
1873 * anyway, so it needn't be pretty.
1874 */
1875 if (isCommit)
1876 {
1877 int i;
1878
1879 for (i = 0; i < num_seq_scans; i++)
1880 {
1881 elog(WARNING, "leaked hash_seq_search scan for hash table %p",
1883 }
1884 }
1885 num_seq_scans = 0;
1886}

References elog, fb(), i, num_seq_scans, seq_scan_tables, and WARNING.

Referenced by AbortTransaction(), AutoVacLauncherMain(), BackgroundWriterMain(), CheckpointerMain(), CommitTransaction(), pgarch_archiveXlog(), PrepareTransaction(), WalSummarizerMain(), and WalWriterMain().

◆ get_hash_value()

uint32 get_hash_value ( HTAB hashp,
const void keyPtr 
)
extern

Definition at line 845 of file dynahash.c.

846{
847 return hashp->hash(keyPtr, hashp->keysize);
848}
HashValueFunc hash
Definition dynahash.c:228
Size keysize
Definition dynahash.c:241

References fb(), HTAB::hash, and HTAB::keysize.

Referenced by BufTableHashCode(), LockTagHashCode(), and lookup_type_cache().

◆ hash_create()

HTAB * hash_create ( const char tabname,
int64  nelem,
const HASHCTL info,
int  flags 
)
extern

Definition at line 360 of file dynahash.c.

361{
362 HTAB *hashp;
363 HASHHDR *hctl;
364 MemoryContext hcxt;
365
366 /*
367 * Hash tables now allocate space for key and data, but you have to say
368 * how much space to allocate.
369 */
370 Assert(flags & HASH_ELEM);
371 Assert(info->keysize > 0);
372 Assert(info->entrysize >= info->keysize);
373
374 /*
375 * For shared hash tables, we have a local hash header (HTAB struct) that
376 * we allocate in TopMemoryContext; all else is in shared memory.
377 *
378 * For non-shared hash tables, everything including the hash header is in
379 * a memory context created specially for the hash table --- this makes
380 * hash_destroy very simple. The memory context is made a child of either
381 * a context specified by the caller, or TopMemoryContext if nothing is
382 * specified.
383 *
384 * Note that HASH_ALLOC had better be set as well.
385 */
386 if (flags & HASH_SHARED_MEM)
387 {
388 /* Set up to allocate the hash header */
389 hcxt = TopMemoryContext;
390 }
391 else
392 {
393 /* Create the hash table's private memory context */
394 if (flags & HASH_CONTEXT)
395 hcxt = info->hcxt;
396 else
397 hcxt = TopMemoryContext;
398 hcxt = AllocSetContextCreate(hcxt, "dynahash",
400 }
401
402 /* Initialize the hash header, plus a copy of the table name */
403 hashp = (HTAB *) MemoryContextAlloc(hcxt,
404 sizeof(HTAB) + strlen(tabname) + 1);
405 MemSet(hashp, 0, sizeof(HTAB));
406
407 hashp->tabname = (char *) (hashp + 1);
408 strcpy(hashp->tabname, tabname);
409
410 /* If we have a private context, label it with hashtable's name */
411 if (!(flags & HASH_SHARED_MEM))
413
414 /*
415 * Select the appropriate hash function (see comments at head of file).
416 */
417 if (flags & HASH_FUNCTION)
418 {
419 Assert(!(flags & (HASH_BLOBS | HASH_STRINGS)));
420 hashp->hash = info->hash;
421 }
422 else if (flags & HASH_BLOBS)
423 {
424 Assert(!(flags & HASH_STRINGS));
425 /* We can optimize hashing for common key sizes */
426 if (info->keysize == sizeof(uint32))
427 hashp->hash = uint32_hash;
428 else
429 hashp->hash = tag_hash;
430 }
431 else
432 {
433 /*
434 * string_hash used to be considered the default hash method, and in a
435 * non-assert build it effectively still is. But we now consider it
436 * an assertion error to not say HASH_STRINGS explicitly. To help
437 * catch mistaken usage of HASH_STRINGS, we also insist on a
438 * reasonably long string length: if the keysize is only 4 or 8 bytes,
439 * it's almost certainly an integer or pointer not a string.
440 */
441 Assert(flags & HASH_STRINGS);
442 Assert(info->keysize > 8);
443
444 hashp->hash = string_hash;
445 }
446
447 /*
448 * If you don't specify a match function, it defaults to string_compare if
449 * you used string_hash, and to memcmp otherwise.
450 *
451 * Note: explicitly specifying string_hash is deprecated, because this
452 * might not work for callers in loadable modules on some platforms due to
453 * referencing a trampoline instead of the string_hash function proper.
454 * Specify HASH_STRINGS instead.
455 */
456 if (flags & HASH_COMPARE)
457 hashp->match = info->match;
458 else if (hashp->hash == string_hash)
460 else
461 hashp->match = memcmp;
462
463 /*
464 * Similarly, the key-copying function defaults to strlcpy or memcpy.
465 */
466 if (flags & HASH_KEYCOPY)
467 hashp->keycopy = info->keycopy;
468 else if (hashp->hash == string_hash)
469 {
470 /*
471 * The signature of keycopy is meant for memcpy(), which returns
472 * void*, but strlcpy() returns size_t. Since we never use the return
473 * value of keycopy, and size_t is pretty much always the same size as
474 * void *, this should be safe. The extra cast in the middle is to
475 * avoid warnings from -Wcast-function-type.
476 */
478 }
479 else
480 hashp->keycopy = memcpy;
481
482 /* And select the entry allocation function, too. */
483 if (flags & HASH_ALLOC)
484 {
485 hashp->alloc = info->alloc;
486 hashp->alloc_arg = info->alloc_arg;
487 }
488 else
489 {
490 hashp->alloc = DynaHashAlloc;
491 hashp->alloc_arg = hcxt;
492 }
493
494 if (flags & HASH_SHARED_MEM)
495 {
496 hashp->hcxt = NULL;
497 hashp->isshared = true;
498
499 /* hash table already exists, we're just attaching to it */
500 if (flags & HASH_ATTACH)
501 {
502 /* Caller must pass the pointer to the shared header */
503 Assert(info->hctl);
504 hashp->hctl = info->hctl;
505
506 /* make local copies of some heavily-used values */
507 hashp->dir = info->hctl->dir;
508 hashp->keysize = info->hctl->keysize;
509
510 return hashp;
511 }
512 }
513 else
514 {
515 /* setup hash table defaults */
516 hashp->hctl = NULL;
517 hashp->dir = NULL;
518 hashp->hcxt = hcxt;
519 hashp->isshared = false;
520 }
521
522 /*
523 * Allocate the header structure.
524 *
525 * XXX: In case of a shared memory hash table, other processes need the
526 * pointer to the header to re-find the hash table. There is currently no
527 * explicit way to pass it back from here, the caller relies on the fact
528 * that this is the first allocation made with the alloc function. That's
529 * a little ugly, but works for now.
530 */
531 hashp->hctl = (HASHHDR *) hashp->alloc(sizeof(HASHHDR), hashp->alloc_arg);
532 if (!hashp->hctl)
535 errmsg("out of memory")));
536
537 hashp->frozen = false;
538
539 hdefault(hashp);
540
541 hctl = hashp->hctl;
542
543 if (flags & HASH_PARTITION)
544 {
545 /* Doesn't make sense to partition a local hash table */
546 Assert(flags & HASH_SHARED_MEM);
547
548 /*
549 * The number of partitions had better be a power of 2. Also, it must
550 * be less than INT_MAX (see init_htab()), so call the int version of
551 * next_pow2.
552 */
554
555 hctl->num_partitions = info->num_partitions;
556 }
557
558 /* remember the entry sizes, too */
559 hctl->keysize = info->keysize;
560 hctl->entrysize = info->entrysize;
561
562 /* make local copies of heavily-used constant fields */
563 hashp->keysize = hctl->keysize;
564
565 /* Build the hash directory structure */
566 if (!init_htab(hashp, nelem))
567 elog(ERROR, "failed to initialize hash table \"%s\"", hashp->tabname);
568
569 /*
570 * For a shared hash table, preallocate the requested number of elements.
571 * This reduces problems with run-time out-of-shared-memory conditions.
572 *
573 * For a non-shared hash table, preallocate the requested number of
574 * elements if it's less than our chosen nelem_alloc. This avoids wasting
575 * space if the caller correctly estimates a small table size.
576 */
577 if ((flags & HASH_SHARED_MEM) ||
578 nelem < hctl->nelem_alloc)
579 {
580 int i,
582 nelem_alloc,
584
585 /*
586 * If hash table is partitioned, give each freelist an equal share of
587 * the initial allocation. Otherwise only freeList[0] is used.
588 */
589 if (IS_PARTITIONED(hashp->hctl))
591 else
593
594 nelem_alloc = nelem / freelist_partitions;
595 if (nelem_alloc <= 0)
596 nelem_alloc = 1;
597
598 /*
599 * Make sure we'll allocate all the requested elements; freeList[0]
600 * gets the excess if the request isn't divisible by NUM_FREELISTS.
601 */
602 if (nelem_alloc * freelist_partitions < nelem)
604 nelem - nelem_alloc * (freelist_partitions - 1);
605 else
606 nelem_alloc_first = nelem_alloc;
607
608 for (i = 0; i < freelist_partitions; i++)
609 {
610 int temp = (i == 0) ? nelem_alloc_first : nelem_alloc;
611
612 if (!element_alloc(hashp, temp, i))
615 errmsg("out of memory")));
616 }
617 }
618
619 /* Set isfixed if requested, but not till after we build initial entries */
620 if (flags & HASH_FIXED_SIZE)
621 hctl->isfixed = true;
622
623 return hashp;
624}
#define Assert(condition)
Definition c.h:943
uint32_t uint32
Definition c.h:624
#define MemSet(start, val, len)
Definition c.h:1107
void(* pg_funcptr_t)(void)
Definition c.h:548
memcpy(sums, checksumBaseOffsets, sizeof(checksumBaseOffsets))
static bool element_alloc(HTAB *hashp, int nelem, int freelist_idx)
Definition dynahash.c:1635
static int next_pow2_int(int64 num)
Definition dynahash.c:1772
static void * DynaHashAlloc(Size size, void *alloc_arg)
Definition dynahash.c:297
#define IS_PARTITIONED(hctl)
Definition dynahash.c:215
#define NUM_FREELISTS
Definition dynahash.c:130
static int string_compare(const char *key1, const char *key2, Size keysize)
Definition dynahash.c:314
static void hdefault(HTAB *hashp)
Definition dynahash.c:630
static bool init_htab(HTAB *hashp, int64 nelem)
Definition dynahash.c:686
int errcode(int sqlerrcode)
Definition elog.c:874
#define ERROR
Definition elog.h:40
#define ereport(elevel,...)
Definition elog.h:152
uint32 tag_hash(const void *key, Size keysize)
Definition hashfn.c:677
uint32 uint32_hash(const void *key, Size keysize)
Definition hashfn.c:688
uint32 string_hash(const void *key, Size keysize)
Definition hashfn.c:660
#define HASH_KEYCOPY
Definition hsearch.h:95
#define HASH_STRINGS
Definition hsearch.h:91
int(* HashCompareFunc)(const void *key1, const void *key2, Size keysize)
Definition hsearch.h:29
#define HASH_CONTEXT
Definition hsearch.h:97
#define HASH_ELEM
Definition hsearch.h:90
#define HASH_ALLOC
Definition hsearch.h:96
#define HASH_ATTACH
Definition hsearch.h:99
#define HASH_COMPARE
Definition hsearch.h:94
#define HASH_FUNCTION
Definition hsearch.h:93
#define HASH_BLOBS
Definition hsearch.h:92
#define HASH_SHARED_MEM
Definition hsearch.h:98
#define HASH_FIXED_SIZE
Definition hsearch.h:100
#define HASH_PARTITION
Definition hsearch.h:87
void *(* HashCopyFunc)(void *dest, const void *src, Size keysize)
Definition hsearch.h:37
void * MemoryContextAlloc(MemoryContext context, Size size)
Definition mcxt.c:1232
MemoryContext TopMemoryContext
Definition mcxt.c:166
void MemoryContextSetIdentifier(MemoryContext context, const char *id)
Definition mcxt.c:661
#define AllocSetContextCreate
Definition memutils.h:129
#define ALLOCSET_DEFAULT_SIZES
Definition memutils.h:160
static char * errmsg
size_t strlcpy(char *dst, const char *src, size_t siz)
Definition strlcpy.c:45
HashAllocFunc alloc
Definition hsearch.h:78
Size keysize
Definition hsearch.h:69
HashValueFunc hash
Definition hsearch.h:72
Size entrysize
Definition hsearch.h:70
void * alloc_arg
Definition hsearch.h:79
HashCompareFunc match
Definition hsearch.h:74
HASHHDR * hctl
Definition hsearch.h:83
MemoryContext hcxt
Definition hsearch.h:81
int64 num_partitions
Definition hsearch.h:67
HashCopyFunc keycopy
Definition hsearch.h:76
Size entrysize
Definition dynahash.c:194
HASHSEGMENT * dir
Definition dynahash.c:201
Size keysize
Definition dynahash.c:193
bool isfixed
Definition dynahash.c:198
int64 num_partitions
Definition dynahash.c:195
bool isshared
Definition dynahash.c:235
HashCompareFunc match
Definition dynahash.c:229
char * tabname
Definition dynahash.c:234
HASHHDR * hctl
Definition dynahash.c:226
MemoryContext hcxt
Definition dynahash.c:233
HashAllocFunc alloc
Definition dynahash.c:231
void * alloc_arg
Definition dynahash.c:232
HASHSEGMENT * dir
Definition dynahash.c:227
HashCopyFunc keycopy
Definition dynahash.c:230
bool frozen
Definition dynahash.c:238

References HTAB::alloc, HASHCTL::alloc, HTAB::alloc_arg, HASHCTL::alloc_arg, ALLOCSET_DEFAULT_SIZES, AllocSetContextCreate, Assert, HASHHDR::dir, HTAB::dir, DynaHashAlloc(), element_alloc(), elog, HASHHDR::entrysize, HASHCTL::entrysize, ereport, errcode(), errmsg, ERROR, fb(), HTAB::frozen, HTAB::hash, HASHCTL::hash, HASH_ALLOC, HASH_ATTACH, HASH_BLOBS, HASH_COMPARE, HASH_CONTEXT, HASH_ELEM, HASH_FIXED_SIZE, HASH_FUNCTION, HASH_KEYCOPY, HASH_PARTITION, HASH_SHARED_MEM, HASH_STRINGS, HTAB::hctl, HASHCTL::hctl, HTAB::hcxt, HASHCTL::hcxt, hdefault(), i, init_htab(), IS_PARTITIONED, HASHHDR::isfixed, HTAB::isshared, HTAB::keycopy, HASHCTL::keycopy, HASHHDR::keysize, HTAB::keysize, HASHCTL::keysize, HTAB::match, HASHCTL::match, memcpy(), MemoryContextAlloc(), MemoryContextSetIdentifier(), MemSet, next_pow2_int(), NUM_FREELISTS, HASHHDR::num_partitions, HASHCTL::num_partitions, string_compare(), string_hash(), strlcpy(), HTAB::tabname, tag_hash(), TopMemoryContext, and uint32_hash().

Referenced by _hash_finish_split(), _PG_init(), AddEventToPendingNotifies(), AddPendingSync(), assign_record_type_typmod(), begin_heap_rewrite(), build_colinfo_names_hash(), build_guc_variables(), build_join_rel_hash(), BuildEventTriggerCache(), cfunc_hashtable_init(), CheckForSessionAndXactLocks(), CompactCheckpointerRequestQueue(), compute_array_stats(), compute_tsvector_stats(), create_seq_hashtable(), createConnHash(), CreateLocalPredicateLockHash(), CreatePartitionDirectory(), do_autovacuum(), EnablePortalManager(), ExecInitModifyTable(), ExecuteTruncateGuts(), find_all_inheritors(), find_oper_cache_entry(), find_rendezvous_variable(), get_json_object_as_hash(), get_relation_notnullatts(), GetComboCommandId(), GetConnection(), gistInitBuildBuffers(), gistInitParentMap(), init_missing_cache(), init_procedure_caches(), init_rel_sync_cache(), init_timezone_hashtable(), init_ts_config_cache(), init_uncommitted_enum_types(), init_uncommitted_enum_values(), InitializeAttoptCache(), InitializeRelfilenumberMap(), InitializeShippableCache(), InitializeTableSpaceCache(), InitLocalBuffers(), initLocalChannelTable(), InitLockManagerAccess(), initPendingListenActions(), InitQueryHashTable(), InitRecoveryTransactionEnvironment(), InitSync(), json_unique_check_init(), load_categories_hash(), log_invalid_page(), logical_begin_heap_rewrite(), logicalrep_partmap_init(), logicalrep_relmap_init(), lookup_proof_cache(), lookup_ts_dictionary_cache(), lookup_ts_parser_cache(), lookup_type_cache(), LookupOpclassInfo(), pa_allocate_worker(), pg_get_backend_memory_contexts(), plpgsql_estate_setup(), PLy_add_exceptions(), populate_recordset_object_start(), ProcessSyncingTablesForApply(), rebuild_database_list(), record_C_func(), RegisterExtensibleNodeEntry(), RelationCacheInitialize(), ReorderBufferAllocate(), ReorderBufferBuildTupleCidHash(), ReorderBufferToastInitHash(), ResetUnloggedRelationsInDbspaceDir(), ri_FastPathGetEntry(), ri_InitHashTables(), select_perl_context(), SerializePendingSyncs(), set_rtable_names(), shmem_hash_create(), smgropen(), transformGraph(), and XLogPrefetcherAllocate().

◆ hash_destroy()

void hash_destroy ( HTAB hashp)
extern

◆ hash_estimate_size()

Size hash_estimate_size ( int64  num_entries,
Size  entrysize 
)
extern

Definition at line 763 of file dynahash.c.

764{
765 Size size;
767 nSegments,
772
773 /* estimate number of buckets wanted */
774 nBuckets = next_pow2_int64(num_entries);
775 /* # of segments needed for nBuckets */
777 /* directory entries */
779
780 /* fixed control info */
781 size = MAXALIGN(sizeof(HASHHDR)); /* but not HTAB, per above */
782 /* directory */
783 size = add_size(size, mul_size(nDirEntries, sizeof(HASHSEGMENT)));
784 /* segments */
785 size = add_size(size, mul_size(nSegments,
786 MAXALIGN(HASH_SEGSIZE * sizeof(HASHBUCKET))));
787 /* elements --- allocated in groups of choose_nelem_alloc() entries */
789 nElementAllocs = (num_entries - 1) / elementAllocCnt + 1;
790 elementSize = MAXALIGN(sizeof(HASHELEMENT)) + MAXALIGN(entrysize);
791 size = add_size(size,
794
795 return size;
796}
#define MAXALIGN(LEN)
Definition c.h:896
#define Max(x, y)
Definition c.h:1085
int64_t int64
Definition c.h:621
size_t Size
Definition c.h:689
#define DEF_DIRSIZE
Definition dynahash.c:127
static int choose_nelem_alloc(Size entrysize)
Definition dynahash.c:653
static int64 next_pow2_int64(int64 num)
Definition dynahash.c:1764
#define HASH_SEGSIZE
Definition dynahash.c:125
Size add_size(Size s1, Size s2)
Definition shmem.c:1048
Size mul_size(Size s1, Size s2)
Definition shmem.c:1063

References add_size(), choose_nelem_alloc(), DEF_DIRSIZE, fb(), HASH_SEGSIZE, Max, MAXALIGN, mul_size(), and next_pow2_int64().

Referenced by InitShmemAllocator(), ShmemGetRequestedSize(), ShmemInitHash(), and ShmemRequestHashWithOpts().

◆ hash_freeze()

void hash_freeze ( HTAB hashp)
extern

Definition at line 1464 of file dynahash.c.

1465{
1466 if (hashp->isshared)
1467 elog(ERROR, "cannot freeze shared hashtable \"%s\"", hashp->tabname);
1468 if (!hashp->frozen && has_seq_scans(hashp))
1469 elog(ERROR, "cannot freeze hashtable \"%s\" because it has active scans",
1470 hashp->tabname);
1471 hashp->frozen = true;
1472}
static bool has_seq_scans(HTAB *hashp)
Definition dynahash.c:1850

References elog, ERROR, HTAB::frozen, has_seq_scans(), HTAB::isshared, and HTAB::tabname.

◆ hash_get_num_entries()

int64 hash_get_num_entries ( HTAB hashp)
extern

Definition at line 1273 of file dynahash.c.

1274{
1275 int i;
1276 int64 sum = hashp->hctl->freeList[0].nentries;
1277
1278 /*
1279 * We currently don't bother with acquiring the mutexes; it's only
1280 * sensible to call this function if you've got lock on all partitions of
1281 * the table.
1282 */
1283 if (IS_PARTITIONED(hashp->hctl))
1284 {
1285 for (i = 1; i < NUM_FREELISTS; i++)
1286 sum += hashp->hctl->freeList[i].nentries;
1287 }
1288
1289 return sum;
1290}
int64 nentries
Definition dynahash.c:158
FreeListData freeList[NUM_FREELISTS]
Definition dynahash.c:182

References HASHHDR::freeList, HTAB::hctl, i, IS_PARTITIONED, FreeListData::nentries, and NUM_FREELISTS.

Referenced by build_guc_variables(), compute_array_stats(), compute_tsvector_stats(), entry_alloc(), entry_dealloc(), entry_reset(), EstimatePendingSyncsSpace(), EstimateUncommittedEnumsSpace(), get_crosstab_tuplestore(), get_explain_guc_options(), get_guc_variables(), GetLockStatusData(), GetPredicateLockStatusData(), GetRunningTransactionLocks(), GetWaitEventCustomNames(), hash_stats(), pgss_shmem_shutdown(), ResetUnloggedRelationsInDbspaceDir(), SerializePendingSyncs(), transformGraph(), and XLogHaveInvalidPages().

◆ hash_search()

void * hash_search ( HTAB hashp,
const void keyPtr,
HASHACTION  action,
bool foundPtr 
)
extern

Definition at line 889 of file dynahash.c.

893{
894 return hash_search_with_hash_value(hashp,
895 keyPtr,
896 hashp->hash(keyPtr, hashp->keysize),
897 action,
898 foundPtr);
899}
void * hash_search_with_hash_value(HTAB *hashp, const void *keyPtr, uint32 hashvalue, HASHACTION action, bool *foundPtr)
Definition dynahash.c:902

References fb(), HTAB::hash, hash_search_with_hash_value(), and HTAB::keysize.

Referenced by _hash_finish_split(), _hash_splitbucket(), add_guc_variable(), add_join_rel(), add_to_names_hash(), AddEnumLabel(), AddEventToPendingNotifies(), AddPendingSync(), ApplyLogicalMappingFile(), ApplyPendingListenActions(), assign_record_type_typmod(), AsyncExistsPendingNotify(), AtEOSubXact_RelationCache(), AtEOXact_RelationCache(), AttachShmemIndexEntry(), build_guc_variables(), build_join_rel_hash(), BuildEventTriggerCache(), CallShmemCallbacksAfterStartup(), cfunc_hashtable_delete(), cfunc_hashtable_insert(), cfunc_hashtable_lookup(), CheckAndPromotePredicateLockRequest(), CheckForSerializableConflictOut(), CheckForSessionAndXactLocks(), colname_is_unique(), CompactCheckpointerRequestQueue(), compile_plperl_function(), compile_pltcl_function(), compute_array_stats(), compute_tsvector_stats(), createNewConnection(), define_custom_variable(), delete_rel_type_cache_if_needed(), deleteConnection(), do_autovacuum(), DropAllPredicateLocksFromTable(), DropAllPreparedStatements(), DropPreparedStatement(), entry_alloc(), entry_dealloc(), entry_reset(), EnumTypeUncommitted(), EnumUncommitted(), EnumValuesCreate(), EventCacheLookup(), ExecInitModifyTable(), ExecLookupResultRelByOid(), ExecuteTruncateGuts(), ExtendBufferedRelLocal(), FetchPreparedStatement(), finalize_in_progress_typentries(), find_all_inheritors(), find_join_rel(), find_oper_cache_entry(), find_option(), find_relation_notnullatts(), find_rendezvous_variable(), forget_invalid_pages(), forget_invalid_pages_db(), get_attribute_options(), get_cast_hashentry(), get_rel_sync_entry(), get_relation_notnullatts(), get_tablespace(), GetComboCommandId(), GetConnection(), getConnectionByName(), GetExtensibleNodeEntry(), getmissingattr(), getState(), GetWaitEventCustomIdentifier(), gistGetNodeBuffer(), gistGetParent(), gistMemorizeParent(), gistRelocateBuildBuffersOnSplit(), hash_object_field_end(), init_sequence(), InitShmemAllocator(), InitShmemIndexEntry(), insert_rel_type_cache_if_needed(), InvalidateAttoptCacheCallback(), InvalidateLocalBuffer(), InvalidateOprCacheCallBack(), InvalidateShippableCacheCallback(), InvalidateTableSpaceCacheCallback(), is_shippable(), IsListeningOn(), JsObjectGetField(), json_unique_check_key(), LocalBufferAlloc(), LockAcquireExtended(), LockHasWaiters(), LockHeldByMe(), LockRelease(), log_invalid_page(), logical_rewrite_log_mapping(), logicalrep_partition_open(), logicalrep_rel_open(), logicalrep_relmap_update(), lookup_C_func(), lookup_proof_cache(), lookup_ts_config_cache(), lookup_ts_dictionary_cache(), lookup_ts_parser_cache(), lookup_type_cache(), LookupOpclassInfo(), make_oper_cache_entry(), MarkGUCPrefixReserved(), pa_allocate_worker(), pa_find_worker(), pa_free_worker(), PartitionDirectoryLookup(), pg_get_backend_memory_contexts(), pg_tzset(), pgss_store(), plperl_spi_exec_prepared(), plperl_spi_freeplan(), plperl_spi_prepare(), plperl_spi_query_prepared(), pltcl_fetch_interp(), PLy_commit(), PLy_generate_spi_exceptions(), PLy_procedure_get(), PLy_rollback(), PLy_spi_subtransaction_abort(), populate_recordset_object_field_end(), predicatelock_twophase_recover(), PredicateLockExists(), PredicateLockShmemInit(), PredicateLockTwoPhaseFinish(), PrefetchLocalBuffer(), PrepareTableEntriesForListen(), PrepareTableEntriesForUnlisten(), PrepareTableEntriesForUnlistenAll(), ProcessSyncingTablesForApply(), ProcessSyncRequests(), prune_element_hashtable(), prune_lexemes_hashtable(), PutMemoryContextsStatsTupleStore(), rebuild_database_list(), record_C_func(), RegisterExtensibleNodeEntry(), RegisterPredicateLockingXid(), rel_sync_cache_relation_cb(), RelationPreTruncate(), ReleaseOneSerializableXact(), RelFileLocatorSkippingWAL(), RelfilenumberMapInvalidateCallback(), RelidByRelfilenumber(), RememberSyncRequest(), RemoveLocalLock(), ReorderBufferBuildTupleCidHash(), ReorderBufferCleanupTXN(), ReorderBufferToastAppendChunk(), ReorderBufferToastReplace(), ReorderBufferTXNByXid(), ResetUnloggedRelationsInDbspaceDir(), ResolveCminCmaxDuringDecoding(), RestoreUncommittedEnums(), rewrite_heap_dead_tuple(), rewrite_heap_tuple(), ri_FastPathGetEntry(), ri_FetchPreparedPlan(), ri_HashCompareOp(), ri_HashPreparedPlan(), ri_LoadConstraintInfo(), select_perl_context(), SerializePendingSyncs(), set_rtable_names(), smgrdestroy(), smgrDoPendingSyncs(), smgropen(), smgrreleaserellocator(), StandbyAcquireAccessExclusiveLock(), StandbyReleaseAllLocks(), StandbyReleaseLocks(), StandbyReleaseOldLocks(), StandbyReleaseXidEntryLocks(), StorePreparedStatement(), table_recheck_autovac(), TypeCacheRelCallback(), WaitEventCustomNew(), XLogPrefetcherAddFilter(), XLogPrefetcherCompleteFilters(), and XLogPrefetcherIsFiltered().

◆ hash_search_with_hash_value()

void * hash_search_with_hash_value ( HTAB hashp,
const void keyPtr,
uint32  hashvalue,
HASHACTION  action,
bool foundPtr 
)
extern

Definition at line 902 of file dynahash.c.

907{
908 HASHHDR *hctl = hashp->hctl;
909 int freelist_idx = FREELIST_IDX(hctl, hashvalue);
910 Size keysize;
913 HashCompareFunc match;
914
915#ifdef HASH_STATISTICS
916 hctl->accesses++;
917#endif
918
919 /*
920 * If inserting, check if it is time to split a bucket.
921 *
922 * NOTE: failure to expand table is not a fatal error, it just means we
923 * have to run at higher fill factor than we wanted. However, if we're
924 * using the palloc allocator then it will throw error anyway on
925 * out-of-memory, so we must do this before modifying the table.
926 */
927 if (action == HASH_ENTER || action == HASH_ENTER_NULL)
928 {
929 /*
930 * Can't split if running in partitioned mode, nor if frozen, nor if
931 * table is the subject of any active hash_seq_search scans.
932 */
933 if (hctl->freeList[0].nentries > (int64) hctl->max_bucket &&
934 !IS_PARTITIONED(hctl) && !hashp->frozen &&
935 !has_seq_scans(hashp))
936 (void) expand_table(hashp);
937 }
938
939 /*
940 * Do the initial lookup
941 */
942 (void) hash_initial_lookup(hashp, hashvalue, &prevBucketPtr);
944
945 /*
946 * Follow collision chain looking for matching key
947 */
948 match = hashp->match; /* save one fetch in inner loop */
949 keysize = hashp->keysize; /* ditto */
950
951 while (currBucket != NULL)
952 {
953 if (currBucket->hashvalue == hashvalue &&
954 match(ELEMENTKEY(currBucket), keyPtr, keysize) == 0)
955 break;
956 prevBucketPtr = &(currBucket->link);
958#ifdef HASH_STATISTICS
959 hctl->collisions++;
960#endif
961 }
962
963 if (foundPtr)
964 *foundPtr = (bool) (currBucket != NULL);
965
966 /*
967 * OK, now what?
968 */
969 switch (action)
970 {
971 case HASH_FIND:
972 if (currBucket != NULL)
973 return ELEMENTKEY(currBucket);
974 return NULL;
975
976 case HASH_REMOVE:
977 if (currBucket != NULL)
978 {
979 /* if partitioned, must lock to touch nentries and freeList */
980 if (IS_PARTITIONED(hctl))
982
983 /* delete the record from the appropriate nentries counter. */
986
987 /* remove record from hash bucket's chain. */
988 *prevBucketPtr = currBucket->link;
989
990 /* add the record to the appropriate freelist. */
993
994 if (IS_PARTITIONED(hctl))
996
997 /*
998 * better hope the caller is synchronizing access to this
999 * element, because someone else is going to reuse it the next
1000 * time something is added to the table
1001 */
1002 return ELEMENTKEY(currBucket);
1003 }
1004 return NULL;
1005
1006 case HASH_ENTER:
1007 case HASH_ENTER_NULL:
1008 /* Return existing element if found, else create one */
1009 if (currBucket != NULL)
1010 return ELEMENTKEY(currBucket);
1011
1012 /* disallow inserts if frozen */
1013 if (hashp->frozen)
1014 elog(ERROR, "cannot insert into frozen hashtable \"%s\"",
1015 hashp->tabname);
1016
1018 if (currBucket == NULL)
1019 {
1020 /* out of memory */
1021 if (action == HASH_ENTER_NULL)
1022 return NULL;
1023 /* report a generic message */
1024 if (hashp->isshared)
1025 ereport(ERROR,
1027 errmsg("out of shared memory")));
1028 else
1029 ereport(ERROR,
1031 errmsg("out of memory")));
1032 }
1033
1034 /* link into hashbucket chain */
1036 currBucket->link = NULL;
1037
1038 /* copy key into record */
1039 currBucket->hashvalue = hashvalue;
1040 hashp->keycopy(ELEMENTKEY(currBucket), keyPtr, keysize);
1041
1042 /*
1043 * Caller is expected to fill the data field on return. DO NOT
1044 * insert any code that could possibly throw error here, as doing
1045 * so would leave the table entry incomplete and hence corrupt the
1046 * caller's data structure.
1047 */
1048
1049 return ELEMENTKEY(currBucket);
1050 }
1051
1052 elog(ERROR, "unrecognized hash action code: %d", (int) action);
1053
1054 return NULL; /* keep compiler quiet */
1055}
static HASHBUCKET get_hash_entry(HTAB *hashp, int freelist_idx)
Definition dynahash.c:1188
static bool expand_table(HTAB *hashp)
Definition dynahash.c:1481
#define ELEMENTKEY(helem)
Definition dynahash.c:257
#define FREELIST_IDX(hctl, hashcode)
Definition dynahash.c:217
static uint32 hash_initial_lookup(HTAB *hashp, uint32 hashvalue, HASHBUCKET **bucketptr)
Definition dynahash.c:1712
static void SpinLockRelease(volatile slock_t *lock)
Definition spin.h:62
static void SpinLockAcquire(volatile slock_t *lock)
Definition spin.h:56
slock_t mutex
Definition dynahash.c:157
HASHELEMENT * freeList
Definition dynahash.c:159
uint32 max_bucket
Definition dynahash.c:188

References Assert, ELEMENTKEY, elog, ereport, errcode(), errmsg, ERROR, expand_table(), fb(), FreeListData::freeList, HASHHDR::freeList, FREELIST_IDX, HTAB::frozen, get_hash_entry(), has_seq_scans(), HASH_ENTER, HASH_ENTER_NULL, HASH_FIND, hash_initial_lookup(), HASH_REMOVE, HTAB::hctl, IS_PARTITIONED, HTAB::isshared, HTAB::keycopy, HTAB::keysize, HTAB::match, HASHHDR::max_bucket, FreeListData::mutex, FreeListData::nentries, SpinLockAcquire(), SpinLockRelease(), and HTAB::tabname.

Referenced by BufTableDelete(), BufTableInsert(), BufTableLookup(), CheckTargetForConflictsIn(), CleanUpLock(), ClearOldPredicateLocks(), CreatePredicateLock(), DecrementParentLocks(), DeleteChildTargetLocks(), DeleteLockTarget(), DropAllPredicateLocksFromTable(), FastPathGetRelationLockEntry(), GetLockConflicts(), hash_search(), lock_twophase_recover(), LockAcquireExtended(), LockRefindAndRelease(), LockRelease(), LockWaiterCount(), PageIsPredicateLocked(), PredicateLockAcquire(), ReleaseOneSerializableXact(), RemoveScratchTarget(), RemoveTargetIfNoLongerUsed(), RestoreScratchTarget(), SetupLockInTable(), and TransferPredicateLocksToNewTarget().

◆ hash_seq_init()

void hash_seq_init ( HASH_SEQ_STATUS status,
HTAB hashp 
)
extern

Definition at line 1317 of file dynahash.c.

1318{
1319 status->hashp = hashp;
1320 status->curBucket = 0;
1321 status->curEntry = NULL;
1322 status->hasHashvalue = false;
1323 if (!hashp->frozen)
1324 register_seq_scan(hashp);
1325}
static void register_seq_scan(HTAB *hashp)
Definition dynahash.c:1817
HASHELEMENT * curEntry
Definition hsearch.h:119
uint32 curBucket
Definition hsearch.h:118
bool hasHashvalue
Definition hsearch.h:120

References HASH_SEQ_STATUS::curBucket, HASH_SEQ_STATUS::curEntry, fb(), HTAB::frozen, HASH_SEQ_STATUS::hasHashvalue, HASH_SEQ_STATUS::hashp, and register_seq_scan().

Referenced by ApplyPendingListenActions(), AtAbort_Portals(), AtCleanup_Portals(), AtEOSubXact_RelationCache(), AtEOXact_RelationCache(), AtPrepare_Locks(), AtSubAbort_Portals(), AtSubCleanup_Portals(), AtSubCommit_Portals(), BeginReportingGUCOptions(), CheckForSessionAndXactLocks(), CheckTableForSerializableConflictIn(), cleanup_rel_sync_cache(), compute_array_stats(), compute_tsvector_stats(), dblink_get_connections(), DestroyPartitionDirectory(), disconnect_cached_connections(), DropAllPredicateLocksFromTable(), DropAllPreparedStatements(), end_heap_rewrite(), entry_dealloc(), entry_reset(), ExecuteTruncateGuts(), forget_invalid_pages(), forget_invalid_pages_db(), ForgetPortalSnapshots(), gc_qtexts(), get_guc_variables(), GetLockStatusData(), GetPredicateLockStatusData(), GetRunningTransactionLocks(), GetWaitEventCustomNames(), hash_seq_init_with_hash_value(), HoldPinnedPortals(), InitializeGUCOptions(), InvalidateAttoptCacheCallback(), InvalidateOprCacheCallBack(), InvalidateOprProofCacheCallBack(), InvalidateShippableCacheCallback(), InvalidateTableSpaceCacheCallback(), InvalidateTSCacheCallBack(), LockReassignCurrentOwner(), LockReleaseAll(), LockReleaseCurrentOwner(), LockReleaseSession(), logical_end_heap_rewrite(), logical_heap_rewrite_flush_mappings(), logicalrep_partmap_invalidate_cb(), logicalrep_partmap_reset_relmap(), logicalrep_relmap_invalidate_cb(), MarkGUCPrefixReserved(), packGraph(), pg_cursor(), pg_get_shmem_allocations(), pg_get_shmem_allocations_numa(), pg_listening_channels(), pg_prepared_statement(), pg_stat_statements_internal(), pgfdw_inval_callback(), pgfdw_subxact_callback(), pgfdw_xact_callback(), pgss_shmem_shutdown(), plperl_fini(), PortalErrorCleanup(), PortalHashTableDeleteAll(), postgres_fdw_get_connections_internal(), PostPrepare_Locks(), PreCommit_Notify(), PreCommit_Portals(), PrepareTableEntriesForUnlistenAll(), ProcessConfigFileInternal(), ProcessSyncRequests(), prune_element_hashtable(), prune_lexemes_hashtable(), rebuild_database_list(), rel_sync_cache_publication_cb(), rel_sync_cache_relation_cb(), RelationCacheInitializePhase3(), RelationCacheInvalidate(), RelfilenumberMapInvalidateCallback(), RememberSyncRequest(), ReorderBufferToastReset(), ri_FastPathEndBatch(), ri_FastPathTeardown(), selectColorTrigrams(), SerializePendingSyncs(), SerializeUncommittedEnums(), smgrDoPendingSyncs(), smgrreleaseall(), StandbyReleaseAllLocks(), StandbyReleaseOldLocks(), ThereAreNoReadyPortals(), TypeCacheOpcCallback(), TypeCacheRelCallback(), TypeCacheTypCallback(), write_relcache_init_file(), and XLogCheckInvalidPages().

◆ hash_seq_init_with_hash_value()

void hash_seq_init_with_hash_value ( HASH_SEQ_STATUS status,
HTAB hashp,
uint32  hashvalue 
)
extern

Definition at line 1337 of file dynahash.c.

1339{
1341
1342 hash_seq_init(status, hashp);
1343
1344 status->hasHashvalue = true;
1345 status->hashvalue = hashvalue;
1346
1347 status->curBucket = hash_initial_lookup(hashp, hashvalue, &bucketPtr);
1348 status->curEntry = *bucketPtr;
1349}
void hash_seq_init(HASH_SEQ_STATUS *status, HTAB *hashp)
Definition dynahash.c:1317
uint32 hashvalue
Definition hsearch.h:121

References HASH_SEQ_STATUS::curBucket, HASH_SEQ_STATUS::curEntry, fb(), hash_initial_lookup(), hash_seq_init(), HASH_SEQ_STATUS::hasHashvalue, and HASH_SEQ_STATUS::hashvalue.

Referenced by InvalidateAttoptCacheCallback(), and TypeCacheTypCallback().

◆ hash_seq_search()

void * hash_seq_search ( HASH_SEQ_STATUS status)
extern

Definition at line 1352 of file dynahash.c.

1353{
1354 HTAB *hashp;
1355 HASHHDR *hctl;
1356 uint32 max_bucket;
1360 uint32 curBucket;
1362
1363 if (status->hasHashvalue)
1364 {
1365 /*
1366 * Scan entries only in the current bucket because only this bucket
1367 * can contain entries with the given hash value.
1368 */
1369 while ((curElem = status->curEntry) != NULL)
1370 {
1371 status->curEntry = curElem->link;
1372 if (status->hashvalue != curElem->hashvalue)
1373 continue;
1374 return (void *) ELEMENTKEY(curElem);
1375 }
1376
1377 hash_seq_term(status);
1378 return NULL;
1379 }
1380
1381 if ((curElem = status->curEntry) != NULL)
1382 {
1383 /* Continuing scan of curBucket... */
1384 status->curEntry = curElem->link;
1385 if (status->curEntry == NULL) /* end of this bucket */
1386 ++status->curBucket;
1387 return ELEMENTKEY(curElem);
1388 }
1389
1390 /*
1391 * Search for next nonempty bucket starting at curBucket.
1392 */
1393 curBucket = status->curBucket;
1394 hashp = status->hashp;
1395 hctl = hashp->hctl;
1396 max_bucket = hctl->max_bucket;
1397
1398 if (curBucket > max_bucket)
1399 {
1400 hash_seq_term(status);
1401 return NULL; /* search is done */
1402 }
1403
1404 /*
1405 * first find the right segment in the table directory.
1406 */
1407 segment_num = curBucket >> HASH_SEGSIZE_SHIFT;
1408 segment_ndx = MOD(curBucket, HASH_SEGSIZE);
1409
1410 segp = hashp->dir[segment_num];
1411
1412 /*
1413 * Pick up the first item in this bucket's chain. If chain is not empty
1414 * we can begin searching it. Otherwise we have to advance to find the
1415 * next nonempty bucket. We try to optimize that case since searching a
1416 * near-empty hashtable has to iterate this loop a lot.
1417 */
1418 while ((curElem = segp[segment_ndx]) == NULL)
1419 {
1420 /* empty bucket, advance to next */
1421 if (++curBucket > max_bucket)
1422 {
1423 status->curBucket = curBucket;
1424 hash_seq_term(status);
1425 return NULL; /* search is done */
1426 }
1427 if (++segment_ndx >= HASH_SEGSIZE)
1428 {
1429 segment_num++;
1430 segment_ndx = 0;
1431 segp = hashp->dir[segment_num];
1432 }
1433 }
1434
1435 /* Begin scan of curBucket... */
1436 status->curEntry = curElem->link;
1437 if (status->curEntry == NULL) /* end of this bucket */
1438 ++curBucket;
1439 status->curBucket = curBucket;
1440 return ELEMENTKEY(curElem);
1441}
#define HASH_SEGSIZE_SHIFT
Definition dynahash.c:126
#define MOD(x, y)
Definition dynahash.c:268
void hash_seq_term(HASH_SEQ_STATUS *status)
Definition dynahash.c:1444
struct HASHELEMENT * link
Definition hsearch.h:52

References HASH_SEQ_STATUS::curBucket, HASH_SEQ_STATUS::curEntry, HTAB::dir, ELEMENTKEY, fb(), HASH_SEGSIZE, HASH_SEGSIZE_SHIFT, hash_seq_term(), HASH_SEQ_STATUS::hasHashvalue, HASH_SEQ_STATUS::hashp, HASH_SEQ_STATUS::hashvalue, HTAB::hctl, HASHELEMENT::link, HASHHDR::max_bucket, and MOD.

Referenced by ApplyPendingListenActions(), AtAbort_Portals(), AtCleanup_Portals(), AtEOSubXact_RelationCache(), AtEOXact_RelationCache(), AtPrepare_Locks(), AtSubAbort_Portals(), AtSubCleanup_Portals(), AtSubCommit_Portals(), BeginReportingGUCOptions(), CheckForSessionAndXactLocks(), CheckTableForSerializableConflictIn(), cleanup_rel_sync_cache(), compute_array_stats(), compute_tsvector_stats(), dblink_get_connections(), DestroyPartitionDirectory(), disconnect_cached_connections(), DropAllPredicateLocksFromTable(), DropAllPreparedStatements(), end_heap_rewrite(), entry_dealloc(), entry_reset(), ExecuteTruncateGuts(), forget_invalid_pages(), forget_invalid_pages_db(), ForgetPortalSnapshots(), gc_qtexts(), get_guc_variables(), GetLockStatusData(), GetPredicateLockStatusData(), GetRunningTransactionLocks(), GetWaitEventCustomNames(), HoldPinnedPortals(), InitializeGUCOptions(), InvalidateAttoptCacheCallback(), InvalidateOprCacheCallBack(), InvalidateOprProofCacheCallBack(), InvalidateShippableCacheCallback(), InvalidateTableSpaceCacheCallback(), InvalidateTSCacheCallBack(), LockReassignCurrentOwner(), LockReleaseAll(), LockReleaseCurrentOwner(), LockReleaseSession(), logical_end_heap_rewrite(), logical_heap_rewrite_flush_mappings(), logicalrep_partmap_invalidate_cb(), logicalrep_partmap_reset_relmap(), logicalrep_relmap_invalidate_cb(), MarkGUCPrefixReserved(), packGraph(), pg_cursor(), pg_get_shmem_allocations(), pg_get_shmem_allocations_numa(), pg_listening_channels(), pg_prepared_statement(), pg_stat_statements_internal(), pgfdw_inval_callback(), pgfdw_subxact_callback(), pgfdw_xact_callback(), pgss_shmem_shutdown(), plperl_fini(), PortalErrorCleanup(), PortalHashTableDeleteAll(), postgres_fdw_get_connections_internal(), PostPrepare_Locks(), PreCommit_Notify(), PreCommit_Portals(), PrepareTableEntriesForUnlistenAll(), ProcessConfigFileInternal(), ProcessSyncRequests(), prune_element_hashtable(), prune_lexemes_hashtable(), rebuild_database_list(), rel_sync_cache_publication_cb(), rel_sync_cache_relation_cb(), RelationCacheInitializePhase3(), RelationCacheInvalidate(), RelfilenumberMapInvalidateCallback(), RememberSyncRequest(), ReorderBufferToastReset(), ri_FastPathEndBatch(), ri_FastPathTeardown(), selectColorTrigrams(), SerializePendingSyncs(), SerializeUncommittedEnums(), smgrDoPendingSyncs(), smgrreleaseall(), StandbyReleaseAllLocks(), StandbyReleaseOldLocks(), ThereAreNoReadyPortals(), TypeCacheOpcCallback(), TypeCacheRelCallback(), TypeCacheTypCallback(), write_relcache_init_file(), and XLogCheckInvalidPages().

◆ hash_seq_term()

◆ hash_stats()

void hash_stats ( const char caller,
HTAB hashp 
)
extern

Definition at line 821 of file dynahash.c.

822{
823#ifdef HASH_STATISTICS
824 HASHHDR *hctl = hashp->hctl;
825
826 elog(DEBUG4,
827 "hash_stats: Caller: %s Table Name: \"%s\" Accesses: " UINT64_FORMAT " Collisions: " UINT64_FORMAT " Expansions: " UINT64_FORMAT " Entries: " INT64_FORMAT " Key Size: %zu Max Bucket: %u Segment Count: " INT64_FORMAT,
828 caller != NULL ? caller : "(unknown)", hashp->tabname, hctl->accesses,
829 hctl->collisions, hctl->expansions, hash_get_num_entries(hashp),
830 hctl->keysize, hctl->max_bucket, hctl->nsegs);
831#endif
832}
#define INT64_FORMAT
Definition c.h:634
#define UINT64_FORMAT
Definition c.h:635
int64 hash_get_num_entries(HTAB *hashp)
Definition dynahash.c:1273
#define DEBUG4
Definition elog.h:28

References DEBUG4, elog, fb(), hash_get_num_entries(), HTAB::hctl, INT64_FORMAT, HASHHDR::keysize, HASHHDR::max_bucket, HASHHDR::nsegs, HTAB::tabname, and UINT64_FORMAT.

Referenced by hash_destroy().

◆ hash_update_hash_key()

bool hash_update_hash_key ( HTAB hashp,
void existingEntry,
const void newKeyPtr 
)
extern

Definition at line 1077 of file dynahash.c.

1080{
1083 Size keysize;
1084 uint32 bucket;
1089 HashCompareFunc match;
1090
1091#ifdef HASH_STATISTICS
1092 HASHHDR *hctl = hashp->hctl;
1093
1094 hctl->accesses++;
1095#endif
1096
1097 /* disallow updates if frozen */
1098 if (hashp->frozen)
1099 elog(ERROR, "cannot update in frozen hashtable \"%s\"",
1100 hashp->tabname);
1101
1102 /*
1103 * Lookup the existing element using its saved hash value. We need to do
1104 * this to be able to unlink it from its hash chain, but as a side benefit
1105 * we can verify the validity of the passed existingEntry pointer.
1106 */
1107 bucket = hash_initial_lookup(hashp, existingElement->hashvalue,
1108 &prevBucketPtr);
1110
1111 while (currBucket != NULL)
1112 {
1114 break;
1115 prevBucketPtr = &(currBucket->link);
1117 }
1118
1119 if (currBucket == NULL)
1120 elog(ERROR, "hash_update_hash_key argument is not in hashtable \"%s\"",
1121 hashp->tabname);
1122
1124
1125 /*
1126 * Now perform the equivalent of a HASH_ENTER operation to locate the hash
1127 * chain we want to put the entry into.
1128 */
1129 newhashvalue = hashp->hash(newKeyPtr, hashp->keysize);
1132
1133 /*
1134 * Follow collision chain looking for matching key
1135 */
1136 match = hashp->match; /* save one fetch in inner loop */
1137 keysize = hashp->keysize; /* ditto */
1138
1139 while (currBucket != NULL)
1140 {
1141 if (currBucket->hashvalue == newhashvalue &&
1142 match(ELEMENTKEY(currBucket), newKeyPtr, keysize) == 0)
1143 break;
1144 prevBucketPtr = &(currBucket->link);
1146#ifdef HASH_STATISTICS
1147 hctl->collisions++;
1148#endif
1149 }
1150
1151 if (currBucket != NULL)
1152 return false; /* collision with an existing entry */
1153
1155
1156 /*
1157 * If old and new hash values belong to the same bucket, we need not
1158 * change any chain links, and indeed should not since this simplistic
1159 * update will corrupt the list if currBucket is the last element. (We
1160 * cannot fall out earlier, however, since we need to scan the bucket to
1161 * check for duplicate keys.)
1162 */
1163 if (bucket != newbucket)
1164 {
1165 /* OK to remove record from old hash bucket's chain. */
1166 *oldPrevPtr = currBucket->link;
1167
1168 /* link into new hashbucket chain */
1170 currBucket->link = NULL;
1171 }
1172
1173 /* copy new key into record */
1174 currBucket->hashvalue = newhashvalue;
1175 hashp->keycopy(ELEMENTKEY(currBucket), newKeyPtr, keysize);
1176
1177 /* rest of record is untouched */
1178
1179 return true;
1180}
#define ELEMENT_FROM_KEY(key)
Definition dynahash.c:262

References ELEMENT_FROM_KEY, ELEMENTKEY, elog, ERROR, fb(), HTAB::frozen, HTAB::hash, hash_initial_lookup(), HTAB::hctl, HTAB::keycopy, HTAB::keysize, HTAB::match, and HTAB::tabname.

Referenced by PostPrepare_Locks().