View Source KineticEcto.RepoTransact (KineticEcto v1.1.1)
Add Saša Jurić's Repo.transact/2
to your repo with use
KineticEcto.RepoTransact.
Repo.transact/2is a replacement for
Repo.transaction/2with a better developer experience. In many cases, the use of
Repo.transact/2can provide code that is easier to understand than an equivalent
Ecto.Multiimplementation. In Saša's own [words][1]: > I wrote
Repo.transactafter seeing a lot of production code along the lines of what's > written in that excellent [blog post][2] by @tomkonidas. > > The value proposition of
Repo.transactis that control flow features such as passing > data around, branching, early exit, can be implemented with standard Elixir features, > such as variables, functions, and the
withexpression. The transactional logic is > less special, and it doesn't rely on some implicit behaviour of a function from some > library. > > Combined with the provable fact that the
transactcode is shorter (often > significantly), even in such simple example as in that blog post, I have no doubt that > the
transactversion is simpler and clearer. > > That's not to say that
Multiis universally bad. The ability to provide each db > operation as data is definitely interesting, and could be useful in the cases where > the transactional steps need to be assembled dynamically (perhaps provided by the > client code). But in the vast majority of cases I've encountered, I find the multi > code needlessly difficult to read. This is true even in simple cases, and it becomes > progressively worse if the transactional logic is more involved (e.g. if it requires > branching early on in the transaction). > > Hence, I strongly prefer
transact`, and it's what I advise using in most situations.
[1]: https://elixirforum.com/t/seeking-thoughts-on-advantages-of-the-repo-transact-pattern-vs-disadvantages-i-ve-read-about-ecto-multi/61733/2
[2]: https://tomkonidas.com/repo-transact/
Summary
Functions
Runs the given function inside a transaction for the provided Ecto repo.
Functions
@spec transact(Ecto.Repo.t(), (-> result) | (module() -> result), Keyword.t()) :: result when result: :ok | {:ok, any()} | :error | {:error, any()}
Runs the given function inside a transaction for the provided Ecto repo.
This function is a wrapper around Ecto.Repo.transaction
, with the following differences:
- It accepts only a lambda of arity 0 or 1 (i.e. it doesn't work with
Ecto.Multi
). If the lambda returns
:ok | {:ok, result}
the transaction is committed.If the lambda returns
:error | {:error, reason}
the transaction is rolled back.- If the lambda returns any other kind of result, an exception is raised, and the transaction is rolled back.
- The result of
transact
is the value returned by the lambda.
This function accepts the same options as Ecto.Repo.transaction/2
.