Skip to content

Commit

Permalink
uuid: set nsec part of timestamp to 0 for uuid7(x)
Browse files Browse the repository at this point in the history
  • Loading branch information
nalgeon committed Dec 8, 2024
1 parent ac10ca6 commit 2e02f6c
Show file tree
Hide file tree
Showing 2 changed files with 10 additions and 6 deletions.
15 changes: 9 additions & 6 deletions src/uuid/extension.c
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,8 @@
*
* uuid4() - generate a version 4 UUID as a string
* uuid7() - generate a version 7 UUID as a string
* uuid7(X) - generate a version 7 UUID as a string using X seconds since the unix epoch as the timestamp
* uuid7(X) - generate a version 7 UUID as a string
* with a unix timestamp of X seconds.
* uuid_str(X) - convert a UUID X into a well-formed UUID string
* uuid_blob(X) - convert a UUID X into a 16-byte blob
* uuid7_timestamp_ms(X) - extract unix timestamp in miliseconds
Expand Down Expand Up @@ -191,11 +192,12 @@ static void uuid_v7_generate(sqlite3_context* context, int argc, sqlite3_value**
(void)argv;

struct timespec ts;
if (argc == 1 && sqlite3_value_type(argv[0])==SQLITE_INTEGER) {
sqlite3_int64 seconds = sqlite3_value_int64(argv[0]);
ts.tv_sec = seconds;
if (argc == 1 && sqlite3_value_type(argv[0]) == SQLITE_INTEGER) {
sqlite3_int64 seconds = sqlite3_value_int64(argv[0]);
ts.tv_sec = seconds;
ts.tv_nsec = 0;
} else {
timespec_get(&ts, TIME_UTC);
timespec_get(&ts, TIME_UTC);
}
unsigned long long timestampMs = ts.tv_sec * 1000ULL + ts.tv_nsec / 1000000;

Expand Down Expand Up @@ -272,7 +274,8 @@ int uuid_init(sqlite3* db) {
sqlite3_create_function(db, "uuid4", 0, flags, 0, uuid_v4_generate, 0, 0);
sqlite3_create_function(db, "gen_random_uuid", 0, flags, 0, uuid_v4_generate, 0, 0);
#ifndef SQLEAN_OMIT_UUID7
sqlite3_create_function(db, "uuid7", -1, flags, 0, uuid_v7_generate, 0, 0);
sqlite3_create_function(db, "uuid7", 0, flags, 0, uuid_v7_generate, 0, 0);
sqlite3_create_function(db, "uuid7", 1, flags, 0, uuid_v7_generate, 0, 0);
sqlite3_create_function(db, "uuid7_timestamp_ms", 1, det_flags, 0, uuid_v7_extract_timestamp_ms,
0, 0);
#endif
Expand Down
1 change: 1 addition & 0 deletions test/uuid.sql
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@ select '3_07', uuid_blob(null) is null;
-- uuid7
select '4_01', uuid7() like '________-____-7___-____-____________';
select '4_02', uuid7(0) like '00000000-0000-7___-____-____________';
select '4_03', uuid7(1733668387) like '0193a6b0-38b8-7___-____-____________';

-- uuid7_timestamp_ms
select '5_01', uuid7_timestamp_ms('018ff38a-a5c9-712d-bc80-0550b3ad41a2') = 1717777901001;
Expand Down

0 comments on commit 2e02f6c

Please sign in to comment.