Best way to print out Mnesia table

Yola picture Yola · Oct 14, 2011 · Viewed 11.1k times · Source

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.

Answer

legoscia picture legoscia · Oct 14, 2011

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.