Run Transactions with Functions

Learn how to run transactions with functions.

The first way to run Repo.transaction is to pass in a function containing the operations we’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.

The working of Repo.transaction

To illustrate how this works, we will 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 we want to perform. It’s not too fancy, but it will suffice for our purposes here.

Here’s what we would do if we wanted to insert a new Artist record and log the change:

Get hands-on with 1200+ tech skills courses.