Skip to content

Commit f0a6346

Browse files
Update Ecto.UUID.generate/1 docs
1 parent f27cf18 commit f0a6346

File tree

1 file changed

+41
-1
lines changed

1 file changed

+41
-1
lines changed

lib/ecto/uuid.ex

Lines changed: 41 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -215,14 +215,54 @@ defmodule Ecto.UUID do
215215

216216
@default_version 4
217217
@doc """
218-
Generates a uuid with the given options.
218+
Generates a UUID string.
219+
220+
## Options
221+
222+
* `:version` - The UUID version to generate. Supported values are `4` (random)
223+
and `7` (time-ordered). Defaults to `4`.
224+
225+
## Options (version 7)
226+
227+
* `:precision` - The timestamp precision for version 7 UUIDs. Supported values
228+
are `:millisecond` and `:nanosecond`. Defaults to `:millisecond`. When using
229+
`:nanosecond`, the sub-millisecond precision is encoded in the `rand_a` field.
230+
NOTE: Due to the 12-bit space available, nanosecond precision is limited
231+
to 4096 (2^12) distinct values per millisecond.
232+
233+
* `:monotonic` - When `true`, ensures that generated version 7 UUIDs are
234+
strictly monotonically increasing, even when multiple UUIDs are generated
235+
within the same timestamp. This is useful for maintaining insertion order
236+
in databases. Defaults to `false`.
237+
NOTE: With `:millisecond` precision, generating multiple UUIDs within the
238+
same millisecond increments the timestamp by 1ms for each UUID, causing the
239+
embedded timestamp to drift ahead of real time under high throughput.
240+
Using `precision: :nanosecond` reduces this drift significantly, as
241+
timestamps only advance by ~244ns per UUID when generation outpaces real
242+
time.
243+
244+
## Examples
245+
246+
> Ecto.UUID.generate()
247+
"a0eebc99-9c0b-4ef8-bb6d-6bb9bd380a11"
248+
249+
> Ecto.UUID.generate(version: 7)
250+
"018ec4c1-ae46-7f5a-8f5a-6f5a8f5a6f5a"
251+
252+
> Ecto.UUID.generate(version: 7, precision: :nanosecond)
253+
"018ec4c1-ae46-7f5a-8f5a-6f5a8f5a6f5a"
254+
255+
> Ecto.UUID.generate(version: 7, monotonic: true)
256+
"018ec4c1-ae46-7f5a-8f5a-6f5a8f5a6f5a"
257+
219258
"""
220259
@spec generate() :: t
221260
@spec generate(options) :: t
222261
def generate(opts \\ []), do: encode(bingenerate(opts))
223262

224263
@doc """
225264
Generates a uuid with the given options in binary format.
265+
See `generate/1` for options.
226266
"""
227267
@spec bingenerate(options) :: raw
228268
def bingenerate(opts \\ []) do

0 commit comments

Comments
 (0)