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

Fix incorrect rowCount value when using groupBy with fetchPage #1852

Merged
merged 2 commits into from Jun 4, 2018
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
18 changes: 10 additions & 8 deletions lib/plugins/pagination.js
Expand Up @@ -108,7 +108,11 @@ module.exports = function paginationPlugin (bookshelf) {
const offset = options.offset;
const fetchOptions = _.omit(options, ['page', 'pageSize', 'limit', 'offset']);
const transacting = fetchOptions.transacting;

const fetchMethodName = isModel ? 'fetchAll' : 'fetch';
const targetModel = isModel ? this.constructor : (this.target || this.model);
const tableName = targetModel.prototype.tableName;
const idAttribute = targetModel.prototype.idAttribute || 'id';
const targetIdColumn = [`${tableName}.${idAttribute}`];
let usingPageSize = false; // usingPageSize = false means offset/limit, true means page/pageSize
let _page;
let _pageSize;
Expand All @@ -135,12 +139,6 @@ module.exports = function paginationPlugin (bookshelf) {
_offset = ensureIntWithDefault(offset, DEFAULT_OFFSET);
}

const fetchMethodName = isModel ? 'fetchAll' : 'fetch';
const targetModel = isModel ? this.constructor : (this.target || this.model);
const tableName = targetModel.prototype.tableName;
const idAttribute = targetModel.prototype.idAttribute || 'id';
const targetIdColumn = `${tableName}.${idAttribute}`;

const paginate = () => {
const pager = this.clone();

Expand All @@ -156,6 +154,7 @@ module.exports = function paginationPlugin (bookshelf) {
const count = () => {
const notNeededQueries = ['orderByBasic', 'orderByRaw', 'groupByBasic', 'groupByRaw'];
const counter = this.clone();
const groupColumns = [];

return counter.query(qb => {
Object.assign(qb, this.query().clone());
Expand All @@ -164,6 +163,9 @@ module.exports = function paginationPlugin (bookshelf) {
// for a count, and grouping returns the entire result set
// What we want instead is to use `DISTINCT`
_.remove(qb._statements, statement => {
if (statement.grouping === 'group')
statement.value.forEach(value => groupColumns.push(`${tableName}.${value}`));

return notNeededQueries.indexOf(statement.type) > -1 || statement.grouping === 'columns';
});

Expand All @@ -173,7 +175,7 @@ module.exports = function paginationPlugin (bookshelf) {
counter.relatedData.joinColumns = function() {};
}

qb.countDistinct.apply(qb, [targetIdColumn]);
qb.countDistinct.apply(qb, groupColumns.length > 0 ? groupColumns : targetIdColumn);
})[fetchMethodName]({transacting}).then(result => {
const metadata = usingPageSize ? {page: _page, pageSize: _limit} : {offset: _offset, limit: _limit};

Expand Down
29 changes: 25 additions & 4 deletions test/integration/plugins/pagination.js
Expand Up @@ -5,7 +5,7 @@ module.exports = function (bookshelf) {
bookshelf.plugin('pagination');
var Models = require('../helpers/objects')(bookshelf).Models;

describe('Model instance fetchPage', function () {
describe('Model#fetchPage()', function () {
it('fetches a single page of results with defaults', function () {
return Models.Customer.forge().fetchPage().then(function (results) {
['models', 'pagination'].forEach(function (prop) {
Expand Down Expand Up @@ -76,7 +76,7 @@ module.exports = function (bookshelf) {
})
})

describe('Model static fetchPage', function () {
describe('Model.fetchPage()', function () {
it('fetches a page without calling forge', function () {
return Models.Customer.fetchPage().then(function (results) {
['models', 'pagination'].forEach(function (prop) {
Expand All @@ -86,14 +86,15 @@ module.exports = function (bookshelf) {
})
})

describe('Collection fetchPage', function () {
describe('Collection#fetchPage()', function () {
it('fetches a page from a collection', function () {
return Models.Customer.collection().fetchPage().then(function (results) {
['models', 'pagination'].forEach(function (prop) {
expect(results).to.have.property(prop);
});
})
})

it('fetches a page from a relation collection', function () {
return Models.User.forge({uid: 1}).roles().fetchPage().then(function (results) {
expect(results.length).to.equal(1);
Expand All @@ -102,6 +103,7 @@ module.exports = function (bookshelf) {
});
});
})

it('fetches a page from a relation collection with additional condition', function () {
return Models.User.forge({uid: 1}).roles().query(function (query) {
query.where('roles.rid', '!=', 4);
Expand All @@ -114,7 +116,7 @@ module.exports = function (bookshelf) {
})
})

describe('Inside a transaction', function() {
describe('inside a transaction', function() {
it('returns consistent results for rowCount and number of models', function() {
return bookshelf.transaction(function(t) {
var options = {transacting: t};
Expand All @@ -129,5 +131,24 @@ module.exports = function (bookshelf) {
});
})
})

describe('with groupBy', function() {
it('counts grouped rows instead of total rows', function() {
var total

return Models.Blog.count().then(function(count) {
total = parseInt(count, 10);

return Models.Blog.query(function(qb) {
qb.max('id');
qb.groupBy('site_id');
qb.whereNotNull('site_id');
}).fetchPage()
}).then(function(blogs) {
expect(blogs.pagination.rowCount).to.equal(blogs.length);
expect(blogs.length).to.be.below(total);
})
})
})
});
};