PostgreSQL Source Code git master
Loading...
Searching...
No Matches
uuid.c File Reference
#include "postgres.h"
#include <limits.h>
#include <time.h>
#include "common/hashfn.h"
#include "lib/hyperloglog.h"
#include "libpq/pqformat.h"
#include "port/pg_bswap.h"
#include "utils/fmgrprotos.h"
#include "utils/guc.h"
#include "utils/skipsupport.h"
#include "utils/sortsupport.h"
#include "utils/timestamp.h"
#include "utils/uuid.h"
Include dependency graph for uuid.c:

Go to the source code of this file.

Data Structures

struct  uuid_sortsupport_state
 

Macros

#define NS_PER_S   INT64CONST(1000000000)
 
#define NS_PER_MS   INT64CONST(1000000)
 
#define NS_PER_US   INT64CONST(1000)
 
#define US_PER_MS   INT64CONST(1000)
 
#define PG_UNIX_EPOCH_OFFSET_US    ((int64) (POSTGRES_EPOCH_JDATE - UNIX_EPOCH_JDATE) * SECS_PER_DAY * USECS_PER_SEC)
 
#define UUIDV7_MIN_TIMESTAMP   (-PG_UNIX_EPOCH_OFFSET_US)
 
#define UUIDV7_MAX_TIMESTAMP    (((INT64CONST(1) << 48) - 1) * US_PER_MS - PG_UNIX_EPOCH_OFFSET_US)
 
#define SUBMS_MINIMAL_STEP_BITS   12
 
#define SUBMS_BITS   12
 
#define SUBMS_MINIMAL_STEP_NS   ((NS_PER_MS / (1 << SUBMS_MINIMAL_STEP_BITS)) + 1)
 
#define GREGORIAN_EPOCH_JDATE   INT64CONST(2299161)
 

Functions

static void string_to_uuid (const char *source, pg_uuid_t *uuid, Node *escontext)
 
static int uuid_internal_cmp (const pg_uuid_t *arg1, const pg_uuid_t *arg2)
 
static int uuid_fast_cmp (Datum x, Datum y, SortSupport ssup)
 
static bool uuid_abbrev_abort (int memtupcount, SortSupport ssup)
 
static Datum uuid_abbrev_convert (Datum original, SortSupport ssup)
 
static void uuid_set_version (pg_uuid_t *uuid, unsigned char version)
 
static int64 get_real_time_ns_ascending (void)
 
static pg_uuid_tgenerate_uuidv7 (uint64 unix_ts_ms, uint32 sub_ms)
 
Datum uuid_in (PG_FUNCTION_ARGS)
 
Datum uuid_out (PG_FUNCTION_ARGS)
 
Datum uuid_recv (PG_FUNCTION_ARGS)
 
Datum uuid_send (PG_FUNCTION_ARGS)
 
Datum uuid_lt (PG_FUNCTION_ARGS)
 
Datum uuid_le (PG_FUNCTION_ARGS)
 
Datum uuid_eq (PG_FUNCTION_ARGS)
 
Datum uuid_ge (PG_FUNCTION_ARGS)
 
Datum uuid_gt (PG_FUNCTION_ARGS)
 
Datum uuid_ne (PG_FUNCTION_ARGS)
 
Datum uuid_cmp (PG_FUNCTION_ARGS)
 
Datum uuid_larger (PG_FUNCTION_ARGS)
 
Datum uuid_smaller (PG_FUNCTION_ARGS)
 
Datum uuid_sortsupport (PG_FUNCTION_ARGS)
 
static Datum uuid_decrement (Relation rel, Datum existing, bool *underflow)
 
static Datum uuid_increment (Relation rel, Datum existing, bool *overflow)
 
Datum uuid_skipsupport (PG_FUNCTION_ARGS)
 
Datum uuid_hash (PG_FUNCTION_ARGS)
 
Datum uuid_hash_extended (PG_FUNCTION_ARGS)
 
Datum gen_random_uuid (PG_FUNCTION_ARGS)
 
Datum uuidv7 (PG_FUNCTION_ARGS)
 
Datum uuidv7_interval (PG_FUNCTION_ARGS)
 
Datum uuid_extract_timestamp (PG_FUNCTION_ARGS)
 
Datum uuid_extract_version (PG_FUNCTION_ARGS)
 

Macro Definition Documentation

◆ GREGORIAN_EPOCH_JDATE

#define GREGORIAN_EPOCH_JDATE   INT64CONST(2299161)

Definition at line 755 of file uuid.c.

