Suppose I've got a simple record definition:
-record(data, {primary_key = '_', more_stuff = '_'}).
I want a simple function that adds one of these records to a mnesia database. But I want it to fail if there's already an entry with the same primary key.
(In the following examples, assume I've already defined
db_get_data(Key)->
Q = qlc:q([Datum
|| Datum = #data{primary_key = RecordKey}
<- mnesia:table(data),
RecordKey =:= Key]),
qlc:e(Q).
)
The following works, but strikes me as sort of ugly ...
add_data(D) when is_record(D, data)->
{atomic, Result} = mnesia:transaction(fun()->
case db_get_data(D#data.primary_key) of
[] -> db_add_data(D);
_ -> {error, bzzt_duplicate_primary_key}
end
end),
case Result of
{error, _} = Error -> throw(Error);
_ -> result
end.
This works too, but is also ugly:
add_data(D) when is_record(D, data)->
{atomic, Result} = mnesia:transaction(fun()->
case db_get_data(D#data.primary_key) of
[] -> db_add_data(D);
_ -> throw({error, bzzt_duplicate_primary_key})
end
end).
It differs from the above in that the above throws
{error, bzzt_duplicate_primary_key},
whereas this one throws
{error, {badmatch, {aborted, {throw,{error, bzzt_duplicate_primary_key}}}}}
So: is there some convention for indicating this sort of error? Or is there a built-in way that I can get mnesia to throw this error for me?