diff options
author | Linus Nordberg <linus@nordberg.se> | 2014-09-09 14:04:19 +0200 |
---|---|---|
committer | Linus Nordberg <linus@nordberg.se> | 2014-09-09 14:04:19 +0200 |
commit | e7a1ca43af470b6e99c0e11d845903f9bf00c723 (patch) | |
tree | 1624f8c53abc5b209a105db49feede0742661561 | |
parent | 558a56adfe02a0803bbbbf4ddaef0271e586930b (diff) |
Add db:get_by_index_sorted/2.
-rw-r--r-- | src/db.erl | 30 |
1 files changed, 26 insertions, 4 deletions
@@ -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. |