◆ NS_PER_MS

#define NS_PER_MS   INT64CONST(1000000)

Definition at line 32 of file uuid.c.

◆ NS_PER_S

#define NS_PER_S   INT64CONST(1000000000)

Definition at line 31 of file uuid.c.

◆ NS_PER_US

#define NS_PER_US   INT64CONST(1000)

Definition at line 33 of file uuid.c.

◆ PG_UNIX_EPOCH_OFFSET_US

#define PG_UNIX_EPOCH_OFFSET_US    ((int64) (POSTGRES_EPOCH_JDATE - UNIX_EPOCH_JDATE) * SECS_PER_DAY * USECS_PER_SEC)

Definition at line 41 of file uuid.c.

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

◆ SUBMS_BITS

#define SUBMS_BITS   12

Definition at line 73 of file uuid.c.

◆ SUBMS_MINIMAL_STEP_BITS

#define SUBMS_MINIMAL_STEP_BITS   12

Definition at line 71 of file uuid.c.

◆ SUBMS_MINIMAL_STEP_NS

#define SUBMS_MINIMAL_STEP_NS   ((NS_PER_MS / (1 << SUBMS_MINIMAL_STEP_BITS)) + 1)

Definition at line 74 of file uuid.c.

◆ US_PER_MS

#define US_PER_MS   INT64CONST(1000)

Definition at line 34 of file uuid.c.

◆ UUIDV7_MAX_TIMESTAMP

#define UUIDV7_MAX_TIMESTAMP    (((INT64CONST(1) << 48) - 1) * US_PER_MS - PG_UNIX_EPOCH_OFFSET_US)

Definition at line 50 of file uuid.c.

◆ UUIDV7_MIN_TIMESTAMP

#define UUIDV7_MIN_TIMESTAMP   (-PG_UNIX_EPOCH_OFFSET_US)

Definition at line 49 of file uuid.c.

Function Documentation

◆ gen_random_uuid()

Datum gen_random_uuid ( PG_FUNCTION_ARGS  )

Definition at line 559 of file uuid.c.

560{
562
566 errmsg("could not generate random values")));
567
568 /*
569 * Set magic numbers for a "version 4" (pseudorandom) UUID and variant,
570 * see https://datatracker.ietf.org/doc/html/rfc9562#name-uuid-version-4
571 */
573
575}

References ereport, errcode(), errmsg, ERROR, fb(), palloc(), PG_RETURN_UUID_P, pg_strong_random(), UUID_LEN, and uuid_set_version().

Referenced by pg_random_uuid().

◆ generate_uuidv7()

static pg_uuid_t * generate_uuidv7 ( uint64  unix_ts_ms,
uint32  sub_ms 
)
static

Definition at line 636 of file uuid.c.

637{
640
641 /* Fill in time part */
642 uuid->data[0] = (unsigned char) (unix_ts_ms >> 40);
643 uuid->data[1] = (unsigned char) (unix_ts_ms >> 32);
644 uuid->data[2] = (unsigned char) (unix_ts_ms >> 24);
645 uuid->data[3] = (unsigned char) (unix_ts_ms >> 16);
646 uuid->data[4] = (unsigned char) (unix_ts_ms >> 8);
647 uuid->data[5] = (unsigned char) unix_ts_ms;
648
649 /*
650 * sub-millisecond timestamp fraction (SUBMS_BITS bits, not
651 * SUBMS_MINIMAL_STEP_BITS)
652 */
654
655 /* Fill the increased clock precision to "rand_a" bits */
656 uuid->data[6] = (unsigned char) (increased_clock_precision >> 8);
657 uuid->data[7] = (unsigned char) (increased_clock_precision);
658
659 /* fill everything after the increased clock precision with random bytes */
660 if (!pg_strong_random(&uuid->data[8], UUID_LEN - 8))
663 errmsg("could not generate random values")));
664
665#if SUBMS_MINIMAL_STEP_BITS == 10
666
667 /*
668 * On systems that have only 10 bits of sub-ms precision, 2 least
669 * significant are dependent on other time-specific bits, and they do not
670 * contribute to uniqueness. To make these bit random we mix in two bits
671 * from CSPRNG. SUBMS_MINIMAL_STEP is chosen so that we still guarantee
672 * monotonicity despite altering these bits.
673 */
674 uuid->data[7] = uuid->data[7] ^ (uuid->data[8] >> 6);
675#endif
676
677 /*
678 * Set magic numbers for a "version 7" (pseudorandom) UUID and variant,
679 * see https://www.rfc-editor.org/rfc/rfc9562#name-version-field
680 */
682
683 return uuid;
684}

References ereport, errcode(), errmsg, ERROR, fb(), NS_PER_MS, palloc(), pg_strong_random(), SUBMS_BITS, UUID_LEN, and uuid_set_version().

Referenced by uuidv7(), and uuidv7_interval().

◆ get_real_time_ns_ascending()

static int64 get_real_time_ns_ascending ( void  )
inlinestatic

Definition at line 583 of file uuid.c.

584{
585 static int64 previous_ns = 0;
586 int64 ns;
587
588 /* Get the current real timestamp */
589
590#ifdef _MSC_VER
591 struct timeval tmp;
592
593 gettimeofday(&tmp, NULL);
594 ns = tmp.tv_sec * NS_PER_S + tmp.tv_usec * NS_PER_US;
595#else
596 struct timespec tmp;
597
598 /*
599 * We don't use gettimeofday(), instead use clock_gettime() with
600 * CLOCK_REALTIME where available in order to get a high-precision
601 * (nanoseconds) real timestamp.
602 *
603 * Note while a timestamp returned by clock_gettime() with CLOCK_REALTIME
604 * is nanosecond-precision on most Unix-like platforms, on some platforms
605 * such as macOS it's restricted to microsecond-precision.
606 */
608 ns = tmp.tv_sec * NS_PER_S + tmp.tv_nsec;
609#endif
610
611 /* Guarantee the minimal step advancement of the timestamp */
614 previous_ns = ns;
615
616 return ns;
617}

References fb(), gettimeofday(), NS_PER_S, NS_PER_US, and SUBMS_MINIMAL_STEP_NS.

Referenced by uuidv7(), and uuidv7_interval().

◆ string_to_uuid()

static void string_to_uuid ( const char source,
pg_uuid_t uuid,
Node escontext 
)
static

Definition at line 148 of file uuid.c.

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
191 ereturn(escontext,,
193 errmsg("invalid input syntax for type %s: \"%s\"",
194 "uuid", source)));
195}

References ereturn, errcode(), errmsg, fb(), i, memcpy(), source, syntax_error(), and UUID_LEN.

Referenced by uuid_in().

◆ uuid_abbrev_abort()

static bool uuid_abbrev_abort ( int  memtupcount,
SortSupport  ssup 
)
static

Definition at line 363 of file uuid.c.

364{
366 double abbr_card;
367
369 return false;
370
371 abbr_card = estimateHyperLogLog(&uss->abbr_card);
372
373 /*
374 * If we have >100k distinct values, then even if we were sorting many
375 * billion rows we'd likely still break even, and the penalty of undoing
376 * that many rows of abbrevs would probably not be worth it. Stop even
377 * counting at that point.
378 */
379 if (abbr_card > 100000.0)
380 {
381 if (trace_sort)
382 elog(LOG,
383 "uuid_abbrev: estimation ends at cardinality %f"
384 " after " INT64_FORMAT " values (%d rows)",
385 abbr_card, uss->input_count, memtupcount);
386 uss->estimating = false;
387 return false;
388 }
389
390 /*
391 * Target minimum cardinality is 1 per ~2k of non-null inputs. 0.5 row
392 * fudge factor allows us to abort earlier on genuinely pathological data
393 * where we've had exactly one abbreviated value in the first 2k
394 * (non-null) rows.
395 */
396 if (abbr_card < uss->input_count / 2000.0 + 0.5)
397 {
398 if (trace_sort)
399 elog(LOG,
400 "uuid_abbrev: aborting abbreviation at cardinality %f"
401 " below threshold %f after " INT64_FORMAT " values (%d rows)",
402 abbr_card, uss->input_count / 2000.0 + 0.5, uss->input_count,
403 memtupcount);
404 return true;
405 }
406
407 if (trace_sort)
408 elog(LOG,
409 "uuid_abbrev: cardinality %f after " INT64_FORMAT
410 " values (%d rows)", abbr_card, uss->input_count, memtupcount);
411
412 return false;
413}

References elog, estimateHyperLogLog(), fb(), INT64_FORMAT, LOG, SortSupportData::ssup_extra, and trace_sort.

Referenced by uuid_sortsupport().

◆ uuid_abbrev_convert()

static Datum uuid_abbrev_convert ( Datum  original,
SortSupport  ssup 
)
static

Definition at line 423 of file uuid.c.

