How to wrap multiple bulk updates in transaction

I have a list of maps that I want to use in a bulk update in my database. The list looks something like this:
[%{id: 1, exposed: true}, %{id: 2, exposed: false}, %{id: 3, exposed: true}, ...]
[%{id: 1, exposed: true}, %{id: 2, exposed: false}, %{id: 3, exposed: true}, ...]
I want to update my DB rows accordingly to set the exposed field to true or false for every ID in the list. I don't know if this is possible to do in a single query. It may be with a huge CASE expression in the query, but that's besides the point and probably overkill. So I thought to use Enum.split_with/2 to split the list into two lists: one for IDs to expose and one for IDs to hide. Then I can run two bulk updates. However, I want to wrap them in a transaction. Is that possible and if so, how?
Solution:
Yep 🙂
Jump to solution
3 Replies
Sienhopist
SienhopistOP•3mo ago
Actually I discovered this shortly after writing https://hexdocs.pm/ash/Ash.html#transaction/3 Would it be okay to just wrap the two bulk updates in this?
Solution
ZachDaniel
ZachDaniel•3mo ago
Yep 🙂
ZachDaniel
ZachDaniel•3mo ago
You can also put them both in a generic action and do transaction? true in the action definition

Did you find this page helpful?