Generic way to retrieve all records from a table

Ulf Wiger <>
Fri Aug 5 22:18:00 CEST 2005


Den 2005-08-05 19:02:33 skrev Joel Reymont <>:

> Folks,
>
> Is there a good generic way to retrieve all records from a Mnesia table  
> given a table name?
>
>      Thanks, Joel

There are a few ways to do it, with slightly different
characteristics depending on your needs. Raw performance
will vary between the alternatives, depending on size
of the table, locality, etc.

As a general note, efficiently retrieving the whole table
inside a transaction is non-trivial, since the transaction
store needs to be checked and order possibly preserved.

* * *
match_object(Pattern)
match_object(Tab, Pattern)
dirty_match_object/[1,2]

For Pattern, you can use table_info(Tab, wild_pattern).
Note that the record name of a table doesn't need to be
the same as the table name, but

mnesia:match_object(Tab, mnesia:table_info(Tab, wild_pattern))

will always work.

* * *
mnesia:select(Tab, [{WildPattern, [], ['$_']}])

will do the same thing as match_object/2, but in a more
unintuitive fashion. There's a point, though:

mnesia:select(Tab, MatchSpec, N, Lock)

will retrieve N objects at a time, then return with
the result and a continuation. This can be quite useful
in order to achieve better real-time characteristics
and/or memory characteristics.

* * *
mnesia:foldl(Function, Acc, Table)

works like lists:foldl/3 more or less, and will traverse
the table one object at a time. This sort of traversal
goes easy on the garbage collector, which doesn't
particularly like rapid buildups of live data on the heap.

To simply retrieve all objects from the table,

mnesia:foldl(fun(X, Acc) -> [X|Acc] end, [], Table),

(which is just to illustrate, as obviously, match_object/2
would be much better at this particular task.)

* * *
all_keys(Tab) and dirty_all_keys(Tab)
have been around for a while. Personally, I'm much in
favour of foldl() or select() then.

There is of course also mnesia:dump_to_textfile(Tab),
but I assume that's not what you're after?

/Uffe
-- 
Ulf Wiger



More information about the erlang-questions mailing list