Ecto is a data validation and database persistence Elixir library. This is the backbone of database operations in the Phoenix Webframework, this is the analog to ActiveRecord within the Rails ecosystem.
Transactions in Ectohacks
Ecto well supports database transactions via the Multi module. You can setup arbitrary functions and run them in sequence with good error handling support1:
Notice that the results from the first call are packed into the map argument to the function of the next call under the name that the step was run (:step1call).
Partial Unique Index (Boolean column) in Ecto Migration
Itâs useful to be able to say that for a given column pair, there can be only one of one kind of a pair of attributes. For example, consider a team has many mambas but it can only have one captain.
Assume a structure like
Now we want to enforce that for a given, there is only one player at a
time who can be the captain (is_captain true
).
In the migration that creates the players:
Importantly is the where
clause on the unique index which makes the
constrain unique for team id where the iscaptain is true.
Note that you cannot just do where: is_captain
because the index
definition is finicky in
postgres. Also,
is_captain = true
will not work.
Finally, you can setup the changeset to properly catch this uniqueness conflict:
1. Buszkiewicz, M. How database transactions work in Ecto and why Elixir makes it awesome? Curiosum (2019).