Running Transactions with Functions

The first way to run Repo.transaction is by passing in a function containing the operations you’d like to run within the transaction. This can be an anonymous function or a named function defined elsewhere. This seems like a good idea—we’re functional programmers, and this approach will let us keep using functions. Let’s try it out.

To illustrate how this works, we’re going to introduce a new database table, and a module to go with it. Imagine that we’ve decided that we want to keep a log of the changes we make to our database. Every time we make a change, we’ll insert a new record into a logs table. We’ll use functions in the MusicDB.Log module to create changesets for logging the different operations that ...

Get Programming Ecto now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.