424{
427 Datum res;
428
429 memcpy(&res, authoritative->data, sizeof(Datum));
430 uss->input_count += 1;
431
432 if (uss->estimating)
433 {
434 uint32 tmp;
435
436 tmp = DatumGetUInt32(res) ^ (uint32) (DatumGetUInt64(res) >> 32);
437
438 addHyperLogLog(&uss->abbr_card, DatumGetUInt32(hash_uint32(tmp)));
439 }
440
441 /*
442 * Byteswap on little-endian machines.
443 *
444 * This is needed so that ssup_datum_unsigned_cmp() (an unsigned integer
445 * 3-way comparator) works correctly on all platforms. If we didn't do
446 * this, the comparator would have to call memcmp() with a pair of
447 * pointers to the first byte of each abbreviated key, which is slower.
448 */
449 res = DatumBigEndianToNative(res);
450
451 return res;
452}

References addHyperLogLog(), DatumBigEndianToNative, DatumGetUInt32(), DatumGetUInt64(), DatumGetUUIDP(), fb(), hash_uint32(), memcpy(), and SortSupportData::ssup_extra.

Referenced by uuid_sortsupport().

◆ uuid_cmp()

Datum uuid_cmp ( PG_FUNCTION_ARGS  )

Definition at line 282 of file uuid.c.

References fb(), PG_GETARG_UUID_P, PG_RETURN_INT32, and uuid_internal_cmp().

◆ uuid_decrement()

static Datum uuid_decrement ( Relation  rel,
Datum  existing,
bool underflow 
)
static

Definition at line 455 of file uuid.c.

456{
458
461 for (int i = UUID_LEN - 1; i >= 0; i--)
462 {
463 if (uuid->data[i] > 0)
464 {
465 uuid->data[i]--;
466 *underflow = false;
467 return UUIDPGetDatum(uuid);
468 }
469 uuid->data[i] = UCHAR_MAX;
470 }
471
472 pfree(uuid); /* cannot leak memory */
473
474 /* return value is undefined */
475 *underflow = true;
476 return (Datum) 0;
477}

References DatumGetUUIDP(), fb(), i, memcpy(), palloc(), pfree(), UUID_LEN, and UUIDPGetDatum().

Referenced by uuid_skipsupport().

◆ uuid_eq()

Datum uuid_eq ( PG_FUNCTION_ARGS  )

Definition at line 245 of file uuid.c.

References fb(), PG_GETARG_UUID_P, PG_RETURN_BOOL, and uuid_internal_cmp().

◆ uuid_extract_timestamp()

Datum uuid_extract_timestamp ( PG_FUNCTION_ARGS  )

Definition at line 763 of file uuid.c.

764{
766 int version;
767 uint64 tms;
768 TimestampTz ts;
769
770 /* check if RFC 9562 variant */
771 if ((uuid->data[8] & 0xc0) != 0x80)
773
774 version = uuid->data[6] >> 4;
775
776 if (version == 1)
777 {
778 tms = ((uint64) uuid->data[0] << 24)
779 + ((uint64) uuid->data[1] << 16)
780 + ((uint64) uuid->data[2] << 8)
781 + ((uint64) uuid->data[3])
782 + ((uint64) uuid->data[4] << 40)
783 + ((uint64) uuid->data[5] << 32)
784 + (((uint64) uuid->data[6] & 0xf) << 56)
785 + ((uint64) uuid->data[7] << 48);
786
787 /* convert 100-ns intervals to us, then adjust */
788 ts = (TimestampTz) (tms / 10) -
791 }
792
793 if (version == 7)
794 {
795 tms = (uuid->data[5])
796 + (((uint64) uuid->data[4]) << 8)
797 + (((uint64) uuid->data[3]) << 16)
798 + (((uint64) uuid->data[2]) << 24)
799 + (((uint64) uuid->data[1]) << 32)
800 + (((uint64) uuid->data[0]) << 40);
801
802 /* convert ms to us, then adjust */
804
806 }
807
808 /* not a timestamp-containing UUID version */
810}

References fb(), GREGORIAN_EPOCH_JDATE, PG_GETARG_UUID_P, PG_RETURN_NULL, PG_RETURN_TIMESTAMPTZ, PG_UNIX_EPOCH_OFFSET_US, POSTGRES_EPOCH_JDATE, SECS_PER_DAY, US_PER_MS, and USECS_PER_SEC.

◆ uuid_extract_version()

Datum uuid_extract_version ( PG_FUNCTION_ARGS  )

Definition at line 818 of file uuid.c.

