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 = TransactionA unit of work bound to a checked-out Repo connection.
Examples
Repo.transaction
(succeed ()
|> andThen (\_ -> insert todos user row)
)Values
succeed
succeed : a -> Transaction aSucceed a transaction with a value (no database work).
Examples
succeed 42fail
fail : Transaction aFail the current transaction and trigger a rollback.
Examples
case maybeRow of
Just row ->
succeed row
Nothing ->
failmap
map : (a -> b) -> Transaction a -> Transaction bTransform 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.lengthandThen
andThen : (a -> Transaction b) -> Transaction a -> Transaction bRun 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 }
)