Coverage Report

Created: 2026-12-01 07:00

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