Skip to content

Commit

Permalink
bulkCreate() now has a third argument which gives you the ability to …
Browse files Browse the repository at this point in the history
…validate each row before attempting to bulkInsert.
  • Loading branch information
durango committed Jul 31, 2013
1 parent 9a41b4a commit 8f572eb
Show file tree
Hide file tree
Showing 2 changed files with 56 additions and 2 deletions.
23 changes: 21 additions & 2 deletions lib/dao-factory.js
Original file line number Diff line number Diff line change
Expand Up @@ -434,11 +434,30 @@ module.exports = (function() {
* generated IDs and other default values in a way that can be mapped to
* multiple records
*/
DAOFactory.prototype.bulkCreate = function(records, fields) {
DAOFactory.prototype.bulkCreate = function(records, fields, options) {
options = options || {}
options.validate = options.validate || false

var self = this
, daos = records.map(function(v) { return self.build(v) })
, updatedAtAttr = self.options.underscored ? 'updated_at' : 'updatedAt'
, createdAtAttr = self.options.underscored ? 'created_at' : 'createdAt'
, errors = []
, daos = records.map(function(v) {
var build = self.build(v)
if (options.validate === true) {
var valid = build.validate({type: 'insert'})
if (valid !== null) {
errors[errors.length] = {record: v, errors: valid}
}
}
return build
})

if (options.validate === true && errors.length > 0) {
return new Utils.CustomEventEmitter(function(emitter) {
emitter.emit('error', errors)
}).run()
}

fields = fields || []

Expand Down
35 changes: 35 additions & 0 deletions test/dao-factory.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -715,6 +715,41 @@ describe(Support.getTestDialectTeaser("DAOFactory"), function () {
})
})

it('emits an error when validate is set to true', function(done) {
var Tasks = this.sequelize.define('Task', {
name: {
type: Sequelize.STRING,
validate: {
notNull: { args: true, msg: 'name cannot be null' }
}
},
code: {
type: Sequelize.STRING,
validate: {
len: [3, 10]
}
}
})

Tasks.sync({ force: true }).success(function() {
Tasks.bulkCreate([
{name: 'foo', code: '123'},
{code: '1234'},
{name: 'bar', code: '1'}
], null, {validate: true}).error(function(errors) {
expect(errors).to.not.be.null
expect(errors).to.be.instanceof(Array)
expect(errors).to.have.length(2)
expect(errors[0].record.code).to.equal('1234')
expect(errors[0].errors.name[0]).to.equal('name cannot be null')
expect(errors[1].record.name).to.equal('bar')
expect(errors[1].record.code).to.equal('1')
expect(errors[1].errors.code[0]).to.equal('String is not in range: code')
done()
})
})
})

describe('enums', function() {
it('correctly restores enum values', function(done) {
var self = this
Expand Down

0 comments on commit 8f572eb

Please sign in to comment.