Note that there are some explanatory texts on larger screens.

plurals
  1. POWhat's the best way to prevent adding a record whose primary key is already present in mnesia?
    primarykey
    data
    text
    <p>Suppose I've got a simple record definition:</p> <pre><code>-record(data, {primary_key = '_', more_stuff = '_'}). </code></pre> <p>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.</p> <p>(In the following examples, assume I've already defined</p> <pre><code>db_get_data(Key)-&gt; Q = qlc:q([Datum || Datum = #data{primary_key = RecordKey} &lt;- mnesia:table(data), RecordKey =:= Key]), qlc:e(Q). </code></pre> <p>)</p> <p>The following works, but strikes me as sort of ugly ...</p> <pre><code>add_data(D) when is_record(D, data)-&gt; {atomic, Result} = mnesia:transaction(fun()-&gt; case db_get_data(D#data.primary_key) of [] -&gt; db_add_data(D); _ -&gt; {error, bzzt_duplicate_primary_key} end end), case Result of {error, _} = Error -&gt; throw(Error); _ -&gt; result end. </code></pre> <p>This works too, but is also ugly:</p> <pre><code>add_data(D) when is_record(D, data)-&gt; {atomic, Result} = mnesia:transaction(fun()-&gt; case db_get_data(D#data.primary_key) of [] -&gt; db_add_data(D); _ -&gt; throw({error, bzzt_duplicate_primary_key}) end end). </code></pre> <p>It differs from the above in that the above throws</p> <pre><code>{error, bzzt_duplicate_primary_key}, </code></pre> <p>whereas this one throws</p> <pre><code>{error, {badmatch, {aborted, {throw,{error, bzzt_duplicate_primary_key}}}}} </code></pre> <p>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?</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload