不要怂,就是干,撸起袖子干!

Commit a1c82f3d by Mick Hansen

Merge pull request #3467 from BridgeAR/master

Refactor last tests to use promise style
2 parents 45e6700b c1fa0bb1
...@@ -2,4 +2,4 @@ ...@@ -2,4 +2,4 @@
The entry point. The entry point.
@module Sequelize @module Sequelize
**/ **/
module.exports = require("./lib/sequelize") module.exports = require("./lib/sequelize");
...@@ -203,7 +203,7 @@ module.exports = (function() { ...@@ -203,7 +203,7 @@ module.exports = (function() {
options = Utils._.extend({ options = Utils._.extend({
events: proxyEventKeys, events: proxyEventKeys,
skipEvents: [] skipEvents: []
}, options ||  {}); }, options || {});
options.events = Utils._.difference(options.events, options.skipEvents); options.events = Utils._.difference(options.events, options.skipEvents);
......
...@@ -20,7 +20,7 @@ module.exports = (function() { ...@@ -20,7 +20,7 @@ module.exports = (function() {
this.daos = this.daos.filter(function(_dao) { this.daos = this.daos.filter(function(_dao) {
return _dao.name !== dao.name; return _dao.name !== dao.name;
}); });
delete this.sequelize.models[dao.name]; delete this.sequelize.models[dao.name];
}; };
......
...@@ -81,11 +81,11 @@ module.exports = (function() { ...@@ -81,11 +81,11 @@ module.exports = (function() {
return association.source.update(newValues, { where: query }); return association.source.update(newValues, { where: query });
}); });
}, },
increment: function (targetId) { increment: function (targetId) {
var query = CounterUtil._sourceQuery(targetId); var query = CounterUtil._sourceQuery(targetId);
return association.source.find({ where: query }).then(function (instance) { return association.source.find({ where: query }).then(function (instance) {
return instance.increment(counterCacheInstance.columnName, { by: 1 }); return instance.increment(counterCacheInstance.columnName, { by: 1 });
}); });
}, },
decrement: function (targetId) { decrement: function (targetId) {
......
...@@ -43,7 +43,6 @@ ...@@ -43,7 +43,6 @@
"validator": "^3.34.0" "validator": "^3.34.0"
}, },
"devDependencies": { "devDependencies": {
"async": "~0.9.0",
"chai": "^2.1.2", "chai": "^2.1.2",
"chai-as-promised": "^4.3.0", "chai-as-promised": "^4.3.0",
"chai-datetime": "~1.3.0", "chai-datetime": "~1.3.0",
......
...@@ -1793,7 +1793,7 @@ describe(Support.getTestDialectTeaser('BelongsToMany'), function() { ...@@ -1793,7 +1793,7 @@ describe(Support.getTestDialectTeaser('BelongsToMany'), function() {
self.User.belongsToMany(self.Task, { onDelete: 'RESTRICT'}); self.User.belongsToMany(self.Task, { onDelete: 'RESTRICT'});
self.Task.belongsToMany(self.User, { onDelete: 'CASCADE'}); self.Task.belongsToMany(self.User, { onDelete: 'CASCADE'});
return this.sequelize.sync({ force: true, logging: true }).bind({}).then(function() { return this.sequelize.sync({ force: true }).bind({}).then(function() {
return Sequelize.Promise.join( return Sequelize.Promise.join(
self.User.create({ id: 67, username: 'foo' }), self.User.create({ id: 67, username: 'foo' }),
self.Task.create({ id: 52, title: 'task' }), self.Task.create({ id: 52, title: 'task' }),
......
...@@ -13,7 +13,7 @@ if (dialect.match(/^postgres/)) { ...@@ -13,7 +13,7 @@ if (dialect.match(/^postgres/)) {
describe('[POSTGRES Specific] associations', function() { describe('[POSTGRES Specific] associations', function() {
describe('many-to-many', function() { describe('many-to-many', function() {
describe('where tables have the same prefix', function() { describe('where tables have the same prefix', function() {
it('should create a table wp_table1wp_table2s', function(done) { it('should create a table wp_table1wp_table2s', function() {
var Table2 = this.sequelize.define('wp_table2', {foo: DataTypes.STRING}) var Table2 = this.sequelize.define('wp_table2', {foo: DataTypes.STRING})
, Table1 = this.sequelize.define('wp_table1', {foo: DataTypes.STRING}); , Table1 = this.sequelize.define('wp_table1', {foo: DataTypes.STRING});
...@@ -21,35 +21,24 @@ if (dialect.match(/^postgres/)) { ...@@ -21,35 +21,24 @@ if (dialect.match(/^postgres/)) {
Table2.hasMany(Table1); Table2.hasMany(Table1);
expect(this.sequelize.daoFactoryManager.getDAO('wp_table1swp_table2s')).to.exist; expect(this.sequelize.daoFactoryManager.getDAO('wp_table1swp_table2s')).to.exist;
done();
}); });
}); });
describe('when join table name is specified', function() { describe('when join table name is specified', function() {
beforeEach(function(done) { beforeEach(function() {
var Table2 = this.sequelize.define('ms_table1', {foo: DataTypes.STRING}) var Table2 = this.sequelize.define('ms_table1', {foo: DataTypes.STRING})
, Table1 = this.sequelize.define('ms_table2', {foo: DataTypes.STRING}); , Table1 = this.sequelize.define('ms_table2', {foo: DataTypes.STRING});
Table1.hasMany(Table2, {joinTableName: 'table1_to_table2'}); Table1.hasMany(Table2, {joinTableName: 'table1_to_table2'});
Table2.hasMany(Table1, {joinTableName: 'table1_to_table2'}); Table2.hasMany(Table1, {joinTableName: 'table1_to_table2'});
setTimeout(function() {
done();
}, 50);
}); });
it('should not use a combined name', function(done) { it('should not use a combined name', function() {
expect(this.sequelize.daoFactoryManager.getDAO('ms_table1sms_table2s')).not.to.exist; expect(this.sequelize.daoFactoryManager.getDAO('ms_table1sms_table2s')).not.to.exist;
setTimeout(function() {
done();
}, 50);
}); });
it('should use the specified name', function(done) { it('should use the specified name', function() {
expect(this.sequelize.daoFactoryManager.getDAO('table1_to_table2')).to.exist; expect(this.sequelize.daoFactoryManager.getDAO('table1_to_table2')).to.exist;
setTimeout(function() {
done();
}, 50);
}); });
}); });
}); });
......
...@@ -363,38 +363,37 @@ if (dialect.match(/^postgres/)) { ...@@ -363,38 +363,37 @@ if (dialect.match(/^postgres/)) {
}); });
}); });
it('should be able to add enum types', function(done) { it('should be able to add enum types', function() {
var self = this var self = this
, User = this.sequelize.define('UserEnums', { , User = this.sequelize.define('UserEnums', {
mood: DataTypes.ENUM('happy', 'sad', 'meh') mood: DataTypes.ENUM('happy', 'sad', 'meh')
}); })
, count = 0;
var _done = _.after(4, function() {
done();
});
User.sync({ force: true }).then(function() { return User.sync({ force: true }).then(function() {
User = self.sequelize.define('UserEnums', { User = self.sequelize.define('UserEnums', {
mood: DataTypes.ENUM('neutral', 'happy', 'sad', 'ecstatic', 'meh', 'joyful') mood: DataTypes.ENUM('neutral', 'happy', 'sad', 'ecstatic', 'meh', 'joyful')
}); });
User.sync().then(function() { return User.sync().then(function() {
expect(User.rawAttributes.mood.values).to.deep.equal(['neutral', 'happy', 'sad', 'ecstatic', 'meh', 'joyful']); expect(User.rawAttributes.mood.values).to.deep.equal(['neutral', 'happy', 'sad', 'ecstatic', 'meh', 'joyful']);
_done(); count++;
}).on('sql', function(sql) { }).on('sql', function(sql) {
if (sql.indexOf('neutral') > -1) { if (sql.indexOf('neutral') > -1) {
expect(sql).to.equal("ALTER TYPE \"enum_UserEnums_mood\" ADD VALUE 'neutral' BEFORE 'happy'"); expect(sql).to.equal("ALTER TYPE \"enum_UserEnums_mood\" ADD VALUE 'neutral' BEFORE 'happy'");
_done(); count++;
} }
else if (sql.indexOf('ecstatic') > -1) { else if (sql.indexOf('ecstatic') > -1) {
expect(sql).to.equal("ALTER TYPE \"enum_UserEnums_mood\" ADD VALUE 'ecstatic' BEFORE 'meh'"); expect(sql).to.equal("ALTER TYPE \"enum_UserEnums_mood\" ADD VALUE 'ecstatic' BEFORE 'meh'");
_done(); count++;
} }
else if (sql.indexOf('joyful') > -1) { else if (sql.indexOf('joyful') > -1) {
expect(sql).to.equal("ALTER TYPE \"enum_UserEnums_mood\" ADD VALUE 'joyful' AFTER 'meh'"); expect(sql).to.equal("ALTER TYPE \"enum_UserEnums_mood\" ADD VALUE 'joyful' AFTER 'meh'");
_done(); count++;
} }
}); });
}).then(function() {
expect(count).to.equal(4);
}); });
}); });
}); });
......
...@@ -318,20 +318,19 @@ describe(Support.getTestDialectTeaser('Include'), function() { ...@@ -318,20 +318,19 @@ describe(Support.getTestDialectTeaser('Include'), function() {
Task.belongsTo(Project); Task.belongsTo(Project);
return this.sequelize.sync({force: true}).then(function() { return this.sequelize.sync({force: true}).then(function() {
return Promise.all([ return Project.bulkCreate([{ id: 1 }, { id: 2 }]);
Project.bulkCreate([{ id: 1 }, { id: 2 }]), }).then(function (projects) {
User.create({ return User.create({
Tasks: [ Tasks: [
{ProjectId: 1}, {ProjectId: 1},
{ProjectId: 2}, {ProjectId: 2},
{ProjectId: 1}, {ProjectId: 1},
{ProjectId: 2} {ProjectId: 2}
] ]
}, { }, {
include: [Task] include: [Task]
}) });
]); }).then(function (user) {
}).spread(function (projects, user) {
return User.find({ return User.find({
where: { where: {
id: user.id id: user.id
......
...@@ -6,7 +6,6 @@ var chai = require('chai') ...@@ -6,7 +6,6 @@ var chai = require('chai')
, Support = require(__dirname + '/../support') , Support = require(__dirname + '/../support')
, DataTypes = require(__dirname + '/../../../lib/data-types') , DataTypes = require(__dirname + '/../../../lib/data-types')
, datetime = require('chai-datetime') , datetime = require('chai-datetime')
, async = require('async')
, Promise = Sequelize.Promise , Promise = Sequelize.Promise
, _ = require('lodash'); , _ = require('lodash');
...@@ -128,7 +127,7 @@ describe(Support.getTestDialectTeaser('Include'), function() { ...@@ -128,7 +127,7 @@ describe(Support.getTestDialectTeaser('Include'), function() {
, tags = results.tags , tags = results.tags
, companies = results.companies; , companies = results.companies;
return Promise.reduce(_.range(5), function (memo, i) { return Promise.resolve([0, 1, 2, 3, 4]).each(function (i) {
return Promise.props({ return Promise.props({
user: User.create(), user: User.create(),
products: Product.bulkCreate([ products: Product.bulkCreate([
...@@ -195,7 +194,7 @@ describe(Support.getTestDialectTeaser('Include'), function() { ...@@ -195,7 +194,7 @@ describe(Support.getTestDialectTeaser('Include'), function() {
]) ])
); );
}); });
}, []); });
}); });
}); });
}; };
...@@ -380,139 +379,101 @@ describe(Support.getTestDialectTeaser('Include'), function() { ...@@ -380,139 +379,101 @@ describe(Support.getTestDialectTeaser('Include'), function() {
Group.hasMany(GroupMember, {as: 'Memberships'}); Group.hasMany(GroupMember, {as: 'Memberships'});
return this.sequelize.sync({force: true}).then(function() { return this.sequelize.sync({force: true}).then(function() {
return new Promise(function (resolve, reject) { return Promise.all([
var count = 4 Group.bulkCreate([
, i = -1; {name: 'Developers'},
{name: 'Designers'}
async.auto({ ]).then(function() {
groups: function(callback) { return Group.findAll();
Group.bulkCreate([ }),
{name: 'Developers'}, Rank.bulkCreate([
{name: 'Designers'} {name: 'Admin', canInvite: 1, canRemove: 1},
]).then(function() { {name: 'Member', canInvite: 1, canRemove: 0}
return Group.findAll(); ]).then(function() {
}).nodeify(callback); return Rank.findAll();
}, }),
ranks: function(callback) { Tag.bulkCreate([
Rank.bulkCreate([ {name: 'A'},
{name: 'Admin', canInvite: 1, canRemove: 1}, {name: 'B'},
{name: 'Member', canInvite: 1, canRemove: 0} {name: 'C'}
]).then(function() { ]).then(function() {
return Rank.findAll(); return Tag.findAll();
}).nodeify(callback); })
}, ]).spread(function(groups, ranks, tags) {
tags: function(callback) { return Promise.resolve([0, 1, 2, 3, 4]).each(function (i) {
Tag.bulkCreate([ return Promise.all([
{name: 'A'}, User.create(),
{name: 'B'}, Product.bulkCreate([
{name: 'C'} {title: 'Chair'},
{title: 'Desk'}
]).then(function() { ]).then(function() {
return Tag.findAll(); return Product.findAll();
}).nodeify(callback); })
}, ]).spread(function(user, products) {
loop: ['groups', 'ranks', 'tags', function(done, results) { return Promise.all([
var groups = results.groups GroupMember.bulkCreate([
, ranks = results.ranks {UserId: user.id, GroupId: groups[0].id, RankId: ranks[0].id},
, tags = results.tags; {UserId: user.id, GroupId: groups[1].id, RankId: ranks[1].id}
]),
async.whilst( user.setProducts([
function() { return i < count; }, products[(i * 2) + 0],
function(callback) { products[(i * 2) + 1]
i++; ]),
products[(i * 2) + 0].setTags([
async.auto({ tags[0],
user: function(callback) { tags[2]
User.create().nodeify(callback); ]),
}, products[(i * 2) + 1].setTags([
memberships: ['user', function(callback, results) { tags[1]
GroupMember.bulkCreate([ ]),
{UserId: results.user.id, GroupId: groups[0].id, RankId: ranks[0].id}, products[(i * 2) + 0].setCategory(tags[1]),
{UserId: results.user.id, GroupId: groups[1].id, RankId: ranks[1].id} Price.bulkCreate([
]).nodeify(callback); {ProductId: products[(i * 2) + 0].id, value: 5},
}], {ProductId: products[(i * 2) + 0].id, value: 10},
products: function(callback) { {ProductId: products[(i * 2) + 1].id, value: 5},
Product.bulkCreate([ {ProductId: products[(i * 2) + 1].id, value: 10},
{title: 'Chair'}, {ProductId: products[(i * 2) + 1].id, value: 15},
{title: 'Desk'} {ProductId: products[(i * 2) + 1].id, value: 20}
]).then(function() { ])
return Product.findAll(); ]);
}).nodeify(callback); });
}, }).then(function() {
userProducts: ['user', 'products', function(callback, results) { return User.findAll({
results.user.setProducts([ include: [
results.products[(i * 2) + 0], {model: GroupMember, as: 'Memberships', include: [
results.products[(i * 2) + 1] Group,
]).nodeify(callback); Rank
}], ]},
productTags: ['products', function(callback, results) { {model: Product, include: [
return Promise.join( Tag,
results.products[(i * 2) + 0].setTags([ {model: Tag, as: 'Category'},
tags[0], Price
tags[2] ]}
]), ],
results.products[(i * 2) + 1].setTags([ order: [
tags[1] ['id', 'ASC']
]), ]
results.products[(i * 2) + 0].setCategory(tags[1]) }).then(function(users) {
).nodeify(callback); users.forEach(function(user) {
}], user.Memberships.sort(sortById);
prices: ['products', function(callback, results) {
Price.bulkCreate([ expect(user.Memberships.length).to.equal(2);
{ProductId: results.products[(i * 2) + 0].id, value: 5}, expect(user.Memberships[0].Group.name).to.equal('Developers');
{ProductId: results.products[(i * 2) + 0].id, value: 10}, expect(user.Memberships[0].Rank.canRemove).to.equal(1);
{ProductId: results.products[(i * 2) + 1].id, value: 5}, expect(user.Memberships[1].Group.name).to.equal('Designers');
{ProductId: results.products[(i * 2) + 1].id, value: 10}, expect(user.Memberships[1].Rank.canRemove).to.equal(0);
{ProductId: results.products[(i * 2) + 1].id, value: 15},
{ProductId: results.products[(i * 2) + 1].id, value: 20} user.Products.sort(sortById);
]).nodeify(callback); expect(user.Products.length).to.equal(2);
}] expect(user.Products[0].Tags.length).to.equal(2);
}, callback); expect(user.Products[1].Tags.length).to.equal(1);
}, expect(user.Products[0].Category).to.be.ok;
function(err) { expect(user.Products[1].Category).not.to.be.ok;
expect(user.Products[0].Prices.length).to.equal(2);
User.findAll({ expect(user.Products[1].Prices.length).to.equal(4);
include: [ });
{model: GroupMember, as: 'Memberships', include: [ });
Group,
Rank
]},
{model: Product, include: [
Tag,
{model: Tag, as: 'Category'},
Price
]}
],
order: [
['id', 'ASC']
]
}).then(function(users) {
users.forEach(function(user) {
user.Memberships.sort(sortById);
expect(user.Memberships.length).to.equal(2);
expect(user.Memberships[0].Group.name).to.equal('Developers');
expect(user.Memberships[0].Rank.canRemove).to.equal(1);
expect(user.Memberships[1].Group.name).to.equal('Designers');
expect(user.Memberships[1].Rank.canRemove).to.equal(0);
user.Products.sort(sortById);
expect(user.Products.length).to.equal(2);
expect(user.Products[0].Tags.length).to.equal(2);
expect(user.Products[1].Tags.length).to.equal(1);
expect(user.Products[0].Category).to.be.ok;
expect(user.Products[1].Category).not.to.be.ok;
expect(user.Products[0].Prices.length).to.equal(2);
expect(user.Products[1].Prices.length).to.equal(4);
});
}).nodeify(done);
}
);
}]
}, function (err) {
if (err) return reject(err);
resolve();
}); });
}); });
}); });
...@@ -560,7 +521,7 @@ describe(Support.getTestDialectTeaser('Include'), function() { ...@@ -560,7 +521,7 @@ describe(Support.getTestDialectTeaser('Include'), function() {
return model.create({}).then(function (instance) { return model.create({}).then(function (instance) {
if (previousInstance) { if (previousInstance) {
return previousInstance['set'+ Sequelize.Utils.uppercaseFirst(model.name)](instance).then(function() { return previousInstance['set'+ Sequelize.Utils.uppercaseFirst(model.name)](instance).then(function() {
previousInstance = instance; previousInstance = instance;
}); });
} else { } else {
previousInstance = b = instance; previousInstance = b = instance;
...@@ -659,7 +620,7 @@ describe(Support.getTestDialectTeaser('Include'), function() { ...@@ -659,7 +620,7 @@ describe(Support.getTestDialectTeaser('Include'), function() {
return model.create(values).then(function (instance) { return model.create(values).then(function (instance) {
if (previousInstance) { if (previousInstance) {
return previousInstance['set'+ Sequelize.Utils.uppercaseFirst(model.name)](instance).then(function() { return previousInstance['set'+ Sequelize.Utils.uppercaseFirst(model.name)](instance).then(function() {
previousInstance = instance; previousInstance = instance;
}); });
} else { } else {
previousInstance = b = instance; previousInstance = b = instance;
...@@ -1290,32 +1251,28 @@ describe(Support.getTestDialectTeaser('Include'), function() { ...@@ -1290,32 +1251,28 @@ describe(Support.getTestDialectTeaser('Include'), function() {
Group.hasMany(GroupMember, {as: 'Memberships'}); Group.hasMany(GroupMember, {as: 'Memberships'});
return this.sequelize.sync({force: true}).then(function() { return this.sequelize.sync({force: true}).then(function() {
return Promise.props({ return Promise.all([
groups: Group.bulkCreate([ Group.bulkCreate([
{name: 'Developers'}, {name: 'Developers'},
{name: 'Designers'} {name: 'Designers'}
]).then(function() { ]).then(function() {
return Group.findAll(); return Group.findAll();
}), }),
ranks: Rank.bulkCreate([ Rank.bulkCreate([
{name: 'Admin', canInvite: 1, canRemove: 1}, {name: 'Admin', canInvite: 1, canRemove: 1},
{name: 'Member', canInvite: 1, canRemove: 0} {name: 'Member', canInvite: 1, canRemove: 0}
]).then(function() { ]).then(function() {
return Rank.findAll(); return Rank.findAll();
}), }),
tags: Tag.bulkCreate([ Tag.bulkCreate([
{name: 'A'}, {name: 'A'},
{name: 'B'}, {name: 'B'},
{name: 'C'} {name: 'C'}
]).then(function() { ]).then(function() {
return Tag.findAll(); return Tag.findAll();
}) })
}).then(function (results) { ]).spread(function (groups, ranks, tags) {
var groups = results.groups return Promise.resolve([0, 1, 2, 3, 4]).each(function (i) {
, ranks = results.ranks
, tags = results.tags;
return Promise.reduce([0, 1, 2, 3, 4], function (memo, i) {
return Promise.props({ return Promise.props({
user: User.create({name: 'FooBarzz'}), user: User.create({name: 'FooBarzz'}),
products: Product.bulkCreate([ products: Product.bulkCreate([
...@@ -1354,7 +1311,7 @@ describe(Support.getTestDialectTeaser('Include'), function() { ...@@ -1354,7 +1311,7 @@ describe(Support.getTestDialectTeaser('Include'), function() {
]) ])
); );
}); });
}, []); });
}).then(function () { }).then(function () {
return User.findAll({ return User.findAll({
include: [ include: [
...@@ -1383,7 +1340,7 @@ describe(Support.getTestDialectTeaser('Include'), function() { ...@@ -1383,7 +1340,7 @@ describe(Support.getTestDialectTeaser('Include'), function() {
expect(user.Products[0].Prices.length).to.equal(1); expect(user.Products[0].Prices.length).to.equal(1);
}); });
}); });
}); });
}); });
}); });
...@@ -1523,7 +1480,7 @@ describe(Support.getTestDialectTeaser('Include'), function() { ...@@ -1523,7 +1480,7 @@ describe(Support.getTestDialectTeaser('Include'), function() {
required: true required: true
} }
] ]
}).then(function(products) { }).then(function(products) {
expect(products).have.length(1); expect(products).have.length(1);
}); });
}); });
......
...@@ -6,8 +6,8 @@ var chai = require('chai') ...@@ -6,8 +6,8 @@ var chai = require('chai')
, Support = require(__dirname + '/../support') , Support = require(__dirname + '/../support')
, DataTypes = require(__dirname + '/../../../lib/data-types') , DataTypes = require(__dirname + '/../../../lib/data-types')
, datetime = require('chai-datetime') , datetime = require('chai-datetime')
, async = require('async')
, Promise = Sequelize.Promise , Promise = Sequelize.Promise
, dialect = Support.getTestDialect()
, _ = require('lodash'); , _ = require('lodash');
chai.use(datetime); chai.use(datetime);
...@@ -93,125 +93,115 @@ describe(Support.getTestDialectTeaser('Includes with schemas'), function() { ...@@ -93,125 +93,115 @@ describe(Support.getTestDialectTeaser('Includes with schemas'), function() {
Group.hasMany(GroupMember, {as: 'Memberships'}); Group.hasMany(GroupMember, {as: 'Memberships'});
return self.sequelize.sync({force: true}).then(function() { return self.sequelize.sync({force: true}).then(function() {
return Promise.props({ return Promise.all([
groups: Group.bulkCreate([ Group.bulkCreate([
{name: 'Developers'}, {name: 'Developers'},
{name: 'Designers'}, {name: 'Designers'},
{name: 'Managers'} {name: 'Managers'}
]).then(function() { ]),
return Group.findAll(); Company.bulkCreate([
}),
companies: Company.bulkCreate([
{name: 'Sequelize'}, {name: 'Sequelize'},
{name: 'Coca Cola'}, {name: 'Coca Cola'},
{name: 'Bonanza'}, {name: 'Bonanza'},
{name: 'NYSE'}, {name: 'NYSE'},
{name: 'Coshopr'} {name: 'Coshopr'}
]).then(function() { ]),
return Company.findAll(); Rank.bulkCreate([
}),
ranks: Rank.bulkCreate([
{name: 'Admin', canInvite: 1, canRemove: 1, canPost: 1}, {name: 'Admin', canInvite: 1, canRemove: 1, canPost: 1},
{name: 'Trustee', canInvite: 1, canRemove: 0, canPost: 1}, {name: 'Trustee', canInvite: 1, canRemove: 0, canPost: 1},
{name: 'Member', canInvite: 1, canRemove: 0, canPost: 0} {name: 'Member', canInvite: 1, canRemove: 0, canPost: 0}
]).then(function() { ]),
return Rank.findAll(); Tag.bulkCreate([
}),
tags: Tag.bulkCreate([
{name: 'A'}, {name: 'A'},
{name: 'B'}, {name: 'B'},
{name: 'C'}, {name: 'C'},
{name: 'D'}, {name: 'D'},
{name: 'E'} {name: 'E'}
]).then(function() { ])
return Tag.findAll(); ]).then(function() {
}) return Promise.all([
}).then(function (results) { Group.findAll(),
var groups = results.groups Company.findAll(),
, ranks = results.ranks Rank.findAll(),
, tags = results.tags Tag.findAll()
, companies = results.companies; ]);
}).spread(function (groups, companies, ranks, tags) {
return Promise.reduce(_.range(5), function (memo, i) { return Promise.resolve([0, 1, 2, 3, 4]).each(function (i) {
return Promise.props({ return Promise.all([
user: AccUser.create(), AccUser.create(),
products: Product.bulkCreate([ Product.bulkCreate([
{title: 'Chair'}, {title: 'Chair'},
{title: 'Desk'}, {title: 'Desk'},
{title: 'Bed'}, {title: 'Bed'},
{title: 'Pen'}, {title: 'Pen'},
{title: 'Monitor'} {title: 'Monitor'}
]).then(function(err) { ]).then(function() {
return Product.findAll(); return Product.findAll();
}) })
}).then(function (results) { ]).spread(function (user, products) {
var user = results.user var groupMembers = [
, products = results.products {AccUserId: user.id, GroupId: groups[0].id, RankId: ranks[0].id},
, groupMembers; {AccUserId: user.id, GroupId: groups[1].id, RankId: ranks[2].id}
];
groupMembers = [ if (i < 3) {
{AccUserId: user.id, GroupId: groups[0].id, RankId: ranks[0].id}, groupMembers.push({AccUserId: user.id, GroupId: groups[2].id, RankId: ranks[1].id});
{AccUserId: user.id, GroupId: groups[1].id, RankId: ranks[2].id} }
];
if (i < 3) { return Promise.join(
groupMembers.push({AccUserId: user.id, GroupId: groups[2].id, RankId: ranks[1].id}); GroupMember.bulkCreate(groupMembers),
} user.setProducts([
products[(i * 5) + 0],
return Promise.join( products[(i * 5) + 1],
GroupMember.bulkCreate(groupMembers), products[(i * 5) + 3]
user.setProducts([ ]),
products[(i * 5) + 0], Promise.join(
products[(i * 5) + 1], products[(i * 5) + 0].setTags([
products[(i * 5) + 3] tags[0],
]), tags[2]
Promise.join( ]),
products[(i * 5) + 0].setTags([ products[(i * 5) + 1].setTags([
tags[0], tags[1]
tags[2] ]),
]), products[(i * 5) + 0].setCategory(tags[1]),
products[(i * 5) + 1].setTags([ products[(i * 5) + 2].setTags([
tags[1] tags[0]
]), ]),
products[(i * 5) + 0].setCategory(tags[1]), products[(i * 5) + 3].setTags([
products[(i * 5) + 2].setTags([ tags[0]
tags[0] ])
]), ),
products[(i * 5) + 3].setTags([ Promise.join(
tags[0] products[(i * 5) + 0].setCompany(companies[4]),
]) products[(i * 5) + 1].setCompany(companies[3]),
), products[(i * 5) + 2].setCompany(companies[2]),
Promise.join( products[(i * 5) + 3].setCompany(companies[1]),
products[(i * 5) + 0].setCompany(companies[4]), products[(i * 5) + 4].setCompany(companies[0])
products[(i * 5) + 1].setCompany(companies[3]), ),
products[(i * 5) + 2].setCompany(companies[2]), Price.bulkCreate([
products[(i * 5) + 3].setCompany(companies[1]), {ProductId: products[(i * 5) + 0].id, value: 5},
products[(i * 5) + 4].setCompany(companies[0]) {ProductId: products[(i * 5) + 0].id, value: 10},
), {ProductId: products[(i * 5) + 1].id, value: 5},
Price.bulkCreate([ {ProductId: products[(i * 5) + 1].id, value: 10},
{ProductId: products[(i * 5) + 0].id, value: 5}, {ProductId: products[(i * 5) + 1].id, value: 15},
{ProductId: products[(i * 5) + 0].id, value: 10}, {ProductId: products[(i * 5) + 1].id, value: 20},
{ProductId: products[(i * 5) + 1].id, value: 5}, {ProductId: products[(i * 5) + 2].id, value: 20},
{ProductId: products[(i * 5) + 1].id, value: 10}, {ProductId: products[(i * 5) + 3].id, value: 20}
{ProductId: products[(i * 5) + 1].id, value: 15}, ])
{ProductId: products[(i * 5) + 1].id, value: 20}, );
{ProductId: products[(i * 5) + 2].id, value: 20}, });
{ProductId: products[(i * 5) + 3].id, value: 20} });
])
);
}); });
}, []);
});
}); });
}); });
}); });
}; };
}); });
it('should support an include with multiple different association types', function(done) { it('should support an include with multiple different association types', function() {
var self = this; var self = this;
self.sequelize.dropAllSchemas().then(function() { return self.sequelize.dropAllSchemas().then(function() {
self.sequelize.createSchema('account').then(function() { return self.sequelize.createSchema('account').then(function() {
var AccUser = self.sequelize.define('AccUser', {}, {schema: 'account'}) var AccUser = self.sequelize.define('AccUser', {}, {schema: 'account'})
, Product = self.sequelize.define('Product', { , Product = self.sequelize.define('Product', {
title: DataTypes.STRING title: DataTypes.STRING
...@@ -259,149 +249,111 @@ describe(Support.getTestDialectTeaser('Includes with schemas'), function() { ...@@ -259,149 +249,111 @@ describe(Support.getTestDialectTeaser('Includes with schemas'), function() {
GroupMember.belongsTo(Group); GroupMember.belongsTo(Group);
Group.hasMany(GroupMember, {as: 'Memberships'}); Group.hasMany(GroupMember, {as: 'Memberships'});
self.sequelize.sync({force: true}).done(function() { return self.sequelize.sync({force: true}).then(function() {
var count = 4 return Promise.all([
, i = -1; Group.bulkCreate([
{name: 'Developers'},
async.auto({ {name: 'Designers'}
groups: function(callback) { ]).then(function() {
Group.bulkCreate([ return Group.findAll();
{name: 'Developers'}, }),
{name: 'Designers'} Rank.bulkCreate([
]).done(function() { {name: 'Admin', canInvite: 1, canRemove: 1},
Group.findAll().done(callback); {name: 'Member', canInvite: 1, canRemove: 0}
}); ]).then(function() {
}, return Rank.findAll();
ranks: function(callback) { }),
Rank.bulkCreate([ Tag.bulkCreate([
{name: 'Admin', canInvite: 1, canRemove: 1}, {name: 'A'},
{name: 'Member', canInvite: 1, canRemove: 0} {name: 'B'},
]).done(function() { {name: 'C'}
Rank.findAll().done(callback); ]).then(function() {
return Tag.findAll();
})
]).spread(function(groups, ranks, tags) {
return Promise.resolve([0, 1, 2, 3, 4]).each(function (i) {
return Promise.all([
AccUser.create(),
Product.bulkCreate([
{title: 'Chair'},
{title: 'Desk'}
]).then(function() {
return Product.findAll();
})
]).spread(function(user, products) {
return Promise.all([
GroupMember.bulkCreate([
{AccUserId: user.id, GroupId: groups[0].id, RankId: ranks[0].id},
{AccUserId: user.id, GroupId: groups[1].id, RankId: ranks[1].id}
]),
user.setProducts([
products[(i * 2) + 0],
products[(i * 2) + 1]
]),
products[(i * 2) + 0].setTags([
tags[0],
tags[2]
]),
products[(i * 2) + 1].setTags([
tags[1]
]),
products[(i * 2) + 0].setCategory(tags[1]),
Price.bulkCreate([
{ProductId: products[(i * 2) + 0].id, value: 5},
{ProductId: products[(i * 2) + 0].id, value: 10},
{ProductId: products[(i * 2) + 1].id, value: 5},
{ProductId: products[(i * 2) + 1].id, value: 10},
{ProductId: products[(i * 2) + 1].id, value: 15},
{ProductId: products[(i * 2) + 1].id, value: 20}
])
]);
}); });
}, });
tags: function(callback) { }).then(function() {
Tag.bulkCreate([ return AccUser.findAll({
{name: 'A'}, include: [
{name: 'B'}, {model: GroupMember, as: 'Memberships', include: [
{name: 'C'} Group,
]).done(function() { Rank
Tag.findAll().done(callback); ]},
{model: Product, include: [
Tag,
{model: Tag, as: 'Category'},
Price
]}
],
order: [
[AccUser.rawAttributes.id, 'ASC']
]
}).then(function(users) {
users.forEach(function(user, a) {
expect(user.Memberships).to.be.ok;
user.Memberships.sort(sortById);
expect(user.Memberships.length).to.equal(2);
expect(user.Memberships[0].Group.name).to.equal('Developers');
expect(user.Memberships[0].Rank.canRemove).to.equal(1);
expect(user.Memberships[1].Group.name).to.equal('Designers');
expect(user.Memberships[1].Rank.canRemove).to.equal(0);
user.Products.sort(sortById);
expect(user.Products.length).to.equal(2);
expect(user.Products[0].Tags.length).to.equal(2);
expect(user.Products[1].Tags.length).to.equal(1);
expect(user.Products[0].Category).to.be.ok;
expect(user.Products[1].Category).not.to.be.ok;
expect(user.Products[0].Prices.length).to.equal(2);
expect(user.Products[1].Prices.length).to.equal(4);
}); });
}, });
loop: ['groups', 'ranks', 'tags', function(done, results) { });
var groups = results.groups
, ranks = results.ranks
, tags = results.tags;
async.whilst(
function() { return i < count; },
function(callback) {
i++;
async.auto({
user: function(callback) {
AccUser.create().done(callback);
},
memberships: ['user', function(callback, results) {
GroupMember.bulkCreate([
{AccUserId: results.user.id, GroupId: groups[0].id, RankId: ranks[0].id},
{AccUserId: results.user.id, GroupId: groups[1].id, RankId: ranks[1].id}
]).done(callback);
}],
products: function(callback) {
Product.bulkCreate([
{title: 'Chair'},
{title: 'Desk'}
]).done(function() {
Product.findAll().done(callback);
});
},
userProducts: ['user', 'products', function(callback, results) {
results.user.setProducts([
results.products[(i * 2) + 0],
results.products[(i * 2) + 1]
]).done(callback);
}],
productTags: ['products', function(callback, results) {
var chainer = new Sequelize.Utils.QueryChainer();
chainer.add(results.products[(i * 2) + 0].setTags([
tags[0],
tags[2]
]));
chainer.add(results.products[(i * 2) + 1].setTags([
tags[1]
]));
chainer.add(results.products[(i * 2) + 0].setCategory(tags[1]));
chainer.run().done(callback);
}],
prices: ['products', function(callback, results) {
Price.bulkCreate([
{ProductId: results.products[(i * 2) + 0].id, value: 5},
{ProductId: results.products[(i * 2) + 0].id, value: 10},
{ProductId: results.products[(i * 2) + 1].id, value: 5},
{ProductId: results.products[(i * 2) + 1].id, value: 10},
{ProductId: results.products[(i * 2) + 1].id, value: 15},
{ProductId: results.products[(i * 2) + 1].id, value: 20}
]).done(callback);
}]
}, callback);
},
function(err) {
expect(err).not.to.be.ok;
AccUser.findAll({
include: [
{model: GroupMember, as: 'Memberships', include: [
Group,
Rank
]},
{model: Product, include: [
Tag,
{model: Tag, as: 'Category'},
Price
]}
],
order: [
[AccUser.rawAttributes.id, 'ASC']
]
}).done(function(err, users) {
expect(err).not.to.be.ok;
users.forEach(function(user) {
expect(user.Memberships).to.be.ok;
user.Memberships.sort(sortById);
expect(user.Memberships.length).to.equal(2);
expect(user.Memberships[0].Group.name).to.equal('Developers');
expect(user.Memberships[0].Rank.canRemove).to.equal(1);
expect(user.Memberships[1].Group.name).to.equal('Designers');
expect(user.Memberships[1].Rank.canRemove).to.equal(0);
user.Products.sort(sortById);
expect(user.Products.length).to.equal(2);
expect(user.Products[0].Tags.length).to.equal(2);
expect(user.Products[1].Tags.length).to.equal(1);
expect(user.Products[0].Category).to.be.ok;
expect(user.Products[1].Category).not.to.be.ok;
expect(user.Products[0].Prices.length).to.equal(2);
expect(user.Products[1].Prices.length).to.equal(4);
done();
});
});
}
);
}]
}, done);
}); });
}); });
}); });
}); });
it('should support many levels of belongsTo', function(done) { it('should support many levels of belongsTo', function() {
var A = this.sequelize.define('a', {}, {schema: 'account'}) var A = this.sequelize.define('a', {}, {schema: 'account'})
, B = this.sequelize.define('b', {}, {schema: 'account'}) , B = this.sequelize.define('b', {}, {schema: 'account'})
, C = this.sequelize.define('c', {}, {schema: 'account'}) , C = this.sequelize.define('c', {}, {schema: 'account'})
...@@ -429,51 +381,32 @@ describe(Support.getTestDialectTeaser('Includes with schemas'), function() { ...@@ -429,51 +381,32 @@ describe(Support.getTestDialectTeaser('Includes with schemas'), function() {
H H
]; ];
this.sequelize.sync().done(function() { return this.sequelize.sync().then(function() {
async.auto({ return A.bulkCreate([
as: function(callback) { {}, {}, {}, {}, {}, {}, {}, {}
A.bulkCreate([ ]).then(function() {
{}, var previousInstance;
{}, return Promise.resolve(singles).each(function(model) {
{}, return model.create({}).then(function(instance) {
{}, if (previousInstance) {
{}, return previousInstance['set'+ Sequelize.Utils.uppercaseFirst(model.name)](instance).then(function() {
{}, previousInstance = instance;
{}, });
{} }
]).done(function() { previousInstance = b = instance;
A.findAll().done(callback); return void(0);
});
},
singleChain: function(callback) {
var previousInstance;
async.eachSeries(singles, function(model, callback) {
model.create({}).done(function(err, instance) {
if (previousInstance) {
previousInstance['set'+ Sequelize.Utils.uppercaseFirst(model.name)](instance).done(function() {
previousInstance = instance;
callback();
});
} else {
previousInstance = b = instance;
callback();
}
});
}, callback);
},
abs: ['as', 'singleChain', function(callback, results) {
var chainer = new Sequelize.Utils.QueryChainer();
results.as.forEach(function(a) {
chainer.add(a.setB(b));
}); });
});
chainer.run().done(callback); }).then(function() {
}] return A.findAll();
}, function() { }).then(function(as) {
var promises = [];
A.findAll({ as.forEach(function(a) {
promises.push(a.setB(b));
});
return Promise.all(promises);
}).then(function() {
return A.findAll({
include: [ include: [
{model: B, include: [ {model: B, include: [
{model: C, include: [ {model: C, include: [
...@@ -489,20 +422,17 @@ describe(Support.getTestDialectTeaser('Includes with schemas'), function() { ...@@ -489,20 +422,17 @@ describe(Support.getTestDialectTeaser('Includes with schemas'), function() {
]} ]}
]} ]}
] ]
}).done(function(err, as) { }).then(function(as) {
expect(err).not.to.be.ok;
expect(as.length).to.be.ok; expect(as.length).to.be.ok;
as.forEach(function(a) { as.forEach(function(a) {
expect(a.b.c.d.e.f.g.h).to.be.ok; expect(a.b.c.d.e.f.g.h).to.be.ok;
}); });
done();
}); });
}); });
}); });
}); });
it('should support ordering with only belongsTo includes', function(done) { it('should support ordering with only belongsTo includes', function() {
var User = this.sequelize.define('SpecialUser', {}, {schema: 'account'}) var User = this.sequelize.define('SpecialUser', {}, {schema: 'account'})
, Item = this.sequelize.define('Item', {'test': DataTypes.STRING}, {schema: 'account'}) , Item = this.sequelize.define('Item', {'test': DataTypes.STRING}, {schema: 'account'})
, Order = this.sequelize.define('Order', {'position': DataTypes.INTEGER}, {schema: 'account'}); , Order = this.sequelize.define('Order', {'position': DataTypes.INTEGER}, {schema: 'account'});
...@@ -511,64 +441,40 @@ describe(Support.getTestDialectTeaser('Includes with schemas'), function() { ...@@ -511,64 +441,40 @@ describe(Support.getTestDialectTeaser('Includes with schemas'), function() {
User.belongsTo(Item, {'as': 'itemB', foreignKey: 'itemB_id'}); User.belongsTo(Item, {'as': 'itemB', foreignKey: 'itemB_id'});
User.belongsTo(Order); User.belongsTo(Order);
this.sequelize.sync().done(function() { return this.sequelize.sync().then(function() {
async.auto({ return Promise.all([
users: function(callback) { User.bulkCreate([{}, {}, {}]),
User.bulkCreate([{}, {}, {}]).done(function() { Item.bulkCreate([
User.findAll().done(callback); {'test': 'abc'},
}); {'test': 'def'},
}, {'test': 'ghi'},
items: function(callback) { {'test': 'jkl'}
Item.bulkCreate([ ]),
{'test': 'abc'}, Order.bulkCreate([
{'test': 'def'}, {'position': 2},
{'test': 'ghi'}, {'position': 3},
{'test': 'jkl'} {'position': 1}
]).done(function() { ])
Item.findAll({order: ['id']}).done(callback); ]).then(function() {
}); return Promise.all([
}, User.findAll(),
orders: function(callback) { Item.findAll({order: ['id']}),
Order.bulkCreate([ Order.findAll({order: ['id']})
{'position': 2}, ]);
{'position': 3}, }).spread(function(users, items, orders) {
{'position': 1} return Promise.all([
]).done(function() { users[0].setItemA(items[0]),
Order.findAll({order: ['id']}).done(callback); users[0].setItemB(items[1]),
}); users[0].setOrder(orders[2]),
}, users[1].setItemA(items[2]),
associate: ['users', 'items', 'orders', function(callback, results) { users[1].setItemB(items[3]),
var chainer = new Sequelize.Utils.QueryChainer(); users[1].setOrder(orders[1]),
users[2].setItemA(items[0]),
var user1 = results.users[0]; users[2].setItemB(items[3]),
var user2 = results.users[1]; users[2].setOrder(orders[0])
var user3 = results.users[2]; ]);
}).spread(function() {
var item1 = results.items[0]; return User.findAll({
var item2 = results.items[1];
var item3 = results.items[2];
var item4 = results.items[3];
var order1 = results.orders[0];
var order2 = results.orders[1];
var order3 = results.orders[2];
chainer.add(user1.setItemA(item1));
chainer.add(user1.setItemB(item2));
chainer.add(user1.setOrder(order3));
chainer.add(user2.setItemA(item3));
chainer.add(user2.setItemB(item4));
chainer.add(user2.setOrder(order2));
chainer.add(user3.setItemA(item1));
chainer.add(user3.setItemB(item4));
chainer.add(user3.setOrder(order1));
chainer.run().done(callback);
}]
}, function() {
User.findAll({
'include': [ 'include': [
{'model': Item, 'as': 'itemA', where: {test: 'abc'}}, {'model': Item, 'as': 'itemA', where: {test: 'abc'}},
{'model': Item, 'as': 'itemB'}, {'model': Item, 'as': 'itemB'},
...@@ -576,23 +482,18 @@ describe(Support.getTestDialectTeaser('Includes with schemas'), function() { ...@@ -576,23 +482,18 @@ describe(Support.getTestDialectTeaser('Includes with schemas'), function() {
'order': [ 'order': [
[Order, 'position'] [Order, 'position']
] ]
}).done(function(err, as) { }).then(function(as) {
expect(err).not.to.be.ok;
expect(as.length).to.eql(2); expect(as.length).to.eql(2);
expect(as[0].itemA.test).to.eql('abc'); expect(as[0].itemA.test).to.eql('abc');
expect(as[1].itemA.test).to.eql('abc'); expect(as[1].itemA.test).to.eql('abc');
expect(as[0].Order.position).to.eql(1); expect(as[0].Order.position).to.eql(1);
expect(as[1].Order.position).to.eql(2); expect(as[1].Order.position).to.eql(2);
done();
}); });
}); });
}); });
}); });
it('should include attributes from through models', function(done) { it('should include attributes from through models', function() {
var Product = this.sequelize.define('Product', { var Product = this.sequelize.define('Product', {
title: DataTypes.STRING title: DataTypes.STRING
}, {schema: 'account'}) }, {schema: 'account'})
...@@ -606,44 +507,34 @@ describe(Support.getTestDialectTeaser('Includes with schemas'), function() { ...@@ -606,44 +507,34 @@ describe(Support.getTestDialectTeaser('Includes with schemas'), function() {
Product.hasMany(Tag, {through: ProductTag}); Product.hasMany(Tag, {through: ProductTag});
Tag.hasMany(Product, {through: ProductTag}); Tag.hasMany(Product, {through: ProductTag});
this.sequelize.sync({force: true}).done(function() { return this.sequelize.sync({force: true}).then(function() {
async.auto({ return Promise.all([
products: function(callback) { Product.bulkCreate([
Product.bulkCreate([ {title: 'Chair'},
{title: 'Chair'}, {title: 'Desk'},
{title: 'Desk'}, {title: 'Dress'}
{title: 'Dress'} ]),
]).done(function() { Tag.bulkCreate([
Product.findAll().done(callback); {name: 'A'},
}); {name: 'B'},
}, {name: 'C'}
tags: function(callback) { ])
Tag.bulkCreate([ ]).spread(function() {
{name: 'A'}, return Promise.all([
{name: 'B'}, Product.findAll(),
{name: 'C'} Tag.findAll()
]).done(function() { ]);
Tag.findAll().done(callback); }).spread(function(products, tags) {
}); return Promise.all([
}, products[0].addTag(tags[0], {priority: 1}),
productTags: ['products', 'tags', function(callback, results) { products[0].addTag(tags[1], {priority: 2}),
var chainer = new Sequelize.Utils.QueryChainer(); products[1].addTag(tags[1], {priority: 1}),
products[2].addTag(tags[0], {priority: 3}),
chainer.add(results.products[0].addTag(results.tags[0], {priority: 1})); products[2].addTag(tags[1], {priority: 1}),
chainer.add(results.products[0].addTag(results.tags[1], {priority: 2})); products[2].addTag(tags[2], {priority: 2})
]);
chainer.add(results.products[1].addTag(results.tags[1], {priority: 1})); }).spread(function() {
return Product.findAll({
chainer.add(results.products[2].addTag(results.tags[0], {priority: 3}));
chainer.add(results.products[2].addTag(results.tags[1], {priority: 1}));
chainer.add(results.products[2].addTag(results.tags[2], {priority: 2}));
chainer.run().done(callback);
}]
}, function(err) {
expect(err).not.to.be.ok;
Product.findAll({
include: [ include: [
{model: Tag} {model: Tag}
], ],
...@@ -651,63 +542,49 @@ describe(Support.getTestDialectTeaser('Includes with schemas'), function() { ...@@ -651,63 +542,49 @@ describe(Support.getTestDialectTeaser('Includes with schemas'), function() {
['id', 'ASC'], ['id', 'ASC'],
[Tag, 'id', 'ASC'] [Tag, 'id', 'ASC']
] ]
}).done(function(err, products) { }).then(function(products) {
expect(err).not.to.be.ok;
expect(products[0].Tags[0].ProductTag.priority).to.equal(1); expect(products[0].Tags[0].ProductTag.priority).to.equal(1);
expect(products[0].Tags[1].ProductTag.priority).to.equal(2); expect(products[0].Tags[1].ProductTag.priority).to.equal(2);
expect(products[1].Tags[0].ProductTag.priority).to.equal(1); expect(products[1].Tags[0].ProductTag.priority).to.equal(1);
expect(products[2].Tags[0].ProductTag.priority).to.equal(3); expect(products[2].Tags[0].ProductTag.priority).to.equal(3);
expect(products[2].Tags[1].ProductTag.priority).to.equal(1); expect(products[2].Tags[1].ProductTag.priority).to.equal(1);
expect(products[2].Tags[2].ProductTag.priority).to.equal(2); expect(products[2].Tags[2].ProductTag.priority).to.equal(2);
done();
}); });
}); });
}); });
}); });
it('should support a required belongsTo include', function(done) { it('should support a required belongsTo include', function() {
var User = this.sequelize.define('User', {}, {schema: 'account'}) var User = this.sequelize.define('User', {}, {schema: 'account'})
, Group = this.sequelize.define('Group', {}, {schema: 'account'}); , Group = this.sequelize.define('Group', {}, {schema: 'account'});
User.belongsTo(Group); User.belongsTo(Group);
this.sequelize.sync({force: true}).done(function() { return this.sequelize.sync({force: true}).then(function() {
async.auto({ return Promise.all([
groups: function(callback) { Group.bulkCreate([{}, {}]),
Group.bulkCreate([{}, {}]).done(function() { User.bulkCreate([{}, {}, {}])
Group.findAll().done(callback); ]).then(function() {
}); return Promise.all([
}, Group.findAll(),
users: function(callback) { User.findAll()
User.bulkCreate([{}, {}, {}]).done(function() { ]);
User.findAll().done(callback); }).spread(function(groups, users) {
}); return users[2].setGroup(groups[1]);
}, }).then(function() {
userGroups: ['users', 'groups', function(callback, results) { return User.findAll({
results.users[2].setGroup(results.groups[1]).done(callback);
}]
}, function(err) {
expect(err).not.to.be.ok;
User.findAll({
include: [ include: [
{model: Group, required: true} {model: Group, required: true}
] ]
}).done(function(err, users) { }).then(function(users) {
expect(err).not.to.be.ok;
expect(users.length).to.equal(1); expect(users.length).to.equal(1);
expect(users[0].Group).to.be.ok; expect(users[0].Group).to.be.ok;
done();
}); });
}); });
}); });
}); });
it('should be possible to extend the on clause with a where option on a belongsTo include', function(done) { it('should be possible to extend the on clause with a where option on a belongsTo include', function() {
var User = this.sequelize.define('User', {}, {schema: 'account'}) var User = this.sequelize.define('User', {}, {schema: 'account'})
, Group = this.sequelize.define('Group', { , Group = this.sequelize.define('Group', {
name: DataTypes.STRING name: DataTypes.STRING
...@@ -715,46 +592,38 @@ describe(Support.getTestDialectTeaser('Includes with schemas'), function() { ...@@ -715,46 +592,38 @@ describe(Support.getTestDialectTeaser('Includes with schemas'), function() {
User.belongsTo(Group); User.belongsTo(Group);
this.sequelize.sync({force: true}).done(function() { return this.sequelize.sync({force: true}).then(function() {
async.auto({ return Promise.all([
groups: function(callback) { Group.bulkCreate([
Group.bulkCreate([ {name: 'A'},
{name: 'A'}, {name: 'B'}
{name: 'B'} ]),
]).done(function() { User.bulkCreate([{}, {}])
Group.findAll().done(callback); ]).then(function() {
}); return Promise.all([
}, Group.findAll(),
users: function(callback) { User.findAll()
User.bulkCreate([{}, {}]).done(function() { ]);
User.findAll().done(callback); }).spread(function(groups, users) {
}); return Promise.all([
}, users[0].setGroup(groups[1]),
userGroups: ['users', 'groups', function(callback, results) { users[1].setGroup(groups[0])
var chainer = new Sequelize.Utils.QueryChainer(); ]);
chainer.add(results.users[0].setGroup(results.groups[1])); }).then(function() {
chainer.add(results.users[1].setGroup(results.groups[0])); return User.findAll({
chainer.run().done(callback);
}]
}, function(err) {
expect(err).not.to.be.ok;
User.findAll({
include: [ include: [
{model: Group, where: {name: 'A'}} {model: Group, where: {name: 'A'}}
] ]
}).done(function(err, users) { }).then(function(users) {
expect(err).not.to.be.ok;
expect(users.length).to.equal(1); expect(users.length).to.equal(1);
expect(users[0].Group).to.be.ok; expect(users[0].Group).to.be.ok;
expect(users[0].Group.name).to.equal('A'); expect(users[0].Group.name).to.equal('A');
done();
}); });
}); });
}); });
}); });
it('should be possible to extend the on clause with a where option on a belongsTo include', function(done) { it('should be possible to extend the on clause with a where option on a belongsTo include', function() {
var User = this.sequelize.define('User', {}, {schema: 'account'}) var User = this.sequelize.define('User', {}, {schema: 'account'})
, Group = this.sequelize.define('Group', { , Group = this.sequelize.define('Group', {
name: DataTypes.STRING name: DataTypes.STRING
...@@ -762,46 +631,38 @@ describe(Support.getTestDialectTeaser('Includes with schemas'), function() { ...@@ -762,46 +631,38 @@ describe(Support.getTestDialectTeaser('Includes with schemas'), function() {
User.belongsTo(Group); User.belongsTo(Group);
this.sequelize.sync({force: true}).done(function() { return this.sequelize.sync({force: true}).then(function() {
async.auto({ return Promise.all([
groups: function(callback) { Group.bulkCreate([
Group.bulkCreate([ {name: 'A'},
{name: 'A'}, {name: 'B'}
{name: 'B'} ]),
]).done(function() { User.bulkCreate([{}, {}])
Group.findAll().done(callback); ]).then(function() {
}); return Promise.all([
}, Group.findAll(),
users: function(callback) { User.findAll()
User.bulkCreate([{}, {}]).done(function() { ]);
User.findAll().done(callback); }).spread(function(groups, users) {
}); return Promise.all([
}, users[0].setGroup(groups[1]),
userGroups: ['users', 'groups', function(callback, results) { users[1].setGroup(groups[0])
var chainer = new Sequelize.Utils.QueryChainer(); ]);
chainer.add(results.users[0].setGroup(results.groups[1])); }).then(function() {
chainer.add(results.users[1].setGroup(results.groups[0])); return User.findAll({
chainer.run().done(callback);
}]
}, function(err) {
expect(err).not.to.be.ok;
User.findAll({
include: [ include: [
{model: Group, required: true} {model: Group, required: true}
] ]
}).done(function(err, users) { }).then(function(users) {
expect(err).not.to.be.ok;
users.forEach(function(user) { users.forEach(function(user) {
expect(user.Group).to.be.ok; expect(user.Group).to.be.ok;
}); });
done();
}); });
}); });
}); });
}); });
it('should be possible to define a belongsTo include as required with child hasMany with limit', function(done) { it('should be possible to define a belongsTo include as required with child hasMany with limit', function() {
var User = this.sequelize.define('User', {}, {schema: 'account'}) , Group = this.sequelize.define('Group', { var User = this.sequelize.define('User', {}, {schema: 'account'}) , Group = this.sequelize.define('Group', {
name: DataTypes.STRING name: DataTypes.STRING
}, {schema: 'account'}) }, {schema: 'account'})
...@@ -812,65 +673,49 @@ describe(Support.getTestDialectTeaser('Includes with schemas'), function() { ...@@ -812,65 +673,49 @@ describe(Support.getTestDialectTeaser('Includes with schemas'), function() {
User.belongsTo(Group); User.belongsTo(Group);
Group.hasMany(Category); Group.hasMany(Category);
this.sequelize.sync({force: true}).done(function() { return this.sequelize.sync({force: true}).then(function() {
async.auto({ return Promise.all([
groups: function(callback) { Group.bulkCreate([
Group.bulkCreate([ {name: 'A'},
{name: 'A'}, {name: 'B'}
{name: 'B'} ]),
]).done(function() { User.bulkCreate([{}, {}]),
Group.findAll().done(callback); Category.bulkCreate([{}, {}])
}); ]).then(function() {
}, return Promise.all([
users: function(callback) { Group.findAll(),
User.bulkCreate([{}, {}]).done(function() { User.findAll(),
User.findAll().done(callback); Category.findAll()
}); ]);
}, }).spread(function(groups, users, categories) {
categories: function(callback) { var promises = [
Category.bulkCreate([{}, {}]).done(function() { users[0].setGroup(groups[1]),
Category.findAll().done(callback); users[1].setGroup(groups[0])
}); ];
}, groups.forEach(function(group) {
userGroups: ['users', 'groups', function(callback, results) { promises.push(group.setCategories(categories));
var chainer = new Sequelize.Utils.QueryChainer(); });
chainer.add(results.users[0].setGroup(results.groups[1])); return Promise.all(promises);
chainer.add(results.users[1].setGroup(results.groups[0])); }).then(function() {
chainer.run().done(callback); return User.findAll({
}],
groupCategories: ['groups', 'categories', function(callback, results) {
var chainer = new Sequelize.Utils.QueryChainer();
results.groups.forEach(function(group) {
chainer.add(group.setCategories(results.categories));
});
chainer.run().done(callback);
}]
}, function(err) {
expect(err).not.to.be.ok;
User.findAll({
include: [ include: [
{model: Group, required: true, include: [ {model: Group, required: true, include: [
{model: Category} {model: Category}
]} ]}
], ],
limit: 1 limit: 1
}).done(function(err, users) { }).then(function(users) {
expect(err).not.to.be.ok;
expect(users.length).to.equal(1); expect(users.length).to.equal(1);
users.forEach(function(user) { users.forEach(function(user) {
expect(user.Group).to.be.ok; expect(user.Group).to.be.ok;
expect(user.Group.Categories).to.be.ok; expect(user.Group.Categories).to.be.ok;
}); });
done();
}); });
}); });
}); });
}); });
it('should be possible to define a belongsTo include as required with child hasMany with limit and aliases', function(done) { it('should be possible to define a belongsTo include as required with child hasMany with limit and aliases', function() {
var User = this.sequelize.define('User', {}, {schema: 'account'}) var User = this.sequelize.define('User', {}, {schema: 'account'})
, Group = this.sequelize.define('Group', { , Group = this.sequelize.define('Group', {
name: DataTypes.STRING name: DataTypes.STRING
...@@ -882,65 +727,49 @@ describe(Support.getTestDialectTeaser('Includes with schemas'), function() { ...@@ -882,65 +727,49 @@ describe(Support.getTestDialectTeaser('Includes with schemas'), function() {
User.belongsTo(Group, {as: 'Team'}); User.belongsTo(Group, {as: 'Team'});
Group.hasMany(Category, {as: 'Tags'}); Group.hasMany(Category, {as: 'Tags'});
this.sequelize.sync({force: true}).done(function() { return this.sequelize.sync({force: true}).then(function() {
async.auto({ return Promise.all([
groups: function(callback) { Group.bulkCreate([
Group.bulkCreate([ {name: 'A'},
{name: 'A'}, {name: 'B'}
{name: 'B'} ]),
]).done(function() { User.bulkCreate([{}, {}]),
Group.findAll().done(callback); Category.bulkCreate([{}, {}])
}); ]).then(function() {
}, return Promise.all([
users: function(callback) { Group.findAll(),
User.bulkCreate([{}, {}]).done(function() { User.findAll(),
User.findAll().done(callback); Category.findAll()
}); ]);
}, }).spread(function(groups, users, categories) {
categories: function(callback) { var promises = [
Category.bulkCreate([{}, {}]).done(function() { users[0].setTeam(groups[1]),
Category.findAll().done(callback); users[1].setTeam(groups[0])
}); ];
}, groups.forEach(function(group) {
userGroups: ['users', 'groups', function(callback, results) { promises.push(group.setTags(categories));
var chainer = new Sequelize.Utils.QueryChainer(); });
chainer.add(results.users[0].setTeam(results.groups[1])); return Promise.all(promises);
chainer.add(results.users[1].setTeam(results.groups[0])); }).then(function() {
chainer.run().done(callback); return User.findAll({
}],
groupCategories: ['groups', 'categories', function(callback, results) {
var chainer = new Sequelize.Utils.QueryChainer();
results.groups.forEach(function(group) {
chainer.add(group.setTags(results.categories));
});
chainer.run().done(callback);
}]
}, function(err) {
expect(err).not.to.be.ok;
User.findAll({
include: [ include: [
{model: Group, required: true, as: 'Team', include: [ {model: Group, required: true, as: 'Team', include: [
{model: Category, as: 'Tags'} {model: Category, as: 'Tags'}
]} ]}
], ],
limit: 1 limit: 1
}).done(function(err, users) { }).then(function(users) {
expect(err).not.to.be.ok;
expect(users.length).to.equal(1); expect(users.length).to.equal(1);
users.forEach(function(user) { users.forEach(function(user) {
expect(user.Team).to.be.ok; expect(user.Team).to.be.ok;
expect(user.Team.Tags).to.be.ok; expect(user.Team.Tags).to.be.ok;
}); });
done();
}); });
}); });
}); });
}); });
it('should be possible to define a belongsTo include as required with child hasMany which is not required with limit', function(done) { it('should be possible to define a belongsTo include as required with child hasMany which is not required with limit', function() {
var User = this.sequelize.define('User', {}, {schema: 'account'}) var User = this.sequelize.define('User', {}, {schema: 'account'})
, Group = this.sequelize.define('Group', { , Group = this.sequelize.define('Group', {
name: DataTypes.STRING name: DataTypes.STRING
...@@ -952,65 +781,49 @@ describe(Support.getTestDialectTeaser('Includes with schemas'), function() { ...@@ -952,65 +781,49 @@ describe(Support.getTestDialectTeaser('Includes with schemas'), function() {
User.belongsTo(Group); User.belongsTo(Group);
Group.hasMany(Category); Group.hasMany(Category);
this.sequelize.sync({force: true}).done(function() { return this.sequelize.sync({force: true}).then(function() {
async.auto({ return Promise.all([
groups: function(callback) { Group.bulkCreate([
Group.bulkCreate([ {name: 'A'},
{name: 'A'}, {name: 'B'}
{name: 'B'} ]),
]).done(function() { User.bulkCreate([{}, {}]),
Group.findAll().done(callback); Category.bulkCreate([{}, {}])
}); ]).then(function() {
}, return Promise.all([
users: function(callback) { Group.findAll(),
User.bulkCreate([{}, {}]).done(function() { User.findAll(),
User.findAll().done(callback); Category.findAll()
}); ]);
}, }).spread(function (groups, users, categories) {
categories: function(callback) { var promises = [
Category.bulkCreate([{}, {}]).done(function() { users[0].setGroup(groups[1]),
Category.findAll().done(callback); users[1].setGroup(groups[0])
}); ];
}, groups.forEach(function(group) {
userGroups: ['users', 'groups', function(callback, results) { promises.push(group.setCategories(categories));
var chainer = new Sequelize.Utils.QueryChainer(); });
chainer.add(results.users[0].setGroup(results.groups[1])); return Promise.all(promises);
chainer.add(results.users[1].setGroup(results.groups[0])); }).then(function() {
chainer.run().done(callback); return User.findAll({
}],
groupCategories: ['groups', 'categories', function(callback, results) {
var chainer = new Sequelize.Utils.QueryChainer();
results.groups.forEach(function(group) {
chainer.add(group.setCategories(results.categories));
});
chainer.run().done(callback);
}]
}, function(err) {
expect(err).not.to.be.ok;
User.findAll({
include: [ include: [
{model: Group, required: true, include: [ {model: Group, required: true, include: [
{model: Category, required: false} {model: Category, required: false}
]} ]}
], ],
limit: 1 limit: 1
}).done(function(err, users) { }).then(function(users) {
expect(err).not.to.be.ok;
expect(users.length).to.equal(1); expect(users.length).to.equal(1);
users.forEach(function(user) { users.forEach(function(user) {
expect(user.Group).to.be.ok; expect(user.Group).to.be.ok;
expect(user.Group.Categories).to.be.ok; expect(user.Group.Categories).to.be.ok;
}); });
done();
}); });
}); });
}); });
}); });
it('should be possible to extend the on clause with a where option on a hasOne include', function(done) { it('should be possible to extend the on clause with a where option on a hasOne include', function() {
var User = this.sequelize.define('User', {}, {schema: 'account'}) var User = this.sequelize.define('User', {}, {schema: 'account'})
, Project = this.sequelize.define('Project', { , Project = this.sequelize.define('Project', {
title: DataTypes.STRING title: DataTypes.STRING
...@@ -1018,46 +831,38 @@ describe(Support.getTestDialectTeaser('Includes with schemas'), function() { ...@@ -1018,46 +831,38 @@ describe(Support.getTestDialectTeaser('Includes with schemas'), function() {
User.hasOne(Project, {as: 'LeaderOf'}); User.hasOne(Project, {as: 'LeaderOf'});
this.sequelize.sync({force: true}).done(function() { return this.sequelize.sync({force: true}).then(function() {
async.auto({ return Promise.all([
projects: function(callback) { Project.bulkCreate([
Project.bulkCreate([ {title: 'Alpha'},
{title: 'Alpha'}, {title: 'Beta'}
{title: 'Beta'} ]),
]).done(function() { User.bulkCreate([{}, {}])
Project.findAll().done(callback); ]).then(function() {
}); return Promise.all([
}, Project.findAll(),
users: function(callback) { User.findAll()
User.bulkCreate([{}, {}]).done(function() { ]);
User.findAll().done(callback); }).spread(function(projects, users) {
}); return Promise.all([
}, users[1].setLeaderOf(projects[1]),
userProjects: ['users', 'projects', function(callback, results) { users[0].setLeaderOf(projects[0])
var chainer = new Sequelize.Utils.QueryChainer(); ]);
chainer.add(results.users[1].setLeaderOf(results.projects[1])); }).then(function() {
chainer.add(results.users[0].setLeaderOf(results.projects[0])); return User.findAll({
chainer.run().done(callback);
}]
}, function(err) {
expect(err).not.to.be.ok;
User.findAll({
include: [ include: [
{model: Project, as: 'LeaderOf', where: {title: 'Beta'}} {model: Project, as: 'LeaderOf', where: {title: 'Beta'}}
] ]
}).done(function(err, users) { }).then(function(users) {
expect(err).not.to.be.ok;
expect(users.length).to.equal(1); expect(users.length).to.equal(1);
expect(users[0].LeaderOf).to.be.ok; expect(users[0].LeaderOf).to.be.ok;
expect(users[0].LeaderOf.title).to.equal('Beta'); expect(users[0].LeaderOf.title).to.equal('Beta');
done();
}); });
}); });
}); });
}); });
it('should be possible to extend the on clause with a where option on a hasMany include with a through model', function(done) { it('should be possible to extend the on clause with a where option on a hasMany include with a through model', function() {
var Product = this.sequelize.define('Product', { var Product = this.sequelize.define('Product', {
title: DataTypes.STRING title: DataTypes.STRING
}, {schema: 'account'}) }, {schema: 'account'})
...@@ -1071,60 +876,46 @@ describe(Support.getTestDialectTeaser('Includes with schemas'), function() { ...@@ -1071,60 +876,46 @@ describe(Support.getTestDialectTeaser('Includes with schemas'), function() {
Product.hasMany(Tag, {through: ProductTag}); Product.hasMany(Tag, {through: ProductTag});
Tag.hasMany(Product, {through: ProductTag}); Tag.hasMany(Product, {through: ProductTag});
this.sequelize.sync({force: true}).done(function() { return this.sequelize.sync({force: true}).then(function() {
async.auto({ return Promise.all([
products: function(callback) { Product.bulkCreate([
Product.bulkCreate([ {title: 'Chair'},
{title: 'Chair'}, {title: 'Desk'},
{title: 'Desk'}, {title: 'Dress'}
{title: 'Dress'} ]),
]).done(function() { Tag.bulkCreate([
Product.findAll().done(callback); {name: 'A'},
}); {name: 'B'},
}, {name: 'C'}
tags: function(callback) { ])
Tag.bulkCreate([ ]).then(function() {
{name: 'A'}, return Promise.all([
{name: 'B'}, Product.findAll(),
{name: 'C'} Tag.findAll()
]).done(function() { ]);
Tag.findAll().done(callback); }).spread(function(products, tags) {
}); return Promise.all([
}, products[0].addTag(tags[0], {priority: 1}),
productTags: ['products', 'tags', function(callback, results) { products[0].addTag(tags[1], {priority: 2}),
var chainer = new Sequelize.Utils.QueryChainer(); products[1].addTag(tags[1], {priority: 1}),
products[2].addTag(tags[0], {priority: 3}),
chainer.add(results.products[0].addTag(results.tags[0], {priority: 1})); products[2].addTag(tags[1], {priority: 1}),
chainer.add(results.products[0].addTag(results.tags[1], {priority: 2})); products[2].addTag(tags[2], {priority: 2})
]);
chainer.add(results.products[1].addTag(results.tags[1], {priority: 1})); }).then(function() {
return Product.findAll({
chainer.add(results.products[2].addTag(results.tags[0], {priority: 3}));
chainer.add(results.products[2].addTag(results.tags[1], {priority: 1}));
chainer.add(results.products[2].addTag(results.tags[2], {priority: 2}));
chainer.run().done(callback);
}]
}, function(err) {
expect(err).not.to.be.ok;
Product.findAll({
include: [ include: [
{model: Tag, where: {name: 'C'}} {model: Tag, where: {name: 'C'}}
] ]
}).done(function(err, products) { }).then(function(products) {
expect(err).not.to.be.ok;
expect(products.length).to.equal(1); expect(products.length).to.equal(1);
expect(products[0].Tags.length).to.equal(1); expect(products[0].Tags.length).to.equal(1);
done();
}); });
}); });
}); });
}); });
it('should be possible to extend the on clause with a where option on nested includes', function(done) { it('should be possible to extend the on clause with a where option on nested includes', function() {
var User = this.sequelize.define('User', { var User = this.sequelize.define('User', {
name: DataTypes.STRING name: DataTypes.STRING
}, {schema: 'account'}) }, {schema: 'account'})
...@@ -1174,134 +965,95 @@ describe(Support.getTestDialectTeaser('Includes with schemas'), function() { ...@@ -1174,134 +965,95 @@ describe(Support.getTestDialectTeaser('Includes with schemas'), function() {
GroupMember.belongsTo(Group); GroupMember.belongsTo(Group);
Group.hasMany(GroupMember, {as: 'Memberships'}); Group.hasMany(GroupMember, {as: 'Memberships'});
this.sequelize.sync({force: true}).done(function() { return this.sequelize.sync({force: true}).then(function() {
var count = 4 return Promise.all([
, i = -1; Group.bulkCreate([
{name: 'Developers'},
async.auto({ {name: 'Designers'}
groups: function(callback) { ]),
Group.bulkCreate([ Rank.bulkCreate([
{name: 'Developers'}, {name: 'Admin', canInvite: 1, canRemove: 1},
{name: 'Designers'} {name: 'Member', canInvite: 1, canRemove: 0}
]).done(function() { ]),
Group.findAll().done(callback); Tag.bulkCreate([
}); {name: 'A'},
}, {name: 'B'},
ranks: function(callback) { {name: 'C'}
Rank.bulkCreate([ ])
{name: 'Admin', canInvite: 1, canRemove: 1}, ]).then(function() {
{name: 'Member', canInvite: 1, canRemove: 0} return Promise.all([
]).done(function() { Group.findAll(),
Rank.findAll().done(callback); Rank.findAll(),
Tag.findAll()
]);
}).spread(function(groups, ranks, tags) {
return Promise.resolve([0, 1, 2, 3, 4]).each(function (i) {
return Promise.all([
User.create({name: 'FooBarzz'}),
Product.bulkCreate([
{title: 'Chair'},
{title: 'Desk'}
]).then(function() {
return Product.findAll();
})
]).spread(function(user, products) {
return Promise.all([
GroupMember.bulkCreate([
{UserId: user.id, GroupId: groups[0].id, RankId: ranks[0].id},
{UserId: user.id, GroupId: groups[1].id, RankId: ranks[1].id}
]),
user.setProducts([
products[(i * 2) + 0],
products[(i * 2) + 1]
]),
products[(i * 2) + 0].setTags([
tags[0],
tags[2]
]),
products[(i * 2) + 1].setTags([
tags[1]
]),
products[(i * 2) + 0].setCategory(tags[1]),
Price.bulkCreate([
{ProductId: products[(i * 2) + 0].id, value: 5},
{ProductId: products[(i * 2) + 0].id, value: 10},
{ProductId: products[(i * 2) + 1].id, value: 5},
{ProductId: products[(i * 2) + 1].id, value: 10},
{ProductId: products[(i * 2) + 1].id, value: 15},
{ProductId: products[(i * 2) + 1].id, value: 20}
])
]);
}); });
}, });
tags: function(callback) { }).then(function(){
Tag.bulkCreate([ return User.findAll({
{name: 'A'}, include: [
{name: 'B'}, {model: GroupMember, as: 'Memberships', include: [
{name: 'C'} Group,
]).done(function() { {model: Rank, where: {name: 'Admin'}}
Tag.findAll().done(callback); ]},
{model: Product, include: [
Tag,
{model: Tag, as: 'Category'},
{model: Price, where: {
value: {
gt: 15
}
}}
]}
],
order: [
['id', 'ASC']
]
}).then(function(users) {
users.forEach(function(user) {
expect(user.Memberships.length).to.equal(1);
expect(user.Memberships[0].Rank.name).to.equal('Admin');
expect(user.Products.length).to.equal(1);
expect(user.Products[0].Prices.length).to.equal(1);
}); });
}, });
loop: ['groups', 'ranks', 'tags', function(done, results) { });
var groups = results.groups
, ranks = results.ranks
, tags = results.tags;
async.whilst(
function() { return i < count; },
function(callback) {
i++;
async.auto({
user: function(callback) {
User.create({name: 'FooBarzz'}).done(callback);
},
memberships: ['user', function(callback, results) {
GroupMember.bulkCreate([
{UserId: results.user.id, GroupId: groups[0].id, RankId: ranks[0].id},
{UserId: results.user.id, GroupId: groups[1].id, RankId: ranks[1].id}
]).done(callback);
}],
products: function(callback) {
Product.bulkCreate([
{title: 'Chair'},
{title: 'Desk'}
]).done(function() {
Product.findAll().done(callback);
});
},
userProducts: ['user', 'products', function(callback, results) {
results.user.setProducts([
results.products[(i * 2) + 0],
results.products[(i * 2) + 1]
]).done(callback);
}],
productTags: ['products', function(callback, results) {
var chainer = new Sequelize.Utils.QueryChainer();
chainer.add(results.products[(i * 2) + 0].setTags([
tags[0],
tags[2]
]));
chainer.add(results.products[(i * 2) + 1].setTags([
tags[1]
]));
chainer.add(results.products[(i * 2) + 0].setCategory(tags[1]));
chainer.run().done(callback);
}],
prices: ['products', function(callback, results) {
Price.bulkCreate([
{ProductId: results.products[(i * 2) + 0].id, value: 5},
{ProductId: results.products[(i * 2) + 0].id, value: 10},
{ProductId: results.products[(i * 2) + 1].id, value: 5},
{ProductId: results.products[(i * 2) + 1].id, value: 10},
{ProductId: results.products[(i * 2) + 1].id, value: 15},
{ProductId: results.products[(i * 2) + 1].id, value: 20}
]).done(callback);
}]
}, callback);
},
function(err) {
expect(err).not.to.be.ok;
User.findAll({
include: [
{model: GroupMember, as: 'Memberships', include: [
Group,
{model: Rank, where: {name: 'Admin'}}
]},
{model: Product, include: [
Tag,
{model: Tag, as: 'Category'},
{model: Price, where: {
value: {
gt: 15
}
}}
]}
],
order: [
['id', 'ASC']
]
}).done(function(err, users) {
expect(err).not.to.be.ok;
users.forEach(function(user) {
expect(user.Memberships.length).to.equal(1);
expect(user.Memberships[0].Rank.name).to.equal('Admin');
expect(user.Products.length).to.equal(1);
expect(user.Products[0].Prices.length).to.equal(1);
});
done();
});
}
);
}]
}, done);
}); });
}); });
...@@ -1432,7 +1184,7 @@ describe(Support.getTestDialectTeaser('Includes with schemas'), function() { ...@@ -1432,7 +1184,7 @@ describe(Support.getTestDialectTeaser('Includes with schemas'), function() {
}); });
}); });
it.skip('should support including date fields, with the correct timeszone', function() { it('should support including date fields, with the correct timeszone', function() {
var User = this.sequelize.define('user', { var User = this.sequelize.define('user', {
dateField: Sequelize.DATE dateField: Sequelize.DATE
}, {timestamps: false, schema: 'account'}) }, {timestamps: false, schema: 'account'})
...@@ -1453,8 +1205,13 @@ describe(Support.getTestDialectTeaser('Includes with schemas'), function() { ...@@ -1453,8 +1205,13 @@ describe(Support.getTestDialectTeaser('Includes with schemas'), function() {
}, },
include: [Group] include: [Group]
}).then(function(users) { }).then(function(users) {
expect(users[0].dateField.getTime()).to.equal(Date.UTC(2014, 1, 20)); if (dialect === 'sqlite') {
expect(users[0].groups[0].dateField.getTime()).to.equal(Date.UTC(2014, 1, 20)); expect(new Date(users[0].dateField).getTime()).to.equal(Date.UTC(2014, 1, 20));
expect(new Date(users[0].groups[0].dateField).getTime()).to.equal(Date.UTC(2014, 1, 20));
} else {
expect(users[0].dateField.getTime()).to.equal(Date.UTC(2014, 1, 20));
expect(users[0].groups[0].dateField.getTime()).to.equal(Date.UTC(2014, 1, 20));
}
}); });
}); });
}); });
......
...@@ -341,11 +341,11 @@ describe(Support.getTestDialectTeaser('Instance'), function() { ...@@ -341,11 +341,11 @@ describe(Support.getTestDialectTeaser('Instance'), function() {
it('should still work right with other concurrent increments', function() { it('should still work right with other concurrent increments', function() {
var self = this; var self = this;
return this.User.find(1).then(function(user1) { return this.User.find(1).then(function(user1) {
return user1.increment(['aNumber'], { by: 2 }).then(function() { return this.sequelize.Promise.all([
return user1.increment(['aNumber'], { by: 2 }); user1.increment(['aNumber'], { by: 2 }),
}).then(function() { user1.increment(['aNumber'], { by: 2 }),
return user1.increment(['aNumber'], { by: 2 }); user1.increment(['aNumber'], { by: 2 })
}).then(function() { ]).then(function() {
return self.User.find(1).then(function(user2) { return self.User.find(1).then(function(user2) {
expect(user2.aNumber).to.equal(6); expect(user2.aNumber).to.equal(6);
}); });
...@@ -468,11 +468,11 @@ describe(Support.getTestDialectTeaser('Instance'), function() { ...@@ -468,11 +468,11 @@ describe(Support.getTestDialectTeaser('Instance'), function() {
it('should still work right with other concurrent increments', function() { it('should still work right with other concurrent increments', function() {
var self = this; var self = this;
return this.User.find(1).then(function(user1) { return this.User.find(1).then(function(user1) {
return user1.decrement(['aNumber'], { by: 2 }).then(function() { return this.sequelize.Promise.all([
return user1.decrement(['aNumber'], { by: 2 }); user1.decrement(['aNumber'], { by: 2 }),
}).then(function() { user1.decrement(['aNumber'], { by: 2 }),
return user1.decrement(['aNumber'], { by: 2 }); user1.decrement(['aNumber'], { by: 2 })
}).then(function() { ]).then(function() {
return self.User.find(1).then(function(user2) { return self.User.find(1).then(function(user2) {
expect(user2.aNumber).to.equal(-6); expect(user2.aNumber).to.equal(-6);
}); });
......
...@@ -11,7 +11,6 @@ var chai = require('chai') ...@@ -11,7 +11,6 @@ var chai = require('chai')
, datetime = require('chai-datetime') , datetime = require('chai-datetime')
, _ = require('lodash') , _ = require('lodash')
, moment = require('moment') , moment = require('moment')
, async = require('async')
, current = Support.sequelize; , current = Support.sequelize;
chai.use(datetime); chai.use(datetime);
...@@ -2348,12 +2347,13 @@ describe(Support.getTestDialectTeaser('Model'), function() { ...@@ -2348,12 +2347,13 @@ describe(Support.getTestDialectTeaser('Model'), function() {
}); });
if (dialect !== 'sqlite' && current.dialect.supports.transactions) { if (dialect !== 'sqlite' && current.dialect.supports.transactions) {
it('supports multiple async transactions', function(done) { it('supports multiple async transactions', function() {
this.timeout(25000); this.timeout(25000);
var self = this;
return Support.prepareTransactionTest(this.sequelize).bind({}).then(function(sequelize) { return Support.prepareTransactionTest(this.sequelize).bind({}).then(function(sequelize) {
var User = sequelize.define('User', { username: Sequelize.STRING }); var User = sequelize.define('User', { username: Sequelize.STRING });
var testAsync = function(i, done) { var testAsync = function() {
sequelize.transaction().then(function(t) { return sequelize.transaction().then(function(t) {
return User.create({ return User.create({
username: 'foo' username: 'foo'
}, { }, {
...@@ -2380,14 +2380,19 @@ describe(Support.getTestDialectTeaser('Model'), function() { ...@@ -2380,14 +2380,19 @@ describe(Support.getTestDialectTeaser('Model'), function() {
}); });
}).then(function(t) { }).then(function(t) {
return t.rollback(); return t.rollback();
}).nodeify(done); });
}; };
User.sync({ force: true }).then(function() { return User.sync({ force: true }).then(function() {
var tasks = []; var tasks = [];
for (var i = 0; i < 1000; i++) { for (var i = 0; i < 1000; i++) {
tasks.push(testAsync.bind(this, i)); tasks.push(testAsync.bind(this));
} }
async.parallelLimit(tasks, (sequelize.config.pool && sequelize.config.pool.max || 5) - 1, done); // Needs to be one less than 1 else the non transaction query won't ever get a connection return self.sequelize.Promise.resolve(tasks).map(function(entry) {
return entry();
}, {
// Needs to be one less than ??? else the non transaction query won't ever get a connection
concurrency: (sequelize.config.pool && sequelize.config.pool.max || 5) - 1
});
}); });
}); });
}); });
......
...@@ -924,12 +924,12 @@ describe(Support.getTestDialectTeaser('Model'), function() { ...@@ -924,12 +924,12 @@ describe(Support.getTestDialectTeaser('Model'), function() {
}); });
}); });
it('can omit autoincremental columns', function(done) { it('can omit autoincremental columns', function() {
var self = this var self = this
, data = { title: 'Iliad' } , data = { title: 'Iliad' }
, dataTypes = [Sequelize.INTEGER, Sequelize.BIGINT] , dataTypes = [Sequelize.INTEGER, Sequelize.BIGINT]
, chain = new Sequelize.Utils.QueryChainer() , sync = []
, chain2 = new Sequelize.Utils.QueryChainer() , promises = []
, books = []; , books = [];
dataTypes.forEach(function(dataType, index) { dataTypes.forEach(function(dataType, index) {
...@@ -940,21 +940,18 @@ describe(Support.getTestDialectTeaser('Model'), function() { ...@@ -940,21 +940,18 @@ describe(Support.getTestDialectTeaser('Model'), function() {
}); });
books.forEach(function(b) { books.forEach(function(b) {
chain.add(b.sync({ force: true })); sync.push(b.sync({ force: true }));
}); });
chain.run().then(function() { return Promise.all(sync).then(function() {
books.forEach(function(b) { books.forEach(function(b, index) {
chain2.add(b.create(data)); promises.push(b.create(data).then(function(book) {
});
chain2.run().then(function(results) {
results.forEach(function(book, index) {
expect(book.title).to.equal(data.title); expect(book.title).to.equal(data.title);
expect(book.author).to.equal(data.author); expect(book.author).to.equal(data.author);
expect(books[index].rawAttributes.id.type instanceof dataTypes[index]).to.be.ok; expect(books[index].rawAttributes.id.type instanceof dataTypes[index]).to.be.ok;
}); }));
done();
}); });
return Promise.all(promises);
}); });
}); });
......
...@@ -11,7 +11,6 @@ var chai = require('chai') ...@@ -11,7 +11,6 @@ var chai = require('chai')
, datetime = require('chai-datetime') , datetime = require('chai-datetime')
, promised = require('chai-as-promised') , promised = require('chai-as-promised')
, _ = require('lodash') , _ = require('lodash')
, async = require('async')
, current = Support.sequelize; , current = Support.sequelize;
chai.use(promised); chai.use(promised);
...@@ -760,104 +759,71 @@ describe(Support.getTestDialectTeaser('Model'), function() { ...@@ -760,104 +759,71 @@ describe(Support.getTestDialectTeaser('Model'), function() {
this.Tag = this.sequelize.define('Tag', { name: Sequelize.STRING }); this.Tag = this.sequelize.define('Tag', { name: Sequelize.STRING });
}); });
it('returns the associated models when using through as string and alias', function(done) { it('returns the associated models when using through as string and alias', function() {
var self = this; var self = this;
this.Product.hasMany(this.Tag, {as: 'tags', through: 'product_tag'}); this.Product.hasMany(this.Tag, {as: 'tags', through: 'product_tag'});
this.Tag.hasMany(this.Product, {as: 'products', through: 'product_tag'}); this.Tag.hasMany(this.Product, {as: 'products', through: 'product_tag'});
this.sequelize.sync().done(function() { return this.sequelize.sync().then(function() {
async.auto({ return Promise.all([
createProducts: function(callback) { self.Product.bulkCreate([
self.Product.bulkCreate([ {title: 'Chair'},
{title: 'Chair'}, {title: 'Desk'},
{title: 'Desk'}, {title: 'Handbag'},
{title: 'Handbag'}, {title: 'Dress'},
{title: 'Dress'}, {title: 'Jan'}
{title: 'Jan'} ]),
]).done(callback); self.Tag.bulkCreate([
}, {name: 'Furniture'},
// bulkCreate doesn't include id for some reason, not going to fix tis now {name: 'Clothing'},
products: ['createProducts', function(callback) { {name: 'People'}
self.Product.findAll().done(callback); ])
}], ]).then(function() {
createTags: function(callback) { return Promise.all([
self.Tag.bulkCreate([ self.Product.findAll(),
{name: 'Furniture'}, self.Tag.findAll()
{name: 'Clothing'}, ]);
{name: 'People'} }).spread(function(products, tags) {
]).done(callback); self.products = products;
}, self.tags = tags;
tags: ['createTags', function(callback) { return Promise.all([
self.Tag.findAll().done(callback); products[0].setTags([tags[0], tags[1]]),
}] products[1].addTag(tags[0]),
}, function(err, results) { products[2].addTag(tags[1]),
expect(err).not.to.exist; products[3].setTags([tags[1]]),
products[4].setTags([tags[2]])
var products = results.products ]).then(function() {
, tags = results.tags; return Promise.all([
self.Tag.find({
async.parallel([ where: {
function(callback) { id: tags[0].id
products[0].setTags([tags[0], tags[1]]).done(callback); },
}, include: [
function(callback) { {model: self.Product, as: 'products'}
products[1].addTag(tags[0]).done(callback); ]
}, }).then(function(tag) {
function(callback) { expect(tag).to.exist;
products[2].addTag(tags[1]).done(callback); expect(tag.products.length).to.equal(2);
}, }),
function(callback) { tags[1].getProducts().then(function(products) {
products[3].setTags([tags[1]]).done(callback); expect(products.length).to.equal(3);
}, }),
function(callback) { self.Product.find({
products[4].setTags([tags[2]]).done(callback); where: {
} id: products[0].id
], function(err) { },
expect(err).not.to.exist; include: [
{model: self.Tag, as: 'tags'}
async.parallel([ ]
function(callback) { }).then(function(product) {
self.Tag.find({ expect(product).to.exist;
where: { expect(product.tags.length).to.equal(2);
id: tags[0].id }),
}, products[1].getTags().then(function(tags) {
include: [ expect(tags.length).to.equal(1);
{model: self.Product, as: 'products'} })
] ]);
}).done(function(err, tag) {
expect(tag).to.exist;
expect(tag.products.length).to.equal(2);
callback();
});
},
function(callback) {
tags[1].getProducts().done(function(err, products) {
expect(products.length).to.equal(3);
callback();
});
},
function(callback) {
self.Product.find({
where: {
id: products[0].id
},
include: [
{model: self.Tag, as: 'tags'}
]
}).done(function(err, product) {
expect(product).to.exist;
expect(product.tags.length).to.equal(2);
callback();
});
},
function(callback) {
products[1].getTags().done(function(err, tags) {
expect(tags.length).to.equal(1);
callback();
});
}
], done);
}); });
}); });
}); });
......
...@@ -43,14 +43,14 @@ describe(Support.getTestDialectTeaser('Promise'), function() { ...@@ -43,14 +43,14 @@ describe(Support.getTestDialectTeaser('Promise'), function() {
}); });
describe('increment', function() { describe('increment', function() {
beforeEach(function(done) { beforeEach(function() {
this.User.create({ id: 1, aNumber: 0, bNumber: 0 }).done(done); return this.User.create({ id: 1, aNumber: 0, bNumber: 0 });
}); });
it('with array', function(done) { it('with array', function() {
var self = this; var self = this;
this.User return this.User
.find(1) .find(1)
.then(function(user) { .then(function(user) {
expect(user.id).to.equal(1); expect(user.id).to.equal(1);
...@@ -63,15 +63,14 @@ describe(Support.getTestDialectTeaser('Promise'), function() { ...@@ -63,15 +63,14 @@ describe(Support.getTestDialectTeaser('Promise'), function() {
}) })
.then(function(user) { .then(function(user) {
expect(user.aNumber).to.equal(2); expect(user.aNumber).to.equal(2);
done();
}); });
}); });
it('should still work right with other concurrent updates', function(done) { it('should still work right with other concurrent updates', function() {
var self = this; var self = this;
// Select something // Select something
this.User return this.User
.find(1) .find(1)
.then(function(user1) { .then(function(user1) {
// Select the user again (simulating a concurrent query) // Select the user again (simulating a concurrent query)
...@@ -83,16 +82,15 @@ describe(Support.getTestDialectTeaser('Promise'), function() { ...@@ -83,16 +82,15 @@ describe(Support.getTestDialectTeaser('Promise'), function() {
.then(function() { return self.User.find(1); }) .then(function() { return self.User.find(1); })
.then(function(user5) { .then(function(user5) {
expect(user5.aNumber).to.equal(3); expect(user5.aNumber).to.equal(3);
done();
}); });
}); });
}); });
}); });
it('with key value pair', function(done) { it('with key value pair', function() {
var self = this; var self = this;
this.User return this.User
.find(1) .find(1)
.then(function(user1) { .then(function(user1) {
return user1.increment({ 'aNumber': 1, 'bNumber': 2}); return user1.increment({ 'aNumber': 1, 'bNumber': 2});
...@@ -103,20 +101,19 @@ describe(Support.getTestDialectTeaser('Promise'), function() { ...@@ -103,20 +101,19 @@ describe(Support.getTestDialectTeaser('Promise'), function() {
.then(function(user3) { .then(function(user3) {
expect(user3.aNumber).to.equal(1); expect(user3.aNumber).to.equal(1);
expect(user3.bNumber).to.equal(2); expect(user3.bNumber).to.equal(2);
done();
}); });
}); });
}); });
describe('decrement', function() { describe('decrement', function() {
beforeEach(function(done) { beforeEach(function() {
this.User.create({ id: 1, aNumber: 0, bNumber: 0 }).done(done); return this.User.create({ id: 1, aNumber: 0, bNumber: 0 });
}); });
it('with array', function(done) { it('with array', function() {
var self = this; var self = this;
this.User return this.User
.find(1) .find(1)
.then(function(user1) { .then(function(user1) {
return user1.decrement(['aNumber'], { by: 2 }); return user1.decrement(['aNumber'], { by: 2 });
...@@ -126,14 +123,12 @@ describe(Support.getTestDialectTeaser('Promise'), function() { ...@@ -126,14 +123,12 @@ describe(Support.getTestDialectTeaser('Promise'), function() {
}) })
.then(function(user3) { .then(function(user3) {
expect(user3.aNumber).to.equal(-2); expect(user3.aNumber).to.equal(-2);
done();
}); });
}); });
it('with single field', function(done) { it('with single field', function() {
var self = this; var self = this;
return this.User
this.User
.find(1) .find(1)
.then(function(user1) { .then(function(user1) {
return user1.decrement(['aNumber'], { by: 2 }); return user1.decrement(['aNumber'], { by: 2 });
...@@ -143,35 +138,32 @@ describe(Support.getTestDialectTeaser('Promise'), function() { ...@@ -143,35 +138,32 @@ describe(Support.getTestDialectTeaser('Promise'), function() {
}) })
.then(function(user3) { .then(function(user3) {
expect(user3.aNumber).to.equal(-2); expect(user3.aNumber).to.equal(-2);
done();
}); });
}); });
it('should still work right with other concurrent decrements', function(done) { it('should still work right with other concurrent decrements', function() {
var self = this; var self = this;
return this.User
this.User
.find(1) .find(1)
.then(function(user1) { .then(function(user1) {
var _done = _.after(3, function() { return this.sequelize.Promise.all([
self.User user1.decrement(['aNumber'], { by: 2 }),
user1.decrement(['aNumber'], { by: 2 }),
user1.decrement(['aNumber'], { by: 2 })
]).then(function() {
return self.User
.find(1) .find(1)
.then(function(user2) { .then(function(user2) {
expect(user2.aNumber).to.equal(-6); expect(user2.aNumber).to.equal(-6);
done();
}); });
}); });
user1.decrement(['aNumber'], { by: 2 }).done(_done);
user1.decrement(['aNumber'], { by: 2 }).done(_done);
user1.decrement(['aNumber'], { by: 2 }).done(_done);
}); });
}); });
}); });
describe('reload', function() { describe('reload', function() {
it('should return a reference to the same DAO instead of creating a new one', function(done) { it('should return a reference to the same DAO instead of creating a new one', function() {
this.User return this.User
.create({ username: 'John Doe' }) .create({ username: 'John Doe' })
.then(function(originalUser) { .then(function(originalUser) {
return originalUser return originalUser
...@@ -181,15 +173,13 @@ describe(Support.getTestDialectTeaser('Promise'), function() { ...@@ -181,15 +173,13 @@ describe(Support.getTestDialectTeaser('Promise'), function() {
}) })
.then(function(updatedUser) { .then(function(updatedUser) {
expect(originalUser === updatedUser).to.be.true; expect(originalUser === updatedUser).to.be.true;
done();
}); });
}); });
}); });
it('should update the values on all references to the DAO', function(done) { it('should update the values on all references to the DAO', function() {
var self = this; var self = this;
return this.User
this.User
.create({ username: 'John Doe' }) .create({ username: 'John Doe' })
.then(function(originalUser) { .then(function(originalUser) {
return self.User return self.User
...@@ -204,23 +194,22 @@ describe(Support.getTestDialectTeaser('Promise'), function() { ...@@ -204,23 +194,22 @@ describe(Support.getTestDialectTeaser('Promise'), function() {
}).then(function(updatedUser) { }).then(function(updatedUser) {
expect(originalUser.username).to.equal('Doe John'); expect(originalUser.username).to.equal('Doe John');
expect(updatedUser.username).to.equal('Doe John'); expect(updatedUser.username).to.equal('Doe John');
done();
}); });
}); });
}); });
it('should update the associations as well', function(done) { it('should update the associations as well', function() {
var Book = this.sequelize.define('Book', { title: DataTypes.STRING }) var Book = this.sequelize.define('Book', { title: DataTypes.STRING })
, Page = this.sequelize.define('Page', { content: DataTypes.TEXT }); , Page = this.sequelize.define('Page', { content: DataTypes.TEXT });
Book.hasMany(Page); Book.hasMany(Page);
Page.belongsTo(Book); Page.belongsTo(Book);
Book return Book
.sync({ force: true }) .sync({ force: true })
.then(function() { .then(function() {
Page return Page
.sync({ force: true }) .sync({ force: true })
.then(function() { .then(function() {
return Book.create({ title: 'A very old book' }); return Book.create({ title: 'A very old book' });
...@@ -249,49 +238,42 @@ describe(Support.getTestDialectTeaser('Promise'), function() { ...@@ -249,49 +238,42 @@ describe(Support.getTestDialectTeaser('Promise'), function() {
.then(function(leBook) { .then(function(leBook) {
expect(leBook.Pages[0].content).to.equal('something totally different'); expect(leBook.Pages[0].content).to.equal('something totally different');
expect(page.content).to.equal('something totally different'); expect(page.content).to.equal('something totally different');
done();
}); });
}); });
}); });
}); });
}); });
}, done); });
}); });
}); });
}); });
describe('complete', function() { describe('complete', function() {
it('gets triggered if an error occurs', function(done) { it('gets triggered if an error occurs', function() {
this.User.find({ where: 'asdasdasd' }).then(null, function(err) { return expect( this.User.find({ where: 'asdasdasd' })).to.be.rejected;
expect(err).to.be.ok;
expect(err.message).to.be.ok;
done();
});
}); });
it('gets triggered if everything was ok', function(done) { it('gets triggered if everything was ok', function() {
this.User.count().then(function(result) { return this.User.count().then(function(result) {
expect(result).to.not.be.undefined; expect(result).to.not.be.undefined;
done();
}); });
}); });
}); });
describe('save', function() { describe('save', function() {
it('should fail a validation upon creating', function(done) { it('should fail a validation upon creating', function() {
this.User.create({aNumber: 0, validateTest: 'hello'}) return this.User.create({aNumber: 0, validateTest: 'hello'})
.catch (function(err) { .catch (function(err) {
expect(err).to.be.ok; expect(err).to.be.ok;
expect(err).to.be.an('object'); expect(err).to.be.an('object');
expect(err.get('validateTest')).to.be.an('array'); expect(err.get('validateTest')).to.be.an('array');
expect(err.get('validateTest')[0]).to.be.ok; expect(err.get('validateTest')[0]).to.be.ok;
expect(err.get('validateTest')[0].message).to.equal('Validation isInt failed'); expect(err.get('validateTest')[0].message).to.equal('Validation isInt failed');
done();
}); });
}); });
it('should fail a validation upon building', function(done) { it('should fail a validation upon building', function() {
this.User.build({aNumber: 0, validateCustom: 'aaaaaaaaaaaaaaaaaaaaaaaaaa'}).save() return this.User.build({aNumber: 0, validateCustom: 'aaaaaaaaaaaaaaaaaaaaaaaaaa'}).save()
.catch (function(err) { .catch (function(err) {
expect(err).to.be.ok; expect(err).to.be.ok;
expect(err).to.be.an('object'); expect(err).to.be.an('object');
...@@ -299,12 +281,11 @@ describe(Support.getTestDialectTeaser('Promise'), function() { ...@@ -299,12 +281,11 @@ describe(Support.getTestDialectTeaser('Promise'), function() {
expect(err.get('validateCustom')).to.be.an('array'); expect(err.get('validateCustom')).to.be.an('array');
expect(err.get('validateCustom')[0]).to.be.ok; expect(err.get('validateCustom')[0]).to.be.ok;
expect(err.get('validateCustom')[0].message).to.equal('Length failed.'); expect(err.get('validateCustom')[0].message).to.equal('Length failed.');
done();
}); });
}); });
it('should fail a validation when updating', function(done) { it('should fail a validation when updating', function() {
this.User.create({aNumber: 0}).then(function(user) { return this.User.create({aNumber: 0}).then(function(user) {
return user.updateAttributes({validateTest: 'hello'}); return user.updateAttributes({validateTest: 'hello'});
}).catch (function(err) { }).catch (function(err) {
expect(err).to.be.ok; expect(err).to.be.ok;
...@@ -313,36 +294,33 @@ describe(Support.getTestDialectTeaser('Promise'), function() { ...@@ -313,36 +294,33 @@ describe(Support.getTestDialectTeaser('Promise'), function() {
expect(err.get('validateTest')).to.be.an('array'); expect(err.get('validateTest')).to.be.an('array');
expect(err.get('validateTest')[0]).to.be.ok; expect(err.get('validateTest')[0]).to.be.ok;
expect(err.get('validateTest')[0].message).to.equal('Validation isInt failed'); expect(err.get('validateTest')[0].message).to.equal('Validation isInt failed');
done();
}); });
}); });
}); });
describe('findOrCreate', function() { describe('findOrCreate', function() {
beforeEach(function(done) { beforeEach(function() {
this.User.create({ id: 1, aNumber: 0, bNumber: 0 }).done(done); return this.User.create({ id: 1, aNumber: 0, bNumber: 0 });
}); });
describe('with spread', function() { describe('with spread', function() {
it('user not created', function(done) { it('user not created', function() {
this.User return this.User
.findOrCreate({ where: { id: 1}}) .findOrCreate({ where: { id: 1}})
.spread(function(user, created) { .spread(function(user, created) {
expect(user.id).to.equal(1); expect(user.id).to.equal(1);
expect(created).to.equal(false); expect(created).to.equal(false);
expect(arguments.length).to.equal(2); expect(arguments.length).to.equal(2);
done();
}); });
}); });
it('user created', function(done) { it('user created', function() {
this.User return this.User
.findOrCreate({ where: { id: 2}}) .findOrCreate({ where: { id: 2}})
.spread(function(user, created) { .spread(function(user, created) {
expect(user.id).to.equal(2); expect(user.id).to.equal(2);
expect(created).to.equal(true); expect(created).to.equal(true);
expect(arguments.length).to.equal(2); expect(arguments.length).to.equal(2);
done();
}); });
}); });
}); });
...@@ -377,7 +355,7 @@ describe(Support.getTestDialectTeaser('Promise'), function() { ...@@ -377,7 +355,7 @@ describe(Support.getTestDialectTeaser('Promise'), function() {
}); });
}); });
it('should still work with .on(\'success\') when resolving', function(done) { it('should still work with then when resolving', function(done) {
var spy = sinon.spy() var spy = sinon.spy()
, promise = new SequelizePromise(function(resolve, reject) { , promise = new SequelizePromise(function(resolve, reject) {
resolve('yoohoo'); resolve('yoohoo');
...@@ -407,18 +385,17 @@ describe(Support.getTestDialectTeaser('Promise'), function() { ...@@ -407,18 +385,17 @@ describe(Support.getTestDialectTeaser('Promise'), function() {
}); });
}); });
it('should still work with .complete() after chaining', function(done) { it('should still work with .complete() after chaining', function() {
var spy = sinon.spy() var spy = sinon.spy()
, promise = new SequelizePromise(function(resolve, reject) { , promise = new SequelizePromise(function(resolve, reject) {
resolve('Heyo'); resolve('Heyo');
}); });
promise.then(function(result) { return promise.then(function(result) {
return result + '123'; return result + '123';
}).complete(function(err, result) { }).complete(function(err, result) {
expect(err).not.to.be.ok; expect(err).not.to.be.ok;
expect(result).to.equal('Heyo123'); expect(result).to.equal('Heyo123');
done();
}); });
}); });
...@@ -496,7 +473,7 @@ describe(Support.getTestDialectTeaser('Promise'), function() { ...@@ -496,7 +473,7 @@ describe(Support.getTestDialectTeaser('Promise'), function() {
promise.emit('error', new Error('noway')); promise.emit('error', new Error('noway'));
}); });
it('should still support sql events', function(done) { it('should still support sql events', function() {
var spy = sinon.spy() var spy = sinon.spy()
, promise = new SequelizePromise(function(resolve, reject) { , promise = new SequelizePromise(function(resolve, reject) {
resolve('yay'); resolve('yay');
...@@ -507,9 +484,8 @@ describe(Support.getTestDialectTeaser('Promise'), function() { ...@@ -507,9 +484,8 @@ describe(Support.getTestDialectTeaser('Promise'), function() {
promise.emit('sql', 'SQL STATEMENT 1'); promise.emit('sql', 'SQL STATEMENT 1');
promise.emit('sql', 'SQL STATEMENT 2'); promise.emit('sql', 'SQL STATEMENT 2');
promise.then(function() { return promise.then(function() {
expect(spy.calledTwice).to.be.true; expect(spy.calledTwice).to.be.true;
done();
}); });
}); });
......
...@@ -9,24 +9,21 @@ var chai = require('chai') ...@@ -9,24 +9,21 @@ var chai = require('chai')
chai.config.includeStack = true; chai.config.includeStack = true;
describe(Support.getTestDialectTeaser('QueryChainer'), function() { describe(Support.getTestDialectTeaser('QueryChainer'), function() {
beforeEach(function(done) { beforeEach(function() {
this.queryChainer = new QueryChainer(); this.queryChainer = new QueryChainer();
done();
}); });
describe('add', function() { describe('add', function() {
it('adds a new serial item if method is passed', function(done) { it('adds a new serial item if method is passed', function() {
expect(this.queryChainer.serials.length).to.equal(0); expect(this.queryChainer.serials.length).to.equal(0);
this.queryChainer.add({}, 'foo'); this.queryChainer.add({}, 'foo');
expect(this.queryChainer.serials.length).to.equal(1); expect(this.queryChainer.serials.length).to.equal(1);
done();
}); });
it('adds a new emitter if no method is passed', function(done) { it('adds a new emitter if no method is passed', function() {
expect(this.queryChainer.emitters.length).to.equal(0); expect(this.queryChainer.emitters.length).to.equal(0);
this.queryChainer.add(new CustomEventEmitter()); this.queryChainer.add(new CustomEventEmitter());
expect(this.queryChainer.emitters.length).to.equal(1); expect(this.queryChainer.emitters.length).to.equal(1);
done();
}); });
}); });
......
...@@ -131,27 +131,22 @@ describe(Support.getTestDialectTeaser('Sequelize#transaction'), function() { ...@@ -131,27 +131,22 @@ describe(Support.getTestDialectTeaser('Sequelize#transaction'), function() {
}); });
}); });
it('triggers the error event for the second transactions', function(done) { it('triggers the error event for the second transactions', function() {
var self = this; var self = this;
this.sequelize.transaction().then(function(t1) { return this.sequelize.transaction().then(function(t1) {
self.sequelize.transaction().then(function(t2) { return self.sequelize.transaction().then(function(t2) {
self return self.Model.create({ name: 'omnom' }, { transaction: t1 }).then(function(m1) {
.Model return Promise.all([
.create({ name: 'omnom' }, { transaction: t1 }) self.Model.create({ name: 'omnom' }, { transaction: t2 }).catch(function(err) {
.success(function(m1) { expect(err).to.be.defined;
self return t2.rollback();
.Model }),
.create({ name: 'omnom' }, { transaction: t2 }) Promise.delay(100).then(function() {
.error(function(err) { return t1.commit();
t2.rollback().success(function() { })
expect(err).to.be.defined; ]);
done(); });
});
});
setTimeout(function() { t1.commit(); }, 100);
});
}); });
}); });
}); });
......
...@@ -57,7 +57,7 @@ var Support = { ...@@ -57,7 +57,7 @@ var Support = {
, _sequelize = new Sequelize(sequelize.config.database, null, null, options); , _sequelize = new Sequelize(sequelize.config.database, null, null, options);
if (callback) { if (callback) {
_sequelize.sync({ force: true }).success(function() { callback(_sequelize); }); _sequelize.sync({ force: true }).then(function() { callback(_sequelize); });
} else { } else {
return _sequelize.sync({ force: true }).return (_sequelize); return _sequelize.sync({ force: true }).return (_sequelize);
} }
......
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!