Inserting without overwriting with mnesia or ets

Ulf Wiger (AL/EAB) ulf.wiger@REDACTED
Fri May 7 14:44:48 CEST 2004

The solution below is perhaps not fast, but it's generic.
Iff you know that the table exists as a ram_copy locally
(+ you know that the object cannot have been created earlier
in the same transaction, in which case it would exist 
temporarily in another ets table - and that the object could
not be in the process of being created in another 
simultaneous transaction, etc.),
you can "cheat" and use ets:member/2, but you need to make
sure you understand the implications of this, and determine
whether it is safe to do so in _your_ case. Then you should
highlight the code with comments reminding yourself that you've 
done something dirty.

Given that some of the above conditions hold, you could check
with mnesia:dirty_read/1, which works on all types of tables
and even if the table is remote, but still has the same 
problems re. transaction safety.


> -----Original Message-----
> From: owner-erlang-questions@REDACTED
> [mailto:owner-erlang-questions@REDACTED]On Behalf Of Einar Karttunen
> Sent: den 7 maj 2004 14:29
> To: erlang-questions@REDACTED
> Subject: Inserting without overwriting with mnesia or ets
> Hello
> I need a way to insert into ets/mnesia and fail if the
> key already exists. These failures should be very rare
> and exceptional, but not checking for them could corrupt 
> data... Is there an efficient solution to this?
> The naive approach is not very good:
> insert(K,V) ->
> 	fun() ->
> 		case mnesia:wread(K) of
> 		[Exist] -> {abort, Exist};
> 		_ -> mnesia:write(V)
> 		end
> 	end.
> - Einar Karttunen

More information about the erlang-questions mailing list