Search code examples
erlangmnesia

mnesia delete_object exception?


I don't see what's wrong here, but I may just misunderstand the syntax. I'm trying to delete a "user" record from my "user" mnesia table who have the first name of "ryan" (there are multiples of them). Here is what I do:

Delete=#user{first_name = "ryan", _ = '_'},
mnesia:dirty_delete_object(Delete)

Here is my record definition:

-record(user, {id,
               username,
               password,
               email,
               first_name,
               last_name,
               last_login, % Date/time user last logged in
               reg_date}). % Date/time user registered the account

And here is the exception I'm getting:

** exception exit: {aborted,
                       {bad_type,user,
                           {user,'_','_','_','_',"ryan",'_','_','_'}}}
     in function  mnesia:abort/1
     in call from users:register/1

It seems like a perfect match. What could cause this problem?


Solution

  • mnesia:delete_object/1 and /3 are used to delete given record from the table. It does not delete multiple records based on match specification. It is just a more precise version of mnesia:delete/* - it gives you a way to delete specific record from the bag table.

    To delete multiple records matching specification (e.g. with name="ryan") use the following code:

    Delete=#user{first_name = "ryan", _ = '_'},
    List = mnesia:dirty_match_object(Delete)
    lists:foreach(fun(X) ->
                          mnesia:dirty_delete_object(X)
                  end, List).
    

    or it's transactional version:

    Delete=#user{first_name = "ryan", _ = '_'},
    Fun = fun() ->
                  List = mnesia:match_object(Delete)
                  lists:foreach(fun(X) ->
                                        mnesia:delete_object(X)
                                end, List)
          end,
    mnesia:transaction(Fun).