Database.Uuid

Database

Work with Universally Unique Identifiers inside a Transaction.

For non-transaction work, prefer Uuid (Uuid.generate / Uuid.generateAs). The Uuid type is shared with that module.

Universally Unique Identifiers

Universally Unique Identifiers (UUID v4) are randomly generated 128-bit values. It is extremely unlikely that a given 16 byte Uuid will ever be generated by anyone else ever again. That is why they are called "universally" unique!

So while a Sequence is great for indexing and generating unique values within a single database, a Uuid can be more appropriate in certain situations. Most importantly, sequences can leak information if the values are shared outside of the database. For example:

- Knowing a user ID might reveal the number of users. - Getting a purchase ID at the beginning and end of the month could reveal the sales volume. - Signing up for a service around the same time as someone else could help you guess their account ID.

Using a Uuid allows you to avoid revealing these counts. This is nice for things like cookies, where you do not want someone to be able to guess the cookie value based on user ID or anything.

import Database.Uuid as Uuid exposing (Uuid)

type SessionSecret = SessionSecret Uuid
type ArticleID = ArticleID Uuid

doSomethingExciting : Transaction ()
doSomethingExciting =
    let
        secret := Uuid.generate SessionSecret
        article := Uuid.generate ArticleID
    in
    ...

This way you never confuse a SessionSecret with an ArticleID!

String Conversions

Types

Uuid

type Uuid = Uuid

Universally Unique Identifiers (UUID v4). Same type as Uuid.Uuid.

Values

generate

generate : (Uuid -> a) -> Transaction a

Generate a 128-bit random Uuid inside a transaction. Pass a constructor to distinguish kinds:

Examples

type SessionSecret = SessionSecret Uuid

secret := Uuid.generate SessionSecret

Outside transactions, use Uuid.generate or Uuid.generateAs.

toBase64

toBase64 : Uuid -> String

Convert the 16 bytes directly into Base64 encoding, producing 22 ASCII characters that are sensible to use for cookie values.

Examples

toBase64 uuid1 == "AAAAAAAAAAAAAAAAAAAAAA"

fromBase64

fromBase64 : String -> Maybe Uuid

Try to convert a Base64 encoded String into a Uuid.

Examples

fromBase64 "AAAAAAAAAAAAAAAAAAAAAA" == Just uuid1
fromBase64 "kel7A1aURfClkxOtERvA" == Nothing