819{
821 uint16 version;
822
823 /* check if RFC 9562 variant */
824 if ((uuid->data[8] & 0xc0) != 0x80)
826
827 version = uuid->data[6] >> 4;
828
829 PG_RETURN_UINT16(version);
830}

References fb(), PG_GETARG_UUID_P, PG_RETURN_NULL, and PG_RETURN_UINT16.

◆ uuid_fast_cmp()

static int uuid_fast_cmp ( Datum  x,
Datum  y,
SortSupport  ssup 
)
static

Definition at line 348 of file uuid.c.

349{
352
353 return uuid_internal_cmp(arg1, arg2);
354}

References DatumGetUUIDP(), fb(), uuid_internal_cmp(), x, and y.

Referenced by uuid_sortsupport().

◆ uuid_ge()

Datum uuid_ge ( PG_FUNCTION_ARGS  )

Definition at line 254 of file uuid.c.

References fb(), PG_GETARG_UUID_P, PG_RETURN_BOOL, and uuid_internal_cmp().

◆ uuid_gt()

Datum uuid_gt ( PG_FUNCTION_ARGS  )

Definition at line 263 of file uuid.c.

References fb(), PG_GETARG_UUID_P, PG_RETURN_BOOL, and uuid_internal_cmp().

◆ uuid_hash()

Datum uuid_hash ( PG_FUNCTION_ARGS  )

Definition at line 524 of file uuid.c.

525{
527
528 return hash_any(key->data, UUID_LEN);
529}

References hash_any(), PG_GETARG_UUID_P, and UUID_LEN.

◆ uuid_hash_extended()

Datum uuid_hash_extended ( PG_FUNCTION_ARGS  )

Definition at line 532 of file uuid.c.

533{
535
537}

References hash_any_extended(), PG_GETARG_INT64, PG_GETARG_UUID_P, and UUID_LEN.

◆ uuid_in()

Datum uuid_in ( PG_FUNCTION_ARGS  )

Definition at line 95 of file uuid.c.

96{
97 char *uuid_str = PG_GETARG_CSTRING(0);
99
101 string_to_uuid(uuid_str, uuid, fcinfo->context);
103}

References fb(), palloc_object, PG_GETARG_CSTRING, PG_RETURN_UUID_P, and string_to_uuid().

Referenced by uuid_generate_internal().

◆ uuid_increment()

static Datum uuid_increment ( Relation  rel,
Datum  existing,
bool overflow 
)
static

Definition at line 480 of file uuid.c.

481{
483
486 for (int i = UUID_LEN - 1; i >= 0; i--)
487 {
488 if (uuid->data[i] < UCHAR_MAX)
489 {
490 uuid->data[i]++;
491 *overflow = false;
492 return UUIDPGetDatum(uuid);
493 }
494 uuid->data[i] = 0;
495 }
496
497 pfree(uuid); /* cannot leak memory */
498
499 /* return value is undefined */
500 *overflow = true;
501 return (Datum) 0;
502}

References DatumGetUUIDP(), fb(), i, memcpy(), palloc(), pfree(), UUID_LEN, and UUIDPGetDatum().

Referenced by uuid_skipsupport().

◆ uuid_internal_cmp()

static int uuid_internal_cmp ( const pg_uuid_t arg1,
const pg_uuid_t arg2 
)
static

Definition at line 221 of file uuid.c.

222{
223 return memcmp(arg1->data, arg2->data, UUID_LEN);
224}

References fb(), and UUID_LEN.

Referenced by uuid_cmp(), uuid_eq(), uuid_fast_cmp(), uuid_ge(), uuid_gt(), uuid_larger(), uuid_le(), uuid_lt(), uuid_ne(), and uuid_smaller().

◆ uuid_larger()

Datum uuid_larger ( PG_FUNCTION_ARGS  )

Definition at line 291 of file uuid.c.

References fb(), PG_GETARG_UUID_P, PG_RETURN_UUID_P, and uuid_internal_cmp().

◆ uuid_le()

Datum uuid_le ( PG_FUNCTION_ARGS  )

Definition at line 236 of file uuid.c.

References fb(), PG_GETARG_UUID_P, PG_RETURN_BOOL, and uuid_internal_cmp().

Referenced by brin_minmax_multi_distance_uuid().

◆ uuid_lt()

Datum uuid_lt ( PG_FUNCTION_ARGS  )

Definition at line 227 of file uuid.c.

References fb(), PG_GETARG_UUID_P, PG_RETURN_BOOL, and uuid_internal_cmp().

