From d147bb0e35a46c01d783b32f5a8569cbc1d7e88a Mon Sep 17 00:00:00 2001 From: Diogo Resende Date: Wed, 17 Apr 2013 11:04:05 +0100 Subject: [PATCH] Adds exception for .distinct() to behave a little different from other aggregate functions (#123) --- lib/AggregateFunctions.js | 21 +++++++++++++---- test/integration/test-aggregate-distinct.js | 25 +++++++++++++++++++++ 2 files changed, 42 insertions(+), 4 deletions(-) create mode 100644 test/integration/test-aggregate-distinct.js diff --git a/lib/AggregateFunctions.js b/lib/AggregateFunctions.js index b5c8ab96..d022b414 100644 --- a/lib/AggregateFunctions.js +++ b/lib/AggregateFunctions.js @@ -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 () { @@ -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; }; }; @@ -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); } diff --git a/test/integration/test-aggregate-distinct.js b/test/integration/test-aggregate-distinct.js new file mode 100644 index 00000000..6cf5808b --- /dev/null +++ b/test/integration/test-aggregate-distinct.js @@ -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(); + }); + }); + }); +});