From 437d37fa4b3380ce904f35a7e8fea1f530aadcbf Mon Sep 17 00:00:00 2001 From: "David N. Welton" Date: Thu, 23 Jan 2014 11:53:49 +0100 Subject: [PATCH 1/2] Added paginate function to help users paginate through database results. --- src/boss_db.erl | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) diff --git a/src/boss_db.erl b/src/boss_db.erl index 5eeea276..d7d0ace9 100644 --- a/src/boss_db.erl +++ b/src/boss_db.erl @@ -19,6 +19,7 @@ count/1, count/2, counter/1, + paginate/3, incr/1, incr/2, delete/1, @@ -48,6 +49,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), @@ -201,6 +203,23 @@ count(Type, Conditions) -> counter(Key) -> db_call({counter, Key}). +%% @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) -> From 60dc24e0b91912a0fabb0950c699ce4f87ea2263 Mon Sep 17 00:00:00 2001 From: "David N. Welton" Date: Mon, 27 Jan 2014 11:14:03 +0100 Subject: [PATCH 2/2] Accept UUID as a data type. This is so that foreign keys like, say, student_id can be ::uuid() and not ::string(), to better reflect the underlying database. --- src/boss_db.erl | 2 ++ 1 file changed, 2 insertions(+) diff --git a/src/boss_db.erl b/src/boss_db.erl index d7d0ace9..9b407426 100644 --- a/src/boss_db.erl +++ b/src/boss_db.erl @@ -403,6 +403,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),