LCOV - code coverage report
Current view: top level - src/backend/utils/adt - uuid.c (source / functions) Coverage Total Hit
Test: PostgreSQL 20devel Lines: 81.0 % 258 209
Test Date: 2026-07-12 08:15:39 Functions: 87.5 % 32 28
Legend: Lines:     hit not hit
Branches: + taken - not taken # not executed
Branches: 63.0 % 92 58

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

Generated by: LCOV version 2.0-1