what is the proper way to backup/restore a mnesia database?

后端 未结 2 588
野的像风
野的像风 2021-02-05 11:00

WARNING: the background info is pretty long. Skip to the bottom if you think you need the question before the background info. Appreciate the time this is gonna

2条回答
  •  深忆病人
    2021-02-05 12:01

    I think that this problem falls in the broader category of Mnesia questions that are related to a simple one:

    How do I rename a Mnesia node?

    The first and simplest solution, if your db is not huge, is to use the mnesia:traverse_backup function (see Mnesia User guide). Following is an example from the Mnesia User guide:

    change_node_name(Mod, From, To, Source, Target) ->
        Switch =
            fun(Node) when Node == From -> To;
               (Node) when Node == To -> throw({error, already_exists});
               (Node) -> Node
            end,
        Convert =
            fun({schema, db_nodes, Nodes}, Acc) ->
                    {[{schema, db_nodes, lists:map(Switch,Nodes)}], Acc};
               ({schema, version, Version}, Acc) ->
                    {[{schema, version, Version}], Acc};
               ({schema, cookie, Cookie}, Acc) ->
                    {[{schema, cookie, Cookie}], Acc};
               ({schema, Tab, CreateList}, Acc) ->
                    Keys = [ram_copies, disc_copies, disc_only_copies],
                    OptSwitch =
                        fun({Key, Val}) ->
                                case lists:member(Key, Keys) of
                                    true -> {Key, lists:map(Switch, Val)};
                                    false-> {Key, Val}
                                end
                        end,
                    {[{schema, Tab, lists:map(OptSwitch, CreateList)}], Acc};
               (Other, Acc) ->
                    {[Other], Acc}
            end,
        mnesia:traverse_backup(Source, Mod, Target, Mod, Convert, switched).
    
    view(Source, Mod) ->
        View = fun(Item, Acc) ->
                       io:format("~p.~n",[Item]),
                       {[Item], Acc + 1}
               end,
        mnesia:traverse_backup(Source, Mod, dummy, read_only, View, 0).
    

    The most important part here is the manipulation of the {schema, db_nodes, Nodes} tuple which let you rename or replace the db nodes.

    BTW, I've used that function in the past and one thing I noticed is that the backup terms format changes between mnesia versions, but maybe it was simply me writing bad code. Just print a backup log for a small mnesia database to check backup term format, if you wanna be sure.

    Hope this helps!

提交回复
热议问题