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

Commit 35af6838 by Andy Edwards Committed by GitHub

test(integration/model): asyncify (#12287)

1 parent 796b6b7d
Showing with 587 additions and 689 deletions
...@@ -8,7 +8,7 @@ const chai = require('chai'), ...@@ -8,7 +8,7 @@ const chai = require('chai'),
describe(Support.getTestDialectTeaser('Model'), () => { describe(Support.getTestDialectTeaser('Model'), () => {
describe('attributes', () => { describe('attributes', () => {
describe('set', () => { describe('set', () => {
it('should only be called once when used on a join model called with an association getter', function() { it('should only be called once when used on a join model called with an association getter', async function() {
let callCount = 0; let callCount = 0;
this.Student = this.sequelize.define('student', { this.Student = this.sequelize.define('student', {
...@@ -44,33 +44,29 @@ describe(Support.getTestDialectTeaser('Model'), () => { ...@@ -44,33 +44,29 @@ describe(Support.getTestDialectTeaser('Model'), () => {
this.Student.belongsToMany(this.Course, { through: this.Score, foreignKey: 'StudentId' }); this.Student.belongsToMany(this.Course, { through: this.Score, foreignKey: 'StudentId' });
this.Course.belongsToMany(this.Student, { through: this.Score, foreignKey: 'CourseId' }); this.Course.belongsToMany(this.Student, { through: this.Score, foreignKey: 'CourseId' });
return this.sequelize.sync({ force: true }).then(() => { await this.sequelize.sync({ force: true });
return Promise.all([
const [student, course] = await Promise.all([
this.Student.create({ no: 1, name: 'ryan' }), this.Student.create({ no: 1, name: 'ryan' }),
this.Course.create({ no: 100, name: 'history' }) this.Course.create({ no: 100, name: 'history' })
]).then(([student, course]) => { ]);
return student.addCourse(course, { through: { score: 98, test_value: 1000 } });
}).then(() => { await student.addCourse(course, { through: { score: 98, test_value: 1000 } });
expect(callCount).to.equal(1); expect(callCount).to.equal(1);
return this.Score.findOne({ where: { StudentId: 1, CourseId: 100 } }).then(score => { const score0 = await this.Score.findOne({ where: { StudentId: 1, CourseId: 100 } });
expect(score.test_value).to.equal(1001); expect(score0.test_value).to.equal(1001);
});
}) const [courses, score] = await Promise.all([
.then(() => {
return Promise.all([
this.Student.build({ no: 1 }).getCourses({ where: { no: 100 } }), this.Student.build({ no: 1 }).getCourses({ where: { no: 100 } }),
this.Score.findOne({ where: { StudentId: 1, CourseId: 100 } }) this.Score.findOne({ where: { StudentId: 1, CourseId: 100 } })
]); ]);
})
.then(([courses, score]) => {
expect(score.test_value).to.equal(1001); expect(score.test_value).to.equal(1001);
expect(courses[0].score.toJSON().test_value).to.equal(1001); expect(courses[0].score.toJSON().test_value).to.equal(1001);
expect(callCount).to.equal(1); expect(callCount).to.equal(1);
}); });
});
});
it('allows for an attribute to be called "toString"', function() { it('allows for an attribute to be called "toString"', async function() {
const Person = this.sequelize.define('person', { const Person = this.sequelize.define('person', {
name: Sequelize.STRING, name: Sequelize.STRING,
nick: Sequelize.STRING nick: Sequelize.STRING
...@@ -78,9 +74,10 @@ describe(Support.getTestDialectTeaser('Model'), () => { ...@@ -78,9 +74,10 @@ describe(Support.getTestDialectTeaser('Model'), () => {
timestamps: false timestamps: false
}); });
return this.sequelize.sync({ force: true }) await this.sequelize.sync({ force: true });
.then(() => Person.create({ name: 'Jozef', nick: 'Joe' })) await Person.create({ name: 'Jozef', nick: 'Joe' });
.then(() => Person.findOne({
const person = await Person.findOne({
attributes: [ attributes: [
'nick', 'nick',
['name', 'toString'] ['name', 'toString']
...@@ -88,14 +85,13 @@ describe(Support.getTestDialectTeaser('Model'), () => { ...@@ -88,14 +85,13 @@ describe(Support.getTestDialectTeaser('Model'), () => {
where: { where: {
name: 'Jozef' name: 'Jozef'
} }
})) });
.then(person => {
expect(person.dataValues['toString']).to.equal('Jozef'); expect(person.dataValues['toString']).to.equal('Jozef');
expect(person.get('toString')).to.equal('Jozef'); expect(person.get('toString')).to.equal('Jozef');
}); });
});
it('allows for an attribute to be called "toString" with associations', function() { it('allows for an attribute to be called "toString" with associations', async function() {
const Person = this.sequelize.define('person', { const Person = this.sequelize.define('person', {
name: Sequelize.STRING, name: Sequelize.STRING,
nick: Sequelize.STRING nick: Sequelize.STRING
...@@ -107,10 +103,11 @@ describe(Support.getTestDialectTeaser('Model'), () => { ...@@ -107,10 +103,11 @@ describe(Support.getTestDialectTeaser('Model'), () => {
Person.hasMany(Computer); Person.hasMany(Computer);
return this.sequelize.sync({ force: true }) await this.sequelize.sync({ force: true });
.then(() => Person.create({ name: 'Jozef', nick: 'Joe' })) const person = await Person.create({ name: 'Jozef', nick: 'Joe' });
.then(person => person.createComputer({ hostname: 'laptop' })) await person.createComputer({ hostname: 'laptop' });
.then(() => Person.findAll({
const result = await Person.findAll({
attributes: [ attributes: [
'nick', 'nick',
['name', 'toString'] ['name', 'toString']
...@@ -121,28 +118,25 @@ describe(Support.getTestDialectTeaser('Model'), () => { ...@@ -121,28 +118,25 @@ describe(Support.getTestDialectTeaser('Model'), () => {
where: { where: {
name: 'Jozef' name: 'Jozef'
} }
})) });
.then(result => {
expect(result.length).to.equal(1); expect(result.length).to.equal(1);
expect(result[0].dataValues['toString']).to.equal('Jozef'); expect(result[0].dataValues['toString']).to.equal('Jozef');
expect(result[0].get('toString')).to.equal('Jozef'); expect(result[0].get('toString')).to.equal('Jozef');
expect(result[0].get('computers')[0].hostname).to.equal('laptop'); expect(result[0].get('computers')[0].hostname).to.equal('laptop');
}); });
}); });
});
describe('quote', () => { describe('quote', () => {
it('allows for an attribute with dots', function() { it('allows for an attribute with dots', async function() {
const User = this.sequelize.define('user', { const User = this.sequelize.define('user', {
'foo.bar.baz': Sequelize.TEXT 'foo.bar.baz': Sequelize.TEXT
}); });
return this.sequelize.sync({ force: true }) await this.sequelize.sync({ force: true });
.then(() => User.findAll()) const result = await User.findAll();
.then(result => {
expect(result.length).to.equal(0); expect(result.length).to.equal(0);
}); });
}); });
}); });
});
}); });
...@@ -10,7 +10,7 @@ describe(Support.getTestDialectTeaser('Model'), () => { ...@@ -10,7 +10,7 @@ describe(Support.getTestDialectTeaser('Model'), () => {
describe('attributes', () => { describe('attributes', () => {
describe('types', () => { describe('types', () => {
describe('VIRTUAL', () => { describe('VIRTUAL', () => {
beforeEach(function() { beforeEach(async function() {
this.User = this.sequelize.define('user', { this.User = this.sequelize.define('user', {
storage: Sequelize.STRING, storage: Sequelize.STRING,
field1: { field1: {
...@@ -48,7 +48,7 @@ describe(Support.getTestDialectTeaser('Model'), () => { ...@@ -48,7 +48,7 @@ describe(Support.getTestDialectTeaser('Model'), () => {
expect(sql).to.not.include('field2'); expect(sql).to.not.include('field2');
}; };
return this.sequelize.sync({ force: true }); await this.sequelize.sync({ force: true });
}); });
it('should not be ignored in dataValues get', function() { it('should not be ignored in dataValues get', function() {
...@@ -60,14 +60,13 @@ describe(Support.getTestDialectTeaser('Model'), () => { ...@@ -60,14 +60,13 @@ describe(Support.getTestDialectTeaser('Model'), () => {
expect(user.get()).to.deep.equal({ storage: 'field1_value', field1: 'field1_value', virtualWithDefault: 'cake', field2: 42, id: null }); expect(user.get()).to.deep.equal({ storage: 'field1_value', field1: 'field1_value', virtualWithDefault: 'cake', field2: 42, id: null });
}); });
it('should be ignored in table creation', function() { it('should be ignored in table creation', async function() {
return this.sequelize.getQueryInterface().describeTable(this.User.tableName).then(fields => { const fields = await this.sequelize.getQueryInterface().describeTable(this.User.tableName);
expect(Object.keys(fields).length).to.equal(2); expect(Object.keys(fields).length).to.equal(2);
}); });
});
it('should be ignored in find, findAll and includes', function() { it('should be ignored in find, findAll and includes', async function() {
return Promise.all([ await Promise.all([
this.User.findOne({ this.User.findOne({
logging: this.sqlAssert logging: this.sqlAssert
}), }),
...@@ -89,7 +88,7 @@ describe(Support.getTestDialectTeaser('Model'), () => { ...@@ -89,7 +88,7 @@ describe(Support.getTestDialectTeaser('Model'), () => {
]); ]);
}); });
it('should allow me to store selected values', function() { it('should allow me to store selected values', async function() {
const Post = this.sequelize.define('Post', { const Post = this.sequelize.define('Post', {
text: Sequelize.TEXT, text: Sequelize.TEXT,
someBoolean: { someBoolean: {
...@@ -97,94 +96,91 @@ describe(Support.getTestDialectTeaser('Model'), () => { ...@@ -97,94 +96,91 @@ describe(Support.getTestDialectTeaser('Model'), () => {
} }
}); });
return this.sequelize.sync({ force: true }).then(() => { await this.sequelize.sync({ force: true });
return Post.bulkCreate([{ text: 'text1' }, { text: 'text2' }]); await Post.bulkCreate([{ text: 'text1' }, { text: 'text2' }]);
}).then(() => {
let boolQuery = 'EXISTS(SELECT 1) AS "someBoolean"'; let boolQuery = 'EXISTS(SELECT 1) AS "someBoolean"';
if (dialect === 'mssql') { if (dialect === 'mssql') {
boolQuery = 'CAST(CASE WHEN EXISTS(SELECT 1) THEN 1 ELSE 0 END AS BIT) AS "someBoolean"'; boolQuery = 'CAST(CASE WHEN EXISTS(SELECT 1) THEN 1 ELSE 0 END AS BIT) AS "someBoolean"';
} }
return Post.findOne({ attributes: ['id', 'text', Sequelize.literal(boolQuery)] }); const post = await Post.findOne({ attributes: ['id', 'text', Sequelize.literal(boolQuery)] });
}).then(post => {
expect(post.get('someBoolean')).to.be.ok; expect(post.get('someBoolean')).to.be.ok;
expect(post.get().someBoolean).to.be.ok; expect(post.get().someBoolean).to.be.ok;
}); });
});
it('should be ignored in create and update', function() { it('should be ignored in create and update', async function() {
return this.User.create({ const user0 = await this.User.create({
field1: 'something' field1: 'something'
}).then(user => { });
// We already verified that the virtual is not added to the table definition, // We already verified that the virtual is not added to the table definition,
// so if this succeeds, were good // so if this succeeds, were good
expect(user.virtualWithDefault).to.equal('cake'); expect(user0.virtualWithDefault).to.equal('cake');
expect(user.storage).to.equal('something'); expect(user0.storage).to.equal('something');
return user.update({
const user = await user0.update({
field1: 'something else' field1: 'something else'
}, { }, {
fields: ['storage'] fields: ['storage']
}); });
}).then(user => {
expect(user.virtualWithDefault).to.equal('cake'); expect(user.virtualWithDefault).to.equal('cake');
expect(user.storage).to.equal('something else'); expect(user.storage).to.equal('something else');
}); });
});
it('should be ignored in bulkCreate and and bulkUpdate', function() { it('should be ignored in bulkCreate and and bulkUpdate', async function() {
return this.User.bulkCreate([{ await this.User.bulkCreate([{
field1: 'something' field1: 'something'
}], { }], {
logging: this.sqlAssert logging: this.sqlAssert
}).then(() => {
return this.User.findAll();
}).then(users => {
expect(users[0].storage).to.equal('something');
}); });
const users = await this.User.findAll();
expect(users[0].storage).to.equal('something');
}); });
it('should be able to exclude with attributes', function() { it('should be able to exclude with attributes', async function() {
return this.User.bulkCreate([{ await this.User.bulkCreate([{
field1: 'something' field1: 'something'
}], { }], {
logging: this.sqlAssert logging: this.sqlAssert
}).then(() => { });
return this.User.findAll({
const users0 = await this.User.findAll({
logging: this.sqlAssert logging: this.sqlAssert
}); });
}).then(users => {
const user = users[0].get();
expect(user.storage).to.equal('something'); const user0 = users0[0].get();
expect(user).to.include.all.keys(['field1', 'field2']);
expect(user0.storage).to.equal('something');
expect(user0).to.include.all.keys(['field1', 'field2']);
return this.User.findAll({ const users = await this.User.findAll({
attributes: { attributes: {
exclude: ['field1'] exclude: ['field1']
}, },
logging: this.sqlAssert logging: this.sqlAssert
}); });
}).then(users => {
const user = users[0].get(); const user = users[0].get();
expect(user.storage).to.equal('something'); expect(user.storage).to.equal('something');
expect(user).not.to.include.all.keys(['field1']); expect(user).not.to.include.all.keys(['field1']);
expect(user).to.include.all.keys(['field2']); expect(user).to.include.all.keys(['field2']);
}); });
});
it('should be able to include model with virtual attributes', function() { it('should be able to include model with virtual attributes', async function() {
return this.User.create({}).then(user => { const user0 = await this.User.create({});
return user.createTask(); await user0.createTask();
}).then(() => {
return this.Task.findAll({ const tasks = await this.Task.findAll({
include: [{ include: [{
attributes: ['field2', 'id'], attributes: ['field2', 'id'],
model: this.User model: this.User
}] }]
}); });
}).then(tasks => {
const user = tasks[0].user.get(); const user = tasks[0].user.get();
expect(user.field2).to.equal(42); expect(user.field2).to.equal(42);
...@@ -192,5 +188,4 @@ describe(Support.getTestDialectTeaser('Model'), () => { ...@@ -192,5 +188,4 @@ describe(Support.getTestDialectTeaser('Model'), () => {
}); });
}); });
}); });
});
}); });
...@@ -7,7 +7,7 @@ const chai = require('chai'), ...@@ -7,7 +7,7 @@ const chai = require('chai'),
describe(Support.getTestDialectTeaser('Model'), () => { describe(Support.getTestDialectTeaser('Model'), () => {
describe('count', () => { describe('count', () => {
beforeEach(function() { beforeEach(async function() {
this.User = this.sequelize.define('User', { this.User = this.sequelize.define('User', {
username: DataTypes.STRING, username: DataTypes.STRING,
age: DataTypes.INTEGER age: DataTypes.INTEGER
...@@ -19,112 +19,118 @@ describe(Support.getTestDialectTeaser('Model'), () => { ...@@ -19,112 +19,118 @@ describe(Support.getTestDialectTeaser('Model'), () => {
this.User.hasMany(this.Project); this.User.hasMany(this.Project);
this.Project.belongsTo(this.User); this.Project.belongsTo(this.User);
return this.sequelize.sync({ force: true }); await this.sequelize.sync({ force: true });
}); });
it('should count rows', function() { it('should count rows', async function() {
return this.User.bulkCreate([ await this.User.bulkCreate([
{ username: 'foo' }, { username: 'foo' },
{ username: 'bar' } { username: 'bar' }
]).then(() => { ]);
return expect(this.User.count()).to.eventually.equal(2);
}); await expect(this.User.count()).to.eventually.equal(2);
}); });
it('should support include', function() { it('should support include', async function() {
return this.User.bulkCreate([ await this.User.bulkCreate([
{ username: 'foo' }, { username: 'foo' },
{ username: 'bar' } { username: 'bar' }
]).then(() => this.User.findOne()) ]);
.then(user => user.createProject({ name: 'project1' }))
.then(() => { const user = await this.User.findOne();
return expect(this.User.count({ await user.createProject({ name: 'project1' });
await expect(this.User.count({
include: [{ include: [{
model: this.Project, model: this.Project,
where: { name: 'project1' } where: { name: 'project1' }
}] }]
})).to.eventually.equal(1); })).to.eventually.equal(1);
}); });
});
it('should count groups correctly and return attributes', function() { it('should count groups correctly and return attributes', async function() {
return this.User.bulkCreate([ await this.User.bulkCreate([
{ username: 'foo' }, { username: 'foo' },
{ username: 'bar' }, { username: 'bar' },
{ {
username: 'valak', username: 'valak',
createdAt: new Date().setFullYear(2015) createdAt: new Date().setFullYear(2015)
} }
]).then(() => this.User.count({ ]);
const users = await this.User.count({
attributes: ['createdAt'], attributes: ['createdAt'],
group: ['createdAt'] group: ['createdAt']
})).then(users => { });
expect(users.length).to.be.eql(2); expect(users.length).to.be.eql(2);
expect(users[0].createdAt).to.exist; expect(users[0].createdAt).to.exist;
expect(users[1].createdAt).to.exist; expect(users[1].createdAt).to.exist;
}); });
});
it('should not return NaN', function() { it('should not return NaN', async function() {
return this.User.bulkCreate([ await this.User.bulkCreate([
{ username: 'valak', age: 10 }, { username: 'valak', age: 10 },
{ username: 'conjuring', age: 20 }, { username: 'conjuring', age: 20 },
{ username: 'scary', age: 10 } { username: 'scary', age: 10 }
]).then(() => this.User.count({ ]);
const result = await this.User.count({
where: { age: 10 }, where: { age: 10 },
group: ['age'], group: ['age'],
order: ['age'] order: ['age']
})).then(result => { });
// TODO: `parseInt` should not be needed, see #10533 // TODO: `parseInt` should not be needed, see #10533
expect(parseInt(result[0].count, 10)).to.be.eql(2); expect(parseInt(result[0].count, 10)).to.be.eql(2);
return this.User.count({
const count0 = await this.User.count({
where: { username: 'fire' } where: { username: 'fire' }
}); });
}).then(count => {
expect(count).to.be.eql(0); expect(count0).to.be.eql(0);
return this.User.count({
const count = await this.User.count({
where: { username: 'fire' }, where: { username: 'fire' },
group: 'age' group: 'age'
}); });
}).then(count => {
expect(count).to.be.eql([]); expect(count).to.be.eql([]);
}); });
});
it('should be able to specify column for COUNT()', function() { it('should be able to specify column for COUNT()', async function() {
return this.User.bulkCreate([ await this.User.bulkCreate([
{ username: 'ember', age: 10 }, { username: 'ember', age: 10 },
{ username: 'angular', age: 20 }, { username: 'angular', age: 20 },
{ username: 'mithril', age: 10 } { username: 'mithril', age: 10 }
]).then(() => this.User.count({ col: 'username' })) ]);
.then(count => {
expect(count).to.be.eql(3); const count0 = await this.User.count({ col: 'username' });
return this.User.count({ expect(count0).to.be.eql(3);
const count = await this.User.count({
col: 'age', col: 'age',
distinct: true distinct: true
}); });
})
.then(count => {
expect(count).to.be.eql(2); expect(count).to.be.eql(2);
}); });
});
it('should be able to specify NO column for COUNT() with DISTINCT', function() { it('should be able to specify NO column for COUNT() with DISTINCT', async function() {
return this.User.bulkCreate([ await this.User.bulkCreate([
{ username: 'ember', age: 10 }, { username: 'ember', age: 10 },
{ username: 'angular', age: 20 }, { username: 'angular', age: 20 },
{ username: 'mithril', age: 10 } { username: 'mithril', age: 10 }
]).then(() => { ]);
return this.User.count({
const count = await this.User.count({
distinct: true distinct: true
}); });
})
.then(count => {
expect(count).to.be.eql(3); expect(count).to.be.eql(3);
}); });
});
it('should be able to use where clause on included models', function() { it('should be able to use where clause on included models', async function() {
const countOptions = { const countOptions = {
col: 'username', col: 'username',
include: [this.Project], include: [this.Project],
...@@ -132,51 +138,53 @@ describe(Support.getTestDialectTeaser('Model'), () => { ...@@ -132,51 +138,53 @@ describe(Support.getTestDialectTeaser('Model'), () => {
'$Projects.name$': 'project1' '$Projects.name$': 'project1'
} }
}; };
return this.User.bulkCreate([
await this.User.bulkCreate([
{ username: 'foo' }, { username: 'foo' },
{ username: 'bar' } { username: 'bar' }
]).then(() => this.User.findOne()) ]);
.then(user => user.createProject({ name: 'project1' }))
.then(() => { const user = await this.User.findOne();
return this.User.count(countOptions).then(count => { await user.createProject({ name: 'project1' });
expect(count).to.be.eql(1); const count0 = await this.User.count(countOptions);
expect(count0).to.be.eql(1);
countOptions.where['$Projects.name$'] = 'project2'; countOptions.where['$Projects.name$'] = 'project2';
return this.User.count(countOptions); const count = await this.User.count(countOptions);
});
})
.then(count => {
expect(count).to.be.eql(0); expect(count).to.be.eql(0);
}); });
});
it('should be able to specify column for COUNT() with includes', function() { it('should be able to specify column for COUNT() with includes', async function() {
return this.User.bulkCreate([ await this.User.bulkCreate([
{ username: 'ember', age: 10 }, { username: 'ember', age: 10 },
{ username: 'angular', age: 20 }, { username: 'angular', age: 20 },
{ username: 'mithril', age: 10 } { username: 'mithril', age: 10 }
]).then(() => this.User.count({ ]);
const count0 = await this.User.count({
col: 'username', col: 'username',
distinct: true, distinct: true,
include: [this.Project] include: [this.Project]
})).then(count => { });
expect(count).to.be.eql(3);
return this.User.count({ expect(count0).to.be.eql(3);
const count = await this.User.count({
col: 'age', col: 'age',
distinct: true, distinct: true,
include: [this.Project] include: [this.Project]
}); });
}).then(count => {
expect(count).to.be.eql(2); expect(count).to.be.eql(2);
}); });
});
it('should work correctly with include and whichever raw option', function() { it('should work correctly with include and whichever raw option', async function() {
const Post = this.sequelize.define('Post', {}); const Post = this.sequelize.define('Post', {});
this.User.hasMany(Post); this.User.hasMany(Post);
return Post.sync({ force: true }) await Post.sync({ force: true });
.then(() => Promise.all([this.User.create({}), Post.create({})])) const [user, post] = await Promise.all([this.User.create({}), Post.create({})]);
.then(([user, post]) => user.addPost(post)) await user.addPost(post);
.then(() => Promise.all([
const counts = await Promise.all([
this.User.count(), this.User.count(),
this.User.count({ raw: undefined }), this.User.count({ raw: undefined }),
this.User.count({ raw: false }), this.User.count({ raw: false }),
...@@ -185,11 +193,10 @@ describe(Support.getTestDialectTeaser('Model'), () => { ...@@ -185,11 +193,10 @@ describe(Support.getTestDialectTeaser('Model'), () => {
this.User.count({ include: Post, raw: undefined }), this.User.count({ include: Post, raw: undefined }),
this.User.count({ include: Post, raw: false }), this.User.count({ include: Post, raw: false }),
this.User.count({ include: Post, raw: true }) this.User.count({ include: Post, raw: true })
])) ]);
.then(counts => {
expect(counts).to.deep.equal([1, 1, 1, 1, 1, 1, 1, 1]); expect(counts).to.deep.equal([1, 1, 1, 1, 1, 1, 1, 1]);
}); });
});
}); });
}); });
...@@ -10,8 +10,7 @@ const chai = require('chai'), ...@@ -10,8 +10,7 @@ const chai = require('chai'),
describe(Support.getTestDialectTeaser('Model'), () => { describe(Support.getTestDialectTeaser('Model'), () => {
describe('findAll', () => { describe('findAll', () => {
describe('group', () => { describe('group', () => {
it('should correctly group with attributes, #3009', () => { it('should correctly group with attributes, #3009', async () => {
const Post = current.define('Post', { const Post = current.define('Post', {
id: { type: DataTypes.INTEGER, autoIncrement: true, primaryKey: true }, id: { type: DataTypes.INTEGER, autoIncrement: true, primaryKey: true },
name: { type: DataTypes.STRING, allowNull: false } name: { type: DataTypes.STRING, allowNull: false }
...@@ -24,22 +23,23 @@ describe(Support.getTestDialectTeaser('Model'), () => { ...@@ -24,22 +23,23 @@ describe(Support.getTestDialectTeaser('Model'), () => {
Post.hasMany(Comment); Post.hasMany(Comment);
return current.sync({ force: true }).then(() => { await current.sync({ force: true });
// Create an enviroment // Create an enviroment
return Post.bulkCreate([ await Post.bulkCreate([
{ name: 'post-1' }, { name: 'post-1' },
{ name: 'post-2' } { name: 'post-2' }
]); ]);
}).then(() => {
return Comment.bulkCreate([ await Comment.bulkCreate([
{ text: 'Market', PostId: 1 }, { text: 'Market', PostId: 1 },
{ text: 'Text', PostId: 2 }, { text: 'Text', PostId: 2 },
{ text: 'Abc', PostId: 2 }, { text: 'Abc', PostId: 2 },
{ text: 'Semaphor', PostId: 1 }, { text: 'Semaphor', PostId: 1 },
{ text: 'Text', PostId: 1 } { text: 'Text', PostId: 1 }
]); ]);
}).then(() => {
return Post.findAll({ const posts = await Post.findAll({
attributes: [[Sequelize.fn('COUNT', Sequelize.col('Comments.id')), 'comment_count']], attributes: [[Sequelize.fn('COUNT', Sequelize.col('Comments.id')), 'comment_count']],
include: [ include: [
{ model: Comment, attributes: [] } { model: Comment, attributes: [] }
...@@ -49,13 +49,12 @@ describe(Support.getTestDialectTeaser('Model'), () => { ...@@ -49,13 +49,12 @@ describe(Support.getTestDialectTeaser('Model'), () => {
['id'] ['id']
] ]
}); });
}).then(posts => {
expect(parseInt(posts[0].get('comment_count'), 10)).to.be.equal(3); expect(parseInt(posts[0].get('comment_count'), 10)).to.be.equal(3);
expect(parseInt(posts[1].get('comment_count'), 10)).to.be.equal(2); expect(parseInt(posts[1].get('comment_count'), 10)).to.be.equal(2);
}); });
});
it('should not add primary key when grouping using a belongsTo association', () => { it('should not add primary key when grouping using a belongsTo association', async () => {
const Post = current.define('Post', { const Post = current.define('Post', {
id: { type: DataTypes.INTEGER, autoIncrement: true, primaryKey: true }, id: { type: DataTypes.INTEGER, autoIncrement: true, primaryKey: true },
name: { type: DataTypes.STRING, allowNull: false } name: { type: DataTypes.STRING, allowNull: false }
...@@ -69,21 +68,22 @@ describe(Support.getTestDialectTeaser('Model'), () => { ...@@ -69,21 +68,22 @@ describe(Support.getTestDialectTeaser('Model'), () => {
Post.hasMany(Comment); Post.hasMany(Comment);
Comment.belongsTo(Post); Comment.belongsTo(Post);
return current.sync({ force: true }).then(() => { await current.sync({ force: true });
return Post.bulkCreate([
await Post.bulkCreate([
{ name: 'post-1' }, { name: 'post-1' },
{ name: 'post-2' } { name: 'post-2' }
]); ]);
}).then(() => {
return Comment.bulkCreate([ await Comment.bulkCreate([
{ text: 'Market', PostId: 1 }, { text: 'Market', PostId: 1 },
{ text: 'Text', PostId: 2 }, { text: 'Text', PostId: 2 },
{ text: 'Abc', PostId: 2 }, { text: 'Abc', PostId: 2 },
{ text: 'Semaphor', PostId: 1 }, { text: 'Semaphor', PostId: 1 },
{ text: 'Text', PostId: 1 } { text: 'Text', PostId: 1 }
]); ]);
}).then(() => {
return Comment.findAll({ const posts = await Comment.findAll({
attributes: ['PostId', [Sequelize.fn('COUNT', Sequelize.col('Comment.id')), 'comment_count']], attributes: ['PostId', [Sequelize.fn('COUNT', Sequelize.col('Comment.id')), 'comment_count']],
include: [ include: [
{ model: Post, attributes: [] } { model: Post, attributes: [] }
...@@ -93,7 +93,7 @@ describe(Support.getTestDialectTeaser('Model'), () => { ...@@ -93,7 +93,7 @@ describe(Support.getTestDialectTeaser('Model'), () => {
['PostId'] ['PostId']
] ]
}); });
}).then(posts => {
expect(posts[0].get().hasOwnProperty('id')).to.equal(false); expect(posts[0].get().hasOwnProperty('id')).to.equal(false);
expect(posts[1].get().hasOwnProperty('id')).to.equal(false); expect(posts[1].get().hasOwnProperty('id')).to.equal(false);
expect(parseInt(posts[0].get('comment_count'), 10)).to.be.equal(3); expect(parseInt(posts[0].get('comment_count'), 10)).to.be.equal(3);
...@@ -101,5 +101,4 @@ describe(Support.getTestDialectTeaser('Model'), () => { ...@@ -101,5 +101,4 @@ describe(Support.getTestDialectTeaser('Model'), () => {
}); });
}); });
}); });
});
}); });
...@@ -25,7 +25,7 @@ if (current.dialect.supports['UNION ALL']) { ...@@ -25,7 +25,7 @@ if (current.dialect.supports['UNION ALL']) {
this.clock.restore(); this.clock.restore();
}); });
beforeEach(function() { beforeEach(async function() {
this.User = this.sequelize.define('user', { this.User = this.sequelize.define('user', {
age: Sequelize.INTEGER age: Sequelize.INTEGER
}); });
...@@ -49,17 +49,18 @@ if (current.dialect.supports['UNION ALL']) { ...@@ -49,17 +49,18 @@ if (current.dialect.supports['UNION ALL']) {
this.User.Tasks = this.User.hasMany(this.Task); this.User.Tasks = this.User.hasMany(this.Task);
return this.sequelize.sync({ force: true }).then(() => { await this.sequelize.sync({ force: true });
return Promise.all([
await Promise.all([
this.User.bulkCreate([{ age: -5 }, { age: 45 }, { age: 7 }, { age: -9 }, { age: 8 }, { age: 15 }, { age: -9 }]), this.User.bulkCreate([{ age: -5 }, { age: 45 }, { age: 7 }, { age: -9 }, { age: 8 }, { age: 15 }, { age: -9 }]),
this.Project.bulkCreate([{}, {}]), this.Project.bulkCreate([{}, {}]),
this.Task.bulkCreate([{}, {}]) this.Task.bulkCreate([{}, {}])
]); ]);
})
.then(() => Promise.all([this.User.findAll(), this.Project.findAll(), this.Task.findAll()])) const [users, projects, tasks] = await Promise.all([this.User.findAll(), this.Project.findAll(), this.Task.findAll()]);
.then(([users, projects, tasks]) => {
this.projects = projects; this.projects = projects;
return Promise.all([
await Promise.all([
projects[0].setMembers(users.slice(0, 4)), projects[0].setMembers(users.slice(0, 4)),
projects[1].setMembers(users.slice(2)), projects[1].setMembers(users.slice(2)),
projects[0].setParanoidMembers(users.slice(0, 4)), projects[0].setParanoidMembers(users.slice(0, 4)),
...@@ -67,17 +68,17 @@ if (current.dialect.supports['UNION ALL']) { ...@@ -67,17 +68,17 @@ if (current.dialect.supports['UNION ALL']) {
users[2].setTasks(tasks) users[2].setTasks(tasks)
]); ]);
}); });
});
describe('on: belongsToMany', () => { describe('on: belongsToMany', () => {
it('maps attributes from a grouped limit to models', function() { it('maps attributes from a grouped limit to models', async function() {
return this.User.findAll({ const users = await this.User.findAll({
groupedLimit: { groupedLimit: {
limit: 3, limit: 3,
on: this.User.Projects, on: this.User.Projects,
values: this.projects.map(item => item.get('id')) values: this.projects.map(item => item.get('id'))
} }
}).then(users => { });
expect(users).to.have.length(5); expect(users).to.have.length(5);
users.filter(u => u.get('id') !== 3).forEach(u => { users.filter(u => u.get('id') !== 3).forEach(u => {
expect(u.get('projects')).to.have.length(1); expect(u.get('projects')).to.have.length(1);
...@@ -86,10 +87,9 @@ if (current.dialect.supports['UNION ALL']) { ...@@ -86,10 +87,9 @@ if (current.dialect.supports['UNION ALL']) {
expect(u.get('projects')).to.have.length(2); expect(u.get('projects')).to.have.length(2);
}); });
}); });
});
it('maps attributes from a grouped limit to models with include', function() { it('maps attributes from a grouped limit to models with include', async function() {
return this.User.findAll({ const users = await this.User.findAll({
groupedLimit: { groupedLimit: {
limit: 3, limit: 3,
on: this.User.Projects, on: this.User.Projects,
...@@ -97,7 +97,8 @@ if (current.dialect.supports['UNION ALL']) { ...@@ -97,7 +97,8 @@ if (current.dialect.supports['UNION ALL']) {
}, },
order: ['id'], order: ['id'],
include: [this.User.Tasks] include: [this.User.Tasks]
}).then(users => { });
/* /*
project1 - 1, 2, 3 project1 - 1, 2, 3
project2 - 3, 4, 5 project2 - 3, 4, 5
...@@ -113,10 +114,9 @@ if (current.dialect.supports['UNION ALL']) { ...@@ -113,10 +114,9 @@ if (current.dialect.supports['UNION ALL']) {
expect(u.get('projects')).to.have.length(2); expect(u.get('projects')).to.have.length(2);
}); });
}); });
});
it('works with computed order', function() { it('works with computed order', async function() {
return this.User.findAll({ const users = await this.User.findAll({
attributes: ['id'], attributes: ['id'],
groupedLimit: { groupedLimit: {
limit: 3, limit: 3,
...@@ -127,7 +127,8 @@ if (current.dialect.supports['UNION ALL']) { ...@@ -127,7 +127,8 @@ if (current.dialect.supports['UNION ALL']) {
Sequelize.fn('ABS', Sequelize.col('age')) Sequelize.fn('ABS', Sequelize.col('age'))
], ],
include: [this.User.Tasks] include: [this.User.Tasks]
}).then(users => { });
/* /*
project1 - 1, 3, 4 project1 - 1, 3, 4
project2 - 3, 5, 4 project2 - 3, 5, 4
...@@ -135,10 +136,9 @@ if (current.dialect.supports['UNION ALL']) { ...@@ -135,10 +136,9 @@ if (current.dialect.supports['UNION ALL']) {
expect(users).to.have.length(4); expect(users).to.have.length(4);
expect(users.map(u => u.get('id'))).to.deep.equal([1, 3, 5, 4]); expect(users.map(u => u.get('id'))).to.deep.equal([1, 3, 5, 4]);
}); });
});
it('works with multiple orders', function() { it('works with multiple orders', async function() {
return this.User.findAll({ const users = await this.User.findAll({
attributes: ['id'], attributes: ['id'],
groupedLimit: { groupedLimit: {
limit: 3, limit: 3,
...@@ -150,7 +150,8 @@ if (current.dialect.supports['UNION ALL']) { ...@@ -150,7 +150,8 @@ if (current.dialect.supports['UNION ALL']) {
['id', 'DESC'] ['id', 'DESC']
], ],
include: [this.User.Tasks] include: [this.User.Tasks]
}).then(users => { });
/* /*
project1 - 1, 3, 4 project1 - 1, 3, 4
project2 - 3, 5, 7 project2 - 3, 5, 7
...@@ -158,10 +159,9 @@ if (current.dialect.supports['UNION ALL']) { ...@@ -158,10 +159,9 @@ if (current.dialect.supports['UNION ALL']) {
expect(users).to.have.length(5); expect(users).to.have.length(5);
expect(users.map(u => u.get('id'))).to.deep.equal([1, 3, 5, 7, 4]); expect(users.map(u => u.get('id'))).to.deep.equal([1, 3, 5, 7, 4]);
}); });
});
it('works with paranoid junction models', function() { it('works with paranoid junction models', async function() {
return this.User.findAll({ const users0 = await this.User.findAll({
attributes: ['id'], attributes: ['id'],
groupedLimit: { groupedLimit: {
limit: 3, limit: 3,
...@@ -173,20 +173,21 @@ if (current.dialect.supports['UNION ALL']) { ...@@ -173,20 +173,21 @@ if (current.dialect.supports['UNION ALL']) {
['id', 'DESC'] ['id', 'DESC']
], ],
include: [this.User.Tasks] include: [this.User.Tasks]
}).then(users => { });
/* /*
project1 - 1, 3, 4 project1 - 1, 3, 4
project2 - 3, 5, 7 project2 - 3, 5, 7
*/ */
expect(users).to.have.length(5); expect(users0).to.have.length(5);
expect(users.map(u => u.get('id'))).to.deep.equal([1, 3, 5, 7, 4]); expect(users0.map(u => u.get('id'))).to.deep.equal([1, 3, 5, 7, 4]);
return Promise.all([ await Promise.all([
this.projects[0].setParanoidMembers(users.slice(0, 2)), this.projects[0].setParanoidMembers(users0.slice(0, 2)),
this.projects[1].setParanoidMembers(users.slice(4)) this.projects[1].setParanoidMembers(users0.slice(4))
]); ]);
}).then(() => {
return this.User.findAll({ const users = await this.User.findAll({
attributes: ['id'], attributes: ['id'],
groupedLimit: { groupedLimit: {
limit: 3, limit: 3,
...@@ -199,7 +200,7 @@ if (current.dialect.supports['UNION ALL']) { ...@@ -199,7 +200,7 @@ if (current.dialect.supports['UNION ALL']) {
], ],
include: [this.User.Tasks] include: [this.User.Tasks]
}); });
}).then(users => {
/* /*
project1 - 1, 3 project1 - 1, 3
project2 - 4 project2 - 4
...@@ -208,33 +209,32 @@ if (current.dialect.supports['UNION ALL']) { ...@@ -208,33 +209,32 @@ if (current.dialect.supports['UNION ALL']) {
expect(users.map(u => u.get('id'))).to.deep.equal([1, 3, 4]); expect(users.map(u => u.get('id'))).to.deep.equal([1, 3, 4]);
}); });
}); });
});
describe('on: hasMany', () => { describe('on: hasMany', () => {
beforeEach(function() { beforeEach(async function() {
this.User = this.sequelize.define('user'); this.User = this.sequelize.define('user');
this.Task = this.sequelize.define('task'); this.Task = this.sequelize.define('task');
this.User.Tasks = this.User.hasMany(this.Task); this.User.Tasks = this.User.hasMany(this.Task);
return this.sequelize.sync({ force: true }).then(() => { await this.sequelize.sync({ force: true });
return Promise.all([
await Promise.all([
this.User.bulkCreate([{}, {}, {}]), this.User.bulkCreate([{}, {}, {}]),
this.Task.bulkCreate([{ id: 1 }, { id: 2 }, { id: 3 }, { id: 4 }, { id: 5 }, { id: 6 }]) this.Task.bulkCreate([{ id: 1 }, { id: 2 }, { id: 3 }, { id: 4 }, { id: 5 }, { id: 6 }])
]); ]);
})
.then(() => Promise.all([this.User.findAll(), this.Task.findAll()])) const [users, tasks] = await Promise.all([this.User.findAll(), this.Task.findAll()]);
.then(([users, tasks]) => {
this.users = users; this.users = users;
return Promise.all([
await Promise.all([
users[0].setTasks(tasks[0]), users[0].setTasks(tasks[0]),
users[1].setTasks(tasks.slice(1, 4)), users[1].setTasks(tasks.slice(1, 4)),
users[2].setTasks(tasks.slice(4)) users[2].setTasks(tasks.slice(4))
]); ]);
}); });
});
it('Applies limit and order correctly', function() { it('Applies limit and order correctly', async function() {
return this.Task.findAll({ const tasks = await this.Task.findAll({
order: [ order: [
['id', 'DESC'] ['id', 'DESC']
], ],
...@@ -243,7 +243,8 @@ if (current.dialect.supports['UNION ALL']) { ...@@ -243,7 +243,8 @@ if (current.dialect.supports['UNION ALL']) {
on: this.User.Tasks, on: this.User.Tasks,
values: this.users.map(item => item.get('id')) values: this.users.map(item => item.get('id'))
} }
}).then(tasks => { });
const byUser = _.groupBy(tasks, _.property('userId')); const byUser = _.groupBy(tasks, _.property('userId'));
expect(Object.keys(byUser)).to.have.length(3); expect(Object.keys(byUser)).to.have.length(3);
...@@ -256,5 +257,4 @@ if (current.dialect.supports['UNION ALL']) { ...@@ -256,5 +257,4 @@ if (current.dialect.supports['UNION ALL']) {
}); });
}); });
}); });
});
} }
...@@ -10,58 +10,58 @@ describe(Support.getTestDialectTeaser('Model'), () => { ...@@ -10,58 +10,58 @@ describe(Support.getTestDialectTeaser('Model'), () => {
describe('findAll', () => { describe('findAll', () => {
describe('order', () => { describe('order', () => {
describe('Sequelize.literal()', () => { describe('Sequelize.literal()', () => {
beforeEach(function() { beforeEach(async function() {
this.User = this.sequelize.define('User', { this.User = this.sequelize.define('User', {
email: DataTypes.STRING email: DataTypes.STRING
}); });
return this.User.sync({ force: true }).then(() => { await this.User.sync({ force: true });
return this.User.create({
await this.User.create({
email: 'test@sequelizejs.com' email: 'test@sequelizejs.com'
}); });
}); });
});
if (current.dialect.name !== 'mssql') { if (current.dialect.name !== 'mssql') {
it('should work with order: literal()', function() { it('should work with order: literal()', async function() {
return this.User.findAll({ const users = await this.User.findAll({
order: this.sequelize.literal(`email = ${this.sequelize.escape('test@sequelizejs.com')}`) order: this.sequelize.literal(`email = ${this.sequelize.escape('test@sequelizejs.com')}`)
}).then(users => { });
expect(users.length).to.equal(1); expect(users.length).to.equal(1);
users.forEach(user => { users.forEach(user => {
expect(user.get('email')).to.be.ok; expect(user.get('email')).to.be.ok;
}); });
}); });
});
it('should work with order: [literal()]', function() { it('should work with order: [literal()]', async function() {
return this.User.findAll({ const users = await this.User.findAll({
order: [this.sequelize.literal(`email = ${this.sequelize.escape('test@sequelizejs.com')}`)] order: [this.sequelize.literal(`email = ${this.sequelize.escape('test@sequelizejs.com')}`)]
}).then(users => { });
expect(users.length).to.equal(1); expect(users.length).to.equal(1);
users.forEach(user => { users.forEach(user => {
expect(user.get('email')).to.be.ok; expect(user.get('email')).to.be.ok;
}); });
}); });
});
it('should work with order: [[literal()]]', function() { it('should work with order: [[literal()]]', async function() {
return this.User.findAll({ const users = await this.User.findAll({
order: [ order: [
[this.sequelize.literal(`email = ${this.sequelize.escape('test@sequelizejs.com')}`)] [this.sequelize.literal(`email = ${this.sequelize.escape('test@sequelizejs.com')}`)]
] ]
}).then(users => { });
expect(users.length).to.equal(1); expect(users.length).to.equal(1);
users.forEach(user => { users.forEach(user => {
expect(user.get('email')).to.be.ok; expect(user.get('email')).to.be.ok;
}); });
}); });
});
} }
}); });
describe('injections', () => { describe('injections', () => {
beforeEach(function() { beforeEach(async function() {
this.User = this.sequelize.define('user', { this.User = this.sequelize.define('user', {
name: DataTypes.STRING name: DataTypes.STRING
}); });
...@@ -69,12 +69,12 @@ describe(Support.getTestDialectTeaser('Model'), () => { ...@@ -69,12 +69,12 @@ describe(Support.getTestDialectTeaser('Model'), () => {
}); });
this.User.belongsTo(this.Group); this.User.belongsTo(this.Group);
return this.sequelize.sync({ force: true }); await this.sequelize.sync({ force: true });
}); });
if (current.dialect.supports['ORDER NULLS']) { if (current.dialect.supports['ORDER NULLS']) {
it('should not throw with on NULLS LAST/NULLS FIRST', function() { it('should not throw with on NULLS LAST/NULLS FIRST', async function() {
return this.User.findAll({ await this.User.findAll({
include: [this.Group], include: [this.Group],
order: [ order: [
['id', 'ASC NULLS LAST'], ['id', 'ASC NULLS LAST'],
...@@ -84,16 +84,16 @@ describe(Support.getTestDialectTeaser('Model'), () => { ...@@ -84,16 +84,16 @@ describe(Support.getTestDialectTeaser('Model'), () => {
}); });
} }
it('should not throw on a literal', function() { it('should not throw on a literal', async function() {
return this.User.findAll({ await this.User.findAll({
order: [ order: [
['id', this.sequelize.literal('ASC, name DESC')] ['id', this.sequelize.literal('ASC, name DESC')]
] ]
}); });
}); });
it('should not throw with include when last order argument is a field', function() { it('should not throw with include when last order argument is a field', async function() {
return this.User.findAll({ await this.User.findAll({
include: [this.Group], include: [this.Group],
order: [ order: [
[this.Group, 'id'] [this.Group, 'id']
......
...@@ -9,7 +9,7 @@ const current = Support.sequelize; ...@@ -9,7 +9,7 @@ const current = Support.sequelize;
describe(Support.getTestDialectTeaser('Model'), () => { describe(Support.getTestDialectTeaser('Model'), () => {
describe('findAll', () => { describe('findAll', () => {
describe('separate with limit', () => { describe('separate with limit', () => {
it('should not throw syntax error (union)', () => { it('should not throw syntax error (union)', async () => {
// #9813 testcase // #9813 testcase
const Project = current.define('Project', { name: DataTypes.STRING }); const Project = current.define('Project', { name: DataTypes.STRING });
const LevelTwo = current.define('LevelTwo', { name: DataTypes.STRING }); const LevelTwo = current.define('LevelTwo', { name: DataTypes.STRING });
...@@ -22,20 +22,23 @@ describe(Support.getTestDialectTeaser('Model'), () => { ...@@ -22,20 +22,23 @@ describe(Support.getTestDialectTeaser('Model'), () => {
LevelTwo.hasMany(LevelThree, { as: 'type_twos' }); LevelTwo.hasMany(LevelThree, { as: 'type_twos' });
LevelThree.belongsTo(LevelTwo); LevelThree.belongsTo(LevelTwo);
return current.sync({ force: true }).then(() => { try {
return Promise.all([ try {
await current.sync({ force: true });
const [project, level21, level22] = await Promise.all([
Project.create({ name: 'testProject' }), Project.create({ name: 'testProject' }),
LevelTwo.create({ name: 'testL21' }), LevelTwo.create({ name: 'testL21' }),
LevelTwo.create({ name: 'testL22' }) LevelTwo.create({ name: 'testL22' })
]); ]);
}).then(([project, level21, level22]) => {
return Promise.all([ await Promise.all([
project.addLevelTwo(level21), project.addLevelTwo(level21),
project.addLevelTwo(level22) project.addLevelTwo(level22)
]); ]);
}).then(() => {
// one include case // one include case
return Project.findAll({ const projects0 = await Project.findAll({
where: { name: 'testProject' }, where: { name: 'testProject' },
include: [ include: [
{ {
...@@ -53,16 +56,17 @@ describe(Support.getTestDialectTeaser('Model'), () => { ...@@ -53,16 +56,17 @@ describe(Support.getTestDialectTeaser('Model'), () => {
} }
] ]
}); });
}).then(projects => {
expect(projects).to.have.length(1); expect(projects0).to.have.length(1);
expect(projects[0].LevelTwos).to.have.length(2); expect(projects0[0].LevelTwos).to.have.length(2);
expect(projects[0].LevelTwos[0].type_ones).to.have.length(0); expect(projects0[0].LevelTwos[0].type_ones).to.have.length(0);
expect(projects[0].LevelTwos[1].type_ones).to.have.length(0); expect(projects0[0].LevelTwos[1].type_ones).to.have.length(0);
}, () => { } catch (err) {
expect.fail(); expect.fail();
}).then(() => { }
// two includes case // two includes case
return Project.findAll({ const projects = await Project.findAll({
where: { name: 'testProject' }, where: { name: 'testProject' },
include: [ include: [
{ {
...@@ -88,14 +92,14 @@ describe(Support.getTestDialectTeaser('Model'), () => { ...@@ -88,14 +92,14 @@ describe(Support.getTestDialectTeaser('Model'), () => {
} }
] ]
}); });
}).then(projects => {
expect(projects).to.have.length(1); expect(projects).to.have.length(1);
expect(projects[0].LevelTwos).to.have.length(2); expect(projects[0].LevelTwos).to.have.length(2);
expect(projects[0].LevelTwos[0].type_ones).to.have.length(0); expect(projects[0].LevelTwos[0].type_ones).to.have.length(0);
expect(projects[0].LevelTwos[1].type_ones).to.have.length(0); expect(projects[0].LevelTwos[1].type_ones).to.have.length(0);
}, () => { } catch (err) {
expect.fail(); expect.fail();
}); }
}); });
}); });
}); });
......
...@@ -6,7 +6,7 @@ const chai = require('chai'), ...@@ -6,7 +6,7 @@ const chai = require('chai'),
DataTypes = require('../../../lib/data-types'); DataTypes = require('../../../lib/data-types');
describe(Support.getTestDialectTeaser('Model'), () => { describe(Support.getTestDialectTeaser('Model'), () => {
beforeEach(function() { beforeEach(async function() {
this.User = this.sequelize.define('User', { this.User = this.sequelize.define('User', {
username: DataTypes.STRING, username: DataTypes.STRING,
age: DataTypes.INTEGER age: DataTypes.INTEGER
...@@ -18,21 +18,24 @@ describe(Support.getTestDialectTeaser('Model'), () => { ...@@ -18,21 +18,24 @@ describe(Support.getTestDialectTeaser('Model'), () => {
this.User.hasMany(this.Project); this.User.hasMany(this.Project);
this.Project.belongsTo(this.User); this.Project.belongsTo(this.User);
return this.sequelize.sync({ force: true }); await this.sequelize.sync({ force: true });
}); });
describe('findOrBuild', () => { describe('findOrBuild', () => {
it('initialize with includes', function() { it('initialize with includes', async function() {
return this.User.bulkCreate([ const [, user2] = await this.User.bulkCreate([
{ username: 'Mello', age: 10 }, { username: 'Mello', age: 10 },
{ username: 'Mello', age: 20 } { username: 'Mello', age: 20 }
], { returning: true }).then(([, user2]) => { ], { returning: true });
return this.Project.create({
const project = await this.Project.create({
name: 'Investigate' name: 'Investigate'
}).then(project => user2.setProjects([project])); });
}).then(() => {
return this.User.findOrBuild({ await user2.setProjects([project]);
const [user, created] = await this.User.findOrBuild({
defaults: { defaults: {
username: 'Mello', username: 'Mello',
age: 10 age: 10
...@@ -44,7 +47,7 @@ describe(Support.getTestDialectTeaser('Model'), () => { ...@@ -44,7 +47,7 @@ describe(Support.getTestDialectTeaser('Model'), () => {
model: this.Project model: this.Project
}] }]
}); });
}).then(([user, created]) => {
expect(created).to.be.false; expect(created).to.be.false;
expect(user.get('id')).to.be.ok; expect(user.get('id')).to.be.ok;
expect(user.get('username')).to.equal('Mello'); expect(user.get('username')).to.equal('Mello');
...@@ -54,5 +57,4 @@ describe(Support.getTestDialectTeaser('Model'), () => { ...@@ -54,5 +57,4 @@ describe(Support.getTestDialectTeaser('Model'), () => {
expect(user.Projects[0].get('name')).to.equal('Investigate'); expect(user.Projects[0].get('name')).to.equal('Investigate');
}); });
}); });
});
}); });
...@@ -8,7 +8,7 @@ const expect = chai.expect; ...@@ -8,7 +8,7 @@ const expect = chai.expect;
describe(Support.getTestDialectTeaser('Model'), () => { describe(Support.getTestDialectTeaser('Model'), () => {
describe('optimistic locking', () => { describe('optimistic locking', () => {
let Account; let Account;
beforeEach(function() { beforeEach(async function() {
Account = this.sequelize.define('Account', { Account = this.sequelize.define('Account', {
number: { number: {
type: DataTypes.INTEGER type: DataTypes.INTEGER
...@@ -16,65 +16,54 @@ describe(Support.getTestDialectTeaser('Model'), () => { ...@@ -16,65 +16,54 @@ describe(Support.getTestDialectTeaser('Model'), () => {
}, { }, {
version: true version: true
}); });
return Account.sync({ force: true }); await Account.sync({ force: true });
}); });
it('should increment the version on save', () => { it('should increment the version on save', async () => {
return Account.create({ number: 1 }).then(account => { const account0 = await Account.create({ number: 1 });
account.number += 1; account0.number += 1;
expect(account.version).to.eq(0); expect(account0.version).to.eq(0);
return account.save(); const account = await account0.save();
}).then(account => {
expect(account.version).to.eq(1); expect(account.version).to.eq(1);
}); });
});
it('should increment the version on update', () => { it('should increment the version on update', async () => {
return Account.create({ number: 1 }).then(account => { const account1 = await Account.create({ number: 1 });
expect(account.version).to.eq(0); expect(account1.version).to.eq(0);
return account.update({ number: 2 }); const account0 = await account1.update({ number: 2 });
}).then(account => { expect(account0.version).to.eq(1);
expect(account.version).to.eq(1); account0.number += 1;
account.number += 1; const account = await account0.save();
return account.save();
}).then(account => {
expect(account.number).to.eq(3); expect(account.number).to.eq(3);
expect(account.version).to.eq(2); expect(account.version).to.eq(2);
}); });
});
it('prevents stale instances from being saved', () => { it('prevents stale instances from being saved', async () => {
return expect(Account.create({ number: 1 }).then(accountA => { await expect((async () => {
return Account.findByPk(accountA.id).then(accountB => { const accountA = await Account.create({ number: 1 });
const accountB0 = await Account.findByPk(accountA.id);
accountA.number += 1; accountA.number += 1;
return accountA.save().then(() => { return accountB; }); await accountA.save();
}); const accountB = await accountB0;
}).then(accountB => {
accountB.number += 1; accountB.number += 1;
return accountB.save(); return await accountB.save();
})).to.eventually.be.rejectedWith(Support.Sequelize.OptimisticLockError); })()).to.eventually.be.rejectedWith(Support.Sequelize.OptimisticLockError);
}); });
it('increment() also increments the version', () => { it('increment() also increments the version', async () => {
return Account.create({ number: 1 }).then(account => { const account1 = await Account.create({ number: 1 });
expect(account.version).to.eq(0); expect(account1.version).to.eq(0);
return account.increment('number', { by: 1 } ); const account0 = await account1.increment('number', { by: 1 } );
}).then(account => { const account = await account0.reload();
return account.reload();
}).then(account => {
expect(account.version).to.eq(1); expect(account.version).to.eq(1);
}); });
});
it('decrement() also increments the version', () => { it('decrement() also increments the version', async () => {
return Account.create({ number: 1 }).then(account => { const account1 = await Account.create({ number: 1 });
expect(account.version).to.eq(0); expect(account1.version).to.eq(0);
return account.decrement('number', { by: 1 } ); const account0 = await account1.decrement('number', { by: 1 } );
}).then(account => { const account = await account0.reload();
return account.reload();
}).then(account => {
expect(account.version).to.eq(1); expect(account.version).to.eq(1);
}); });
}); });
});
}); });
...@@ -17,7 +17,7 @@ describe(Support.getTestDialectTeaser('Model'), () => { ...@@ -17,7 +17,7 @@ describe(Support.getTestDialectTeaser('Model'), () => {
this.clock.restore(); this.clock.restore();
}); });
it('should be able to soft delete with timestamps', function() { it('should be able to soft delete with timestamps', async function() {
const Account = this.sequelize.define('Account', { const Account = this.sequelize.define('Account', {
ownerId: { ownerId: {
type: DataTypes.INTEGER, type: DataTypes.INTEGER,
...@@ -32,32 +32,22 @@ describe(Support.getTestDialectTeaser('Model'), () => { ...@@ -32,32 +32,22 @@ describe(Support.getTestDialectTeaser('Model'), () => {
timestamps: true timestamps: true
}); });
return Account.sync({ force: true }) await Account.sync({ force: true });
.then(() => Account.create({ ownerId: 12 })) await Account.create({ ownerId: 12 });
.then(() => Account.count()) const count2 = await Account.count();
.then(count => { expect(count2).to.be.equal(1);
expect(count).to.be.equal(1); const result = await Account.destroy({ where: { ownerId: 12 } });
return Account.destroy({ where: { ownerId: 12 } })
.then(result => {
expect(result).to.be.equal(1); expect(result).to.be.equal(1);
}); const count1 = await Account.count();
}) expect(count1).to.be.equal(0);
.then(() => Account.count()) const count0 = await Account.count({ paranoid: false });
.then(count => { expect(count0).to.be.equal(1);
expect(count).to.be.equal(0); await Account.restore({ where: { ownerId: 12 } });
return Account.count({ paranoid: false }); const count = await Account.count();
})
.then(count => {
expect(count).to.be.equal(1);
return Account.restore({ where: { ownerId: 12 } });
})
.then(() => Account.count())
.then(count => {
expect(count).to.be.equal(1); expect(count).to.be.equal(1);
}); });
});
it('should be able to soft delete without timestamps', function() { it('should be able to soft delete without timestamps', async function() {
const Account = this.sequelize.define('Account', { const Account = this.sequelize.define('Account', {
ownerId: { ownerId: {
type: DataTypes.INTEGER, type: DataTypes.INTEGER,
...@@ -80,27 +70,19 @@ describe(Support.getTestDialectTeaser('Model'), () => { ...@@ -80,27 +70,19 @@ describe(Support.getTestDialectTeaser('Model'), () => {
updatedAt: false updatedAt: false
}); });
return Account.sync({ force: true }) await Account.sync({ force: true });
.then(() => Account.create({ ownerId: 12 })) await Account.create({ ownerId: 12 });
.then(() => Account.count()) const count2 = await Account.count();
.then(count => { expect(count2).to.be.equal(1);
expect(count).to.be.equal(1); await Account.destroy({ where: { ownerId: 12 } });
return Account.destroy({ where: { ownerId: 12 } }); const count1 = await Account.count();
}) expect(count1).to.be.equal(0);
.then(() => Account.count()) const count0 = await Account.count({ paranoid: false });
.then(count => { expect(count0).to.be.equal(1);
expect(count).to.be.equal(0); await Account.restore({ where: { ownerId: 12 } });
return Account.count({ paranoid: false }); const count = await Account.count();
})
.then(count => {
expect(count).to.be.equal(1);
return Account.restore({ where: { ownerId: 12 } });
})
.then(() => Account.count())
.then(count => {
expect(count).to.be.equal(1); expect(count).to.be.equal(1);
}); });
});
if (current.dialect.supports.JSON) { if (current.dialect.supports.JSON) {
describe('JSON', () => { describe('JSON', () => {
...@@ -124,12 +106,12 @@ describe(Support.getTestDialectTeaser('Model'), () => { ...@@ -124,12 +106,12 @@ describe(Support.getTestDialectTeaser('Model'), () => {
}); });
}); });
beforeEach(function() { beforeEach(async function() {
return this.Model.sync({ force: true }); await this.Model.sync({ force: true });
}); });
it('should soft delete with JSON condition', function() { it('should soft delete with JSON condition', async function() {
return this.Model.bulkCreate([{ await this.Model.bulkCreate([{
name: 'One', name: 'One',
data: { data: {
field: { field: {
...@@ -143,7 +125,9 @@ describe(Support.getTestDialectTeaser('Model'), () => { ...@@ -143,7 +125,9 @@ describe(Support.getTestDialectTeaser('Model'), () => {
deep: false deep: false
} }
} }
}]).then(() => this.Model.destroy({ }]);
await this.Model.destroy({
where: { where: {
data: { data: {
field: { field: {
...@@ -151,12 +135,13 @@ describe(Support.getTestDialectTeaser('Model'), () => { ...@@ -151,12 +135,13 @@ describe(Support.getTestDialectTeaser('Model'), () => {
} }
} }
} }
})).then(() => this.Model.findAll()).then(records => { });
const records = await this.Model.findAll();
expect(records.length).to.equal(1); expect(records.length).to.equal(1);
expect(records[0].get('name')).to.equal('Two'); expect(records[0].get('name')).to.equal('Two');
}); });
}); });
});
} }
}); });
}); });
...@@ -8,7 +8,7 @@ const chai = require('chai'), ...@@ -8,7 +8,7 @@ const chai = require('chai'),
describe(Support.getTestDialectTeaser('Model'), () => { describe(Support.getTestDialectTeaser('Model'), () => {
describe('scope', () => { describe('scope', () => {
beforeEach(function() { beforeEach(async function() {
this.ScopeMe = this.sequelize.define('ScopeMe', { this.ScopeMe = this.sequelize.define('ScopeMe', {
username: Sequelize.STRING, username: Sequelize.STRING,
email: Sequelize.STRING, email: Sequelize.STRING,
...@@ -57,66 +57,54 @@ describe(Support.getTestDialectTeaser('Model'), () => { ...@@ -57,66 +57,54 @@ describe(Support.getTestDialectTeaser('Model'), () => {
} }
}); });
return this.sequelize.sync({ force: true }).then(() => { await this.sequelize.sync({ force: true });
const records = [ const records = [
{ username: 'tony', email: 'tony@sequelizejs.com', access_level: 3, other_value: 7 }, { username: 'tony', email: 'tony@sequelizejs.com', access_level: 3, other_value: 7 },
{ username: 'tobi', email: 'tobi@fakeemail.com', access_level: 10, other_value: 11 }, { username: 'tobi', email: 'tobi@fakeemail.com', access_level: 10, other_value: 11 },
{ username: 'dan', email: 'dan@sequelizejs.com', access_level: 5, other_value: 10 }, { username: 'dan', email: 'dan@sequelizejs.com', access_level: 5, other_value: 10 },
{ username: 'fred', email: 'fred@foobar.com', access_level: 3, other_value: 7 } { username: 'fred', email: 'fred@foobar.com', access_level: 3, other_value: 7 }
]; ];
return this.ScopeMe.bulkCreate(records);
}); await this.ScopeMe.bulkCreate(records);
}); });
it('should be able to merge attributes as array', function() { it('should be able to merge attributes as array', async function() {
return this.ScopeMe.scope('lowAccess', 'withName').findOne() const record = await this.ScopeMe.scope('lowAccess', 'withName').findOne();
.then(record => {
expect(record.other_value).to.exist; expect(record.other_value).to.exist;
expect(record.username).to.exist; expect(record.username).to.exist;
expect(record.access_level).to.exist; expect(record.access_level).to.exist;
}); });
});
it('should work with Symbol operators', function() { it('should work with Symbol operators', async function() {
return this.ScopeMe.scope('highAccess').findOne() const record = await this.ScopeMe.scope('highAccess').findOne();
.then(record => {
expect(record.username).to.equal('tobi'); expect(record.username).to.equal('tobi');
return this.ScopeMe.scope('lessThanFour').findAll(); const records0 = await this.ScopeMe.scope('lessThanFour').findAll();
}) expect(records0).to.have.length(2);
.then(records => { expect(records0[0].get('access_level')).to.equal(3);
expect(records).to.have.length(2); expect(records0[1].get('access_level')).to.equal(3);
expect(records[0].get('access_level')).to.equal(3); const records = await this.ScopeMe.scope('issue8473').findAll();
expect(records[1].get('access_level')).to.equal(3);
return this.ScopeMe.scope('issue8473').findAll();
})
.then(records => {
expect(records).to.have.length(1); expect(records).to.have.length(1);
expect(records[0].get('access_level')).to.equal(5); expect(records[0].get('access_level')).to.equal(5);
expect(records[0].get('other_value')).to.equal(10); expect(records[0].get('other_value')).to.equal(10);
}); });
});
it('should keep symbols after default assignment', function() { it('should keep symbols after default assignment', async function() {
return this.ScopeMe.scope('highAccess').findOne() const record = await this.ScopeMe.scope('highAccess').findOne();
.then(record => {
expect(record.username).to.equal('tobi'); expect(record.username).to.equal('tobi');
return this.ScopeMe.scope('lessThanFour').findAll({
const records = await this.ScopeMe.scope('lessThanFour').findAll({
where: {} where: {}
}); });
})
.then(records => {
expect(records).to.have.length(2); expect(records).to.have.length(2);
expect(records[0].get('access_level')).to.equal(3); expect(records[0].get('access_level')).to.equal(3);
expect(records[1].get('access_level')).to.equal(3); expect(records[1].get('access_level')).to.equal(3);
return this.ScopeMe.scope('issue8473').findAll(); await this.ScopeMe.scope('issue8473').findAll();
});
}); });
it('should not throw error with sequelize.where', function() { it('should not throw error with sequelize.where', async function() {
return this.ScopeMe.scope('like_t').findAll() const records = await this.ScopeMe.scope('like_t').findAll();
.then(records => {
expect(records).to.have.length(2); expect(records).to.have.length(2);
}); });
}); });
});
}); });
...@@ -9,7 +9,7 @@ const chai = require('chai'), ...@@ -9,7 +9,7 @@ const chai = require('chai'),
describe(Support.getTestDialectTeaser('Model'), () => { describe(Support.getTestDialectTeaser('Model'), () => {
describe('scope', () => { describe('scope', () => {
describe('aggregate', () => { describe('aggregate', () => {
beforeEach(function() { beforeEach(async function() {
this.Child = this.sequelize.define('Child', { this.Child = this.sequelize.define('Child', {
priority: Sequelize.INTEGER priority: Sequelize.INTEGER
}); });
...@@ -50,18 +50,17 @@ describe(Support.getTestDialectTeaser('Model'), () => { ...@@ -50,18 +50,17 @@ describe(Support.getTestDialectTeaser('Model'), () => {
this.Child.belongsTo(this.ScopeMe); this.Child.belongsTo(this.ScopeMe);
this.ScopeMe.hasMany(this.Child); this.ScopeMe.hasMany(this.Child);
return this.sequelize.sync({ force: true }).then(() => { await this.sequelize.sync({ force: true });
const records = [ const records0 = [
{ username: 'tony', email: 'tony@sequelizejs.com', access_level: 3, other_value: 7 }, { username: 'tony', email: 'tony@sequelizejs.com', access_level: 3, other_value: 7 },
{ username: 'tobi', email: 'tobi@fakeemail.com', access_level: 10, other_value: 11 }, { username: 'tobi', email: 'tobi@fakeemail.com', access_level: 10, other_value: 11 },
{ username: 'dan', email: 'dan@sequelizejs.com', access_level: 5, other_value: 10 }, { username: 'dan', email: 'dan@sequelizejs.com', access_level: 5, other_value: 10 },
{ username: 'fred', email: 'fred@foobar.com', access_level: 3, other_value: 7 } { username: 'fred', email: 'fred@foobar.com', access_level: 3, other_value: 7 }
]; ];
return this.ScopeMe.bulkCreate(records); await this.ScopeMe.bulkCreate(records0);
}).then(() => { const records = await this.ScopeMe.findAll();
return this.ScopeMe.findAll();
}).then(records => { await Promise.all([
return Promise.all([
records[0].createChild({ records[0].createChild({
priority: 1 priority: 1
}), }),
...@@ -70,30 +69,29 @@ describe(Support.getTestDialectTeaser('Model'), () => { ...@@ -70,30 +69,29 @@ describe(Support.getTestDialectTeaser('Model'), () => {
}) })
]); ]);
}); });
});
it('should apply defaultScope', function() { it('should apply defaultScope', async function() {
return expect(this.ScopeMe.aggregate( '*', 'count' )).to.eventually.equal(2); await expect(this.ScopeMe.aggregate( '*', 'count' )).to.eventually.equal(2);
}); });
it('should be able to override default scope', function() { it('should be able to override default scope', async function() {
return expect(this.ScopeMe.aggregate( '*', 'count', { where: { access_level: { [Op.gt]: 5 } } })).to.eventually.equal(1); await expect(this.ScopeMe.aggregate( '*', 'count', { where: { access_level: { [Op.gt]: 5 } } })).to.eventually.equal(1);
}); });
it('should be able to unscope', function() { it('should be able to unscope', async function() {
return expect(this.ScopeMe.unscoped().aggregate( '*', 'count' )).to.eventually.equal(4); await expect(this.ScopeMe.unscoped().aggregate( '*', 'count' )).to.eventually.equal(4);
}); });
it('should be able to apply other scopes', function() { it('should be able to apply other scopes', async function() {
return expect(this.ScopeMe.scope('lowAccess').aggregate( '*', 'count' )).to.eventually.equal(3); await expect(this.ScopeMe.scope('lowAccess').aggregate( '*', 'count' )).to.eventually.equal(3);
}); });
it('should be able to merge scopes with where', function() { it('should be able to merge scopes with where', async function() {
return expect(this.ScopeMe.scope('lowAccess').aggregate( '*', 'count', { where: { username: 'dan' } })).to.eventually.equal(1); await expect(this.ScopeMe.scope('lowAccess').aggregate( '*', 'count', { where: { username: 'dan' } })).to.eventually.equal(1);
}); });
it('should be able to use where on include', function() { it('should be able to use where on include', async function() {
return expect(this.ScopeMe.scope('withInclude').aggregate( 'ScopeMe.id', 'count', { await expect(this.ScopeMe.scope('withInclude').aggregate( 'ScopeMe.id', 'count', {
plain: true, plain: true,
dataType: new Sequelize.INTEGER(), dataType: new Sequelize.INTEGER(),
includeIgnoreAttributes: false, includeIgnoreAttributes: false,
...@@ -105,27 +103,21 @@ describe(Support.getTestDialectTeaser('Model'), () => { ...@@ -105,27 +103,21 @@ describe(Support.getTestDialectTeaser('Model'), () => {
}); });
if (Support.sequelize.dialect.supports.schemas) { if (Support.sequelize.dialect.supports.schemas) {
it('aggregate with schema', function() { it('aggregate with schema', async function() {
this.Hero = this.sequelize.define('Hero', { this.Hero = this.sequelize.define('Hero', {
codename: Sequelize.STRING codename: Sequelize.STRING
}, { schema: 'heroschema' }); }, { schema: 'heroschema' });
return this.sequelize.createSchema('heroschema') await this.sequelize.createSchema('heroschema');
.then(() => { await this.sequelize.sync({ force: true });
return this.sequelize.sync({ force: true });
})
.then(() => {
const records = [ const records = [
{ codename: 'hulk' }, { codename: 'hulk' },
{ codename: 'rantanplan' } { codename: 'rantanplan' }
]; ];
return this.Hero.bulkCreate(records); await this.Hero.bulkCreate(records);
})
.then(() => { await expect(
return expect(
this.Hero.unscoped().aggregate('*', 'count', this.Hero.unscoped().aggregate('*', 'count',
{ schema: 'heroschema' })).to.eventually.equal( { schema: 'heroschema' })).to.eventually.equal(2);
2);
});
}); });
} }
}); });
......
...@@ -9,7 +9,7 @@ const chai = require('chai'), ...@@ -9,7 +9,7 @@ const chai = require('chai'),
describe(Support.getTestDialectTeaser('Model'), () => { describe(Support.getTestDialectTeaser('Model'), () => {
describe('scope', () => { describe('scope', () => {
describe('count', () => { describe('count', () => {
beforeEach(function() { beforeEach(async function() {
this.Child = this.sequelize.define('Child', { this.Child = this.sequelize.define('Child', {
priority: Sequelize.INTEGER priority: Sequelize.INTEGER
}); });
...@@ -80,18 +80,17 @@ describe(Support.getTestDialectTeaser('Model'), () => { ...@@ -80,18 +80,17 @@ describe(Support.getTestDialectTeaser('Model'), () => {
this.Child.belongsTo(this.ScopeMe); this.Child.belongsTo(this.ScopeMe);
this.ScopeMe.hasMany(this.Child); this.ScopeMe.hasMany(this.Child);
return this.sequelize.sync({ force: true }).then(() => { await this.sequelize.sync({ force: true });
const records = [ const records0 = [
{ username: 'tony', email: 'tony@sequelizejs.com', access_level: 3, other_value: 7, aliasValue: 12 }, { username: 'tony', email: 'tony@sequelizejs.com', access_level: 3, other_value: 7, aliasValue: 12 },
{ username: 'tobi', email: 'tobi@fakeemail.com', access_level: 10, other_value: 11, aliasValue: 5 }, { username: 'tobi', email: 'tobi@fakeemail.com', access_level: 10, other_value: 11, aliasValue: 5 },
{ username: 'dan', email: 'dan@sequelizejs.com', access_level: 5, other_value: 10, aliasValue: 1 }, { username: 'dan', email: 'dan@sequelizejs.com', access_level: 5, other_value: 10, aliasValue: 1 },
{ username: 'fred', email: 'fred@foobar.com', access_level: 3, other_value: 7, aliasValue: 10 } { username: 'fred', email: 'fred@foobar.com', access_level: 3, other_value: 7, aliasValue: 10 }
]; ];
return this.ScopeMe.bulkCreate(records); await this.ScopeMe.bulkCreate(records0);
}).then(() => { const records = await this.ScopeMe.findAll();
return this.ScopeMe.findAll();
}).then(records => { await Promise.all([
return Promise.all([
records[0].createChild({ records[0].createChild({
priority: 1 priority: 1
}), }),
...@@ -100,46 +99,45 @@ describe(Support.getTestDialectTeaser('Model'), () => { ...@@ -100,46 +99,45 @@ describe(Support.getTestDialectTeaser('Model'), () => {
}) })
]); ]);
}); });
});
it('should apply defaultScope', function() { it('should apply defaultScope', async function() {
return expect(this.ScopeMe.count()).to.eventually.equal(2); await expect(this.ScopeMe.count()).to.eventually.equal(2);
}); });
it('should be able to override default scope', function() { it('should be able to override default scope', async function() {
return expect(this.ScopeMe.count({ where: { access_level: { [Op.gt]: 5 } } })).to.eventually.equal(1); await expect(this.ScopeMe.count({ where: { access_level: { [Op.gt]: 5 } } })).to.eventually.equal(1);
}); });
it('should be able to unscope', function() { it('should be able to unscope', async function() {
return expect(this.ScopeMe.unscoped().count()).to.eventually.equal(4); await expect(this.ScopeMe.unscoped().count()).to.eventually.equal(4);
}); });
it('should be able to apply other scopes', function() { it('should be able to apply other scopes', async function() {
return expect(this.ScopeMe.scope('lowAccess').count()).to.eventually.equal(3); await expect(this.ScopeMe.scope('lowAccess').count()).to.eventually.equal(3);
}); });
it('should be able to merge scopes with where', function() { it('should be able to merge scopes with where', async function() {
return expect(this.ScopeMe.scope('lowAccess').count({ where: { username: 'dan' } })).to.eventually.equal(1); await expect(this.ScopeMe.scope('lowAccess').count({ where: { username: 'dan' } })).to.eventually.equal(1);
}); });
it('should be able to merge scopes with where on aliased fields', function() { it('should be able to merge scopes with where on aliased fields', async function() {
return expect(this.ScopeMe.scope('withAliasedField').count({ where: { aliasValue: 5 } })).to.eventually.equal(1); await expect(this.ScopeMe.scope('withAliasedField').count({ where: { aliasValue: 5 } })).to.eventually.equal(1);
}); });
it('should ignore the order option if it is found within the scope', function() { it('should ignore the order option if it is found within the scope', async function() {
return expect(this.ScopeMe.scope('withOrder').count()).to.eventually.equal(4); await expect(this.ScopeMe.scope('withOrder').count()).to.eventually.equal(4);
}); });
it('should be able to use where on include', function() { it('should be able to use where on include', async function() {
return expect(this.ScopeMe.scope('withInclude').count()).to.eventually.equal(1); await expect(this.ScopeMe.scope('withInclude').count()).to.eventually.equal(1);
}); });
it('should be able to use include with function scope', function() { it('should be able to use include with function scope', async function() {
return expect(this.ScopeMe.scope('withIncludeFunction').count()).to.eventually.equal(1); await expect(this.ScopeMe.scope('withIncludeFunction').count()).to.eventually.equal(1);
}); });
it('should be able to use include with function scope and string association', function() { it('should be able to use include with function scope and string association', async function() {
return expect(this.ScopeMe.scope('withIncludeFunctionAndStringAssociation').count()).to.eventually.equal(1); await expect(this.ScopeMe.scope('withIncludeFunctionAndStringAssociation').count()).to.eventually.equal(1);
}); });
}); });
}); });
......
...@@ -9,7 +9,7 @@ const chai = require('chai'), ...@@ -9,7 +9,7 @@ const chai = require('chai'),
describe(Support.getTestDialectTeaser('Model'), () => { describe(Support.getTestDialectTeaser('Model'), () => {
describe('scope', () => { describe('scope', () => {
describe('destroy', () => { describe('destroy', () => {
beforeEach(function() { beforeEach(async function() {
this.ScopeMe = this.sequelize.define('ScopeMe', { this.ScopeMe = this.sequelize.define('ScopeMe', {
username: Sequelize.STRING, username: Sequelize.STRING,
email: Sequelize.STRING, email: Sequelize.STRING,
...@@ -34,71 +34,60 @@ describe(Support.getTestDialectTeaser('Model'), () => { ...@@ -34,71 +34,60 @@ describe(Support.getTestDialectTeaser('Model'), () => {
} }
}); });
return this.sequelize.sync({ force: true }).then(() => { await this.sequelize.sync({ force: true });
const records = [ const records = [
{ username: 'tony', email: 'tony@sequelizejs.com', access_level: 3, other_value: 7 }, { username: 'tony', email: 'tony@sequelizejs.com', access_level: 3, other_value: 7 },
{ username: 'tobi', email: 'tobi@fakeemail.com', access_level: 10, other_value: 11 }, { username: 'tobi', email: 'tobi@fakeemail.com', access_level: 10, other_value: 11 },
{ username: 'dan', email: 'dan@sequelizejs.com', access_level: 5, other_value: 10 }, { username: 'dan', email: 'dan@sequelizejs.com', access_level: 5, other_value: 10 },
{ username: 'fred', email: 'fred@foobar.com', access_level: 3, other_value: 7 } { username: 'fred', email: 'fred@foobar.com', access_level: 3, other_value: 7 }
]; ];
return this.ScopeMe.bulkCreate(records);
}); await this.ScopeMe.bulkCreate(records);
}); });
it('should apply defaultScope', function() { it('should apply defaultScope', async function() {
return this.ScopeMe.destroy({ where: {} }).then(() => { await this.ScopeMe.destroy({ where: {} });
return this.ScopeMe.unscoped().findAll(); const users = await this.ScopeMe.unscoped().findAll();
}).then(users => {
expect(users).to.have.length(2); expect(users).to.have.length(2);
expect(users[0].get('username')).to.equal('tony'); expect(users[0].get('username')).to.equal('tony');
expect(users[1].get('username')).to.equal('fred'); expect(users[1].get('username')).to.equal('fred');
}); });
});
it('should be able to override default scope', function() { it('should be able to override default scope', async function() {
return this.ScopeMe.destroy({ where: { access_level: { [Op.lt]: 5 } } }).then(() => { await this.ScopeMe.destroy({ where: { access_level: { [Op.lt]: 5 } } });
return this.ScopeMe.unscoped().findAll(); const users = await this.ScopeMe.unscoped().findAll();
}).then(users => {
expect(users).to.have.length(2); expect(users).to.have.length(2);
expect(users[0].get('username')).to.equal('tobi'); expect(users[0].get('username')).to.equal('tobi');
expect(users[1].get('username')).to.equal('dan'); expect(users[1].get('username')).to.equal('dan');
}); });
});
it('should be able to unscope destroy', function() { it('should be able to unscope destroy', async function() {
return this.ScopeMe.unscoped().destroy({ where: {} }).then(() => { await this.ScopeMe.unscoped().destroy({ where: {} });
return expect(this.ScopeMe.unscoped().findAll()).to.eventually.have.length(0); await expect(this.ScopeMe.unscoped().findAll()).to.eventually.have.length(0);
});
}); });
it('should be able to apply other scopes', function() { it('should be able to apply other scopes', async function() {
return this.ScopeMe.scope('lowAccess').destroy({ where: {} }).then(() => { await this.ScopeMe.scope('lowAccess').destroy({ where: {} });
return this.ScopeMe.unscoped().findAll(); const users = await this.ScopeMe.unscoped().findAll();
}).then(users => {
expect(users).to.have.length(1); expect(users).to.have.length(1);
expect(users[0].get('username')).to.equal('tobi'); expect(users[0].get('username')).to.equal('tobi');
}); });
});
it('should be able to merge scopes with where', function() { it('should be able to merge scopes with where', async function() {
return this.ScopeMe.scope('lowAccess').destroy({ where: { username: 'dan' } }).then(() => { await this.ScopeMe.scope('lowAccess').destroy({ where: { username: 'dan' } });
return this.ScopeMe.unscoped().findAll(); const users = await this.ScopeMe.unscoped().findAll();
}).then(users => {
expect(users).to.have.length(3); expect(users).to.have.length(3);
expect(users[0].get('username')).to.equal('tony'); expect(users[0].get('username')).to.equal('tony');
expect(users[1].get('username')).to.equal('tobi'); expect(users[1].get('username')).to.equal('tobi');
expect(users[2].get('username')).to.equal('fred'); expect(users[2].get('username')).to.equal('fred');
}); });
});
it('should work with empty where', function() { it('should work with empty where', async function() {
return this.ScopeMe.scope('lowAccess').destroy().then(() => { await this.ScopeMe.scope('lowAccess').destroy();
return this.ScopeMe.unscoped().findAll(); const users = await this.ScopeMe.unscoped().findAll();
}).then(users => {
expect(users).to.have.length(1); expect(users).to.have.length(1);
expect(users[0].get('username')).to.equal('tobi'); expect(users[0].get('username')).to.equal('tobi');
}); });
}); });
}); });
});
}); });
...@@ -8,7 +8,7 @@ const chai = require('chai'), ...@@ -8,7 +8,7 @@ const chai = require('chai'),
describe(Support.getTestDialectTeaser('Model'), () => { describe(Support.getTestDialectTeaser('Model'), () => {
describe('scopes', () => { describe('scopes', () => {
beforeEach(function() { beforeEach(async function() {
this.ScopeMe = this.sequelize.define('ScopeMe', { this.ScopeMe = this.sequelize.define('ScopeMe', {
username: Sequelize.STRING, username: Sequelize.STRING,
email: Sequelize.STRING, email: Sequelize.STRING,
...@@ -62,89 +62,79 @@ describe(Support.getTestDialectTeaser('Model'), () => { ...@@ -62,89 +62,79 @@ describe(Support.getTestDialectTeaser('Model'), () => {
this.ScopeMe.hasMany(this.DefaultScopeExclude); this.ScopeMe.hasMany(this.DefaultScopeExclude);
return this.sequelize.sync({ force: true }).then(() => { await this.sequelize.sync({ force: true });
const records = [ const records = [
{ username: 'tony', email: 'tony@sequelizejs.com', access_level: 3, other_value: 7, parent_id: 1 }, { username: 'tony', email: 'tony@sequelizejs.com', access_level: 3, other_value: 7, parent_id: 1 },
{ username: 'tobi', email: 'tobi@fakeemail.com', access_level: 10, other_value: 11, parent_id: 2 }, { username: 'tobi', email: 'tobi@fakeemail.com', access_level: 10, other_value: 11, parent_id: 2 },
{ username: 'dan', email: 'dan@sequelizejs.com', access_level: 5, other_value: 10, parent_id: 1 }, { username: 'dan', email: 'dan@sequelizejs.com', access_level: 5, other_value: 10, parent_id: 1 },
{ username: 'fred', email: 'fred@foobar.com', access_level: 3, other_value: 7, parent_id: 1 } { username: 'fred', email: 'fred@foobar.com', access_level: 3, other_value: 7, parent_id: 1 }
]; ];
return this.ScopeMe.bulkCreate(records);
}); await this.ScopeMe.bulkCreate(records);
}); });
it('should be able use where in scope', function() { it('should be able use where in scope', async function() {
return this.ScopeMe.scope({ where: { parent_id: 2 } }).findAll().then(users => { const users = await this.ScopeMe.scope({ where: { parent_id: 2 } }).findAll();
expect(users).to.have.length(1); expect(users).to.have.length(1);
expect(users[0].username).to.equal('tobi'); expect(users[0].username).to.equal('tobi');
}); });
});
it('should be able to combine scope and findAll where clauses', function() { it('should be able to combine scope and findAll where clauses', async function() {
return this.ScopeMe.scope({ where: { parent_id: 1 } }).findAll({ where: { access_level: 3 } }).then(users => { const users = await this.ScopeMe.scope({ where: { parent_id: 1 } }).findAll({ where: { access_level: 3 } });
expect(users).to.have.length(2); expect(users).to.have.length(2);
expect(['tony', 'fred'].includes(users[0].username)).to.be.true; expect(['tony', 'fred'].includes(users[0].username)).to.be.true;
expect(['tony', 'fred'].includes(users[1].username)).to.be.true; expect(['tony', 'fred'].includes(users[1].username)).to.be.true;
}); });
});
it('should be able to use a defaultScope if declared', function() { it('should be able to use a defaultScope if declared', async function() {
return this.ScopeMe.findAll().then(users => { const users = await this.ScopeMe.findAll();
expect(users).to.have.length(2); expect(users).to.have.length(2);
expect([10, 5].includes(users[0].access_level)).to.be.true; expect([10, 5].includes(users[0].access_level)).to.be.true;
expect([10, 5].includes(users[1].access_level)).to.be.true; expect([10, 5].includes(users[1].access_level)).to.be.true;
expect(['dan', 'tobi'].includes(users[0].username)).to.be.true; expect(['dan', 'tobi'].includes(users[0].username)).to.be.true;
expect(['dan', 'tobi'].includes(users[1].username)).to.be.true; expect(['dan', 'tobi'].includes(users[1].username)).to.be.true;
}); });
});
it('should be able to handle $and in scopes', function() { it('should be able to handle $and in scopes', async function() {
return this.ScopeMe.scope('andScope').findAll().then(users => { const users = await this.ScopeMe.scope('andScope').findAll();
expect(users).to.have.length(1); expect(users).to.have.length(1);
expect(users[0].username).to.equal('tony'); expect(users[0].username).to.equal('tony');
}); });
});
describe('should not overwrite', () => { describe('should not overwrite', () => {
it('default scope with values from previous finds', function() { it('default scope with values from previous finds', async function() {
return this.ScopeMe.findAll({ where: { other_value: 10 } }).then(users => { const users0 = await this.ScopeMe.findAll({ where: { other_value: 10 } });
expect(users).to.have.length(1); expect(users0).to.have.length(1);
return this.ScopeMe.findAll(); const users = await this.ScopeMe.findAll();
}).then(users => {
// This should not have other_value: 10 // This should not have other_value: 10
expect(users).to.have.length(2); expect(users).to.have.length(2);
}); });
}); it('other scopes with values from previous finds', async function() {
const users0 = await this.ScopeMe.scope('highValue').findAll({ where: { access_level: 10 } });
expect(users0).to.have.length(1);
it('other scopes with values from previous finds', function() { const users = await this.ScopeMe.scope('highValue').findAll();
return this.ScopeMe.scope('highValue').findAll({ where: { access_level: 10 } }).then(users => {
expect(users).to.have.length(1);
return this.ScopeMe.scope('highValue').findAll();
}).then(users => {
// This should not have other_value: 10 // This should not have other_value: 10
expect(users).to.have.length(2); expect(users).to.have.length(2);
}); });
}); });
});
it('should have no problem performing findOrCreate', function() { it('should have no problem performing findOrCreate', async function() {
return this.ScopeMe.findOrCreate({ where: { username: 'fake' } }).then(([user]) => { const [user] = await this.ScopeMe.findOrCreate({ where: { username: 'fake' } });
expect(user.username).to.equal('fake'); expect(user.username).to.equal('fake');
}); });
});
it('should work when included with default scope', function() { it('should work when included with default scope', async function() {
return this.ScopeMe.findOne({ await this.ScopeMe.findOne({
include: [this.DefaultScopeExclude] include: [this.DefaultScopeExclude]
}); });
}); });
}); });
describe('scope in associations', () => { describe('scope in associations', () => {
it('should work when association with a virtual column queried with default scope', function() { it('should work when association with a virtual column queried with default scope', async function() {
const Game = this.sequelize.define('Game', { const Game = this.sequelize.define('Game', {
name: Sequelize.TEXT name: Sequelize.TEXT
}); });
...@@ -167,15 +157,15 @@ describe(Support.getTestDialectTeaser('Model'), () => { ...@@ -167,15 +157,15 @@ describe(Support.getTestDialectTeaser('Model'), () => {
Game.hasMany(User); Game.hasMany(User);
return this.sequelize.sync({ force: true }).then(() => { await this.sequelize.sync({ force: true });
return Game.findAll({
const games = await Game.findAll({
include: [{ include: [{
model: User model: User
}] }]
}); });
}).then(games => {
expect(games).to.have.lengthOf(0); expect(games).to.have.lengthOf(0);
}); });
}); });
});
}); });
...@@ -11,7 +11,7 @@ describe(Support.getTestDialectTeaser('Model'), () => { ...@@ -11,7 +11,7 @@ describe(Support.getTestDialectTeaser('Model'), () => {
describe('findAndCountAll', () => { describe('findAndCountAll', () => {
beforeEach(function() { beforeEach(async function() {
this.ScopeMe = this.sequelize.define('ScopeMe', { this.ScopeMe = this.sequelize.define('ScopeMe', {
username: Sequelize.STRING, username: Sequelize.STRING,
email: Sequelize.STRING, email: Sequelize.STRING,
...@@ -40,60 +40,51 @@ describe(Support.getTestDialectTeaser('Model'), () => { ...@@ -40,60 +40,51 @@ describe(Support.getTestDialectTeaser('Model'), () => {
} }
}); });
return this.sequelize.sync({ force: true }).then(() => { await this.sequelize.sync({ force: true });
const records = [ const records = [
{ username: 'tony', email: 'tony@sequelizejs.com', access_level: 3, other_value: 7 }, { username: 'tony', email: 'tony@sequelizejs.com', access_level: 3, other_value: 7 },
{ username: 'tobi', email: 'tobi@fakeemail.com', access_level: 10, other_value: 11 }, { username: 'tobi', email: 'tobi@fakeemail.com', access_level: 10, other_value: 11 },
{ username: 'dan', email: 'dan@sequelizejs.com', access_level: 5, other_value: 10 }, { username: 'dan', email: 'dan@sequelizejs.com', access_level: 5, other_value: 10 },
{ username: 'fred', email: 'fred@foobar.com', access_level: 3, other_value: 7 } { username: 'fred', email: 'fred@foobar.com', access_level: 3, other_value: 7 }
]; ];
return this.ScopeMe.bulkCreate(records);
}); await this.ScopeMe.bulkCreate(records);
}); });
it('should apply defaultScope', function() { it('should apply defaultScope', async function() {
return this.ScopeMe.findAndCountAll().then(result => { const result = await this.ScopeMe.findAndCountAll();
expect(result.count).to.equal(2); expect(result.count).to.equal(2);
expect(result.rows.length).to.equal(2); expect(result.rows.length).to.equal(2);
}); });
});
it('should be able to override default scope', function() { it('should be able to override default scope', async function() {
return this.ScopeMe.findAndCountAll({ where: { access_level: { [Op.gt]: 5 } } }) const result = await this.ScopeMe.findAndCountAll({ where: { access_level: { [Op.gt]: 5 } } });
.then(result => {
expect(result.count).to.equal(1); expect(result.count).to.equal(1);
expect(result.rows.length).to.equal(1); expect(result.rows.length).to.equal(1);
}); });
});
it('should be able to unscope', function() { it('should be able to unscope', async function() {
return this.ScopeMe.unscoped().findAndCountAll({ limit: 1 }) const result = await this.ScopeMe.unscoped().findAndCountAll({ limit: 1 });
.then(result => {
expect(result.count).to.equal(4); expect(result.count).to.equal(4);
expect(result.rows.length).to.equal(1); expect(result.rows.length).to.equal(1);
}); });
});
it('should be able to apply other scopes', function() { it('should be able to apply other scopes', async function() {
return this.ScopeMe.scope('lowAccess').findAndCountAll() const result = await this.ScopeMe.scope('lowAccess').findAndCountAll();
.then(result => {
expect(result.count).to.equal(3); expect(result.count).to.equal(3);
}); });
});
it('should be able to merge scopes with where', function() { it('should be able to merge scopes with where', async function() {
return this.ScopeMe.scope('lowAccess') const result = await this.ScopeMe.scope('lowAccess')
.findAndCountAll({ where: { username: 'dan' } }).then(result => { .findAndCountAll({ where: { username: 'dan' } });
expect(result.count).to.equal(1); expect(result.count).to.equal(1);
}); });
});
it('should ignore the order option if it is found within the scope', function() { it('should ignore the order option if it is found within the scope', async function() {
return this.ScopeMe.scope('withOrder').findAndCountAll() const result = await this.ScopeMe.scope('withOrder').findAndCountAll();
.then(result => {
expect(result.count).to.equal(4); expect(result.count).to.equal(4);
}); });
}); });
}); });
});
}); });
...@@ -9,8 +9,7 @@ const chai = require('chai'), ...@@ -9,8 +9,7 @@ const chai = require('chai'),
describe(Support.getTestDialectTeaser('Model'), () => { describe(Support.getTestDialectTeaser('Model'), () => {
describe('scope', () => { describe('scope', () => {
describe('simple merge', () => { describe('simple merge', () => {
beforeEach(function() { beforeEach(async function() {
this.Foo = this.sequelize.define('foo', { name: Sequelize.STRING }, { timestamps: false }); this.Foo = this.sequelize.define('foo', { name: Sequelize.STRING }, { timestamps: false });
this.Bar = this.sequelize.define('bar', { name: Sequelize.STRING }, { timestamps: false }); this.Bar = this.sequelize.define('bar', { name: Sequelize.STRING }, { timestamps: false });
this.Baz = this.sequelize.define('baz', { name: Sequelize.STRING }, { timestamps: false }); this.Baz = this.sequelize.define('baz', { name: Sequelize.STRING }, { timestamps: false });
...@@ -18,10 +17,10 @@ describe(Support.getTestDialectTeaser('Model'), () => { ...@@ -18,10 +17,10 @@ describe(Support.getTestDialectTeaser('Model'), () => {
this.Foo.belongsTo(this.Baz, { foreignKey: 'bazId' }); this.Foo.belongsTo(this.Baz, { foreignKey: 'bazId' });
this.Foo.hasOne(this.Bar, { foreignKey: 'fooId' }); this.Foo.hasOne(this.Bar, { foreignKey: 'fooId' });
this.createEntries = () => { this.createEntries = async () => {
return this.Baz.create({ name: 'The Baz' }) const baz = await this.Baz.create({ name: 'The Baz' });
.then(baz => this.Foo.create({ name: 'The Foo', bazId: baz.id })) const foo = await this.Foo.create({ name: 'The Foo', bazId: baz.id });
.then(foo => this.Bar.create({ name: 'The Bar', fooId: foo.id })); return this.Bar.create({ name: 'The Bar', fooId: foo.id });
}; };
this.scopes = { this.scopes = {
...@@ -32,24 +31,21 @@ describe(Support.getTestDialectTeaser('Model'), () => { ...@@ -32,24 +31,21 @@ describe(Support.getTestDialectTeaser('Model'), () => {
this.Foo.addScope('includeBar', this.scopes.includeBar); this.Foo.addScope('includeBar', this.scopes.includeBar);
this.Foo.addScope('includeBaz', this.scopes.includeBaz); this.Foo.addScope('includeBaz', this.scopes.includeBaz);
return this.sequelize.sync({ force: true }).then(this.createEntries); await this.createEntries(await this.sequelize.sync({ force: true }));
}); });
it('should merge simple scopes correctly', function() { it('should merge simple scopes correctly', async function() {
return this.Foo.scope('includeBar', 'includeBaz').findOne().then(result => { const result = await this.Foo.scope('includeBar', 'includeBaz').findOne();
const json = result.toJSON(); const json = result.toJSON();
expect(json.bar).to.be.ok; expect(json.bar).to.be.ok;
expect(json.baz).to.be.ok; expect(json.baz).to.be.ok;
expect(json.bar.name).to.equal('The Bar'); expect(json.bar.name).to.equal('The Bar');
expect(json.baz.name).to.equal('The Baz'); expect(json.baz.name).to.equal('The Baz');
}); });
});
}); });
describe('complex merge', () => { describe('complex merge', () => {
beforeEach(function() { beforeEach(async function() {
this.Foo = this.sequelize.define('foo', { name: Sequelize.STRING }, { timestamps: false }); this.Foo = this.sequelize.define('foo', { name: Sequelize.STRING }, { timestamps: false });
this.Bar = this.sequelize.define('bar', { name: Sequelize.STRING }, { timestamps: false }); this.Bar = this.sequelize.define('bar', { name: Sequelize.STRING }, { timestamps: false });
this.Baz = this.sequelize.define('baz', { name: Sequelize.STRING }, { timestamps: false }); this.Baz = this.sequelize.define('baz', { name: Sequelize.STRING }, { timestamps: false });
...@@ -142,36 +138,36 @@ describe(Support.getTestDialectTeaser('Model'), () => { ...@@ -142,36 +138,36 @@ describe(Support.getTestDialectTeaser('Model'), () => {
'excludeBazName' 'excludeBazName'
]).toArray(); ]).toArray();
return this.sequelize.sync({ force: true }).then(this.createFooWithDescendants); await this.createFooWithDescendants(await this.sequelize.sync({ force: true }));
}); });
it('should merge complex scopes correctly regardless of their order', function() { it('should merge complex scopes correctly regardless of their order', async function() {
return Promise.all(this.scopePermutations.map(scopes => this.Foo.scope(...scopes).findOne())).then(results => { const results = await Promise.all(this.scopePermutations.map(scopes => this.Foo.scope(...scopes).findOne()));
const first = results.shift().toJSON(); const first = results.shift().toJSON();
for (const result of results) { for (const result of results) {
expect(result.toJSON()).to.deep.equal(first); expect(result.toJSON()).to.deep.equal(first);
} }
}); });
});
it('should merge complex scopes with findAll options correctly regardless of their order', function() { it('should merge complex scopes with findAll options correctly regardless of their order', async function() {
return Promise.all(this.scopePermutations.map(([a, b, c, d]) => this.Foo.scope(a, b, c).findAll(this.scopes[d]).then(x => x[0]))).then(results => { const results = await Promise.all(this.scopePermutations.map(async ([a, b, c, d]) => {
const x = await this.Foo.scope(a, b, c).findAll(this.scopes[d]);
return x[0];
}));
const first = results.shift().toJSON(); const first = results.shift().toJSON();
for (const result of results) { for (const result of results) {
expect(result.toJSON()).to.deep.equal(first); expect(result.toJSON()).to.deep.equal(first);
} }
}); });
});
it('should merge complex scopes with findOne options correctly regardless of their order', function() { it('should merge complex scopes with findOne options correctly regardless of their order', async function() {
return Promise.all(this.scopePermutations.map(([a, b, c, d]) => this.Foo.scope(a, b, c).findOne(this.scopes[d]))).then(results => { const results = await Promise.all(this.scopePermutations.map(([a, b, c, d]) => this.Foo.scope(a, b, c).findOne(this.scopes[d])));
const first = results.shift().toJSON(); const first = results.shift().toJSON();
for (const result of results) { for (const result of results) {
expect(result.toJSON()).to.deep.equal(first); expect(result.toJSON()).to.deep.equal(first);
} }
}); });
});
}); });
}); });
......
...@@ -9,7 +9,7 @@ const chai = require('chai'), ...@@ -9,7 +9,7 @@ const chai = require('chai'),
describe(Support.getTestDialectTeaser('Model'), () => { describe(Support.getTestDialectTeaser('Model'), () => {
describe('scope', () => { describe('scope', () => {
describe('update', () => { describe('update', () => {
beforeEach(function() { beforeEach(async function() {
this.ScopeMe = this.sequelize.define('ScopeMe', { this.ScopeMe = this.sequelize.define('ScopeMe', {
username: Sequelize.STRING, username: Sequelize.STRING,
email: Sequelize.STRING, email: Sequelize.STRING,
...@@ -34,69 +34,59 @@ describe(Support.getTestDialectTeaser('Model'), () => { ...@@ -34,69 +34,59 @@ describe(Support.getTestDialectTeaser('Model'), () => {
} }
}); });
return this.sequelize.sync({ force: true }).then(() => { await this.sequelize.sync({ force: true });
const records = [ const records = [
{ username: 'tony', email: 'tony@sequelizejs.com', access_level: 3, other_value: 7 }, { username: 'tony', email: 'tony@sequelizejs.com', access_level: 3, other_value: 7 },
{ username: 'tobi', email: 'tobi@fakeemail.com', access_level: 10, other_value: 11 }, { username: 'tobi', email: 'tobi@fakeemail.com', access_level: 10, other_value: 11 },
{ username: 'dan', email: 'dan@sequelizejs.com', access_level: 5, other_value: 10 }, { username: 'dan', email: 'dan@sequelizejs.com', access_level: 5, other_value: 10 },
{ username: 'fred', email: 'fred@foobar.com', access_level: 3, other_value: 7 } { username: 'fred', email: 'fred@foobar.com', access_level: 3, other_value: 7 }
]; ];
return this.ScopeMe.bulkCreate(records);
}); await this.ScopeMe.bulkCreate(records);
}); });
it('should apply defaultScope', function() { it('should apply defaultScope', async function() {
return this.ScopeMe.update({ username: 'ruben' }, { where: {} }).then(() => { await this.ScopeMe.update({ username: 'ruben' }, { where: {} });
return this.ScopeMe.unscoped().findAll({ where: { username: 'ruben' } }); const users = await this.ScopeMe.unscoped().findAll({ where: { username: 'ruben' } });
}).then(users => {
expect(users).to.have.length(2); expect(users).to.have.length(2);
expect(users[0].get('email')).to.equal('tobi@fakeemail.com'); expect(users[0].get('email')).to.equal('tobi@fakeemail.com');
expect(users[1].get('email')).to.equal('dan@sequelizejs.com'); expect(users[1].get('email')).to.equal('dan@sequelizejs.com');
}); });
});
it('should be able to override default scope', function() { it('should be able to override default scope', async function() {
return this.ScopeMe.update({ username: 'ruben' }, { where: { access_level: { [Op.lt]: 5 } } }).then(() => { await this.ScopeMe.update({ username: 'ruben' }, { where: { access_level: { [Op.lt]: 5 } } });
return this.ScopeMe.unscoped().findAll({ where: { username: 'ruben' } }); const users = await this.ScopeMe.unscoped().findAll({ where: { username: 'ruben' } });
}).then(users => {
expect(users).to.have.length(2); expect(users).to.have.length(2);
expect(users[0].get('email')).to.equal('tony@sequelizejs.com'); expect(users[0].get('email')).to.equal('tony@sequelizejs.com');
expect(users[1].get('email')).to.equal('fred@foobar.com'); expect(users[1].get('email')).to.equal('fred@foobar.com');
}); });
});
it('should be able to unscope destroy', function() { it('should be able to unscope destroy', async function() {
return this.ScopeMe.unscoped().update({ username: 'ruben' }, { where: {} }).then(() => { await this.ScopeMe.unscoped().update({ username: 'ruben' }, { where: {} });
return this.ScopeMe.unscoped().findAll(); const rubens = await this.ScopeMe.unscoped().findAll();
}).then(rubens => {
expect(rubens.every(r => r.get('username') === 'ruben')).to.be.true; expect(rubens.every(r => r.get('username') === 'ruben')).to.be.true;
}); });
});
it('should be able to apply other scopes', function() { it('should be able to apply other scopes', async function() {
return this.ScopeMe.scope('lowAccess').update({ username: 'ruben' }, { where: {} }).then(() => { await this.ScopeMe.scope('lowAccess').update({ username: 'ruben' }, { where: {} });
return this.ScopeMe.unscoped().findAll({ where: { username: { [Op.ne]: 'ruben' } } }); const users = await this.ScopeMe.unscoped().findAll({ where: { username: { [Op.ne]: 'ruben' } } });
}).then(users => {
expect(users).to.have.length(1); expect(users).to.have.length(1);
expect(users[0].get('email')).to.equal('tobi@fakeemail.com'); expect(users[0].get('email')).to.equal('tobi@fakeemail.com');
}); });
});
it('should be able to merge scopes with where', function() { it('should be able to merge scopes with where', async function() {
return this.ScopeMe.scope('lowAccess').update({ username: 'ruben' }, { where: { username: 'dan' } }).then(() => { await this.ScopeMe.scope('lowAccess').update({ username: 'ruben' }, { where: { username: 'dan' } });
return this.ScopeMe.unscoped().findAll({ where: { username: 'ruben' } }); const users = await this.ScopeMe.unscoped().findAll({ where: { username: 'ruben' } });
}).then(users => {
expect(users).to.have.length(1); expect(users).to.have.length(1);
expect(users[0].get('email')).to.equal('dan@sequelizejs.com'); expect(users[0].get('email')).to.equal('dan@sequelizejs.com');
}); });
});
it('should work with empty where', function() { it('should work with empty where', async function() {
return this.ScopeMe.scope('lowAccess').update({ await this.ScopeMe.scope('lowAccess').update({
username: 'ruby' username: 'ruby'
}).then(() => { });
return this.ScopeMe.unscoped().findAll({ where: { username: 'ruby' } });
}).then(users => { const users = await this.ScopeMe.unscoped().findAll({ where: { username: 'ruby' } });
expect(users).to.have.length(3); expect(users).to.have.length(3);
users.forEach(user => { users.forEach(user => {
expect(user.get('username')).to.equal('ruby'); expect(user.get('username')).to.equal('ruby');
...@@ -104,5 +94,4 @@ describe(Support.getTestDialectTeaser('Model'), () => { ...@@ -104,5 +94,4 @@ describe(Support.getTestDialectTeaser('Model'), () => {
}); });
}); });
}); });
});
}); });
...@@ -6,7 +6,7 @@ const chai = require('chai'), ...@@ -6,7 +6,7 @@ const chai = require('chai'),
DataTypes = require('../../../lib/data-types'); DataTypes = require('../../../lib/data-types');
describe(Support.getTestDialectTeaser('Model'), () => { describe(Support.getTestDialectTeaser('Model'), () => {
beforeEach(function() { beforeEach(async function() {
this.Payment = this.sequelize.define('Payment', { this.Payment = this.sequelize.define('Payment', {
amount: DataTypes.DECIMAL, amount: DataTypes.DECIMAL,
mood: { mood: {
...@@ -15,28 +15,28 @@ describe(Support.getTestDialectTeaser('Model'), () => { ...@@ -15,28 +15,28 @@ describe(Support.getTestDialectTeaser('Model'), () => {
} }
}); });
return this.sequelize.sync({ force: true }).then(() => { await this.sequelize.sync({ force: true });
return this.Payment.bulkCreate([
await this.Payment.bulkCreate([
{ amount: 5, mood: 'neutral' }, { amount: 5, mood: 'neutral' },
{ amount: -5, mood: 'neutral' }, { amount: -5, mood: 'neutral' },
{ amount: 10, mood: 'happy' }, { amount: 10, mood: 'happy' },
{ amount: 90, mood: 'happy' } { amount: 90, mood: 'happy' }
]); ]);
}); });
});
describe('sum', () => { describe('sum', () => {
it('should sum without rows', function() { it('should sum without rows', async function() {
return expect(this.Payment.sum('amount', { where: { mood: 'sad' } })).to.eventually.be.equal(0); await expect(this.Payment.sum('amount', { where: { mood: 'sad' } })).to.eventually.be.equal(0);
}); });
it('should sum when is 0', function() { it('should sum when is 0', async function() {
return expect(this.Payment.sum('amount', { where: { mood: 'neutral' } })).to.eventually.be.equal(0); await expect(this.Payment.sum('amount', { where: { mood: 'neutral' } })).to.eventually.be.equal(0);
}); });
it('should sum', function() { it('should sum', async function() {
return expect(this.Payment.sum('amount', { where: { mood: 'happy' } })).to.eventually.be.equal(100); await expect(this.Payment.sum('amount', { where: { mood: 'happy' } })).to.eventually.be.equal(100);
}); });
}); });
}); });
...@@ -10,7 +10,7 @@ const _ = require('lodash'); ...@@ -10,7 +10,7 @@ const _ = require('lodash');
describe(Support.getTestDialectTeaser('Model'), () => { describe(Support.getTestDialectTeaser('Model'), () => {
describe('update', () => { describe('update', () => {
beforeEach(function() { beforeEach(async function() {
this.Account = this.sequelize.define('Account', { this.Account = this.sequelize.define('Account', {
ownerId: { ownerId: {
type: DataTypes.INTEGER, type: DataTypes.INTEGER,
...@@ -21,27 +21,29 @@ describe(Support.getTestDialectTeaser('Model'), () => { ...@@ -21,27 +21,29 @@ describe(Support.getTestDialectTeaser('Model'), () => {
type: DataTypes.STRING type: DataTypes.STRING
} }
}); });
return this.Account.sync({ force: true }); await this.Account.sync({ force: true });
}); });
it('should only update the passed fields', function() { it('should only update the passed fields', async function() {
return this.Account const account = await this.Account
.create({ ownerId: 2 }) .create({ ownerId: 2 });
.then(account => this.Account.update({
await this.Account.update({
name: Math.random().toString() name: Math.random().toString()
}, { }, {
where: { where: {
id: account.get('id') id: account.get('id')
} }
})); });
}); });
describe('skips update query', () => { describe('skips update query', () => {
it('if no data to update', function() { it('if no data to update', async function() {
const spy = sinon.spy(); const spy = sinon.spy();
return this.Account.create({ ownerId: 3 }).then(() => { await this.Account.create({ ownerId: 3 });
return this.Account.update({
const result = await this.Account.update({
unknownField: 'haha' unknownField: 'haha'
}, { }, {
where: { where: {
...@@ -49,13 +51,12 @@ describe(Support.getTestDialectTeaser('Model'), () => { ...@@ -49,13 +51,12 @@ describe(Support.getTestDialectTeaser('Model'), () => {
}, },
logging: spy logging: spy
}); });
}).then(result => {
expect(result[0]).to.equal(0); expect(result[0]).to.equal(0);
expect(spy.called, 'Update query was issued when no data to update').to.be.false; expect(spy.called, 'Update query was issued when no data to update').to.be.false;
}); });
});
it('skips when timestamps disabled', function() { it('skips when timestamps disabled', async function() {
const Model = this.sequelize.define('Model', { const Model = this.sequelize.define('Model', {
ownerId: { ownerId: {
type: DataTypes.INTEGER, type: DataTypes.INTEGER,
...@@ -70,10 +71,10 @@ describe(Support.getTestDialectTeaser('Model'), () => { ...@@ -70,10 +71,10 @@ describe(Support.getTestDialectTeaser('Model'), () => {
}); });
const spy = sinon.spy(); const spy = sinon.spy();
return Model.sync({ force: true }) await Model.sync({ force: true });
.then(() => Model.create({ ownerId: 3 })) await Model.create({ ownerId: 3 });
.then(() => {
return Model.update({ const result = await Model.update({
unknownField: 'haha' unknownField: 'haha'
}, { }, {
where: { where: {
...@@ -81,95 +82,84 @@ describe(Support.getTestDialectTeaser('Model'), () => { ...@@ -81,95 +82,84 @@ describe(Support.getTestDialectTeaser('Model'), () => {
}, },
logging: spy logging: spy
}); });
})
.then(result => {
expect(result[0]).to.equal(0); expect(result[0]).to.equal(0);
expect(spy.called, 'Update query was issued when no data to update').to.be.false; expect(spy.called, 'Update query was issued when no data to update').to.be.false;
}); });
}); });
});
it('changed should be false after reload', function() { it('changed should be false after reload', async function() {
return this.Account.create({ ownerId: 2, name: 'foo' }) const account0 = await this.Account.create({ ownerId: 2, name: 'foo' });
.then(account => { account0.name = 'bar';
account.name = 'bar'; expect(account0.changed()[0]).to.equal('name');
expect(account.changed()[0]).to.equal('name'); const account = await account0.reload();
return account.reload();
})
.then(account => {
expect(account.changed()).to.equal(false); expect(account.changed()).to.equal(false);
}); });
});
it('should ignore undefined values without throwing not null validation', function() { it('should ignore undefined values without throwing not null validation', async function() {
const ownerId = 2; const ownerId = 2;
return this.Account.create({
const account0 = await this.Account.create({
ownerId, ownerId,
name: Math.random().toString() name: Math.random().toString()
}).then(account => { });
return this.Account.update({
await this.Account.update({
name: Math.random().toString(), name: Math.random().toString(),
ownerId: undefined ownerId: undefined
}, { }, {
where: { where: {
id: account.get('id') id: account0.get('id')
} }
}); });
}).then(() => {
return this.Account.findOne(); const account = await this.Account.findOne();
}).then(account => {
expect(account.ownerId).to.be.equal(ownerId); expect(account.ownerId).to.be.equal(ownerId);
}); });
});
if (_.get(current.dialect.supports, 'returnValues.returning')) { if (_.get(current.dialect.supports, 'returnValues.returning')) {
it('should return the updated record', function() { it('should return the updated record', async function() {
return this.Account.create({ ownerId: 2 }).then(account => { const account = await this.Account.create({ ownerId: 2 });
return this.Account.update({ name: 'FooBar' }, {
const [, accounts] = await this.Account.update({ name: 'FooBar' }, {
where: { where: {
id: account.get('id') id: account.get('id')
}, },
returning: true returning: true
}).then(([, accounts]) => { });
const firstAcc = accounts[0]; const firstAcc = accounts[0];
expect(firstAcc.ownerId).to.be.equal(2); expect(firstAcc.ownerId).to.be.equal(2);
expect(firstAcc.name).to.be.equal('FooBar'); expect(firstAcc.name).to.be.equal('FooBar');
}); });
});
});
} }
if (current.dialect.supports['LIMIT ON UPDATE']) { if (current.dialect.supports['LIMIT ON UPDATE']) {
it('should only update one row', function() { it('should only update one row', async function() {
return this.Account.create({ await this.Account.create({
ownerId: 2, ownerId: 2,
name: 'Account Name 1' name: 'Account Name 1'
}) });
.then(() => {
return this.Account.create({ await this.Account.create({
ownerId: 2, ownerId: 2,
name: 'Account Name 2' name: 'Account Name 2'
}); });
})
.then(() => { await this.Account.create({
return this.Account.create({
ownerId: 2, ownerId: 2,
name: 'Account Name 3' name: 'Account Name 3'
}); });
})
.then(() => {
const options = { const options = {
where: { where: {
ownerId: 2 ownerId: 2
}, },
limit: 1 limit: 1
}; };
return this.Account.update({ name: 'New Name' }, options); const account = await this.Account.update({ name: 'New Name' }, options);
})
.then(account => {
expect(account[0]).to.equal(1); expect(account[0]).to.equal(1);
}); });
});
} }
}); });
}); });
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!