Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Added paginate function to help users paginate through database results. #153

Closed
wants to merge 4 commits into from
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
26 changes: 26 additions & 0 deletions src/boss_db.erl
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,12 @@
find_last/4,
count/1,
count/2,
counter/1,
paginate/3,
incr/1,
incr/2,
delete/1,
save_record/1,
count/3,
counter/1,
counter/2,
Expand Down Expand Up @@ -65,6 +71,7 @@

-define(DEFAULT_TIMEOUT, (30 * 1000)).
-define(POOLNAME, boss_db_pool).
-define(DEFAULT_PAGE_SIZE, 10).

start(Options) ->
AdapterName = proplists:get_value(adapter, Options, mock),
Expand Down Expand Up @@ -257,6 +264,23 @@ counter(Key) ->
counter(Key, Timeout) ->
db_call({counter, Key}, Timeout).

%% @spec paginate( Model::atom(), Conditions, Opts ) -> Value | {error, Reason}
%% @doc Paginate through the results from boss_db:find. Use `Opts' {page,
%% PageNum} and {page_size, PageSize} to control which page to fetch,
%% and how many results per page. Page size defaults to 10.
paginate(Model, Conditions, Opts) ->
CleanOpts = proplists:delete(offset, proplists:delete(limit, Opts)),
Page = proplists:get_value(page, Opts, 1),
PageSize = proplists:get_value(page_size, Opts, ?DEFAULT_PAGE_SIZE),
OptList = proplists:delete(page_size, proplists:delete(page, CleanOpts)) ++
[{offset, PageSize * (Page - 1)}, {limit, PageSize}],
Total = boss_db:count(Model, Conditions),
TotalPages = (Total div PageSize) + (case Total rem PageSize of
0 -> 0;
_ -> 1
end),
{Page, TotalPages, boss_db:find(Model, Conditions, OptList)}.

%% @spec incr( Id::string() ) -> integer()
%% @doc Treat the record associated with `Id' as a counter and atomically increment its value by 1.
incr(Key) ->
Expand Down Expand Up @@ -479,6 +503,8 @@ validate_record_types(Record) ->
true;
{Data, string} when is_list(Data) ->
true;
{Data, uuid} when is_list(Data) ->
true;
{Data, binary} when is_binary(Data) ->
true;
{{{D1, D2, D3}, {T1, T2, T3}}, datetime} when is_integer(D1), is_integer(D2), is_integer(D3),
Expand Down