Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best way to print out Mnesia table

Tags:

erlang

mnesia

I tried this code snippet:

print_next(Current) ->
    case mnesia:dirty_next(muppet, Current) of
        '$end_of_table' ->
            io:format("~n", []),
            ok;
        Next ->
            [Muppet] = mnesia:dirty_read({muppet, Next}),
            io:format("~p~n", [Muppet]),
            print_next(Next),
            ok
    end.

print() ->
    case mnesia:dirty_first(muppet) of
        '$end_of_table' ->
            ok;
        First ->
            [Muppet] = mnesia:dirty_read({muppet, First}),
            io:format("~p~n", [Muppet]),
            print_next(First),
            ok
    end.

But it is so long. Also I can use dirty_all_keys and then iterate through key list, but I want to know if there is a better way to print out Mnesia table contents.

like image 357
Yola Avatar asked Oct 14 '11 06:10

Yola


2 Answers

If you just want a quick and dirty way to print the contents of a Mnesia table in the shell, and if your table is not of type disc_only_copies, then you can take advantage of the fact that Mnesia stores its data in ETS tables and run:

ets:tab2list(my_table).

or, if you think the shell truncates the data too much:

rp(ets:tab2list(my_table)).

Not recommended for "real" code, of course.

like image 182
legoscia Avatar answered Sep 20 '22 20:09

legoscia


For a simple and quick look at your table contents you can use select function of mnesia with catch-all Match Specification as follows:

CatchAll = [{'_',[],['$_']}].
mnesia:dirty_select(TableName, CatchAll).

and also you can run it inside a transaction context:

CatchAll = [{'_',[],['$_']}].
SelectFun = fun() -> mnesia:select(TableName, CatchAll) end.
mnesia:transaction(SelectFun).

however be careful if you are in a production environment with a big data.

like image 24
Hamidreza Soleimani Avatar answered Sep 21 '22 20:09

Hamidreza Soleimani