Skip to content

Commit

Permalink
fix(Pagination): Handle group by and havings in pagination queries
Browse files Browse the repository at this point in the history
  • Loading branch information
elpete authored Aug 13, 2021
1 parent f55a224 commit 4a4428f
Show file tree
Hide file tree
Showing 2 changed files with 46 additions and 1 deletion.
17 changes: 16 additions & 1 deletion models/Query/QueryBuilder.cfc
Original file line number Diff line number Diff line change
Expand Up @@ -2252,7 +2252,7 @@ component displayname="QueryBuilder" accessors="true" {
* @return PaginationCollector
*/
public any function paginate( numeric page = 1, numeric maxRows = 25, struct options = {} ) {
var totalRecords = count( options = options );
var totalRecords = getCountForPagination( options = options );
var results = forPage( page, maxRows ).get( options = options );
return getPaginationCollector().generateWithResults(
totalRecords = totalRecords,
Expand Down Expand Up @@ -2282,6 +2282,21 @@ component displayname="QueryBuilder" accessors="true" {
);
}

/**
* Gets the count for the pagination query.
* The execution method changes based on different query configurations.
*
* @options Any options to pass to `queryExecute`. Default: {}.
*
* @return numeric
*/
private numeric function getCountForPagination( struct options = {} ) {
if ( !variables.groups.isEmpty() || !variables.havings.isEmpty() ) {
return newQuery().fromSub( "aggregate_table", this ).count( options = arguments.options );
}
return count( options = arguments.options );
}

/*******************************************************************************\
| control flow functions |
\*******************************************************************************/
Expand Down
30 changes: 30 additions & 0 deletions tests/specs/Query/Abstract/PaginationSpec.cfc
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,36 @@ component extends="testbox.system.BaseSpec" {
} );
} );

it( "can paginate a group by query", function() {
var builder = getBuilder();
var expectedResults = [];
for ( var i = 1; i <= 25; i++ ) {
expectedResults.append( { "id": i } );
}
var expectedQuery = queryNew( "id", "integer", expectedResults );
builder.$( "runQuery", expectedQuery );

var nestedBuilder = getBuilder();
nestedBuilder.$( "count", 15 );
builder.$( "newQuery", nestedBuilder );

var results = builder
.from( "users" )
.groupBy( "lastName" )
.paginate();

expect( results ).toBe( {
"pagination": {
"maxRows": 25,
"offset": 0,
"page": 1,
"totalPages": 1,
"totalRecords": 15
},
"results": expectedResults
} );
} );

it( "can get results for subsequent pages", function() {
var builder = getBuilder();
var expectedResults = [];
Expand Down

0 comments on commit 4a4428f

Please sign in to comment.