Skip to content

Instantly share code, notes, and snippets.

@anujpradhaan
Last active April 28, 2016 12:42
Show Gist options
  • Save anujpradhaan/2bf69058e68cbf0cfa27d4834115ada7 to your computer and use it in GitHub Desktop.
Save anujpradhaan/2bf69058e68cbf0cfa27d4834115ada7 to your computer and use it in GitHub Desktop.
%Copy and paste the below Anonymous functions to Erlang Shell
Get_table_structure = fun(TableName) ->
{tables,[{TableName,[{record_name,mnesia:table_info(TableName,record_name)},{attributes,mnesia:table_info(TableName,attributes)}]}]}
end.
Read_tablerows = fun(Rows,TableName,IODevice,Key) ->
lists:foldl(fun(_,Acc) ->
NextKey = mnesia:dirty_next(TableName,Acc),
[Record] = mnesia:dirty_read(TableName,Acc),
io:format(IODevice,"~p.~n",[Record]),
NextKey
end, Key, lists:seq(1,Rows))
end.
Write_table_to_file = fun(TableName,NumberOfRowsToBackup,IODevice) ->
FirstKey = mnesia:dirty_first(TableName),
Read_tablerows(NumberOfRowsToBackup,TableName,IODevice,FirstKey)
end.
Write_fulltable_to_file = fun(TableName,IODevice) ->
TableData = ets:tab2list(TableName),
lists:foreach(fun(Record) ->
io:format(IODevice,"~p.~n",[Record])
end ,TableData),
file:close(IODevice)
end.
%Call this function with the number of rows you want to backup.
%Here Due to memory issues in my dev machine I am keeping the number to 5000 rows max.
Backup_Table = fun(TableName,NumberOfRowsToBackup) ->
GetTableStructure = Get_table_structure(TableName),
Path = lists:concat(["/tmp/",erlang:atom_to_list(TableName),".bak"]),
case file:open(Path,[write]) of
{ok,IODevice} ->
io:format(IODevice,"~p.~n",[GetTableStructure]),
case NumberOfRowsToBackup > 5000 of
true -> Write_table_to_file(TableName,NumberOfRowsToBackup,IODevice);
false -> Write_fulltable_to_file(TableName,IODevice)
end;
{error,Reason} ->
io:format("Error Occured due to ~p~n",[Reason])
end
end.
%Use this Below command to save all mnesia tables in text format. All the files are available in /tmp/ with table_name.bak
%lists:foreach(fun(X) -> TableSize = mnesia:table_info(X,size), Backup_Table(X, case TableSize > 5000 of true -> 5001; false -> 0 end) end,mnesia:system_info(tables)).
%use mnesia:load_textfile(Path) to load the table into another machine
%If you want to backup them as it is.
%lists:foreach(fun(X) -> Path = lists:concat([PATH,erlang:atom_to_list(X),".bak"]), mnesia:load_textfile(Path) end,mnesia:system_info(tables)).
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment