Database.Transaction

Database

Work that commits or rolls back together on one checked-out [Database.Repo] connection.

You do not run a Transaction by yourself. Pass it to Repo.transaction (or Repo.on) from a request handler, job, or CLI task. If any step returns fail, or an insert/select errors, the whole unit rolls back.

saveTitle : String -> String -> Transaction ()
saveTitle id title =
    insert drafts user { id = id, title = title }
        |> andThen
            (\_ ->
                update drafts user (\row -> row.id == id) (\row -> { row | title = title })
            )

-- elsewhere:
Repo.transaction (saveTitle id title)

insert / update / remove / select from [Database.Table] and [Database.Rows] already return `Transaction` values you can chain with `andThen`.

Types

Transaction

type Transaction a = Transaction

A unit of work bound to a checked-out Repo connection.

Examples

Repo.transaction
    (succeed ()
        |> andThen (\_ -> insert todos user row)
    )

Values

succeed

succeed : a -> Transaction a

Succeed a transaction with a value (no database work).

Examples

succeed 42

fail

fail : Transaction a

Fail the current transaction and trigger a rollback.

Examples

case maybeRow of
    Just row ->
        succeed row

    Nothing ->
        fail

map

map : (a -> b) -> Transaction a -> Transaction b

Transform the value produced by a transaction.

Examples

access todos token
    |> map (\todo -> { id = todo.id })
    |> selectAll
    |> andThen (\rows -> succeed (Database.Rows.toList rows))
    |> map List.length

andThen

andThen : (a -> Transaction b) -> Transaction a -> Transaction b

Run another transaction with the previous result. Use this to insert, then select, then update in one atomic unit.

Examples

Seq.next todoIDs
    |> andThen
        (\id ->
            insert todos user { id = id, owner = user, title = title, completed = False }
        )