[erlang-questions] Mnesia - Check for a value in either of the keys in the table

14 views
Skip to first unread message

Manoj Raj

unread,
May 20, 2013, 9:09:23 PM5/20/13
to erlang-q...@erlang.org
Hi,

I have a mnesia table "users" created with the following record

-record(users,{username,nickname,age})

I have a name now to input...I want to check whether name is present in "username" or "nickname"....If someone can suggest me a way, i will really happy...


Thanks...

Gleb Peregud

unread,
May 21, 2013, 3:50:13 AM5/21/13
to Manoj Raj, Erlang
I assume that username is a primary key column, hence you can just use:

mnesia:transaction(fun() ->
case mnesia:read(users, UsernameOrNickname) of
[] -> {error, "Username not found"};
[User] -> {ok, User}
end)

But nickname column is not a key, hence you have to add an index for it first:

mnesia:add_table_index(users, nickname)

and later you can use the following code to fetch user by username or nickname:

mnesia:transaction(fun() ->
case mnesia:read(users, UsernameOrNickname) of
[] ->
case mnesia:index_read(users, UsernameOrNickname, #users.nickname) of
[] -> {error, "User not found"};
[User1] -> {ok, User1}
end;
[User2] -> {ok, User2}
end)

Code written from top of my head without testing, take with a grain of salt.

Cheers,
Gleb
> _______________________________________________
> erlang-questions mailing list
> erlang-q...@erlang.org
> http://erlang.org/mailman/listinfo/erlang-questions
>
_______________________________________________
erlang-questions mailing list
erlang-q...@erlang.org
http://erlang.org/mailman/listinfo/erlang-questions
Reply all
Reply to author
Forward
0 new messages