Thursday, October 18, 2012

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.



install() ->

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:

No comments:

Post a Comment