Mnesia - Create a Fragmented Table

I have created and worked with fragmented tables before. But not having done so in so long it took abit of effort to remember how to do it without looking at my old source code.

Ignore the delete and create schema, you will need to fix these if you want to turn this into a real database as it may delete your database if your not careful when you run install()!

This simple fragmented test table will allow you to create new users calling the add_user() function with a username/password/email address. Keep in mind you can only create the table as type bag or set for disc based tables. There are third party efforts to create a disc based ordered_set (tcerl is one that I use), but these are not straight forward to setup and not part of the OTP framework.

The tuple we have added is frag_properties for the mnesia:create_table function this allows us to configure this table as a fragmented table. In this case the node_pool consists of only this node retrieved by node() function call. 20 fragments specified by n_fragments and 1 disc copy of each fragment specified by n_disc_copies. There are more options and more complex configurations, these depend on the task at hand so it is best to use the reference manual. This code is just a example of one way you can create a new fragmented mnesia table.

-module(test).
-export([install/0,add_user/3]).

-record(user,{username,password,email}).

install() ->
    mnesia:delete_schema([node()]),
    mnesia:create_schema([node()]),
    mnesia:start(),
    io:format("ok\n",[]),
    mnesia:create_table(user,
        [
            {frag_properties,
                [
                {node_pool,[node()]},
                {n_fragments,20},
                {n_disc_copies,1}
                ]
            },
            {attributes,record_info(fields,user)},
            {type,bag}
        ]
    ).
    

add_user({user,Name},{pass,Password},{email,Email}) -> 
    ok = mnesia:activity(async_dirty,fun() -> mnesia:write(user,#user{username=Name,password=Password,email=Email},write) end,[],mnesia_frag).
Further details on the options available regarding fragmented table properties can be found here in the official mnesia documentation: http://www.erlang.org/doc/apps/mnesia/Mnesia_chap5.html#Fragmentation%20Properties

Comments

Popular posts from this blog

WinDBG on 32Bit Applications

EXCEL Macro - Compare Column A to Column B

Powershell Script to Automatically Deploy Sharepoint WSP Packages