Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Document how to get the next ULID #488

Open
tibbe opened this issue Jun 15, 2022 · 2 comments
Open

Document how to get the next ULID #488

tibbe opened this issue Jun 15, 2022 · 2 comments

Comments

@tibbe
Copy link

tibbe commented Jun 15, 2022

If you receive an ULID from some external source (e.g. a database) you might want to compute the next following ULID. This is useful for range-style queries where you are trying to retrieve every item after the aforementioned ULID. The library already does so internally to provide monotonic values but it's not entirely clear how to get the monotonically "next" ULID, given another one.

Example:

prev = ulid.parse(some_str)  # From external source
next = ...  # ???

I was playing with ulid.create but I couldn't quite figure it out. It seems to be that bumping the randomness by one and if that overflow bumping the timestamp by one is what we want.

A ULID.next method would be really nice.

@tibbe
Copy link
Author

tibbe commented Jun 15, 2022

I would have thought something like ulid.monotonic.create(prev, prev)) would work but it doesn't (it produces the same ULID as prev).

@tibbe
Copy link
Author

tibbe commented Jun 15, 2022

Here's a possible implementation:

def next_ulid(prev: ulid.ULID):
    randomness = prev.randomness()
    if randomness == ulid.MAX_RANDOMNESS:
        timestamp = prev.timestamp()
        return ulid.create(timestamp.int + 1, randomness)
    return ulid.create(prev, randomness.int + 1)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant