哈希表
来自 PostgreSQL wiki
跳转到导航跳转到搜索
此代码演示了 PostgreSQL 哈希表的用法
#include "postgres.h"
#include "fmgr.h"
#include "utils/hsearch.h"
PG_MODULE_MAGIC;
/* 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);
hashtable = hash_create("test hash table", 2, &ctl, HASH_ELEM | HASH_BLOBS);
}
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);
else
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);
else
elog(NOTICE, "Couldn't find key %d, though it should be there", i);
}
}