Mnesia returns {aborted, no_transaction}

2019-08-07 06:19发布

问题:

I have a Mnesia table called person, using the following record definition:

-record(person, {id, firstname, lastname, phone}).

The table contains these values:

    12  alen     dumas      97888888
    13  franco   mocci      55522225
    14  ali      othmani    44444449

I want to retreive the last id which is in my case 14.

I try with :

test()->
    Key=mnesia:last(person).

but when I test this function I have this error :

** exception exit: {aborted,no_transaction}
     in function  mnesia:abort/1

Why is that? What can I do about it?

回答1:

The error message exception exit: {aborted,no_transaction} is quite clear: the function is expected to be called in a transaction context, and your code isn't. If you don't need a transaction, you can use mnesia:dirty_last/1 instead. Note that both mnesia:last/1 and mnesia:dirty_last/1 make sense if the table type is ordered_set. For other types there is no explicit order defined.



回答2:

Ppolv gives a clue to the problem: you need to call the mnesia functions in the context of a transaction i.e. an mnesia 'activity access context'. Not tested it but something like this ought to work:

test()->
      Getlastperson = fun() -> Key=mnesia:last(person) end,
      mnesia:activity(transaction, Getlastperson).   


标签: erlang mnesia