Search code examples
erlangdets

How to close a dets table correctly after some operations in erlang?


I have a function which checks if the given username already exists in the dets table or no :

  is_username_web2_exists(Username)->
    dets:open_file(?FILE_PATH),
    case dets:lookup(?FILE_PATH,Username) of
        [_] -> true;
        _ -> false
    end,
    dets:close(?FILE_PATH).

I call it in another module and I always get false, the problem in the last line, because when I remove it, the function works fine. Did I closed the table correctly?


Solution

  • The problem is that functions in Erlang return the value of the last expression, which in your case is dets:close(?FILE_PATH) which returns ok on successfully closing the table. You need to store the value returned by the case and return that:

    is_username_web2_exists(Username)->
      dets:open_file(?FILE_PATH),
      Return = case dets:lookup(?FILE_PATH,Username) of
          [_] -> true;
          _ -> false
      end,
      dets:close(?FILE_PATH),
      Return.