Search code examples
transactionserlangmnesia

Erlang Mnesia - mnesia:transaction(F) vs. mnesia:activity(transaction, F)


I've read and re-read the docs re: mnesia:activity/3, mnesia:activity/4, and mnesia/transaction/2, but they still read like an obscure foreign language to me.

In my limited experiments they seem to return the same result.

Can some kind soul help me understand when and why I would use one vs. the other?

Many thanks,

LRP


Solution

  • There are two differences.

    First, mnesia:activity lets you specify the access module. The only use for this I know of is to use fragmented tables. That is, if you have a table with many records, you may want to split the data among the nodes in your cluster. The mnesia_frag access module lets you do that, and still access the data transparently - as long as you use mnesia:activity and specify mnesia_frag as the access module. See the section on Table Fragmentation in the Mnesia documentation for more information.

    Second, mnesia:transaction returns {atomic, Result} on success and {aborted, Reason} on error. On the other hand, mnesia:activity simply returns the Result on success, and signals an error if there is a problem. Which style you prefer is mostly a matter of taste - but note that mnesia:transaction can fail "silently" if you don't check every return value.

    Apart from those differences in functionality, with mnesia:activity you can easily change the access context in your code as needed. If you start out using transactions but later want to change to dirty operations (or vice versa), you can simply change the first argument to your mnesia:activity calls, while if you have been using mnesia:transaction and direct calls to mnesia:dirty_*, changing from one to another is a bit more involved. (You could mitigate the latter somewhat by using mnesia:sync_dirty and/or mnesia:async_dirty).