mirror of
https://github.com/postgres/postgres.git
synced 2025-07-30 11:03:19 +03:00
Add gen_random_uuid() to contrib/pgcrypto.
This function provides a way of generating version 4 (pseudorandom) UUIDs based on pgcrypto's PRNG. The main reason for doing this is that the OSSP UUID library depended on by contrib/uuid-ossp is becoming more and more of a porting headache, so we need an alternative for people who can't install that. A nice side benefit though is that this implementation is noticeably faster than uuid-ossp's uuid_generate_v4() function. Oskari Saarenmaa, reviewed by Emre Hasegeli
This commit is contained in:
@ -35,6 +35,7 @@
|
||||
|
||||
#include "parser/scansup.h"
|
||||
#include "utils/builtins.h"
|
||||
#include "utils/uuid.h"
|
||||
|
||||
#include "px.h"
|
||||
#include "px-crypt.h"
|
||||
@ -443,6 +444,32 @@ pg_random_bytes(PG_FUNCTION_ARGS)
|
||||
PG_RETURN_BYTEA_P(res);
|
||||
}
|
||||
|
||||
/* SQL function: gen_random_uuid() returns uuid */
|
||||
PG_FUNCTION_INFO_V1(pg_random_uuid);
|
||||
|
||||
Datum
|
||||
pg_random_uuid(PG_FUNCTION_ARGS)
|
||||
{
|
||||
uint8 *buf = (uint8 *) palloc(UUID_LEN);
|
||||
int err;
|
||||
|
||||
/* generate random bits */
|
||||
err = px_get_pseudo_random_bytes(buf, UUID_LEN);
|
||||
if (err < 0)
|
||||
ereport(ERROR,
|
||||
(errcode(ERRCODE_EXTERNAL_ROUTINE_INVOCATION_EXCEPTION),
|
||||
errmsg("Random generator error: %s", px_strerror(err))));
|
||||
|
||||
/*
|
||||
* Set magic numbers for a "version 4" (pseudorandom) UUID, see
|
||||
* http://tools.ietf.org/html/rfc4122#section-4.4
|
||||
*/
|
||||
buf[6] = (buf[6] & 0x0f) | 0x40; /* "version" field */
|
||||
buf[8] = (buf[8] & 0x3f) | 0x80; /* "variant" field */
|
||||
|
||||
PG_RETURN_UUID_P((pg_uuid_t *) buf);
|
||||
}
|
||||
|
||||
static void *
|
||||
find_provider(text *name,
|
||||
PFN provider_lookup,
|
||||
|
Reference in New Issue
Block a user