1 |
|
-module(mongoose_mnesia). |
2 |
|
-export([create_table/2]). |
3 |
|
|
4 |
|
-include("mongoose.hrl"). |
5 |
|
|
6 |
|
%% @doc A wrapper around `mnesia:create_table/2': |
7 |
|
%% - Automatically adds table copies. |
8 |
|
%% - Checks that mnesia is running or fail with an error. |
9 |
|
%% - Checks result of create_table |
10 |
|
-spec create_table(atom(), list()) -> |
11 |
|
{atomic, ok} | {aborted, {already_exists, atom()}}. |
12 |
|
create_table(Table, Opts) -> |
13 |
1091 |
case mnesia:system_info(is_running) of |
14 |
|
no -> |
15 |
:-( |
report_mnesia_table_error(Table, Opts, mnesia_not_running); |
16 |
|
yes -> |
17 |
1091 |
Res = mnesia:create_table(Table, Opts), |
18 |
1091 |
check_create_table_result(Table, Opts, Res), |
19 |
1091 |
Res |
20 |
|
end. |
21 |
|
|
22 |
|
check_create_table_result(_Table, _Opts, {atomic, ok}) -> |
23 |
288 |
ok; |
24 |
|
check_create_table_result(Table, Opts, {aborted, {already_exists, Table}}) -> |
25 |
803 |
[maybe_add_copies(Table, Opts, Type) || Type <- table_types()], |
26 |
803 |
ok; |
27 |
|
check_create_table_result(Table, Opts, Res) -> |
28 |
:-( |
report_mnesia_table_error(Table, Opts, Res). |
29 |
|
|
30 |
|
table_types() -> |
31 |
803 |
[disc_copies, disc_only_copies, ram_copies]. |
32 |
|
|
33 |
|
report_mnesia_table_error(Table, Opts, Res) -> |
34 |
:-( |
?LOG_CRITICAL(#{what => mnesia_create_table_failed, |
35 |
|
table => Table, create_opts => Opts, reason => Res, |
36 |
:-( |
schema_nodes => catch mnesia:table_info(schema, disc_copies)}), |
37 |
:-( |
error({mnesia_create_table_failed, Table, Res}). |
38 |
|
|
39 |
|
maybe_add_copies(Table, Opts, Type) -> |
40 |
2409 |
case proplists:get_value(Type, Opts) of |
41 |
|
[_|_] -> |
42 |
803 |
mnesia:add_table_copy(Table, node(), Type), |
43 |
803 |
ok; |
44 |
|
_ -> |
45 |
1606 |
ok |
46 |
|
end. |