How to read all the records of mnesia database in erlang?
Asked Answered
B

2

5

I ma new in erlang and I need to do some operations for all records I get from mnesia database.

Result = mnesia:dirty_read(mydatabase, {key1, key2}),
        case Result of 
            [] ->
                ?DEBUG("No such record found", []);
            [#mydatabase{key3 = Key3}] ->
                %% some operations
        end

How can I add a loop to my code that execute some operations for all records?

I am not even sure if the code above does it or not?

Biparty answered 7/3, 2016 at 16:56 Comment(0)
G
7

You could use mnesia:foldl/3 for that. It iterates over all records in a table, passing along an "accumulator" value.

It doesn't have an explicit "dirty" counterpart, so if you want to run it as a dirty operation you need to use mnesia:activity/2. (Or you could just use it inside a call to mnesia:transaction.)

In this example, I don't actually do anything with the "accumulator", leaving as ignored_acc throughout.

mnesia:activity(sync_dirty,
  fun() ->
      mnesia:foldl(
          fun(#mydatabase{}, Acc) ->
              %% do something with the record here
              Acc
          end,
          ignored_acc,
          my_table)
  end)
Grassgreen answered 7/3, 2016 at 17:24 Comment(0)
B
4

I think you can try all_keys(Tab)

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.

Batting answered 7/3, 2016 at 17:24 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.