◆ uuid_ne()

Datum uuid_ne ( PG_FUNCTION_ARGS  )

Definition at line 272 of file uuid.c.

References fb(), PG_GETARG_UUID_P, PG_RETURN_BOOL, and uuid_internal_cmp().

◆ uuid_out()

Datum uuid_out ( PG_FUNCTION_ARGS  )

Definition at line 106 of file uuid.c.

107{
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
139}

References buf, fb(), i, palloc(), PG_GETARG_UUID_P, PG_RETURN_CSTRING, and UUID_LEN.

◆ uuid_recv()

Datum uuid_recv ( PG_FUNCTION_ARGS  )

Definition at line 198 of file uuid.c.

199{
202
204 memcpy(uuid->data, pq_getmsgbytes(buffer, UUID_LEN), UUID_LEN);
206}

References fb(), memcpy(), palloc(), PG_GETARG_POINTER, PG_RETURN_POINTER, pq_getmsgbytes(), and UUID_LEN.

◆ uuid_send()

Datum uuid_send ( PG_FUNCTION_ARGS  )

Definition at line 209 of file uuid.c.

210{
212 StringInfoData buffer;
213
214 pq_begintypsend(&buffer);
215 pq_sendbytes(&buffer, uuid->data, UUID_LEN);
217}

References StringInfoData::data, fb(), PG_GETARG_UUID_P, PG_RETURN_BYTEA_P, pq_begintypsend(), pq_endtypsend(), pq_sendbytes(), and UUID_LEN.

Referenced by uuid_bytea().

◆ uuid_set_version()

static void uuid_set_version ( pg_uuid_t uuid,
unsigned char  version 
)
inlinestatic

Definition at line 543 of file uuid.c.

544{
545 /* set version field, top four bits */
546 uuid->data[6] = (uuid->data[6] & 0x0f) | (version << 4);
547
548 /* set variant field, top two bits are 1, 0 */
549 uuid->data[8] = (uuid->data[8] & 0x3f) | 0x80;
550}

References fb().

Referenced by gen_random_uuid(), and generate_uuidv7().

◆ uuid_skipsupport()

◆ uuid_smaller()

Datum uuid_smaller ( PG_FUNCTION_ARGS  )

Definition at line 300 of file uuid.c.

References fb(), PG_GETARG_UUID_P, PG_RETURN_UUID_P, and uuid_internal_cmp().

◆ uuid_sortsupport()

◆ uuidv7()

◆ uuidv7_interval()

Datum uuidv7_interval ( PG_FUNCTION_ARGS  )

Definition at line 702 of file uuid.c.

703{
704 Interval *shift = PG_GETARG_INTERVAL_P(0);
705 TimestampTz ts;
708 int64 us;
709
710 /* Reject infinite intervals before any arithmetic */
711 if (INTERVAL_NOT_FINITE(shift))
714 errmsg("interval out of range for UUID version 7"),
715 errdetail("UUID version 7 does not support infinite intervals.")));
716
717 /*
718 * Shift the current timestamp by the given interval. To calculate time
719 * shift correctly, we convert the UNIX epoch to TimestampTz and use
720 * timestamptz_pl_interval(). This calculation is done with microsecond
721 * precision.
722 */
723
725
726 /* Compute time shift */
729 IntervalPGetDatum(shift)));
730
731 /*
732 * Reject timestamps outside the range representable by UUID version 7's
733 * 48-bit millisecond field. We compare in PostgreSQL-epoch units so that
734 * the subsequent conversion to Unix-epoch microseconds cannot overflow.
735 */
739 errmsg("timestamp out of range for UUID version 7"),
740 errdetail("UUID version 7 supports timestamps from 1970-01-01 to approximately year 10889.")));
741
742 /* Convert the TimestampTz value to a Unix-epoch timestamp in usec */
743 us = ts + PG_UNIX_EPOCH_OFFSET_US;
744
745 /* Generate an UUIDv7 */
747
749}

References DatumGetTimestampTz(), DirectFunctionCall2, ereport, errcode(), errdetail(), errmsg, ERROR, fb(), generate_uuidv7(), get_real_time_ns_ascending(), INTERVAL_NOT_FINITE, IntervalPGetDatum(), NS_PER_US, PG_GETARG_INTERVAL_P, PG_RETURN_UUID_P, PG_UNIX_EPOCH_OFFSET_US, timestamptz_pl_interval(), TimestampTzGetDatum(), US_PER_MS, and UUIDV7_MAX_TIMESTAMP.