Refactor pagination parts to separate function

To make things more readable and extendable, I factored out the pagination bits in the query builder to a separate function (queryPaginate)