-module(id_counter).
-export([create_table/1, next_counter/1, dirty_next_counter/1]).

-record(id_counter, {name, next_value = 0}).

%% 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.
