Transaction with Ecto multi
From the collection Ecto and Postgresql

ecto
transaction
ecto multi

Transaction with Ecto multi

You can show this QR Code to a friend or ask them to scan directly on your screen!

Thanks for sharing! 🫶

The url for this was also copied to your clipboard!
In Elixir, Ecto is the default database library that efficiently and elegantly interacts with relational databases. Ecto.Multi is a powerful feature within Ecto that allows executing database operations in a transactional and combined manner.

Key Features of Ecto.Multi:
  1. Transactional Support: Ecto.Multi allows grouping multiple database operations into a single transaction. This ensures that either all operations succeed or none of them are persisted, maintaining data consistency.
  2. Composition of Operations: You can compose different database operations such as inserts, updates, deletes, and queries in an organized and concise structure.
  3. Parallel Execution: Operations within an Ecto.Multi can be executed in parallel, which can significantly improve performance in scenarios where multiple operations need to be performed simultaneously.

Usage Examples:
Here's a simple example of how you can use Ecto.Multi:

alias Ecto.Multi

multi = Multi.new() |> Multi.insert(:user, User.changeset(%User{}, %{name: "Alice", age: 30})) |> Multi.insert(:address, Address.changeset(%Address{}, %{street: "123 Main St", city: "Anytown"}))

case Repo.transaction(multi) do {:ok, %{user: user, address: address}} -> IO.puts "User and Address created successfully!" {:error, _failed_op, _changeset, _multi} -> IO.puts "Failed to create User or Address." end


In this example:
  • Multi.new() creates a new transactional context.
  • Multi.insert(:user, ...) and Multi.insert(:address, ...) are separate insert operations within the transaction.
  • Repo.transaction(multi) executes all operations defined in multi within a single transaction. If all operations succeed, it returns {:ok, ...}, otherwise {:error, ...}.
Considerations:
  • Atomicity: All operations within an Ecto.Multi are atomic, meaning either all are successfully performed, or none are persisted in the database.
  • Flexibility: In addition to Multi.insert/3, there are functions such as Multi.update/4, Multi.delete/3, and Multi.run/4 that allow executing a wide range of operations within a single transaction.

Ecto.Multi is a powerful tool for handling complex transactions and ensuring data integrity in Elixir applications that use Ecto for relational database interaction.

Elixir docs
Elixir composable transaction with multi 

See more from etori.sangiacomo