Ecto/Transactions

From Elixir Wiki
Jump to navigation Jump to search

Ecto/Transactions[edit]

Transactions in Ecto are a powerful feature that allow for atomic operations to be performed on the database.

Overview[edit]

Transactions provide a way to wrap database operations in a transactional block, ensuring that either all the changes made within the block succeed or none of them do. If any error occurs during the process, the transaction is rolled back, undoing all changes made so far.

Usage[edit]

To use transactions in Ecto, the following steps can be followed:

1. Start a transaction block using the `Ecto.Repo.transaction/2` function. 2. Perform database operations within the transaction block. 3. Commit the transaction using the `Ecto.Repo.commit/1` function if all operations were successful. 4. Rollback the transaction using `Ecto.Repo.rollback/1` if any errors occurred within the transaction block.

Example[edit]

Here is an example of how to use transactions in Ecto:

```elixir transaction_block = fn repo ->

 Ecto.Multi.new()
 |> Ecto.Multi.insert(:step1, %User{name: "John", age: 25})
 |> Ecto.Multi.insert(:step2, %User{name: "Jane", age: 30})
 |> Ecto.Multi.run(:step3, fn _repo, %{step1: user1, step2: user2} ->
   raise "Something went wrong"  # Simulate an error
 end)
 |> Ecto.Multi.run(:step4, fn _repo, _result ->
   {:ok, "Transaction completed successfully!"}
 end)
 |> Ecto.Multi.run(:step5, fn _repo, _result ->
   raise "This step should not be reached"
 end)

Ecto.Repo.transaction(repo, transaction_block) |> case do

 {:ok, result} ->
   IO.puts("Result: #{result}")
 {:error, changeset} ->
   IO.inspect(changeset.errors)

end ```

In this example, a transaction block is created using the `Ecto.Multi.new/0` function. Within the block, two users are inserted into the database. Then, a simulated error occurs in `step3`, causing the transaction to roll back. Finally, the remaining steps `step4` and `step5` are skipped due to the error. The result of the transaction is printed to the console.

Conclusion[edit]

Transactions in Ecto provide a reliable way to ensure the integrity of data changes in a database. By wrapping database operations in a transaction block, it is possible to guarantee that all changes succeed or none of them do. This helps to maintain data consistency and avoid partial updates or corrupted data.

For more information about Ecto transactions, you can refer to the official Ecto documentation.