Search code examples
erlangmnesia

Get all records from mnesia table


I am using mnesia to store Pid's for users that have connected to a certain websocket.

-record(connection, {pid, name}).

handle_join(ServiceName, WebSocketId, State, EventName) ->
  mnesia:dirty_write(#connection{pid=WebSocketId, name=EventName}).

The Pid is the key, using the tv:start() application I am able to see the Pid is being stored properly in the connection table. I want to now be able to send a message to all Pids in that table and also remove the Pid when the websocket connection closes.

What is the best way to retrieve all the Pids from that connection table?


Solution

  • You can use all_keys(Tab) -> KeyList | transaction abort or dirty_all_keys(Tab) -> KeyList | exit({aborted, Reason})..

    all_keys(Tab) -> KeyList | transaction abort

    This function returns a list of all keys in the table named Tab. The semantics of this function is context sensitive. See mnesia:activity/4 for more information. In transaction context it acquires a read lock on the entire table.