Skip to content

Commit

Permalink
Merge pull request #304 from DenisFerrero/master
Browse files Browse the repository at this point in the history
fix: count just the right number of row
  • Loading branch information
icebob committed Jan 17, 2022
2 parents eb62b47 + d3f895c commit 024e740
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 4 deletions.
5 changes: 3 additions & 2 deletions packages/moleculer-db-adapter-sequelize/src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -302,9 +302,10 @@ class SequelizeDbAdapter {
* @returns {Promise}
*/
createCursor(params, isCounting) {
const strictCountRule = { distinct: true, col: `${this.model.name ||this.model.tableName}.${this.model.primaryKeyAttribute}` };
if (!params) {
if (isCounting)
return this.model.count();
return this.model.count(strictCountRule);

return this.model.findAll();
}
Expand Down Expand Up @@ -356,7 +357,7 @@ class SequelizeDbAdapter {
q.limit = params.limit;

if (isCounting)
return this.model.count(q);
return this.model.count(_.merge(q, strictCountRule));

return this.model.findAll(q);
}
Expand Down
14 changes: 12 additions & 2 deletions packages/moleculer-db-adapter-sequelize/test/unit/index.spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,8 @@ const { ServiceBroker } = require("moleculer");
jest.mock("sequelize");

const model = {
tableName: "posts",
primaryKeyAttribute: 'id',
sync: jest.fn(() => Promise.resolve()),
findAll: jest.fn(() => Promise.resolve()),
count: jest.fn(() => Promise.resolve()),
Expand Down Expand Up @@ -40,6 +42,7 @@ function protectReject(err) {
const fakeModel = {
name: "posts",
define: {
id: { type: "number", primaryKey: true },
a: 5
},
options: {
Expand Down Expand Up @@ -163,7 +166,10 @@ describe("Test SequelizeAdapter", () => {
adapter.model.findAll.mockClear();
adapter.createCursor(null, true);
expect(adapter.model.count).toHaveBeenCalledTimes(1);
expect(adapter.model.count).toHaveBeenCalledWith();
expect(adapter.model.count).toHaveBeenCalledWith({
distinct: true,
col: `${model.tableName}.${model.primaryKeyAttribute}`
});
});

it("call with query", () => {
Expand All @@ -179,7 +185,11 @@ describe("Test SequelizeAdapter", () => {
let query = {};
adapter.createCursor({ query }, true);
expect(adapter.model.count).toHaveBeenCalledTimes(1);
expect(adapter.model.count).toHaveBeenCalledWith({ where: query });
expect(adapter.model.count).toHaveBeenCalledWith({
distinct: true,
col: `${model.tableName}.${model.primaryKeyAttribute}`,
where: query
});
});

it("call with sort string", () => {
Expand Down

0 comments on commit 024e740

Please sign in to comment.