Search⌘ K
AI Features

Force a Rollback Within a Transaction

Explore how Ecto transactions behave with insert and insert! functions and understand why unhandled errors trigger rollbacks. Learn to force a rollback using Repo.rollback to ensure your database changes are reverted correctly when operations fail, preserving consistency within multi-step transactions.

How Repo.transaction works

Notice that we’ve been using insert! with a bang rather than insert. The two functions are identical except for one crucial difference—insert will return {: error, value} if the insert fails, but insert! will raise an error. This is a convention used in many Elixir libraries, and it’s essential when executing transactions with a function.

The documentation for Repo.transaction says

“If an unhandled error occurs, the transaction will be rolled back, ...