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

Gleb Peregud gleber.p@REDACTED
Tue May 21 09:50:13 CEST 2013


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

On Tue, May 21, 2013 at 3:09 AM, Manoj Raj <rajmanoj.bottle@REDACTED> wrote:
> 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...
>
> _______________________________________________
> erlang-questions mailing list
> erlang-questions@REDACTED
> http://erlang.org/mailman/listinfo/erlang-questions
>



More information about the erlang-questions mailing list