Skip to content

Commit

Permalink
Adds exception for .distinct() to behave a little different from othe…
Browse files Browse the repository at this point in the history
…r aggregate functions (#123)
  • Loading branch information
dresende committed Apr 17, 2013
1 parent a9915e3 commit d147bb0
Show file tree
Hide file tree
Showing 2 changed files with 42 additions and 4 deletions.
21 changes: 17 additions & 4 deletions lib/AggregateFunctions.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,8 +8,9 @@ function AggregateFunctions(opts) {
throw new Error("This driver does not support aggregate functions");
}

var aggregates = [ [] ];
var group_by = null;
var aggregates = [ [] ];
var group_by = null;
var used_distinct = false;

var appendFunction = function (fun) {
return function () {
Expand All @@ -22,6 +23,10 @@ function AggregateFunctions(opts) {
aggregates[aggregates.length - 1].push({ f: fun, alias: aggregateAlias(fun, args) });
}

if (fun == "distinct") {
used_distinct = true;
}

return proto;
};
};
Expand Down Expand Up @@ -92,9 +97,17 @@ function AggregateFunctions(opts) {
return cb(null, data);
}

var items = [];
var items = [], i;

if (used_distinct && aggregates.length == 1) {
for (i = 0; i < data.length; i++) {
items.push(data[i][Object.keys(data[i]).pop()]);
}

return cb(null, items);
}

for (var i = 0; i < aggregates.length; i++) {
for (i = 0; i < aggregates.length; i++) {
for (var j = 0; j < aggregates[i].length; j++) {
items.push(data[0][aggregates[i][j].alias] || null);
}
Expand Down
25 changes: 25 additions & 0 deletions test/integration/test-aggregate-distinct.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
var common = require('../common');
var assert = require('assert');

common.createConnection(function (err, db) {
common.createModelTable('test_aggregate_distinct', db.driver.db, function () {
common.insertModelData('test_aggregate_distinct', db.driver.db, [
{ id : 1, name : 'test1' },
{ id : 2, name : 'test1' },
{ id : 3, name : 'test2' },
{ id : 4, name : 'test2' },
{ id : 5, name : 'test2' }
], function (err) {
if (err) throw err;

var TestModel = db.define('test_aggregate_distinct', common.getModelProperties());

TestModel.aggregate().distinct('name').get(function (err, names) {
assert.equal(err, null);
assert.equal(Array.isArray(names), true);
assert.equal(names.length, 2);
db.close();
});
});
});
});

0 comments on commit d147bb0

Please sign in to comment.