2011-01-28 06:49:47 -06:00
|
|
|
-module(id_counter).
|
|
|
|
-export([create_table/1, next_counter/1, dirty_next_counter/1]).
|
|
|
|
|
2011-02-02 16:57:58 -06:00
|
|
|
-record(id_counter, {name, next_value = 0}).
|
2011-01-28 06:49:47 -06:00
|
|
|
|
|
|
|
%% Create the table structure for Mnesia
|
|
|
|
create_table(Opts) ->
|
|
|
|
mnesia:create_table(id_counter, Opts ++
|
|
|
|
[{attributes, record_info(fields, id_counter)}]).
|
|
|
|
|
|
|
|
%% Get the next id for a given name
|
|
|
|
next_counter(Name) ->
|
|
|
|
Rec = case mnesia:read({id_counter, Name}) of
|
|
|
|
[] -> #id_counter{name=Name, next_value=0};
|
|
|
|
[Val] -> Val
|
|
|
|
end,
|
|
|
|
NextRec = Rec#id_counter{next_value = Rec#id_counter.next_value+ 1},
|
|
|
|
ok = mnesia:write(NextRec),
|
|
|
|
Rec#id_counter.next_value.
|
|
|
|
|
|
|
|
%% Get the next id for a given name
|
|
|
|
dirty_next_counter(Name) ->
|
|
|
|
mnesia:dirty_update_counter(id_counter, Name, 1) - 1.
|