LCOV - code coverage report
Current view: top level - src/backend/utils/adt - uuid.c (source / functions) Coverage Total Hit
Test: PostgreSQL 20devel Lines: 81.3 % 262 213
Test Date: 2026-07-22 12:15:41 Functions: 87.5 % 32 28
Legend: Lines:     hit not hit
Branches: + taken - not taken # not executed
Branches: 64.3 % 112 72

             Branch data     Line data    Source code
       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 "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(void);
      92                 :             : static pg_uuid_t *generate_uuidv7(uint64 unix_ts_ms, uint32 sub_ms);
      93                 :             : 
      94                 :             : Datum
      95                 :      390414 : uuid_in(PG_FUNCTION_ARGS)
      96                 :             : {
      97                 :      390414 :     char       *uuid_str = PG_GETARG_CSTRING(0);
      98                 :             :     pg_uuid_t  *uuid;
      99                 :             : 
     100                 :      390414 :     uuid = palloc_object(pg_uuid_t);
     101                 :      390414 :     string_to_uuid(uuid_str, uuid, fcinfo->context);
     102                 :      390390 :     PG_RETURN_UUID_P(uuid);
     103                 :             : }
     104                 :             : 
     105                 :             : Datum
     106                 :        3118 : uuid_out(PG_FUNCTION_ARGS)
     107                 :             : {
     108                 :        3118 :     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                 :        3118 :     buf = palloc(2 * UUID_LEN + 5);
     116                 :        3118 :     p = buf;
     117         [ +  + ]:       53006 :     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   [ +  +  +  +  :       49888 :         if (i == 4 || i == 6 || i == 8 || i == 10)
             +  +  +  + ]
     128                 :       12472 :             *p++ = '-';
     129                 :             : 
     130                 :       49888 :         hi = uuid->data[i] >> 4;
     131                 :       49888 :         lo = uuid->data[i] & 0x0F;
     132                 :             : 
     133                 :       49888 :         *p++ = hex_chars[hi];
     134                 :       49888 :         *p++ = hex_chars[lo];
     135                 :             :     }
     136                 :        3118 :     *p = '\0';
     137                 :             : 
     138                 :        3118 :     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                 :      390414 : string_to_uuid(const char *source, pg_uuid_t *uuid, Node *escontext)
     149                 :             : {
     150                 :      390414 :     const char *src = source;
     151                 :      390414 :     bool        braces = false;
     152                 :             :     int         i;
     153                 :             : 
     154         [ +  + ]:      390414 :     if (src[0] == '{')
     155                 :             :     {
     156                 :          16 :         src++;
     157                 :          16 :         braces = true;
     158                 :             :     }
     159                 :             : 
     160         [ +  + ]:     6636762 :     for (i = 0; i < UUID_LEN; i++)
     161                 :             :     {
     162                 :             :         char        str_buf[3];
     163                 :             : 
     164   [ +  +  -  + ]:     6246372 :         if (src[0] == '\0' || src[1] == '\0')
     165                 :          24 :             goto syntax_error;
     166                 :     6246364 :         memcpy(str_buf, src, 2);
     167         [ +  + ]:     6246364 :         if (!isxdigit((unsigned char) str_buf[0]) ||
     168         [ +  + ]:     6246356 :             !isxdigit((unsigned char) str_buf[1]))
     169                 :          16 :             goto syntax_error;
     170                 :             : 
     171                 :     6246348 :         str_buf[2] = '\0';
     172                 :     6246348 :         uuid->data[i] = (unsigned char) strtoul(str_buf, NULL, 16);
     173                 :     6246348 :         src += 2;
     174   [ +  +  +  -  :     6246348 :         if (src[0] == '-' && (i % 2) == 1 && i < UUID_LEN - 1)
                   +  - ]
     175                 :     1289492 :             src++;
     176                 :             :     }
     177                 :             : 
     178         [ +  + ]:      390390 :     if (braces)
     179                 :             :     {
     180         [ +  + ]:          12 :         if (*src != '}')
     181                 :           4 :             goto syntax_error;
     182                 :           8 :         src++;
     183                 :             :     }
     184                 :             : 
     185         [ +  + ]:      390386 :     if (*src != '\0')
     186                 :           4 :         goto syntax_error;
     187                 :             : 
     188                 :      390382 :     return;
     189                 :             : 
     190                 :          32 : syntax_error:
     191         [ +  + ]:          32 :     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                 :           0 : uuid_recv(PG_FUNCTION_ARGS)
     199                 :             : {
     200                 :           0 :     StringInfo  buffer = (StringInfo) PG_GETARG_POINTER(0);
     201                 :             :     pg_uuid_t  *uuid;
     202                 :             : 
     203                 :           0 :     uuid = (pg_uuid_t *) palloc(UUID_LEN);
     204                 :           0 :     memcpy(uuid->data, pq_getmsgbytes(buffer, UUID_LEN), UUID_LEN);
     205                 :           0 :     PG_RETURN_POINTER(uuid);
     206                 :             : }
     207                 :             : 
     208                 :             : Datum
     209                 :          97 : uuid_send(PG_FUNCTION_ARGS)
     210                 :             : {
     211                 :          97 :     pg_uuid_t  *uuid = PG_GETARG_UUID_P(0);
     212                 :             :     StringInfoData buffer;
     213                 :             : 
     214                 :          97 :     pq_begintypsend(&buffer);
     215                 :          97 :     pq_sendbytes(&buffer, uuid->data, UUID_LEN);
     216                 :          97 :     PG_RETURN_BYTEA_P(pq_endtypsend(&buffer));
     217                 :             : }
     218                 :             : 
     219                 :             : /* internal uuid compare function */
     220                 :             : static int
     221                 :    27712873 : uuid_internal_cmp(const pg_uuid_t *arg1, const pg_uuid_t *arg2)
     222                 :             : {
     223                 :    27712873 :     return memcmp(arg1->data, arg2->data, UUID_LEN);
     224                 :             : }
     225                 :             : 
     226                 :             : Datum
     227                 :       55544 : uuid_lt(PG_FUNCTION_ARGS)
     228                 :             : {
     229                 :       55544 :     pg_uuid_t  *arg1 = PG_GETARG_UUID_P(0);
     230                 :       55544 :     pg_uuid_t  *arg2 = PG_GETARG_UUID_P(1);
     231                 :             : 
     232                 :       55544 :     PG_RETURN_BOOL(uuid_internal_cmp(arg1, arg2) < 0);
     233                 :             : }
     234                 :             : 
     235                 :             : Datum
     236                 :       11163 : uuid_le(PG_FUNCTION_ARGS)
     237                 :             : {
     238                 :       11163 :     pg_uuid_t  *arg1 = PG_GETARG_UUID_P(0);
     239                 :       11163 :     pg_uuid_t  *arg2 = PG_GETARG_UUID_P(1);
     240                 :             : 
     241                 :       11163 :     PG_RETURN_BOOL(uuid_internal_cmp(arg1, arg2) <= 0);
     242                 :             : }
     243                 :             : 
     244                 :             : Datum
     245                 :      103598 : uuid_eq(PG_FUNCTION_ARGS)
     246                 :             : {
     247                 :      103598 :     pg_uuid_t  *arg1 = PG_GETARG_UUID_P(0);
     248                 :      103598 :     pg_uuid_t  *arg2 = PG_GETARG_UUID_P(1);
     249                 :             : 
     250                 :      103598 :     PG_RETURN_BOOL(uuid_internal_cmp(arg1, arg2) == 0);
     251                 :             : }
     252                 :             : 
     253                 :             : Datum
     254                 :        8236 : uuid_ge(PG_FUNCTION_ARGS)
     255                 :             : {
     256                 :        8236 :     pg_uuid_t  *arg1 = PG_GETARG_UUID_P(0);
     257                 :        8236 :     pg_uuid_t  *arg2 = PG_GETARG_UUID_P(1);
     258                 :             : 
     259                 :        8236 :     PG_RETURN_BOOL(uuid_internal_cmp(arg1, arg2) >= 0);
     260                 :             : }
     261                 :             : 
     262                 :             : Datum
     263                 :       10659 : uuid_gt(PG_FUNCTION_ARGS)
     264                 :             : {
     265                 :       10659 :     pg_uuid_t  *arg1 = PG_GETARG_UUID_P(0);
     266                 :       10659 :     pg_uuid_t  *arg2 = PG_GETARG_UUID_P(1);
     267                 :             : 
     268                 :       10659 :     PG_RETURN_BOOL(uuid_internal_cmp(arg1, arg2) > 0);
     269                 :             : }
     270                 :             : 
     271                 :             : Datum
     272                 :          52 : uuid_ne(PG_FUNCTION_ARGS)
     273                 :             : {
     274                 :          52 :     pg_uuid_t  *arg1 = PG_GETARG_UUID_P(0);
     275                 :          52 :     pg_uuid_t  *arg2 = PG_GETARG_UUID_P(1);
     276                 :             : 
     277                 :          52 :     PG_RETURN_BOOL(uuid_internal_cmp(arg1, arg2) != 0);
     278                 :             : }
     279                 :             : 
     280                 :             : /* handler for btree index operator */
     281                 :             : Datum
     282                 :        6191 : uuid_cmp(PG_FUNCTION_ARGS)
     283                 :             : {
     284                 :        6191 :     pg_uuid_t  *arg1 = PG_GETARG_UUID_P(0);
     285                 :        6191 :     pg_uuid_t  *arg2 = PG_GETARG_UUID_P(1);
     286                 :             : 
     287                 :        6191 :     PG_RETURN_INT32(uuid_internal_cmp(arg1, arg2));
     288                 :             : }
     289                 :             : 
     290                 :             : Datum
     291                 :           8 : uuid_larger(PG_FUNCTION_ARGS)
     292                 :             : {
     293                 :           8 :     pg_uuid_t  *arg1 = PG_GETARG_UUID_P(0);
     294                 :           8 :     pg_uuid_t  *arg2 = PG_GETARG_UUID_P(1);
     295                 :             : 
     296         [ -  + ]:           8 :     PG_RETURN_UUID_P((uuid_internal_cmp(arg1, arg2) > 0) ? arg1 : arg2);
     297                 :             : }
     298                 :             : 
     299                 :             : Datum
     300                 :           8 : uuid_smaller(PG_FUNCTION_ARGS)
     301                 :             : {
     302                 :           8 :     pg_uuid_t  *arg1 = PG_GETARG_UUID_P(0);
     303                 :           8 :     pg_uuid_t  *arg2 = PG_GETARG_UUID_P(1);
     304                 :             : 
     305         [ +  - ]:           8 :     PG_RETURN_UUID_P((uuid_internal_cmp(arg1, arg2) < 0) ? arg1 : arg2);
     306                 :             : }
     307                 :             : 
     308                 :             : /*
     309                 :             :  * Sort support strategy routine
     310                 :             :  */
     311                 :             : Datum
     312                 :         254 : uuid_sortsupport(PG_FUNCTION_ARGS)
     313                 :             : {
     314                 :         254 :     SortSupport ssup = (SortSupport) PG_GETARG_POINTER(0);
     315                 :             : 
     316                 :         254 :     ssup->comparator = uuid_fast_cmp;
     317                 :         254 :     ssup->ssup_extra = NULL;
     318                 :             : 
     319         [ +  + ]:         254 :     if (ssup->abbreviate)
     320                 :             :     {
     321                 :             :         uuid_sortsupport_state *uss;
     322                 :             :         MemoryContext oldcontext;
     323                 :             : 
     324                 :         204 :         oldcontext = MemoryContextSwitchTo(ssup->ssup_cxt);
     325                 :             : 
     326                 :         204 :         uss = palloc_object(uuid_sortsupport_state);
     327                 :         204 :         uss->input_count = 0;
     328                 :         204 :         uss->estimating = true;
     329                 :         204 :         initHyperLogLog(&uss->abbr_card, 10);
     330                 :             : 
     331                 :         204 :         ssup->ssup_extra = uss;
     332                 :             : 
     333                 :         204 :         ssup->comparator = ssup_datum_unsigned_cmp;
     334                 :         204 :         ssup->abbrev_converter = uuid_abbrev_convert;
     335                 :         204 :         ssup->abbrev_abort = uuid_abbrev_abort;
     336                 :         204 :         ssup->abbrev_full_comparator = uuid_fast_cmp;
     337                 :             : 
     338                 :         204 :         MemoryContextSwitchTo(oldcontext);
     339                 :             :     }
     340                 :             : 
     341                 :         254 :     PG_RETURN_VOID();
     342                 :             : }
     343                 :             : 
     344                 :             : /*
     345                 :             :  * SortSupport comparison func
     346                 :             :  */
     347                 :             : static int
     348                 :    27517414 : uuid_fast_cmp(Datum x, Datum y, SortSupport ssup)
     349                 :             : {
     350                 :    27517414 :     pg_uuid_t  *arg1 = DatumGetUUIDP(x);
     351                 :    27517414 :     pg_uuid_t  *arg2 = DatumGetUUIDP(y);
     352                 :             : 
     353                 :    27517414 :     return uuid_internal_cmp(arg1, arg2);
     354                 :             : }
     355                 :             : 
     356                 :             : /*
     357                 :             :  * Callback for estimating effectiveness of abbreviated key optimization.
     358                 :             :  *
     359                 :             :  * We pay no attention to the cardinality of the non-abbreviated data, because
     360                 :             :  * there is no equality fast-path within authoritative uuid comparator.
     361                 :             :  */
     362                 :             : static bool
     363                 :        1552 : uuid_abbrev_abort(int memtupcount, SortSupport ssup)
     364                 :             : {
     365                 :        1552 :     uuid_sortsupport_state *uss = ssup->ssup_extra;
     366                 :             :     double      abbr_card;
     367                 :             : 
     368   [ +  +  +  -  :        1552 :     if (memtupcount < 10000 || uss->input_count < 10000 || !uss->estimating)
                   -  + ]
     369                 :        1424 :         return false;
     370                 :             : 
     371                 :         128 :     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         [ -  + ]:         128 :     if (abbr_card > 100000.0)
     380                 :             :     {
     381         [ #  # ]:           0 :         if (trace_sort)
     382         [ #  # ]:           0 :             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                 :           0 :         uss->estimating = false;
     387                 :           0 :         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         [ +  + ]:         128 :     if (abbr_card < uss->input_count / 2000.0 + 0.5)
     397                 :             :     {
     398         [ -  + ]:          64 :         if (trace_sort)
     399         [ #  # ]:           0 :             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                 :          64 :         return true;
     405                 :             :     }
     406                 :             : 
     407         [ -  + ]:          64 :     if (trace_sort)
     408         [ #  # ]:           0 :         elog(LOG,
     409                 :             :              "uuid_abbrev: cardinality %f after " INT64_FORMAT
     410                 :             :              " values (%d rows)", abbr_card, uss->input_count, memtupcount);
     411                 :             : 
     412                 :          64 :     return false;
     413                 :             : }
     414                 :             : 
     415                 :             : /*
     416                 :             :  * Conversion routine for sortsupport.  Converts original uuid representation
     417                 :             :  * to abbreviated key representation.  Our encoding strategy is simple -- pack
     418                 :             :  * the first `sizeof(Datum)` bytes of uuid data into a Datum (on little-endian
     419                 :             :  * machines, the bytes are stored in reverse order), and treat it as an
     420                 :             :  * unsigned integer.
     421                 :             :  */
     422                 :             : static Datum
     423                 :     2256104 : uuid_abbrev_convert(Datum original, SortSupport ssup)
     424                 :             : {
     425                 :     2256104 :     uuid_sortsupport_state *uss = ssup->ssup_extra;
     426                 :     2256104 :     pg_uuid_t  *authoritative = DatumGetUUIDP(original);
     427                 :             :     Datum       res;
     428                 :             : 
     429                 :     2256104 :     memcpy(&res, authoritative->data, sizeof(Datum));
     430                 :     2256104 :     uss->input_count += 1;
     431                 :             : 
     432         [ +  - ]:     2256104 :     if (uss->estimating)
     433                 :             :     {
     434                 :             :         uint32      tmp;
     435                 :             : 
     436                 :     2256104 :         tmp = DatumGetUInt32(res) ^ (uint32) (DatumGetUInt64(res) >> 32);
     437                 :             : 
     438                 :     2256104 :         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                 :     2256104 :     res = DatumBigEndianToNative(res);
     450                 :             : 
     451                 :     2256104 :     return res;
     452                 :             : }
     453                 :             : 
     454                 :             : static Datum
     455                 :           0 : uuid_decrement(Relation rel, Datum existing, bool *underflow)
     456                 :             : {
     457                 :             :     pg_uuid_t  *uuid;
     458                 :             : 
     459                 :           0 :     uuid = (pg_uuid_t *) palloc(UUID_LEN);
     460                 :           0 :     memcpy(uuid, DatumGetUUIDP(existing), UUID_LEN);
     461         [ #  # ]:           0 :     for (int i = UUID_LEN - 1; i >= 0; i--)
     462                 :             :     {
     463         [ #  # ]:           0 :         if (uuid->data[i] > 0)
     464                 :             :         {
     465                 :           0 :             uuid->data[i]--;
     466                 :           0 :             *underflow = false;
     467                 :           0 :             return UUIDPGetDatum(uuid);
     468                 :             :         }
     469                 :           0 :         uuid->data[i] = UCHAR_MAX;
     470                 :             :     }
     471                 :             : 
     472                 :           0 :     pfree(uuid);                /* cannot leak memory */
     473                 :             : 
     474                 :             :     /* return value is undefined */
     475                 :           0 :     *underflow = true;
     476                 :           0 :     return (Datum) 0;
     477                 :             : }
     478                 :             : 
     479                 :             : static Datum
     480                 :           0 : uuid_increment(Relation rel, Datum existing, bool *overflow)
     481                 :             : {
     482                 :             :     pg_uuid_t  *uuid;
     483                 :             : 
     484                 :           0 :     uuid = (pg_uuid_t *) palloc(UUID_LEN);
     485                 :           0 :     memcpy(uuid, DatumGetUUIDP(existing), UUID_LEN);
     486         [ #  # ]:           0 :     for (int i = UUID_LEN - 1; i >= 0; i--)
     487                 :             :     {
     488         [ #  # ]:           0 :         if (uuid->data[i] < UCHAR_MAX)
     489                 :             :         {
     490                 :           0 :             uuid->data[i]++;
     491                 :           0 :             *overflow = false;
     492                 :           0 :             return UUIDPGetDatum(uuid);
     493                 :             :         }
     494                 :           0 :         uuid->data[i] = 0;
     495                 :             :     }
     496                 :             : 
     497                 :           0 :     pfree(uuid);                /* cannot leak memory */
     498                 :             : 
     499                 :             :     /* return value is undefined */
     500                 :           0 :     *overflow = true;
     501                 :           0 :     return (Datum) 0;
     502                 :             : }
     503                 :             : 
     504                 :             : Datum
     505                 :           0 : uuid_skipsupport(PG_FUNCTION_ARGS)
     506                 :             : {
     507                 :           0 :     SkipSupport sksup = (SkipSupport) PG_GETARG_POINTER(0);
     508                 :           0 :     pg_uuid_t  *uuid_min = palloc(UUID_LEN);
     509                 :           0 :     pg_uuid_t  *uuid_max = palloc(UUID_LEN);
     510                 :             : 
     511                 :           0 :     memset(uuid_min->data, 0x00, UUID_LEN);
     512                 :           0 :     memset(uuid_max->data, 0xFF, UUID_LEN);
     513                 :             : 
     514                 :           0 :     sksup->decrement = uuid_decrement;
     515                 :           0 :     sksup->increment = uuid_increment;
     516                 :           0 :     sksup->low_elem = UUIDPGetDatum(uuid_min);
     517                 :           0 :     sksup->high_elem = UUIDPGetDatum(uuid_max);
     518                 :             : 
     519                 :           0 :     PG_RETURN_VOID();
     520                 :             : }
     521                 :             : 
     522                 :             : /* hash index support */
     523                 :             : Datum
     524                 :        1614 : uuid_hash(PG_FUNCTION_ARGS)
     525                 :             : {
     526                 :        1614 :     pg_uuid_t  *key = PG_GETARG_UUID_P(0);
     527                 :             : 
     528                 :        1614 :     return hash_any(key->data, UUID_LEN);
     529                 :             : }
     530                 :             : 
     531                 :             : Datum
     532                 :          40 : uuid_hash_extended(PG_FUNCTION_ARGS)
     533                 :             : {
     534                 :          40 :     pg_uuid_t  *key = PG_GETARG_UUID_P(0);
     535                 :             : 
     536                 :          40 :     return hash_any_extended(key->data, UUID_LEN, PG_GETARG_INT64(1));
     537                 :             : }
     538                 :             : 
     539                 :             : /*
     540                 :             :  * Set the given UUID version and the variant bits
     541                 :             :  */
     542                 :             : static inline void
     543                 :       35808 : uuid_set_version(pg_uuid_t *uuid, unsigned char version)
     544                 :             : {
     545                 :             :     /* set version field, top four bits */
     546                 :       35808 :     uuid->data[6] = (uuid->data[6] & 0x0f) | (version << 4);
     547                 :             : 
     548                 :             :     /* set variant field, top two bits are 1, 0 */
     549                 :       35808 :     uuid->data[8] = (uuid->data[8] & 0x3f) | 0x80;
     550                 :       35808 : }
     551                 :             : 
     552                 :             : /*
     553                 :             :  * Generate UUID version 4.
     554                 :             :  *
     555                 :             :  * All UUID bytes are filled with strong random numbers except version and
     556                 :             :  * variant bits.
     557                 :             :  */
     558                 :             : Datum
     559                 :          72 : gen_random_uuid(PG_FUNCTION_ARGS)
     560                 :             : {
     561                 :          72 :     pg_uuid_t  *uuid = palloc(UUID_LEN);
     562                 :             : 
     563         [ -  + ]:          72 :     if (!pg_strong_random(uuid, UUID_LEN))
     564         [ #  # ]:           0 :         ereport(ERROR,
     565                 :             :                 (errcode(ERRCODE_INTERNAL_ERROR),
     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                 :             :      */
     572                 :          72 :     uuid_set_version(uuid, 4);
     573                 :             : 
     574                 :          72 :     PG_RETURN_UUID_P(uuid);
     575                 :             : }
     576                 :             : 
     577                 :             : /*
     578                 :             :  * Get the current timestamp with nanosecond precision for UUID generation.
     579                 :             :  * The returned timestamp is ensured to be at least SUBMS_MINIMAL_STEP greater
     580                 :             :  * than the previous returned timestamp (on this backend).
     581                 :             :  */
     582                 :             : static inline int64
     583                 :       35752 : get_real_time_ns_ascending(void)
     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                 :             :      */
     607                 :       35752 :     clock_gettime(CLOCK_REALTIME, &tmp);
     608                 :       35752 :     ns = tmp.tv_sec * NS_PER_S + tmp.tv_nsec;
     609                 :             : #endif
     610                 :             : 
     611                 :             :     /* Guarantee the minimal step advancement of the timestamp */
     612         [ -  + ]:       35752 :     if (previous_ns + SUBMS_MINIMAL_STEP_NS >= ns)
     613                 :           0 :         ns = previous_ns + SUBMS_MINIMAL_STEP_NS;
     614                 :       35752 :     previous_ns = ns;
     615                 :             : 
     616                 :       35752 :     return ns;
     617                 :             : }
     618                 :             : 
     619                 :             : /*
     620                 :             :  * Generate UUID version 7 per RFC 9562, with the given timestamp.
     621                 :             :  *
     622                 :             :  * UUID version 7 consists of a Unix timestamp in milliseconds (48 bits) and
     623                 :             :  * 74 random bits, excluding the required version and variant bits. To ensure
     624                 :             :  * monotonicity in scenarios of high-frequency UUID generation, we employ the
     625                 :             :  * method "Replace Leftmost Random Bits with Increased Clock Precision (Method 3)",
     626                 :             :  * described in the RFC. This method utilizes 12 bits from the "rand_a" bits
     627                 :             :  * to store a 1/4096 (or 2^12) fraction of sub-millisecond precision.
     628                 :             :  *
     629                 :             :  * unix_ts_ms is a number of milliseconds since start of the UNIX epoch,
     630                 :             :  * and sub_ms is a number of nanoseconds within millisecond. These values are
     631                 :             :  * used for time-dependent bits of UUID.
     632                 :             :  *
     633                 :             :  * NB: all numbers here are unsigned, unix_ts_ms cannot be negative per RFC.
     634                 :             :  */
     635                 :             : static pg_uuid_t *
     636                 :       35736 : generate_uuidv7(uint64 unix_ts_ms, uint32 sub_ms)
     637                 :             : {
     638                 :       35736 :     pg_uuid_t  *uuid = palloc(UUID_LEN);
     639                 :             :     uint32      increased_clock_precision;
     640                 :             : 
     641                 :             :     /* Fill in time part */
     642                 :       35736 :     uuid->data[0] = (unsigned char) (unix_ts_ms >> 40);
     643                 :       35736 :     uuid->data[1] = (unsigned char) (unix_ts_ms >> 32);
     644                 :       35736 :     uuid->data[2] = (unsigned char) (unix_ts_ms >> 24);
     645                 :       35736 :     uuid->data[3] = (unsigned char) (unix_ts_ms >> 16);
     646                 :       35736 :     uuid->data[4] = (unsigned char) (unix_ts_ms >> 8);
     647                 :       35736 :     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                 :             :      */
     653                 :       35736 :     increased_clock_precision = (sub_ms * (1 << SUBMS_BITS)) / NS_PER_MS;
     654                 :             : 
     655                 :             :     /* Fill the increased clock precision to "rand_a" bits */
     656                 :       35736 :     uuid->data[6] = (unsigned char) (increased_clock_precision >> 8);
     657                 :       35736 :     uuid->data[7] = (unsigned char) (increased_clock_precision);
     658                 :             : 
     659                 :             :     /* fill everything after the increased clock precision with random bytes */
     660         [ -  + ]:       35736 :     if (!pg_strong_random(&uuid->data[8], UUID_LEN - 8))
     661         [ #  # ]:           0 :         ereport(ERROR,
     662                 :             :                 (errcode(ERRCODE_INTERNAL_ERROR),
     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                 :             :      */
     681                 :       35736 :     uuid_set_version(uuid, 7);
     682                 :             : 
     683                 :       35736 :     return uuid;
     684                 :             : }
     685                 :             : 
     686                 :             : /*
     687                 :             :  * Generate UUID version 7 with the current timestamp.
     688                 :             :  */
     689                 :             : Datum
     690                 :          52 : uuidv7(PG_FUNCTION_ARGS)
     691                 :             : {
     692                 :          52 :     int64       ns = get_real_time_ns_ascending();
     693                 :          52 :     pg_uuid_t  *uuid = generate_uuidv7(ns / NS_PER_MS, ns % NS_PER_MS);
     694                 :             : 
     695                 :          52 :     PG_RETURN_UUID_P(uuid);
     696                 :             : }
     697                 :             : 
     698                 :             : /*
     699                 :             :  * Similar to uuidv7() but with the timestamp adjusted by the given interval.
     700                 :             :  */
     701                 :             : Datum
     702                 :       35700 : uuidv7_interval(PG_FUNCTION_ARGS)
     703                 :             : {
     704                 :       35700 :     Interval   *shift = PG_GETARG_INTERVAL_P(0);
     705                 :             :     TimestampTz ts;
     706                 :             :     pg_uuid_t  *uuid;
     707                 :       35700 :     int64       ns = get_real_time_ns_ascending();
     708                 :             :     int64       us;
     709                 :             : 
     710                 :             :     /* Reject infinite intervals before any arithmetic */
     711   [ +  +  +  -  :       35700 :     if (INTERVAL_NOT_FINITE(shift))
          -  +  +  +  +  
                -  +  - ]
     712         [ +  - ]:           8 :         ereport(ERROR,
     713                 :             :                 (errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
     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                 :             : 
     724                 :       35692 :     ts = (TimestampTz) (ns / NS_PER_US) - PG_UNIX_EPOCH_OFFSET_US;
     725                 :             : 
     726                 :             :     /* Compute time shift */
     727                 :       35692 :     ts = DatumGetTimestampTz(DirectFunctionCall2(timestamptz_pl_interval,
     728                 :             :                                                  TimestampTzGetDatum(ts),
     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                 :             :      */
     736   [ +  +  +  + ]:       35692 :     if (ts < UUIDV7_MIN_TIMESTAMP || ts > UUIDV7_MAX_TIMESTAMP)
     737         [ +  - ]:           8 :         ereport(ERROR,
     738                 :             :                 (errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
     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                 :       35684 :     us = ts + PG_UNIX_EPOCH_OFFSET_US;
     744                 :             : 
     745                 :             :     /* Generate an UUIDv7 */
     746                 :       35684 :     uuid = generate_uuidv7(us / US_PER_MS, (us % US_PER_MS) * NS_PER_US + ns % NS_PER_US);
     747                 :             : 
     748                 :       35684 :     PG_RETURN_UUID_P(uuid);
     749                 :             : }
     750                 :             : 
     751                 :             : /*
     752                 :             :  * Start of a Gregorian epoch == date2j(1582,10,15)
     753                 :             :  * We cast it to 64-bit because it's used in overflow-prone computations
     754                 :             :  */
     755                 :             : #define GREGORIAN_EPOCH_JDATE  INT64CONST(2299161)
     756                 :             : 
     757                 :             : /*
     758                 :             :  * Extract timestamp from UUID.
     759                 :             :  *
     760                 :             :  * Returns null if not RFC 9562 variant or not a version that has a timestamp.
     761                 :             :  */
     762                 :             : Datum
     763                 :       35699 : uuid_extract_timestamp(PG_FUNCTION_ARGS)
     764                 :             : {
     765                 :       35699 :     pg_uuid_t  *uuid = PG_GETARG_UUID_P(0);
     766                 :             :     int         version;
     767                 :             :     uint64      tms;
     768                 :             :     TimestampTz ts;
     769                 :             : 
     770                 :             :     /* check if RFC 9562 variant */
     771         [ +  + ]:       35699 :     if ((uuid->data[8] & 0xc0) != 0x80)
     772                 :           5 :         PG_RETURN_NULL();
     773                 :             : 
     774                 :       35694 :     version = uuid->data[6] >> 4;
     775                 :             : 
     776         [ +  + ]:       35694 :     if (version == 1)
     777                 :             :     {
     778                 :           5 :         tms = ((uint64) uuid->data[0] << 24)
     779                 :           5 :             + ((uint64) uuid->data[1] << 16)
     780                 :           5 :             + ((uint64) uuid->data[2] << 8)
     781                 :           5 :             + ((uint64) uuid->data[3])
     782                 :           5 :             + ((uint64) uuid->data[4] << 40)
     783                 :           5 :             + ((uint64) uuid->data[5] << 32)
     784                 :           5 :             + (((uint64) uuid->data[6] & 0xf) << 56)
     785                 :           5 :             + ((uint64) uuid->data[7] << 48);
     786                 :             : 
     787                 :             :         /* convert 100-ns intervals to us, then adjust */
     788                 :           5 :         ts = (TimestampTz) (tms / 10) -
     789                 :             :             ((uint64) POSTGRES_EPOCH_JDATE - GREGORIAN_EPOCH_JDATE) * SECS_PER_DAY * USECS_PER_SEC;
     790                 :           5 :         PG_RETURN_TIMESTAMPTZ(ts);
     791                 :             :     }
     792                 :             : 
     793         [ +  + ]:       35689 :     if (version == 7)
     794                 :             :     {
     795                 :       35685 :         tms = (uuid->data[5])
     796                 :       35685 :             + (((uint64) uuid->data[4]) << 8)
     797                 :       35685 :             + (((uint64) uuid->data[3]) << 16)
     798                 :       35685 :             + (((uint64) uuid->data[2]) << 24)
     799                 :       35685 :             + (((uint64) uuid->data[1]) << 32)
     800                 :       35685 :             + (((uint64) uuid->data[0]) << 40);
     801                 :             : 
     802                 :             :         /* convert ms to us, then adjust */
     803                 :       35685 :         ts = (TimestampTz) (tms * US_PER_MS) - PG_UNIX_EPOCH_OFFSET_US;
     804                 :             : 
     805                 :       35685 :         PG_RETURN_TIMESTAMPTZ(ts);
     806                 :             :     }
     807                 :             : 
     808                 :             :     /* not a timestamp-containing UUID version */
     809                 :           4 :     PG_RETURN_NULL();
     810                 :             : }
     811                 :             : 
     812                 :             : /*
     813                 :             :  * Extract UUID version.
     814                 :             :  *
     815                 :             :  * Returns null if not RFC 9562 variant.
     816                 :             :  */
     817                 :             : Datum
     818                 :          22 : uuid_extract_version(PG_FUNCTION_ARGS)
     819                 :             : {
     820                 :          22 :     pg_uuid_t  *uuid = PG_GETARG_UUID_P(0);
     821                 :             :     uint16      version;
     822                 :             : 
     823                 :             :     /* check if RFC 9562 variant */
     824         [ +  + ]:          22 :     if ((uuid->data[8] & 0xc0) != 0x80)
     825                 :           5 :         PG_RETURN_NULL();
     826                 :             : 
     827                 :          17 :     version = uuid->data[6] >> 4;
     828                 :             : 
     829                 :          17 :     PG_RETURN_UINT16(version);
     830                 :             : }
        

Generated by: LCOV version 2.0-1