summaryrefslogtreecommitdiff
path: root/src/db.erl
diff options
context:
space:
mode:
Diffstat (limited to 'src/db.erl')
-rw-r--r--src/db.erl30
1 files changed, 26 insertions, 4 deletions
diff --git a/src/db.erl b/src/db.erl
index f683d48..aa6cc29 100644
--- a/src/db.erl
+++ b/src/db.erl
@@ -7,7 +7,7 @@
%% API.
-export([start_link/0, stop/0]).
-export([init_db/0, init_db/1, init_tables/0, init_tables/1]).
--export([add/1, find/1, get_by_index/2, size/0]).
+-export([add/1, find/1, 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.
@@ -68,7 +68,9 @@ start_link() ->
stop() ->
gen_server:call(?MODULE, stop).
-%% API.
+%%%%%%%%%%%%%%%%%%%%
+%% Public API.
+
add(Entry) ->
gen_server:call(?MODULE, {add, Entry}).
@@ -81,7 +83,13 @@ dump(Table) ->
get_by_index(Start, End) ->
gen_server:call(?MODULE, {get_by_index, {Start, End}}).
+get_by_index_sorted(Start, End) ->
+ gen_server:call(?MODULE, {get_by_index_sorted, {Start, End}}).
+
+
%%%%%%%%%%%%%%%%%%%%
+%% gen_server callbacks.
+
handle_cast(_Request, State) ->
{noreply, State}.
@@ -95,7 +103,10 @@ 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) ->
@@ -123,11 +134,22 @@ handle_call({find, Hash}, _From, State) ->
end,
{reply, Record, 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() ->
MatchHead = #plop{index = '$1', mtl = '$2', _ = '_'},
Guard = [{'>=', '$1', Start}, {'=<', '$1', End}],
- Result = ['$2'],
+ Result = ['$$'],
mnesia:select(plop, [{MatchHead, Guard, Result}])
end,
{atomic, Res} = mnesia:transaction(F),
- {reply, Res, State}.
+ Res.