| 1 |
/*------------------------------------------------------------------------- |
| 2 |
* |
| 3 |
* uuid.c |
| 4 |
* Functions for the built-in type "uuid". |
| 5 |
* |
| 6 |
* Copyright (c) 2007-2025, PostgreSQL Global Development Group |
| 7 |
* |
| 8 |
* IDENTIFICATION |
| 9 |
* src/backend/utils/adt/uuid.c |
| 10 |
* |
| 11 |
*------------------------------------------------------------------------- |
| 12 |
*/ |
| 13 |
|
| 14 |
#include "postgres.h" |
| 15 |
|
| 16 |
#include <limits.h> |
| 17 |
#include <time.h> /* for clock_gettime() */ |
| 18 |
|
| 19 |
#include "common/hashfn.h" |
| 20 |
#include "lib/hyperloglog.h" |
| 21 |
#include "libpq/pqformat.h" |
| 22 |
#include "port/pg_bswap.h" |
| 23 |
#include "utils/fmgrprotos.h" |
| 24 |
#include "utils/guc.h" |
| 25 |
#include "utils/skipsupport.h" |
| 26 |
#include "utils/sortsupport.h" |
| 27 |
#include "utils/timestamp.h" |
| 28 |
#include "utils/uuid.h" |
| 29 |
|
| 30 |
/* helper macros */ |
| 31 |
#define NS_PER_S INT64CONST(1000000000) |
| 32 |
#define NS_PER_MS INT64CONST(1000000) |
| 33 |
#define NS_PER_US INT64CONST(1000) |
| 34 |
#define US_PER_MS INT64CONST(1000) |
| 35 |
|
| 36 |
/* |
| 37 |
* The offset between the PostgreSQL epoch (2000-01-01) and the Unix epoch |
| 38 |
* (1970-01-01) in microseconds. Subtract this from a Unix-epoch microseconds |
| 39 |
* to get a TimestampTz. |
| 40 |
*/ |
| 41 |
#define PG_UNIX_EPOCH_OFFSET_US \ |
| 42 |
((int64) (POSTGRES_EPOCH_JDATE - UNIX_EPOCH_JDATE) * SECS_PER_DAY * USECS_PER_SEC) |
| 43 |
|
| 44 |
/* |
| 45 |
* Valid timestamp range for UUID version 7, expressed in PostgreSQL-epoch |
| 46 |
* microseconds. UUIDv7 uses a 48-bit unsigned millisecond field relative |
| 47 |
* to the Unix epoch, so the representable window is [1970-01-01, ~10889]. |
| 48 |
*/ |
| 49 |
#define UUIDV7_MIN_TIMESTAMP (-PG_UNIX_EPOCH_OFFSET_US) |
| 50 |
#define UUIDV7_MAX_TIMESTAMP \ |
| 51 |
(((INT64CONST(1) << 48) - 1) * US_PER_MS - PG_UNIX_EPOCH_OFFSET_US) |
| 52 |
|
| 53 |
/* |
| 54 |
* UUID version 7 uses 12 bits in "rand_a" to store 1/4096 (or 2^12) fractions of |
| 55 |
* sub-millisecond. While most Unix-like platforms provide nanosecond-precision |
| 56 |
* timestamps, some systems only offer microsecond precision, limiting us to 10 |
| 57 |
* bits of sub-millisecond information. For example, on macOS, real time is |
| 58 |
* truncated to microseconds. Additionally, MSVC uses the ported version of |
| 59 |
* gettimeofday() that returns microsecond precision. |
| 60 |
* |
| 61 |
* On systems with only 10 bits of sub-millisecond precision, we still use |
| 62 |
* 1/4096 parts of a millisecond, but fill lower 2 bits with random numbers |
| 63 |
* (see generate_uuidv7() for details). |
| 64 |
* |
| 65 |
* SUBMS_MINIMAL_STEP_NS defines the minimum number of nanoseconds that guarantees |
| 66 |
* an increase in the UUID's clock precision. |
| 67 |
*/ |
| 68 |
#if defined(__darwin__) || defined(_MSC_VER) |
| 69 |
#define SUBMS_MINIMAL_STEP_BITS 10 |
| 70 |
#else |
| 71 |
#define SUBMS_MINIMAL_STEP_BITS 12 |
| 72 |
#endif |
| 73 |
#define SUBMS_BITS 12 |
| 74 |
#define SUBMS_MINIMAL_STEP_NS ((NS_PER_MS / (1 << SUBMS_MINIMAL_STEP_BITS)) + 1) |
| 75 |
|
| 76 |
/* sortsupport for uuid */ |
| 77 |
typedef struct |
| 78 |
{ |
| 79 |
int64 input_count; /* number of non-null values seen */ |
| 80 |
bool estimating; /* true if estimating cardinality */ |
| 81 |
|
| 82 |
hyperLogLogState abbr_card; /* cardinality estimator */ |
| 83 |
} uuid_sortsupport_state; |
| 84 |
|
| 85 |
static void string_to_uuid(const char *source, pg_uuid_t *uuid, Node *escontext); |
| 86 |
static int uuid_internal_cmp(const pg_uuid_t *arg1, const pg_uuid_t *arg2); |
| 87 |
static int uuid_fast_cmp(Datum x, Datum y, SortSupport ssup); |
| 88 |
static bool uuid_abbrev_abort(int memtupcount, SortSupport ssup); |
| 89 |
static Datum uuid_abbrev_convert(Datum original, SortSupport ssup); |
| 90 |
static inline void uuid_set_version(pg_uuid_t *uuid, unsigned char version); |
| 91 |
static inline int64 get_real_time_ns_ascending(); |
| 92 |
static pg_uuid_t *generate_uuidv7(uint64 unix_ts_ms, uint32 sub_ms); |
| 93 |
|
| 94 |
Datum |
| 95 |
uuid_in(PG_FUNCTION_ARGS) |
| 96 |
{ |
| 97 |
char *uuid_str = PG_GETARG_CSTRING(0); |
| 98 |
pg_uuid_t *uuid; |
| 99 |
|
| 100 |
uuid = (pg_uuid_t *) palloc(sizeof(*uuid)); |
| 101 |
string_to_uuid(uuid_str, uuid, fcinfo->context); |
| 102 |
PG_RETURN_UUID_P(uuid); |
| 103 |
} |
| 104 |
|
| 105 |
Datum |
| 106 |
uuid_out(PG_FUNCTION_ARGS) |
| 107 |
{ |
| 108 |
pg_uuid_t *uuid = PG_GETARG_UUID_P(0); |
| 109 |
static const char hex_chars[] = "0123456789abcdef"; |
| 110 |
char *buf, |
| 111 |
*p; |
| 112 |
int i; |
| 113 |
|
| 114 |
/* counts for the four hyphens and the zero-terminator */ |
| 115 |
buf = palloc(2 * UUID_LEN + 5); |
| 116 |
p = buf; |
| 117 |
for (i = 0; i < UUID_LEN; i++) |
| 118 |
{ |
| 119 |
int hi; |
| 120 |
int lo; |
| 121 |
|
| 122 |
/* |
| 123 |
* We print uuid values as a string of 8, 4, 4, 4, and then 12 |
| 124 |
* hexadecimal characters, with each group is separated by a hyphen |
| 125 |
* ("-"). Therefore, add the hyphens at the appropriate places here. |
| 126 |
*/ |
| 127 |
if (i == 4 || i == 6 || i == 8 || i == 10) |
| 128 |
*p++ = '-'; |
| 129 |
|
| 130 |
hi = uuid->data[i] >> 4; |
| 131 |
lo = uuid->data[i] & 0x0F; |
| 132 |
|
| 133 |
*p++ = hex_chars[hi]; |
| 134 |
*p++ = hex_chars[lo]; |
| 135 |
} |
| 136 |
*p = '\0'; |
| 137 |
|
| 138 |
PG_RETURN_CSTRING(buf); |
| 139 |
} |
| 140 |
|
| 141 |
/* |
| 142 |
* We allow UUIDs as a series of 32 hexadecimal digits with an optional dash |
| 143 |
* after each group of 4 hexadecimal digits, and optionally surrounded by {}. |
| 144 |
* (The canonical format 8x-4x-4x-4x-12x, where "nx" means n hexadecimal |
| 145 |
* digits, is the only one used for output.) |
| 146 |
*/ |
| 147 |
static void |
| 148 |
string_to_uuid(const char *source, pg_uuid_t *uuid, Node *escontext) |
| 149 |
{ |
| 150 |
const char *src = source; |
| 151 |
bool braces = false; |
| 152 |
int i; |
| 153 |
|
| 154 |
if (src[0] == '{') |
| 155 |
{ |
| 156 |
src++; |
| 157 |
braces = true; |
| 158 |
} |
| 159 |
|
| 160 |
for (i = 0; i < UUID_LEN; i++) |
| 161 |
{ |
| 162 |
char str_buf[3]; |
| 163 |
|
| 164 |
if (src[0] == '\0' || src[1] == '\0') |
| 165 |
goto syntax_error; |
| 166 |
memcpy(str_buf, src, 2); |
| 167 |
if (!isxdigit((unsigned char) str_buf[0]) || |
| 168 |
!isxdigit((unsigned char) str_buf[1])) |
| 169 |
goto syntax_error; |
| 170 |
|
| 171 |
str_buf[2] = '\0'; |
| 172 |
uuid->data[i] = (unsigned char) strtoul(str_buf, NULL, 16); |
| 173 |
src += 2; |
| 174 |
if (src[0] == '-' && (i % 2) == 1 && i < UUID_LEN - 1) |
| 175 |
src++; |
| 176 |
} |
| 177 |
|
| 178 |
if (braces) |
| 179 |
{ |
| 180 |
if (*src != '}') |
| 181 |
goto syntax_error; |
| 182 |
src++; |
| 183 |
} |
| 184 |
|
| 185 |
if (*src != '\0') |
| 186 |
goto syntax_error; |
| 187 |
|
| 188 |
return; |
| 189 |
|
| 190 |
syntax_error: |
| 191 |
ereturn(escontext,, |
| 192 |
(errcode(ERRCODE_INVALID_TEXT_REPRESENTATION), |
| 193 |
errmsg("invalid input syntax for type %s: \"%s\"", |
| 194 |
"uuid", source))); |
| 195 |
} |
| 196 |
|
| 197 |
Datum |
| 198 |
uuid_recv(PG_FUNCTION_ARGS) |
| 199 |
{ |
| 200 |
StringInfo buffer = (StringInfo) PG_GETARG_POINTER(0); |
| 201 |
pg_uuid_t *uuid; |
| 202 |
|
| 203 |
uuid = (pg_uuid_t *) palloc(UUID_LEN); |
| 204 |
memcpy(uuid->data, pq_getmsgbytes(buffer, UUID_LEN), UUID_LEN); |
| 205 |
PG_RETURN_POINTER(uuid); |
| 206 |
} |
| 207 |
|
| 208 |
Datum |
| 209 |
uuid_send(PG_FUNCTION_ARGS) |
| 210 |
{ |
| 211 |
pg_uuid_t *uuid = PG_GETARG_UUID_P(0); |
| 212 |
StringInfoData buffer; |
| 213 |
|
| 214 |
pq_begintypsend(&buffer); |
| 215 |
pq_sendbytes(&buffer, uuid->data, UUID_LEN); |
| 216 |
PG_RETURN_BYTEA_P(pq_endtypsend(&buffer)); |
| 217 |
} |
| 218 |
|
| 219 |
/* internal uuid compare function */ |
| 220 |
static int |
| 221 |
uuid_internal_cmp(const pg_uuid_t *arg1, const pg_uuid_t *arg2) |
| 222 |
{ |
| 223 |
return memcmp(arg1->data, arg2->data, UUID_LEN); |
| 224 |
} |
| 225 |
|
| 226 |
Datum |
| 227 |
uuid_lt(PG_FUNCTION_ARGS) |
| 228 |
{ |
| 229 |
pg_uuid_t *arg1 = PG_GETARG_UUID_P(0); |
| 230 |
pg_uuid_t *arg2 = PG_GETARG_UUID_P(1); |
| 231 |
|
| 232 |
PG_RETURN_BOOL(uuid_internal_cmp(arg1, arg2) < 0); |
| 233 |
} |
| 234 |
|
| 235 |
Datum |
| 236 |
uuid_le(PG_FUNCTION_ARGS) |
| 237 |
{ |
| 238 |
pg_uuid_t *arg1 = PG_GETARG_UUID_P(0); |
| 239 |
pg_uuid_t *arg2 = PG_GETARG_UUID_P(1); |
| 240 |
|
| 241 |
PG_RETURN_BOOL(uuid_internal_cmp(arg1, arg2) <= 0); |
| 242 |
} |
| 243 |
|
| 244 |
Datum |
| 245 |
uuid_eq(PG_FUNCTION_ARGS) |
| 246 |
{ |
| 247 |
pg_uuid_t *arg1 = PG_GETARG_UUID_P(0); |
| 248 |
pg_uuid_t *arg2 = PG_GETARG_UUID_P(1); |
| 249 |
|
| 250 |
PG_RETURN_BOOL(uuid_internal_cmp(arg1, arg2) == 0); |
| 251 |
} |
| 252 |
|
| 253 |
Datum |
| 254 |
uuid_ge(PG_FUNCTION_ARGS) |
| 255 |
{ |
| 256 |
pg_uuid_t *arg1 = PG_GETARG_UUID_P(0); |
| 257 |
pg_uuid_t *arg2 = PG_GETARG_UUID_P(1); |
| 258 |
|
| 259 |
PG_RETURN_BOOL(uuid_internal_cmp(arg1, arg2) >= 0); |
| 260 |
} |
| 261 |
|
| 262 |
Datum |
| 263 |
uuid_gt(PG_FUNCTION_ARGS) |
| 264 |
{ |
| 265 |
pg_uuid_t *arg1 = PG_GETARG_UUID_P(0); |
| 266 |
pg_uuid_t *arg2 = PG_GETARG_UUID_P(1); |
| 267 |
|
| 268 |
PG_RETURN_BOOL(uuid_internal_cmp(arg1, arg2) > 0); |
| 269 |
} |
| 270 |
|
| 271 |
Datum |
| 272 |
uuid_ne(PG_FUNCTION_ARGS) |
| 273 |
{ |
| 274 |
pg_uuid_t *arg1 = PG_GETARG_UUID_P(0); |
| 275 |
pg_uuid_t *arg2 = PG_GETARG_UUID_P(1); |
| 276 |
|
| 277 |
PG_RETURN_BOOL(uuid_internal_cmp(arg1, arg2) != 0); |
| 278 |
} |
| 279 |
|
| 280 |
/* handler for btree index operator */ |
| 281 |
Datum |
| 282 |
uuid_cmp(PG_FUNCTION_ARGS) |
| 283 |
{ |
| 284 |
pg_uuid_t *arg1 = PG_GETARG_UUID_P(0); |
| 285 |
pg_uuid_t *arg2 = PG_GETARG_UUID_P(1); |
| 286 |
|
| 287 |
PG_RETURN_INT32(uuid_internal_cmp(arg1, arg2)); |
| 288 |
} |
| 289 |
|
| 290 |
/* |
| 291 |
* Sort support strategy routine |
| 292 |
*/ |
| 293 |
Datum |
| 294 |
uuid_sortsupport(PG_FUNCTION_ARGS) |
| 295 |
{ |
| 296 |
SortSupport ssup = (SortSupport) PG_GETARG_POINTER(0); |
| 297 |
|
| 298 |
ssup->comparator = uuid_fast_cmp; |
| 299 |
ssup->ssup_extra = NULL; |
| 300 |
|
| 301 |
if (ssup->abbreviate) |
| 302 |
{ |
| 303 |
uuid_sortsupport_state *uss; |
| 304 |
MemoryContext oldcontext; |
| 305 |
|
| 306 |
oldcontext = MemoryContextSwitchTo(ssup->ssup_cxt); |
| 307 |
|
| 308 |
uss = palloc(sizeof(uuid_sortsupport_state)); |
| 309 |
uss->input_count = 0; |
| 310 |
uss->estimating = true; |
| 311 |
initHyperLogLog(&uss->abbr_card, 10); |
| 312 |
|
| 313 |
ssup->ssup_extra = uss; |
| 314 |
|
| 315 |
ssup->comparator = ssup_datum_unsigned_cmp; |
| 316 |
ssup->abbrev_converter = uuid_abbrev_convert; |
| 317 |
ssup->abbrev_abort = uuid_abbrev_abort; |
| 318 |
ssup->abbrev_full_comparator = uuid_fast_cmp; |
| 319 |
|
| 320 |
MemoryContextSwitchTo(oldcontext); |
| 321 |
} |
| 322 |
|
| 323 |
PG_RETURN_VOID(); |
| 324 |
} |
| 325 |
|
| 326 |
/* |
| 327 |
* SortSupport comparison func |
| 328 |
*/ |
| 329 |
static int |
| 330 |
uuid_fast_cmp(Datum x, Datum y, SortSupport ssup) |
| 331 |
{ |
| 332 |
pg_uuid_t *arg1 = DatumGetUUIDP(x); |
| 333 |
pg_uuid_t *arg2 = DatumGetUUIDP(y); |
| 334 |
|
| 335 |
return uuid_internal_cmp(arg1, arg2); |
| 336 |
} |
| 337 |
|
| 338 |
/* |
| 339 |
* Callback for estimating effectiveness of abbreviated key optimization. |
| 340 |
* |
| 341 |
* We pay no attention to the cardinality of the non-abbreviated data, because |
| 342 |
* there is no equality fast-path within authoritative uuid comparator. |
| 343 |
*/ |
| 344 |
static bool |
| 345 |
uuid_abbrev_abort(int memtupcount, SortSupport ssup) |
| 346 |
{ |
| 347 |
uuid_sortsupport_state *uss = ssup->ssup_extra; |
| 348 |
double abbr_card; |
| 349 |
|
| 350 |
if (memtupcount < 10000 || uss->input_count < 10000 || !uss->estimating) |
| 351 |
return false; |
| 352 |
|
| 353 |
abbr_card = estimateHyperLogLog(&uss->abbr_card); |
| 354 |
|
| 355 |
/* |
| 356 |
* If we have >100k distinct values, then even if we were sorting many |
| 357 |
* billion rows we'd likely still break even, and the penalty of undoing |
| 358 |
* that many rows of abbrevs would probably not be worth it. Stop even |
| 359 |
* counting at that point. |
| 360 |
*/ |
| 361 |
if (abbr_card > 100000.0) |
| 362 |
{ |
| 363 |
if (trace_sort) |
| 364 |
elog(LOG, |
| 365 |
"uuid_abbrev: estimation ends at cardinality %f" |
| 366 |
" after " INT64_FORMAT " values (%d rows)", |
| 367 |
abbr_card, uss->input_count, memtupcount); |
| 368 |
uss->estimating = false; |
| 369 |
return false; |
| 370 |
} |
| 371 |
|
| 372 |
/* |
| 373 |
* Target minimum cardinality is 1 per ~2k of non-null inputs. 0.5 row |
| 374 |
* fudge factor allows us to abort earlier on genuinely pathological data |
| 375 |
* where we've had exactly one abbreviated value in the first 2k |
| 376 |
* (non-null) rows. |
| 377 |
*/ |
| 378 |
if (abbr_card < uss->input_count / 2000.0 + 0.5) |
| 379 |
{ |
| 380 |
if (trace_sort) |
| 381 |
elog(LOG, |
| 382 |
"uuid_abbrev: aborting abbreviation at cardinality %f" |
| 383 |
" below threshold %f after " INT64_FORMAT " values (%d rows)", |
| 384 |
abbr_card, uss->input_count / 2000.0 + 0.5, uss->input_count, |
| 385 |
memtupcount); |
| 386 |
return true; |
| 387 |
} |
| 388 |
|
| 389 |
if (trace_sort) |
| 390 |
elog(LOG, |
| 391 |
"uuid_abbrev: cardinality %f after " INT64_FORMAT |
| 392 |
" values (%d rows)", abbr_card, uss->input_count, memtupcount); |
| 393 |
|
| 394 |
return false; |
| 395 |
} |
| 396 |
|
| 397 |
/* |
| 398 |
* Conversion routine for sortsupport. Converts original uuid representation |
| 399 |
* to abbreviated key representation. Our encoding strategy is simple -- pack |
| 400 |
* the first `sizeof(Datum)` bytes of uuid data into a Datum (on little-endian |
| 401 |
* machines, the bytes are stored in reverse order), and treat it as an |
| 402 |
* unsigned integer. |
| 403 |
*/ |
| 404 |
static Datum |
| 405 |
uuid_abbrev_convert(Datum original, SortSupport ssup) |
| 406 |
{ |
| 407 |
uuid_sortsupport_state *uss = ssup->ssup_extra; |
| 408 |
pg_uuid_t *authoritative = DatumGetUUIDP(original); |
| 409 |
Datum res; |
| 410 |
|
| 411 |
memcpy(&res, authoritative->data, sizeof(Datum)); |
| 412 |
uss->input_count += 1; |
| 413 |
|
| 414 |
if (uss->estimating) |
| 415 |
{ |
| 416 |
uint32 tmp; |
| 417 |
|
| 418 |
#if SIZEOF_DATUM == 8 |
| 419 |
tmp = (uint32) res ^ (uint32) ((uint64) res >> 32); |
| 420 |
#else /* SIZEOF_DATUM != 8 */ |
| 421 |
tmp = (uint32) res; |
| 422 |
#endif |
| 423 |
|
| 424 |
addHyperLogLog(&uss->abbr_card, DatumGetUInt32(hash_uint32(tmp))); |
| 425 |
} |
| 426 |
|
| 427 |
/* |
| 428 |
* Byteswap on little-endian machines. |
| 429 |
* |
| 430 |
* This is needed so that ssup_datum_unsigned_cmp() (an unsigned integer |
| 431 |
* 3-way comparator) works correctly on all platforms. If we didn't do |
| 432 |
* this, the comparator would have to call memcmp() with a pair of |
| 433 |
* pointers to the first byte of each abbreviated key, which is slower. |
| 434 |
*/ |
| 435 |
res = DatumBigEndianToNative(res); |
| 436 |
|
| 437 |
return res; |
| 438 |
} |
| 439 |
|
| 440 |
static Datum |
| 441 |
uuid_decrement(Relation rel, Datum existing, bool *underflow) |
| 442 |
{ |
| 443 |
pg_uuid_t *uuid; |
| 444 |
|
| 445 |
uuid = (pg_uuid_t *) palloc(UUID_LEN); |
| 446 |
memcpy(uuid, DatumGetUUIDP(existing), UUID_LEN); |
| 447 |
for (int i = UUID_LEN - 1; i >= 0; i--) |
| 448 |
{ |
| 449 |
if (uuid->data[i] > 0) |
| 450 |
{ |
| 451 |
uuid->data[i]--; |
| 452 |
*underflow = false; |
| 453 |
return UUIDPGetDatum(uuid); |
| 454 |
} |
| 455 |
uuid->data[i] = UCHAR_MAX; |
| 456 |
} |
| 457 |
|
| 458 |
pfree(uuid); /* cannot leak memory */ |
| 459 |
|
| 460 |
/* return value is undefined */ |
| 461 |
*underflow = true; |
| 462 |
return (Datum) 0; |
| 463 |
} |
| 464 |
|
| 465 |
static Datum |
| 466 |
uuid_increment(Relation rel, Datum existing, bool *overflow) |
| 467 |
{ |
| 468 |
pg_uuid_t *uuid; |
| 469 |
|
| 470 |
uuid = (pg_uuid_t *) palloc(UUID_LEN); |
| 471 |
memcpy(uuid, DatumGetUUIDP(existing), UUID_LEN); |
| 472 |
for (int i = UUID_LEN - 1; i >= 0; i--) |
| 473 |
{ |
| 474 |
if (uuid->data[i] < UCHAR_MAX) |
| 475 |
{ |
| 476 |
uuid->data[i]++; |
| 477 |
*overflow = false; |
| 478 |
return UUIDPGetDatum(uuid); |
| 479 |
} |
| 480 |
uuid->data[i] = 0; |
| 481 |
} |
| 482 |
|
| 483 |
pfree(uuid); /* cannot leak memory */ |
| 484 |
|
| 485 |
/* return value is undefined */ |
| 486 |
*overflow = true; |
| 487 |
return (Datum) 0; |
| 488 |
} |
| 489 |
|
| 490 |
Datum |
| 491 |
uuid_skipsupport(PG_FUNCTION_ARGS) |
| 492 |
{ |
| 493 |
SkipSupport sksup = (SkipSupport) PG_GETARG_POINTER(0); |
| 494 |
pg_uuid_t *uuid_min = palloc(UUID_LEN); |
| 495 |
pg_uuid_t *uuid_max = palloc(UUID_LEN); |
| 496 |
|
| 497 |
memset(uuid_min->data, 0x00, UUID_LEN); |
| 498 |
memset(uuid_max->data, 0xFF, UUID_LEN); |
| 499 |
|
| 500 |
sksup->decrement = uuid_decrement; |
| 501 |
sksup->increment = uuid_increment; |
| 502 |
sksup->low_elem = UUIDPGetDatum(uuid_min); |
| 503 |
sksup->high_elem = UUIDPGetDatum(uuid_max); |
| 504 |
|
| 505 |
PG_RETURN_VOID(); |
| 506 |
} |
| 507 |
|
| 508 |
/* hash index support */ |
| 509 |
Datum |
| 510 |
uuid_hash(PG_FUNCTION_ARGS) |
| 511 |
{ |
| 512 |
pg_uuid_t *key = PG_GETARG_UUID_P(0); |
| 513 |
|
| 514 |
return hash_any(key->data, UUID_LEN); |
| 515 |
} |
| 516 |
|
| 517 |
Datum |
| 518 |
uuid_hash_extended(PG_FUNCTION_ARGS) |
| 519 |
{ |
| 520 |
pg_uuid_t *key = PG_GETARG_UUID_P(0); |
| 521 |
|
| 522 |
return hash_any_extended(key->data, UUID_LEN, PG_GETARG_INT64(1)); |
| 523 |
} |
| 524 |
|
| 525 |
/* |
| 526 |
* Set the given UUID version and the variant bits |
| 527 |
*/ |
| 528 |
static inline void |
| 529 |
uuid_set_version(pg_uuid_t *uuid, unsigned char version) |
| 530 |
{ |
| 531 |
/* set version field, top four bits */ |
| 532 |
uuid->data[6] = (uuid->data[6] & 0x0f) | (version << 4); |
| 533 |
|
| 534 |
/* set variant field, top two bits are 1, 0 */ |
| 535 |
uuid->data[8] = (uuid->data[8] & 0x3f) | 0x80; |
| 536 |
} |
| 537 |
|
| 538 |
/* |
| 539 |
* Generate UUID version 4. |
| 540 |
* |
| 541 |
* All UUID bytes are filled with strong random numbers except version and |
| 542 |
* variant bits. |
| 543 |
*/ |
| 544 |
Datum |
| 545 |
gen_random_uuid(PG_FUNCTION_ARGS) |
| 546 |
{ |
| 547 |
pg_uuid_t *uuid = palloc(UUID_LEN); |
| 548 |
|
| 549 |
if (!pg_strong_random(uuid, UUID_LEN)) |
| 550 |
ereport(ERROR, |
| 551 |
(errcode(ERRCODE_INTERNAL_ERROR), |
| 552 |
errmsg("could not generate random values"))); |
| 553 |
|
| 554 |
/* |
| 555 |
* Set magic numbers for a "version 4" (pseudorandom) UUID and variant, |
| 556 |
* see https://datatracker.ietf.org/doc/html/rfc9562#name-uuid-version-4 |
| 557 |
*/ |
| 558 |
uuid_set_version(uuid, 4); |
| 559 |
|
| 560 |
PG_RETURN_UUID_P(uuid); |
| 561 |
} |
| 562 |
|
| 563 |
/* |
| 564 |
* Get the current timestamp with nanosecond precision for UUID generation. |
| 565 |
* The returned timestamp is ensured to be at least SUBMS_MINIMAL_STEP greater |
| 566 |
* than the previous returned timestamp (on this backend). |
| 567 |
*/ |
| 568 |
static inline int64 |
| 569 |
get_real_time_ns_ascending() |
| 570 |
{ |
| 571 |
static int64 previous_ns = 0; |
| 572 |
int64 ns; |
| 573 |
|
| 574 |
/* Get the current real timestamp */ |
| 575 |
|
| 576 |
#ifdef _MSC_VER |
| 577 |
struct timeval tmp; |
| 578 |
|
| 579 |
gettimeofday(&tmp, NULL); |
| 580 |
ns = tmp.tv_sec * NS_PER_S + tmp.tv_usec * NS_PER_US; |
| 581 |
#else |
| 582 |
struct timespec tmp; |
| 583 |
|
| 584 |
/* |
| 585 |
* We don't use gettimeofday(), instead use clock_gettime() with |
| 586 |
* CLOCK_REALTIME where available in order to get a high-precision |
| 587 |
* (nanoseconds) real timestamp. |
| 588 |
* |
| 589 |
* Note while a timestamp returned by clock_gettime() with CLOCK_REALTIME |
| 590 |
* is nanosecond-precision on most Unix-like platforms, on some platforms |
| 591 |
* such as macOS it's restricted to microsecond-precision. |
| 592 |
*/ |
| 593 |
clock_gettime(CLOCK_REALTIME, &tmp); |
| 594 |
ns = tmp.tv_sec * NS_PER_S + tmp.tv_nsec; |
| 595 |
#endif |
| 596 |
|
| 597 |
/* Guarantee the minimal step advancement of the timestamp */ |
| 598 |
if (previous_ns + SUBMS_MINIMAL_STEP_NS >= ns) |
| 599 |
ns = previous_ns + SUBMS_MINIMAL_STEP_NS; |
| 600 |
previous_ns = ns; |
| 601 |
|
| 602 |
return ns; |
| 603 |
} |
| 604 |
|
| 605 |
/* |
| 606 |
* Generate UUID version 7 per RFC 9562, with the given timestamp. |
| 607 |
* |
| 608 |
* UUID version 7 consists of a Unix timestamp in milliseconds (48 bits) and |
| 609 |
* 74 random bits, excluding the required version and variant bits. To ensure |
| 610 |
* monotonicity in scenarios of high-frequency UUID generation, we employ the |
| 611 |
* method "Replace Leftmost Random Bits with Increased Clock Precision (Method 3)", |
| 612 |
* described in the RFC. This method utilizes 12 bits from the "rand_a" bits |
| 613 |
* to store a 1/4096 (or 2^12) fraction of sub-millisecond precision. |
| 614 |
* |
| 615 |
* unix_ts_ms is a number of milliseconds since start of the UNIX epoch, |
| 616 |
* and sub_ms is a number of nanoseconds within millisecond. These values are |
| 617 |
* used for time-dependent bits of UUID. |
| 618 |
* |
| 619 |
* NB: all numbers here are unsigned, unix_ts_ms cannot be negative per RFC. |
| 620 |
*/ |
| 621 |
static pg_uuid_t * |
| 622 |
generate_uuidv7(uint64 unix_ts_ms, uint32 sub_ms) |
| 623 |
{ |
| 624 |
pg_uuid_t *uuid = palloc(UUID_LEN); |
| 625 |
uint32 increased_clock_precision; |
| 626 |
|
| 627 |
/* Fill in time part */ |
| 628 |
uuid->data[0] = (unsigned char) (unix_ts_ms >> 40); |
| 629 |
uuid->data[1] = (unsigned char) (unix_ts_ms >> 32); |
| 630 |
uuid->data[2] = (unsigned char) (unix_ts_ms >> 24); |
| 631 |
uuid->data[3] = (unsigned char) (unix_ts_ms >> 16); |
| 632 |
uuid->data[4] = (unsigned char) (unix_ts_ms >> 8); |
| 633 |
uuid->data[5] = (unsigned char) unix_ts_ms; |
| 634 |
|
| 635 |
/* |
| 636 |
* sub-millisecond timestamp fraction (SUBMS_BITS bits, not |
| 637 |
* SUBMS_MINIMAL_STEP_BITS) |
| 638 |
*/ |
| 639 |
increased_clock_precision = (sub_ms * (1 << SUBMS_BITS)) / NS_PER_MS; |
| 640 |
|
| 641 |
/* Fill the increased clock precision to "rand_a" bits */ |
| 642 |
uuid->data[6] = (unsigned char) (increased_clock_precision >> 8); |
| 643 |
uuid->data[7] = (unsigned char) (increased_clock_precision); |
| 644 |
|
| 645 |
/* fill everything after the increased clock precision with random bytes */ |
| 646 |
if (!pg_strong_random(&uuid->data[8], UUID_LEN - 8)) |
| 647 |
ereport(ERROR, |
| 648 |
(errcode(ERRCODE_INTERNAL_ERROR), |
| 649 |
errmsg("could not generate random values"))); |
| 650 |
|
| 651 |
#if SUBMS_MINIMAL_STEP_BITS == 10 |
| 652 |
|
| 653 |
/* |
| 654 |
* On systems that have only 10 bits of sub-ms precision, 2 least |
| 655 |
* significant are dependent on other time-specific bits, and they do not |
| 656 |
* contribute to uniqueness. To make these bit random we mix in two bits |
| 657 |
* from CSPRNG. SUBMS_MINIMAL_STEP is chosen so that we still guarantee |
| 658 |
* monotonicity despite altering these bits. |
| 659 |
*/ |
| 660 |
uuid->data[7] = uuid->data[7] ^ (uuid->data[8] >> 6); |
| 661 |
#endif |
| 662 |
|
| 663 |
/* |
| 664 |
* Set magic numbers for a "version 7" (pseudorandom) UUID and variant, |
| 665 |
* see https://www.rfc-editor.org/rfc/rfc9562#name-version-field |
| 666 |
*/ |
| 667 |
uuid_set_version(uuid, 7); |
| 668 |
|
| 669 |
return uuid; |
| 670 |
} |
| 671 |
|
| 672 |
/* |
| 673 |
* Generate UUID version 7 with the current timestamp. |
| 674 |
*/ |
| 675 |
Datum |
| 676 |
uuidv7(PG_FUNCTION_ARGS) |
| 677 |
{ |
| 678 |
int64 ns = get_real_time_ns_ascending(); |
| 679 |
pg_uuid_t *uuid = generate_uuidv7(ns / NS_PER_MS, ns % NS_PER_MS); |
| 680 |
|
| 681 |
PG_RETURN_UUID_P(uuid); |
| 682 |
} |
| 683 |
|
| 684 |
/* |
| 685 |
* Similar to uuidv7() but with the timestamp adjusted by the given interval. |
| 686 |
*/ |
| 687 |
Datum |
| 688 |
uuidv7_interval(PG_FUNCTION_ARGS) |
| 689 |
{ |
| 690 |
Interval *shift = PG_GETARG_INTERVAL_P(0); |
| 691 |
TimestampTz ts; |
| 692 |
pg_uuid_t *uuid; |
| 693 |
int64 ns = get_real_time_ns_ascending(); |
| 694 |
int64 us; |
| 695 |
|
| 696 |
/* Reject infinite intervals before any arithmetic */ |
| 697 |
if (INTERVAL_NOT_FINITE(shift)) |
| 698 |
ereport(ERROR, |
| 699 |
(errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE), |
| 700 |
errmsg("interval out of range for UUID version 7"), |
| 701 |
errdetail("UUID version 7 does not support infinite intervals."))); |
| 702 |
|
| 703 |
/* |
| 704 |
* Shift the current timestamp by the given interval. To calculate time |
| 705 |
* shift correctly, we convert the UNIX epoch to TimestampTz and use |
| 706 |
* timestamptz_pl_interval(). This calculation is done with microsecond |
| 707 |
* precision. |
| 708 |
*/ |
| 709 |
|
| 710 |
ts = (TimestampTz) (ns / NS_PER_US) - PG_UNIX_EPOCH_OFFSET_US; |
| 711 |
|
| 712 |
/* Compute time shift */ |
| 713 |
ts = DatumGetTimestampTz(DirectFunctionCall2(timestamptz_pl_interval, |
| 714 |
TimestampTzGetDatum(ts), |
| 715 |
IntervalPGetDatum(shift))); |
| 716 |
|
| 717 |
/* |
| 718 |
* Reject timestamps outside the range representable by UUID version 7's |
| 719 |
* 48-bit millisecond field. We compare in PostgreSQL-epoch units so that |
| 720 |
* the subsequent conversion to Unix-epoch microseconds cannot overflow. |
| 721 |
*/ |
| 722 |
if (ts < UUIDV7_MIN_TIMESTAMP || ts > UUIDV7_MAX_TIMESTAMP) |
| 723 |
ereport(ERROR, |
| 724 |
(errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE), |
| 725 |
errmsg("timestamp out of range for UUID version 7"), |
| 726 |
errdetail("UUID version 7 supports timestamps from 1970-01-01 to approximately year 10889."))); |
| 727 |
|
| 728 |
/* Convert the TimestampTz value to a Unix-epoch timestamp in usec */ |
| 729 |
us = ts + PG_UNIX_EPOCH_OFFSET_US; |
| 730 |
|
| 731 |
/* Generate an UUIDv7 */ |
| 732 |
uuid = generate_uuidv7(us / US_PER_MS, (us % US_PER_MS) * NS_PER_US + ns % NS_PER_US); |
| 733 |
|
| 734 |
PG_RETURN_UUID_P(uuid); |
| 735 |
} |
| 736 |
|
| 737 |
/* |
| 738 |
* Start of a Gregorian epoch == date2j(1582,10,15) |
| 739 |
* We cast it to 64-bit because it's used in overflow-prone computations |
| 740 |
*/ |
| 741 |
#define GREGORIAN_EPOCH_JDATE INT64CONST(2299161) |
| 742 |
|
| 743 |
/* |
| 744 |
* Extract timestamp from UUID. |
| 745 |
* |
| 746 |
* Returns null if not RFC 9562 variant or not a version that has a timestamp. |
| 747 |
*/ |
| 748 |
Datum |
| 749 |
uuid_extract_timestamp(PG_FUNCTION_ARGS) |
| 750 |
{ |
| 751 |
pg_uuid_t *uuid = PG_GETARG_UUID_P(0); |
| 752 |
int version; |
| 753 |
uint64 tms; |
| 754 |
TimestampTz ts; |
| 755 |
|
| 756 |
/* check if RFC 9562 variant */ |
| 757 |
if ((uuid->data[8] & 0xc0) != 0x80) |
| 758 |
PG_RETURN_NULL(); |
| 759 |
|
| 760 |
version = uuid->data[6] >> 4; |
| 761 |
|
| 762 |
if (version == 1) |
| 763 |
{ |
| 764 |
tms = ((uint64) uuid->data[0] << 24) |
| 765 |
+ ((uint64) uuid->data[1] << 16) |
| 766 |
+ ((uint64) uuid->data[2] << 8) |
| 767 |
+ ((uint64) uuid->data[3]) |
| 768 |
+ ((uint64) uuid->data[4] << 40) |
| 769 |
+ ((uint64) uuid->data[5] << 32) |
| 770 |
+ (((uint64) uuid->data[6] & 0xf) << 56) |
| 771 |
+ ((uint64) uuid->data[7] << 48); |
| 772 |
|
| 773 |
/* convert 100-ns intervals to us, then adjust */ |
| 774 |
ts = (TimestampTz) (tms / 10) - |
| 775 |
((uint64) POSTGRES_EPOCH_JDATE - GREGORIAN_EPOCH_JDATE) * SECS_PER_DAY * USECS_PER_SEC; |
| 776 |
PG_RETURN_TIMESTAMPTZ(ts); |
| 777 |
} |
| 778 |
|
| 779 |
if (version == 7) |
| 780 |
{ |
| 781 |
tms = (uuid->data[5]) |
| 782 |
+ (((uint64) uuid->data[4]) << 8) |
| 783 |
+ (((uint64) uuid->data[3]) << 16) |
| 784 |
+ (((uint64) uuid->data[2]) << 24) |
| 785 |
+ (((uint64) uuid->data[1]) << 32) |
| 786 |
+ (((uint64) uuid->data[0]) << 40); |
| 787 |
|
| 788 |
/* convert ms to us, then adjust */ |
| 789 |
ts = (TimestampTz) (tms * US_PER_MS) - PG_UNIX_EPOCH_OFFSET_US; |
| 790 |
|
| 791 |
PG_RETURN_TIMESTAMPTZ(ts); |
| 792 |
} |
| 793 |
|
| 794 |
/* not a timestamp-containing UUID version */ |
| 795 |
PG_RETURN_NULL(); |
| 796 |
} |
| 797 |
|
| 798 |
/* |
| 799 |
* Extract UUID version. |
| 800 |
* |
| 801 |
* Returns null if not RFC 9562 variant. |
| 802 |
*/ |
| 803 |
Datum |
| 804 |
uuid_extract_version(PG_FUNCTION_ARGS) |
| 805 |
{ |
| 806 |
pg_uuid_t *uuid = PG_GETARG_UUID_P(0); |
| 807 |
uint16 version; |
| 808 |
|
| 809 |
/* check if RFC 9562 variant */ |
| 810 |
if ((uuid->data[8] & 0xc0) != 0x80) |
| 811 |
PG_RETURN_NULL(); |
| 812 |
|
| 813 |
version = uuid->data[6] >> 4; |
| 814 |
|
| 815 |
PG_RETURN_UINT16(version); |
| 816 |
} |