-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpg_uuid_next.c
96 lines (74 loc) · 2.32 KB
/
pg_uuid_next.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
/*-------------------------------------------------------------------------
*
* pg_uuid_next.c
* UUIDs for better data locality
*
*-------------------------------------------------------------------------
*/
#include "postgres.h"
#include <sys/time.h>
#include "common/hashfn.h"
#include "port/pg_bswap.h"
#include "miscadmin.h"
#include "utils/builtins.h"
#include "utils/uuid.h"
PG_MODULE_MAGIC;
PG_FUNCTION_INFO_V1(gen_uuid_v7);
Datum
gen_uuid_v7(PG_FUNCTION_ARGS)
{
pg_uuid_t *uuid = palloc(UUID_LEN);
struct timeval tp;
uint64_t tms;
gettimeofday(&tp, NULL);
tms = ((uint64_t)tp.tv_sec) * 1000;
tms += ((uint64_t)tp.tv_usec) / 1000;
tms = pg_hton64(tms<<16);
/* Fill in time part */
memcpy(&uuid->data[0], &tms, 6);
/* fill everything after the timestamp with random bytes */
if (!pg_strong_random(&uuid->data[6], UUID_LEN - 6))
ereport(ERROR,
(errcode(ERRCODE_INTERNAL_ERROR),
errmsg("could not generate random values")));
/*
* Set magic numbers for a "version 7" (pseudorandom) UUID, see
* https://datatracker.ietf.org/doc/html/draft-ietf-uuidrev-rfc4122bis#name-creating-a-uuidv8-value
*/
/* set version field, top four bits are 0, 1, 1, 1 */
uuid->data[6] = (uuid->data[6] & 0x0f) | 0x70;
/* set variant field, top two bits are 1, 0 */
uuid->data[8] = (uuid->data[8] & 0x3f) | 0x80;
PG_RETURN_UUID_P(uuid);
}
PG_FUNCTION_INFO_V1(gen_uuid_v8);
static uint8_t sequence;
Datum
gen_uuid_v8(PG_FUNCTION_ARGS)
{
pg_uuid_t *uuid = palloc(UUID_LEN);
struct timeval tp;
uint32_t t;
uint16_t ut;
gettimeofday(&tp, NULL);
t = tp.tv_sec - 1577836800;
t = pg_hton32(t);
memcpy(&uuid->data[0], &t, 4);
/* 16 bit subsecond fraction (~15 microsecond resolution) */
ut = ((uint64_t)tp.tv_usec << 16) / 1000000;
memcpy(&uuid->data[4], &ut, 2);
/* fill everything after the timestamp with random bytes */
if (!pg_strong_random(&uuid->data[6], UUID_LEN - 6))
ereport(ERROR,
(errcode(ERRCODE_INTERNAL_ERROR),
errmsg("could not generate random values")));
/*
* Set magic numbers for a "version 8" UID, see
* https://datatracker.ietf.org/doc/html/draft-ietf-uuidrev-rfc4122bis#name-creating-a-uuidv8-value
*/
uuid->data[6] = (uuid->data[6] & 0x0f) | 0x70;
uuid->data[8] = (uuid->data[8] & 0x3f) | 0x80;
uuid->data[14] = MyProcPid;
uuid->data[15] = sequence++;
PG_RETURN_UUID_P(uuid);
}