Erlang Central

Distributing a Mnesia schema

From ErlangCentral Wiki

Overview

This HOWTO describes how you make your tables replicate over several nodes.

Start several nodes

Start nodes and give them a name. This is how you start node foo@example.com:


erl -name foo@example.com -setcookie cookie

If you run the nodes on different servers you will have to make sure both nodes have the same cookie before they can connected. This is the reason for the explicit -setcookie above.

Following the example above start a foo and bar node on your domain.

Creating a schema

Right now, you should have two shells running. Our example node foo@example.com have a default disc storage paths set to the directory Mnesia.foo@example.com in the current directory.

The directory can be overriden by using -mnesia dir '"/path/of/your/preference"' ' when starting the node.

Are you using disc-less nodes? They involve a bit different solutions Distributing_a_Mnesia_schema/Discless_nodes

Read [5.2 Distribution and Fault Tolerance] in the mnesia user's guide. We learn that the following code creates a table already set to be replicated on several nodes.


 mnesia:create_table(foo,
                          [{ram_copies, [N1, N2]},
                           {attributes, record_info(fields, foo)}]).

In our situation N1 and N2 is 'foo@example.com' and 'bar@example.com'. This will create a table called foo which has all the fields of a record called foo. (What you see called record_info(fields, Name) is a macro that expands to the names of each field of a record Name. Record Name must be bound at compile time as erlang records are 100% compile time.)

The function mnesia:add_table_copy can be used to add replicas of tables when you're already running. If you have nodes running mnesia and want additional node to join existing mnesia setup replicating all tables, following can be used:


%% @doc Initialize database from master node
do_init_db_slave(MasterNode) ->
    mnesia:start(),
    mnesia:change_config(extra_db_nodes, [MasterNode]),
    mnesia:change_table_copy_type(schema, node(), disc_copies),
    Tabs = mnesia:system_info(tables) -- [schema],
    [mnesia:add_table_copy(Tab,node(), disc_copies) || Tab <- Tabs].