Generating unique ids in Mnesia

Rikard Johansson rikard.johansson@REDACTED
Thu Aug 18 17:23:10 CEST 2005


Here are some code I use for sequences. It creates one mnesia table 
(sequence) which can hold multiple sequences.
mnesia:dirty_update_counter is fast and atomic.

Usage:

1> mod:create_sequence([node()]).
2> mod:sequence(player_id).
0
3> mod:sequence(player_id).
1
4> mod:sequence(foo).
0
...

Best regards,

/Rikard

%% --------------------------------------------------
%% sequence
%%

%% sequence table record
-record(sequence, {key, index}).

%% Creates sequence table. Performed once
create_sequence() ->
     create_sequence([node()]).
create_sequence(Nodes) ->
     mnesia:create_table(sequence, [{type, set},
				   {disc_copies, Nodes},
				   {attributes, record_info(fields, sequence)}]).

%% Inits or resets a sequence to Value
init_sequence(Name, Value) ->
     {atomic, ok} =
	mnesia:transaction(fun() ->
				   mnesia:write(#sequence{key=Name, index=Value})
			   end),
     ok.

%% Returns current value for sequence Name and increments
%% Sequence is created if not exists, and initial value 0 is returned.
sequence(Name) ->
     sequence(Name, 1).
%% increment sequence with Inc
sequence(Name, Inc) ->
     mnesia:dirty_update_counter(sequence, Name, Inc).



Joel Reymont wrote:
> Hakan,
> 
> Thanks for the tip but I need sequential, increasing numerical  values. 
> I would like my records to be sequantially numbered and the  sequence 
> number to increase every time I insert a record. How do I  manage that?
> 
>     Joel
> 
> On Aug 18, 2005, at 4:46 PM, Hakan Mattsson wrote:
> 
>> You can use
>>
>>   erlang:now()
>>
>> or
>>
>>   {node(), erlang:now()}
>>
>> in a multi node system.
> 
> 
> 



More information about the erlang-questions mailing list