Permalink
Browse files

model.count

  • Loading branch information...
1 parent 00ebd92 commit d42b47d1430fab92b617a208bedb88c9de82ba69 @sdepold committed May 4, 2011
Showing with 48 additions and 0 deletions.
  1. +11 −0 lib/sequelize/model-definition.js
  2. +4 −0 lib/sequelize/query-generator.js
  3. +33 −0 test/Model/count.js
@@ -81,6 +81,17 @@ ModelDefinition.prototype.__defineGetter__('all', function() {
return this.query(QueryGenerator.selectQuery(this.tableName))
})
+ModelDefinition.prototype.count = function(options) {
+ var self = this
+
+ var emitter = new Utils.CustomEventEmitter(function() {
+ self.query(QueryGenerator.countQuery(self.tableName, options), self, {plain: true}).on('success', function(obj) {
+ emitter.emit('success', obj['count(*)'])
+ })
+ })
+ return emitter.run()
+}
+
ModelDefinition.prototype.findAll = function(options) {
return this.query(QueryGenerator.selectQuery(this.tableName, options))
}
@@ -75,6 +75,10 @@ var QueryGenerator = module.exports = {
return Utils._.template(query)(options)
},
+ countQuery: function(tableName, options) {
+ return QueryGenerator.selectQuery(tableName, options).replace("*", "count(*)")
+ },
+
/*
Returns an insert into command. Parameters: table name + hash of attribute-value-pairs.
*/
View
@@ -0,0 +1,33 @@
+var assert = require("assert")
+ , config = require("./../config")
+ , Sequelize = require("./../../index")
+ , sequelize = new Sequelize(config.database, config.username, config.password, {logging: false})
+
+module.exports = {
+ 'it should correctly count all objects': function(exit) {
+ var User = sequelize.define('User', { username: Sequelize.STRING })
+ User.sync({force: true}).on('success', function() {
+ User.create({username: 'user1'}).on('success', function() {
+ User.create({username: 'user2'}).on('success', function() {
+ User.count().on('success', function(count) {
+ assert.eql(count, 2)
+ exit(function(){})
+ })
+ })
+ })
+ })
+ },
+ 'it should correctly count filtered objects': function(exit) {
+ var User = sequelize.define('User', { username: Sequelize.STRING })
+ User.sync({force: true}).on('success', function() {
+ User.create({username: 'user1'}).on('success', function() {
+ User.create({username: 'foo'}).on('success', function() {
+ User.count({where: "username LIKE '%us%'"}).on('success', function(count) {
+ assert.eql(count, 1)
+ exit(function(){})
+ })
+ })
+ })
+ })
+ }
+}

0 comments on commit d42b47d

Please sign in to comment.