-module(couch_numidx). -behaviour(gen_server). % gen_server exports -export([start_link/0, init/1, handle_call/3, handle_cast/2, handle_info/2, terminate/2, code_change/3]). % API exports -export([get_docs/1, range_search/2]). -include("couch_db.hrl"). get_docs(Db) -> gen_server:call(couch_numidx, {do_get_docs, Db}). range_search(Ni, Range) -> gen_server:call(couch_numidx, {do_range_search, Ni, Range}). start_link() -> ?LOG_DEBUG("Numidx daemon: starting link.", []), gen_server:start_link({local, couch_numidx}, couch_numidx, [], []). init([]) -> {ok, {}}. terminate(_Reason, _Srv) -> ok. handle_call({do_get_docs, Db}, _From, State) -> {ok, _Cnt, Acc} = couch_db:enum_docs_since(Db, 0, fun(DocInfo, _, NumidxDs) -> {ok, Doc} = couch_db:open_doc(Db, DocInfo), {Body} = Doc#doc.body, case proplists:get_value(<<"numidx">>, Body) of undefined -> {ok, NumidxDs}; Numidx -> {doc_info, DocId, _DocSeq, _RevInfo} = DocInfo, NumidxDs2 = numidx:add(NumidxDs, {DocId, Numidx}), {ok, NumidxDs2} end end, nil, []), {reply, Acc, State}; handle_call({do_range_search, Ni, Range}, _From, State) -> Result = numidx:range(Ni, Range), {reply, Result, State}; handle_call(_Req, _From, State) -> {noreply, State}. handle_cast(_Msg, State) -> {noreply, State}. handle_info(_Msg, Server) -> {noreply, Server}. code_change(_OldVsn, State, _Extra) -> {ok, State}.