summaryrefslogtreecommitdiff
path: root/src/db.erl
blob: 91e379e1a4b7941287fc92515826752aebb0f83c (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
%%% Copyright (c) 2014, NORDUnet A/S.
%%% See LICENSE for licensing information.

-module(db).
-behaviour(gen_server).

%% API.
-export([start_link/0, stop/0]).
-export([init_db/0, init_db/1, init_tables/0, init_tables/1]).
-export([add/1, find/2, get_by_index/2, get_by_index_sorted/2, size/0]).
%% API for testing.
-export([dump/1, destroy_tables/0, info_tables/0, dump_to_file/1]).
%% gen_server callbacks.
-export([init/1, handle_call/3, terminate/2, handle_cast/2, handle_info/2,
         code_change/3]).

-include_lib("stdlib/include/qlc.hrl").
-include("db.hrl").
-include("$CTROOT/plop/include/plop.hrl").

%% @doc Set up a database schema on all nodes that are to be included
%% in the "database cluster". Has to be run _before_ mnesia has been
%% started.
init_db() ->
    init_db([node()]).
init_db(Nodes) ->
    ok = mnesia:create_schema(Nodes),
    rpc:multicall(Nodes, application, start, [mnesia]),
    init_tables(Nodes),
    rpc:multicall(Nodes, application, stop, [mnesia]).

%% @doc Run once, or rather every time you start on a new database.
%% If run more than once, we'll get {aborted, {already_exists, TABLE}}.
init_tables() ->
    init_tables([node()]).
init_tables(Nodes) ->
    %% We've once upon a time invoked mnesia:create_schema/1 with the
    %% nodes that will be part of the database.
    RamCopies = [],
    DiscCopies = [],
    DiscOnlyCopies = Nodes,
    mnesia:start(),
    {atomic, ok} =
        mnesia:create_table(plop,
                            [{type, set},
                             {ram_copies, RamCopies},
                             {disc_copies, DiscCopies},
                             {disc_only_copies, DiscOnlyCopies},
                             {attributes, record_info(fields, plop)},
                             {majority, true}]),
    {atomic, ok} = mnesia:add_table_index(plop, entryhash),
    {atomic, ok} = mnesia:add_table_index(plop, mtlhash).

destroy_tables() ->
    mnesia:delete_table(plop).
info_tables() ->
    mnesia:table_info(plop, all).
dump_to_file(Filename) ->
    mnesia:dump_to_textfile(Filename).
size() ->
    mnesia:table_info(plop, size).

init(_Args) ->
    {mnesia:wait_for_tables([plop], 5000), []}.

start_link() ->
    gen_server:start_link({local, ?MODULE}, ?MODULE, [], []).

stop() ->
    gen_server:call(?MODULE, stop).

%%%%%%%%%%%%%%%%%%%%
%% Public API.

-spec add(binary()) -> ok.
add(Entry) ->
    gen_server:call(?MODULE, {add, Entry}).

%% @doc Find one entry.
-spec find(entryhash | mtlhash | index, binary()) -> ht:mtl().
find(Type, Hash) ->
    gen_server:call(?MODULE, {find, Type, Hash}).

-spec get_by_index(non_neg_integer(), non_neg_integer()) -> [ht:mtl()].
get_by_index(Start, End) ->
    gen_server:call(?MODULE, {get_by_index, {Start, End}}).

-spec get_by_index_sorted(non_neg_integer(), non_neg_integer()) -> [listht:mtl()].
get_by_index_sorted(Start, End) ->
    gen_server:call(?MODULE, {get_by_index_sorted, {Start, End}}).

%% Testing and debugging.
dump(Table) ->
    gen_server:call(?MODULE, {dump, Table}).

%%%%%%%%%%%%%%%%%%%%
%% gen_server callbacks.

handle_cast(_Request, State) ->
    {noreply, State}.

handle_info(_Info, State) ->
    {noreply, State}.

code_change(_OldVsn, State, _Extra) ->
    {ok, State}.

terminate(_Reason, _State) ->
    io:format("~p terminating~n", [?MODULE]),
    ok.

%%%%%%%%%%%%%%%%%%%%
%% The meat.

handle_call(stop, _From, State) ->
    {stop, normal, stopped, State};

handle_call({add, Entry}, _From, State) ->
    F = fun() ->
                mnesia:write(Entry)
        end,
    Res = mnesia:transaction(F),
    {reply, Res, State};

handle_call({dump, Table}, _From, State) ->
    F = fun() ->
                Q = qlc:q([E || E <- mnesia:table(Table)]),
                qlc:e(Q)
        end,
    Res = mnesia:transaction(F),
    {reply, Res, State};

handle_call({find, entryhash, Hash}, _From, State) ->
    {reply,
     find_entry(fun() -> mnesia:index_read(plop, Hash, #plop.entryhash) end),
     State};
handle_call({find, mtlhash, Hash}, _From, State) ->
    {reply,
     find_entry(fun() -> mnesia:index_read(plop, Hash, #plop.mtlhash) end),
     State};
handle_call({find, index, Index}, _From, State) ->
    {reply,
     find_entry(fun() -> mnesia:read(plop, Index) end),
     State};

handle_call({get_by_index, {Start, End}}, _From, State) ->
    Res = [X || [_, X] <- select_index(Start, End)],
    {reply, Res, State};

handle_call({get_by_index_sorted, {Start, End}}, _From, State) ->
    %% FIXME: RAM hog -- how bad is it?
    Res = [X || [_, X] <- lists:sort(select_index(Start, End))],
    {reply, Res, State}.

%%%%%%%%%%%%%%%%%%%%
%% Helper functions.

select_index(Start, End) ->
    F = fun() ->
                %% Get index and mtl.
                MatchHead = {plop, '$1', '_', '_', '$2', '_'},
                Guard = [{'>=', '$1', Start}, {'=<', '$1', End}],
                Result = ['$$'],
                mnesia:select(plop, [{MatchHead, Guard, Result}])
        end,
    {atomic, Res} = mnesia:transaction(F),
    Res.

find_entry(Fun) ->
    {atomic, Result} = mnesia:transaction(Fun),
    case length(Result) of
        0 -> [];
        1 -> hd(Result);
        _ -> duplicate_hash_in_db               % FIXME: log an error?
    end.