Helpers for working with UUIDs version 7.
generate/0 delegates to Ecto.UUID's monotonic generator (Ecto >= 3.14),
which guarantees strictly increasing values per node — even for UUIDs generated
within the same millisecond — using the
Section 6.2
counter method. This requires the :ecto application to be started.
generate/1, which embeds a specific DateTime, uses a hand-rolled
implementation with increased clock precision (method 3 of Section 6.2),
inspired by the work of Ryan Winchester on
uuidv7.
Examples
iex> UUIDv7.generate()
"018e90d8-06e8-7f9f-bfd7-6730ba98a51b"
iex> UUIDv7.bingenerate()
<<1, 142, 144, 216, 6, 232, 127, 159, 191, 215, 103, 48, 186, 152, 165, 27>>
Summary
Functions
Generates a version 7 UUID in the binary format.
Decode a string representation of a UUID to the raw binary version.
Encode a raw UUID to the string representation.
Extract the millisecond timestamp from the UUID.
Generates a version 7 UUID using submilliseconds for increased clock precision.
Types
Functions
@spec bingenerate() :: raw()
Generates a version 7 UUID in the binary format.
Optionally accepts a DateTime to embed a specific timestamp, which is useful
when migrating existing records and you need to preserve their original creation order.
Examples
iex> UUIDv7.bingenerate()
<<1, 142, 144, 216, 6, 232, 127, 159, 191, 215, 103, 48, 186, 152, 165, 27>>
@spec bingenerate(DateTime.t()) :: raw()
Decode a string representation of a UUID to the raw binary version.
Example
iex> UUIDv7.decode("018e90d8-06e8-7f9f-bfd7-6730ba98a51b")
<<1, 142, 144, 216, 6, 232, 127, 159, 191, 215, 103, 48, 186, 152, 165, 27>>
Encode a raw UUID to the string representation.
Example
iex> UUIDv7.encode(<<1, 142, 144, 216, 6, 232, 127, 159, 191, 215, 103, 48, 186, 152, 165, 27>>)
"018e90d8-06e8-7f9f-bfd7-6730ba98a51b"
Extract the millisecond timestamp from the UUID.
Example
iex> UUIDv7.extract_timestamp("018ecb40-c457-73e6-a400-000398daddd9")
1712807003223
@spec generate() :: t()
Generates a version 7 UUID using submilliseconds for increased clock precision.
Optionally accepts a DateTime to embed a specific timestamp, which is useful
when migrating existing records and you need to preserve their original creation order.
Examples
iex> UUIDv7.generate()
"018e90d8-06e8-7f9f-bfd7-6730ba98a51b"
iex> UUIDv7.generate(~U[2024-01-01 00:00:00Z])
"018cfa9b-b400-7e72-a400-000398daddd9"
@spec generate(DateTime.t()) :: t()