From PostgreSQL wiki

Revision as of 15:49, 4 August 2010 by Tgl (Talk | contribs)

(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to: navigation, search


Using the PostgreSQL Hash Table

Works with PostgreSQL

any version

Written in


Depends on


This code demonstrates use of the PostgreSQL hash table

#include "postgres.h"
#include "fmgr.h"
#include "utils/hsearch.h"
/* Hash table tester */
const int NUM_ELEMS = 10;
typedef struct hashkey {
    int num;
} HashKey;
typedef struct hashelem {
    HashKey key;
    int mydata;
} HashElem;
static HTAB *hashtable = NULL;
void _PG_init(void) {
    HASHCTL ctl;
    Assert(hashtable == NULL);
    memset(&ctl, 0, sizeof(ctl));
    ctl.keysize = sizeof(HashKey);
    ctl.entrysize = sizeof(HashElem);
    ctl.hash = tag_hash;
    hashtable = hash_create("test hash table", 2, &ctl, HASH_ELEM | HASH_FUNCTION);
Datum hash_tester(PG_FUNCTION_ARGS) {
    int i;
    HashKey key;
    HashElem *elem;
    bool found;
    for (i = 0; i < NUM_ELEMS; i++) {
        key.num = i;
        elem = hash_search(hashtable, (void *)&key, HASH_ENTER, &found);
        if (found)
            elog(WARNING, "Found entry %d before it was supposed to be added", i);
            elog(NOTICE, "Didn't find %d -- good", i);
        elem->mydata = i;
    for (i = 0; i < NUM_ELEMS; i++) {
        key.num = i;
        elem = hash_search(hashtable, (void *)&key, HASH_FIND, &found);
        if (found)
            elog(NOTICE, "Found key id %d with element %d", i, elem->mydata);
            elog(NOTICE, "Couldn't find key %d, though it should be there", i);
Personal tools