[erlang-questions] Mnesia and autogenerated ids

Nick Gerakines nick@REDACTED
Thu Aug 7 21:27:06 CEST 2008


If you don't care about id consistency, as in each id can be
completely different and unrelated, then use something like a UUID or
hash of time + pid + seed.

 * http://github.com/travis/erlang-uuid/tree/master

I've also seen people do something like this:

guid() ->
    <<I:160/integer>> = crypto:sha(term_to_binary({make_ref(), now()})),
    erlang:integer_to_list(I, 16).

If you want something like an incrementing integer then your best bet
is to create a really simple gen_server module who's state refers to a
dets table with records like {Name, Id} (ala [{entries, 3}, {comments,
400}]) where you can do a simple increment op for each.

Mnesia also works well:

-record(counter, {type, count}).

object_counter(Name) -> %% Called from within a transaction
    [OldRecord] = mnesia:read(counter, Name, write),
    Count = OldRecord#counter.count + 1,
    NewRecord = OldRecord#counter{ count = Count },
    mnesia:write(NewRecord),
    Count.

# Nick Gerakines


On Thu, Aug 7, 2008 at 11:32 AM, Luke Galea <galeal@REDACTED> wrote:
> Hi all,
>
> I'm trying to get my head around mnesia. It seems great so far, but
> I'm struggling with the lack of autogenerated ids to have one table
> refer to another. I'm on board with having less normalized data
> requiring fewer tables and thus fewer references.. But when a
> reference is required, is there no "easy" way to reference another
> table without using a natural key (like "user_name", etc)?
>
> I see that I could have a gen_server that serves up ids.. but is there
> a better way to do this? It seems an unnecessary bit of complexity to
> support if everyone ultimately needs to do this.
>
> Thanks in advance
>
> Luke Galea
> http://www.ideaforge.org
> _______________________________________________
> erlang-questions mailing list
> erlang-questions@REDACTED
> http://www.erlang.org/mailman/listinfo/erlang-questions
>



More information about the erlang-questions mailing list