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

Commit 5336424a by Andy Edwards Committed by GitHub

test(integration/dialects): asyncify (#12239)

1 parent a35ec013
...@@ -55,7 +55,7 @@ describe(Support.getTestDialectTeaser('Connection Manager'), () => { ...@@ -55,7 +55,7 @@ describe(Support.getTestDialectTeaser('Connection Manager'), () => {
expect(connectionManager.pool.write).to.be.instanceOf(Pool); expect(connectionManager.pool.write).to.be.instanceOf(Pool);
}); });
it('should round robin calls to the read pool', () => { it('should round robin calls to the read pool', async () => {
if (Support.getTestDialect() === 'sqlite') { if (Support.getTestDialect() === 'sqlite') {
return; return;
} }
...@@ -91,10 +91,9 @@ describe(Support.getTestDialectTeaser('Connection Manager'), () => { ...@@ -91,10 +91,9 @@ describe(Support.getTestDialectTeaser('Connection Manager'), () => {
const _getConnection = connectionManager.getConnection.bind(connectionManager, queryOptions); const _getConnection = connectionManager.getConnection.bind(connectionManager, queryOptions);
return _getConnection() await _getConnection();
.then(_getConnection) await _getConnection();
.then(_getConnection) await _getConnection();
.then(() => {
chai.expect(connectStub.callCount).to.equal(4); chai.expect(connectStub.callCount).to.equal(4);
// First call is the get connection for DB versions - ignore // First call is the get connection for DB versions - ignore
...@@ -103,9 +102,8 @@ describe(Support.getTestDialectTeaser('Connection Manager'), () => { ...@@ -103,9 +102,8 @@ describe(Support.getTestDialectTeaser('Connection Manager'), () => {
chai.expect(calls[2].args[0].host).to.eql('slave2'); chai.expect(calls[2].args[0].host).to.eql('slave2');
chai.expect(calls[3].args[0].host).to.eql('slave1'); chai.expect(calls[3].args[0].host).to.eql('slave1');
}); });
});
it('should trigger deprecation for non supported engine version', () => { it('should trigger deprecation for non supported engine version', async () => {
const deprecationStub = sandbox.stub(deprecations, 'unsupportedEngine'); const deprecationStub = sandbox.stub(deprecations, 'unsupportedEngine');
const sequelize = Support.createSequelizeInstance(); const sequelize = Support.createSequelizeInstance();
const connectionManager = new ConnectionManager(sequelize.dialect, sequelize); const connectionManager = new ConnectionManager(sequelize.dialect, sequelize);
...@@ -126,14 +124,12 @@ describe(Support.getTestDialectTeaser('Connection Manager'), () => { ...@@ -126,14 +124,12 @@ describe(Support.getTestDialectTeaser('Connection Manager'), () => {
useMaster: true useMaster: true
}; };
return connectionManager.getConnection(queryOptions) await connectionManager.getConnection(queryOptions);
.then(() => {
chai.expect(deprecationStub).to.have.been.calledOnce; chai.expect(deprecationStub).to.have.been.calledOnce;
}); });
});
it('should allow forced reads from the write pool', () => { it('should allow forced reads from the write pool', async () => {
const master = { ...poolEntry }; const master = { ...poolEntry };
master.host = 'the-boss'; master.host = 'the-boss';
...@@ -161,15 +157,13 @@ describe(Support.getTestDialectTeaser('Connection Manager'), () => { ...@@ -161,15 +157,13 @@ describe(Support.getTestDialectTeaser('Connection Manager'), () => {
useMaster: true useMaster: true
}; };
return connectionManager.getConnection(queryOptions) await connectionManager.getConnection(queryOptions);
.then(() => {
chai.expect(connectStub).to.have.been.calledTwice; // Once to get DB version, and once to actually get the connection. chai.expect(connectStub).to.have.been.calledTwice; // Once to get DB version, and once to actually get the connection.
const calls = connectStub.getCalls(); const calls = connectStub.getCalls();
chai.expect(calls[1].args[0].host).to.eql('the-boss'); chai.expect(calls[1].args[0].host).to.eql('the-boss');
}); });
});
it('should clear the pool after draining it', () => { it('should clear the pool after draining it', async () => {
const options = { const options = {
replication: null replication: null
}; };
...@@ -181,9 +175,8 @@ describe(Support.getTestDialectTeaser('Connection Manager'), () => { ...@@ -181,9 +175,8 @@ describe(Support.getTestDialectTeaser('Connection Manager'), () => {
const poolDrainSpy = sandbox.spy(connectionManager.pool, 'drain'); const poolDrainSpy = sandbox.spy(connectionManager.pool, 'drain');
const poolClearSpy = sandbox.spy(connectionManager.pool, 'destroyAllNow'); const poolClearSpy = sandbox.spy(connectionManager.pool, 'destroyAllNow');
return connectionManager.close().then(() => { await connectionManager.close();
expect(poolDrainSpy.calledOnce).to.be.true; expect(poolDrainSpy.calledOnce).to.be.true;
expect(poolClearSpy.calledOnce).to.be.true; expect(poolClearSpy.calledOnce).to.be.true;
}); });
});
}); });
...@@ -11,33 +11,30 @@ if (dialect !== 'mariadb') return; ...@@ -11,33 +11,30 @@ if (dialect !== 'mariadb') return;
describe('[MariaDB Specific] Associations', () => { describe('[MariaDB Specific] Associations', () => {
describe('many-to-many', () => { describe('many-to-many', () => {
describe('where tables have the same prefix', () => { describe('where tables have the same prefix', () => {
it('should create a table wp_table1wp_table2s', function() { it('should create a table wp_table1wp_table2s', async function() {
const Table2 = this.sequelize.define('wp_table2', { foo: DataTypes.STRING }), const Table2 = this.sequelize.define('wp_table2', { foo: DataTypes.STRING }),
Table1 = this.sequelize.define('wp_table1', Table1 = this.sequelize.define('wp_table1',
{ foo: DataTypes.STRING }); { foo: DataTypes.STRING });
Table1.belongsToMany(Table2, { through: 'wp_table1swp_table2s' }); Table1.belongsToMany(Table2, { through: 'wp_table1swp_table2s' });
Table2.belongsToMany(Table1, { through: 'wp_table1swp_table2s' }); Table2.belongsToMany(Table1, { through: 'wp_table1swp_table2s' });
return Table1.sync({ force: true }).then(() => { await Table1.sync({ force: true });
return Table2.sync({ force: true }).then(() => { await Table2.sync({ force: true });
expect(this.sequelize.modelManager.getModel( expect(this.sequelize.modelManager.getModel(
'wp_table1swp_table2s')).to.exist; 'wp_table1swp_table2s')).to.exist;
}); });
}); });
});
});
describe('when join table name is specified', () => { describe('when join table name is specified', () => {
beforeEach(function() { beforeEach(async function() {
const Table2 = this.sequelize.define('ms_table1', { foo: DataTypes.STRING }), const Table2 = this.sequelize.define('ms_table1', { foo: DataTypes.STRING }),
Table1 = this.sequelize.define('ms_table2', Table1 = this.sequelize.define('ms_table2',
{ foo: DataTypes.STRING }); { foo: DataTypes.STRING });
Table1.belongsToMany(Table2, { through: 'table1_to_table2' }); Table1.belongsToMany(Table2, { through: 'table1_to_table2' });
Table2.belongsToMany(Table1, { through: 'table1_to_table2' }); Table2.belongsToMany(Table1, { through: 'table1_to_table2' });
return Table1.sync({ force: true }).then(() => { await Table1.sync({ force: true });
return Table2.sync({ force: true }); await Table2.sync({ force: true });
});
}); });
it('should not use only a specified name', function() { it('should not use only a specified name', function() {
...@@ -50,7 +47,7 @@ describe('[MariaDB Specific] Associations', () => { ...@@ -50,7 +47,7 @@ describe('[MariaDB Specific] Associations', () => {
}); });
describe('HasMany', () => { describe('HasMany', () => {
beforeEach(function() { beforeEach(async function() {
//prevent periods from occurring in the table name since they are used to delimit (table.column) //prevent periods from occurring in the table name since they are used to delimit (table.column)
this.User = this.sequelize.define(`User${Math.ceil(Math.random() * 10000000)}`, { name: DataTypes.STRING }); this.User = this.sequelize.define(`User${Math.ceil(Math.random() * 10000000)}`, { name: DataTypes.STRING });
this.Task = this.sequelize.define(`Task${Math.ceil(Math.random() * 10000000)}`, { name: DataTypes.STRING }); this.Task = this.sequelize.define(`Task${Math.ceil(Math.random() * 10000000)}`, { name: DataTypes.STRING });
...@@ -68,10 +65,9 @@ describe('[MariaDB Specific] Associations', () => { ...@@ -68,10 +65,9 @@ describe('[MariaDB Specific] Associations', () => {
tasks[i] = { name: `Task${Math.random()}` }; tasks[i] = { name: `Task${Math.random()}` };
} }
return this.sequelize.sync({ force: true }) await this.sequelize.sync({ force: true });
.then(() => this.User.bulkCreate(users)) await this.User.bulkCreate(users);
.then(() => this.Task.bulkCreate(tasks)); await this.Task.bulkCreate(tasks);
}); });
}); });
......
...@@ -13,17 +13,15 @@ if (dialect !== 'mariadb') { ...@@ -13,17 +13,15 @@ if (dialect !== 'mariadb') {
describe('[MARIADB Specific] Connection Manager', () => { describe('[MARIADB Specific] Connection Manager', () => {
it('has existing init SQL', () => { it('has existing init SQL', async () => {
const sequelize = Support.createSequelizeInstance( const sequelize = Support.createSequelizeInstance(
{ dialectOptions: { initSql: 'SET @myUserVariable=\'myValue\'' } }); { dialectOptions: { initSql: 'SET @myUserVariable=\'myValue\'' } });
return sequelize.query('SELECT @myUserVariable') const res = await sequelize.query('SELECT @myUserVariable');
.then(res => {
expect(res[0]).to.deep.equal([{ '@myUserVariable': 'myValue' }]); expect(res[0]).to.deep.equal([{ '@myUserVariable': 'myValue' }]);
sequelize.close(); sequelize.close();
}); });
});
it('has existing init SQL array', () => { it('has existing init SQL array', async () => {
const sequelize = Support.createSequelizeInstance( const sequelize = Support.createSequelizeInstance(
{ {
dialectOptions: { dialectOptions: {
...@@ -31,42 +29,40 @@ describe('[MARIADB Specific] Connection Manager', () => { ...@@ -31,42 +29,40 @@ describe('[MARIADB Specific] Connection Manager', () => {
'SET @myUserVariable2=\'myValue\''] 'SET @myUserVariable2=\'myValue\'']
} }
}); });
return sequelize.query('SELECT @myUserVariable1, @myUserVariable2') const res = await sequelize.query('SELECT @myUserVariable1, @myUserVariable2');
.then(res => {
expect(res[0]).to.deep.equal( expect(res[0]).to.deep.equal(
[{ '@myUserVariable1': 'myValue', '@myUserVariable2': 'myValue' }]); [{ '@myUserVariable1': 'myValue', '@myUserVariable2': 'myValue' }]);
sequelize.close(); sequelize.close();
}); });
});
describe('Errors', () => { describe('Errors', () => {
const testHost = env.MARIADB_PORT_3306_TCP_ADDR || env.SEQ_MARIADB_HOST || env.SEQ_HOST || '127.0.0.1'; const testHost = env.MARIADB_PORT_3306_TCP_ADDR || env.SEQ_MARIADB_HOST || env.SEQ_HOST || '127.0.0.1';
it('Connection timeout', () => { it('Connection timeout', async () => {
const sequelize = Support.createSequelizeInstance({ host: testHost, port: 65535, dialectOptions: { connectTimeout: 500 } }); const sequelize = Support.createSequelizeInstance({ host: testHost, port: 65535, dialectOptions: { connectTimeout: 500 } });
return expect(sequelize.connectionManager.getConnection()).to.have.been.rejectedWith(Sequelize.SequelizeConnectionError); await expect(sequelize.connectionManager.getConnection()).to.have.been.rejectedWith(Sequelize.SequelizeConnectionError);
}); });
it('ECONNREFUSED', () => { it('ECONNREFUSED', async () => {
const sequelize = Support.createSequelizeInstance({ host: testHost, port: 65535 }); const sequelize = Support.createSequelizeInstance({ host: testHost, port: 65535 });
return expect(sequelize.connectionManager.getConnection()).to.have.been.rejectedWith(Sequelize.ConnectionRefusedError); await expect(sequelize.connectionManager.getConnection()).to.have.been.rejectedWith(Sequelize.ConnectionRefusedError);
}); });
it('ENOTFOUND', () => { it('ENOTFOUND', async () => {
const sequelize = Support.createSequelizeInstance({ host: 'http://wowow.example.com' }); const sequelize = Support.createSequelizeInstance({ host: 'http://wowow.example.com' });
return expect(sequelize.connectionManager.getConnection()).to.have.been.rejectedWith(Sequelize.HostNotFoundError); await expect(sequelize.connectionManager.getConnection()).to.have.been.rejectedWith(Sequelize.HostNotFoundError);
}); });
it('EHOSTUNREACH', () => { it('EHOSTUNREACH', async () => {
const sequelize = Support.createSequelizeInstance({ host: '255.255.255.255' }); const sequelize = Support.createSequelizeInstance({ host: '255.255.255.255' });
return expect(sequelize.connectionManager.getConnection()).to.have.been.rejectedWith(Sequelize.HostNotReachableError); await expect(sequelize.connectionManager.getConnection()).to.have.been.rejectedWith(Sequelize.HostNotReachableError);
}); });
it('ER_ACCESS_DENIED_ERROR | ELOGIN', () => { it('ER_ACCESS_DENIED_ERROR | ELOGIN', async () => {
const sequelize = new Support.Sequelize('localhost', 'was', 'ddsd', Support.sequelize.options); const sequelize = new Support.Sequelize('localhost', 'was', 'ddsd', Support.sequelize.options);
return expect(sequelize.connectionManager.getConnection()).to.have.been.rejectedWith(Sequelize.AccessDeniedError); await expect(sequelize.connectionManager.getConnection()).to.have.been.rejectedWith(Sequelize.AccessDeniedError);
}); });
}); });
......
...@@ -8,14 +8,14 @@ const chai = require('chai'), ...@@ -8,14 +8,14 @@ const chai = require('chai'),
if (dialect !== 'mariadb') return; if (dialect !== 'mariadb') return;
describe('[MariaDB Specific] DAO', () => { describe('[MariaDB Specific] DAO', () => {
beforeEach(function() { beforeEach(async function() {
this.sequelize.options.quoteIdentifiers = true; this.sequelize.options.quoteIdentifiers = true;
this.User = this.sequelize.define('User', { this.User = this.sequelize.define('User', {
username: DataTypes.STRING, username: DataTypes.STRING,
email: DataTypes.STRING, email: DataTypes.STRING,
location: DataTypes.GEOMETRY() location: DataTypes.GEOMETRY()
}); });
return this.User.sync({ force: true }); await this.User.sync({ force: true });
}); });
afterEach(function() { afterEach(function() {
...@@ -24,113 +24,100 @@ describe('[MariaDB Specific] DAO', () => { ...@@ -24,113 +24,100 @@ describe('[MariaDB Specific] DAO', () => {
describe('integers', () => { describe('integers', () => {
describe('integer', () => { describe('integer', () => {
beforeEach(function() { beforeEach(async function() {
this.User = this.sequelize.define('User', { this.User = this.sequelize.define('User', {
aNumber: DataTypes.INTEGER aNumber: DataTypes.INTEGER
}); });
return this.User.sync({ force: true }); await this.User.sync({ force: true });
}); });
it('positive', function() { it('positive', async function() {
const User = this.User; const User = this.User;
return User.create({ aNumber: 2147483647 }).then(user => { const user = await User.create({ aNumber: 2147483647 });
expect(user.aNumber).to.equal(2147483647); expect(user.aNumber).to.equal(2147483647);
return User.findOne({ where: { aNumber: 2147483647 } }).then(_user => { const _user = await User.findOne({ where: { aNumber: 2147483647 } });
expect(_user.aNumber).to.equal(2147483647); expect(_user.aNumber).to.equal(2147483647);
}); });
});
});
it('negative', function() { it('negative', async function() {
const User = this.User; const User = this.User;
return User.create({ aNumber: -2147483647 }).then(user => { const user = await User.create({ aNumber: -2147483647 });
expect(user.aNumber).to.equal(-2147483647); expect(user.aNumber).to.equal(-2147483647);
return User.findOne({ where: { aNumber: -2147483647 } }).then(_user => { const _user = await User.findOne({ where: { aNumber: -2147483647 } });
expect(_user.aNumber).to.equal(-2147483647); expect(_user.aNumber).to.equal(-2147483647);
}); });
}); });
});
});
describe('bigint', () => { describe('bigint', () => {
beforeEach(function() { beforeEach(async function() {
this.User = this.sequelize.define('User', { this.User = this.sequelize.define('User', {
aNumber: DataTypes.BIGINT aNumber: DataTypes.BIGINT
}); });
return this.User.sync({ force: true }); await this.User.sync({ force: true });
}); });
it('positive', function() { it('positive', async function() {
const User = this.User; const User = this.User;
return User.create({ aNumber: '9223372036854775807' }).then(user => { const user = await User.create({ aNumber: '9223372036854775807' });
expect(user.aNumber).to.equal('9223372036854775807'); expect(user.aNumber).to.equal('9223372036854775807');
return User.findOne({ where: { aNumber: '9223372036854775807' } }).then( const _user = await User.findOne({ where: { aNumber: '9223372036854775807' } });
_user => {
return expect(_user.aNumber.toString()).to.equal( await expect(_user.aNumber.toString()).to.equal('9223372036854775807');
'9223372036854775807');
});
});
}); });
it('negative', function() { it('negative', async function() {
const User = this.User; const User = this.User;
return User.create({ aNumber: '-9223372036854775807' }).then(user => { const user = await User.create({ aNumber: '-9223372036854775807' });
expect(user.aNumber).to.equal('-9223372036854775807'); expect(user.aNumber).to.equal('-9223372036854775807');
return User.findOne(
{ where: { aNumber: '-9223372036854775807' } }).then(_user => { const _user = await User.findOne(
return expect(_user.aNumber.toString()).to.equal( { where: { aNumber: '-9223372036854775807' } });
'-9223372036854775807');
}); await expect(_user.aNumber.toString()).to.equal('-9223372036854775807');
});
}); });
}); });
}); });
it('should save geometry correctly', function() { it('should save geometry correctly', async function() {
const point = { type: 'Point', coordinates: [39.807222, -76.984722] }; const point = { type: 'Point', coordinates: [39.807222, -76.984722] };
return this.User.create(
{ username: 'user', email: 'foo@bar.com', location: point }).then( const newUser = await this.User.create(
newUser => { { username: 'user', email: 'foo@bar.com', location: point });
expect(newUser.location).to.deep.eql(point); expect(newUser.location).to.deep.eql(point);
}); });
});
it('should update geometry correctly', function() { it('should update geometry correctly', async function() {
const User = this.User; const User = this.User;
const point1 = { type: 'Point', coordinates: [39.807222, -76.984722] }; const point1 = { type: 'Point', coordinates: [39.807222, -76.984722] };
const point2 = { type: 'Point', coordinates: [39.828333, -77.232222] }; const point2 = { type: 'Point', coordinates: [39.828333, -77.232222] };
return User.create(
{ username: 'user', email: 'foo@bar.com', location: point1 }) const oldUser = await User.create(
.then(oldUser => { { username: 'user', email: 'foo@bar.com', location: point1 });
return User.update({ location: point2 },
{ where: { username: oldUser.username } }) await User.update({ location: point2 },
.then(() => { { where: { username: oldUser.username } });
return User.findOne({ where: { username: oldUser.username } });
}) const updatedUser = await User.findOne({ where: { username: oldUser.username } });
.then(updatedUser => {
expect(updatedUser.location).to.deep.eql(point2); expect(updatedUser.location).to.deep.eql(point2);
}); });
});
});
it('should read geometry correctly', function() { it('should read geometry correctly', async function() {
const User = this.User; const User = this.User;
const point = { type: 'Point', coordinates: [39.807222, -76.984722] }; const point = { type: 'Point', coordinates: [39.807222, -76.984722] };
return User.create( const user0 = await User.create(
{ username: 'user', email: 'foo@bar.com', location: point }).then( { username: 'user', email: 'foo@bar.com', location: point });
user => {
return User.findOne({ where: { username: user.username } }); const user = await User.findOne({ where: { username: user0.username } });
}).then(user => {
expect(user.location).to.deep.eql(point); expect(user.location).to.deep.eql(point);
}); });
});
}); });
...@@ -9,12 +9,16 @@ const chai = require('chai'), ...@@ -9,12 +9,16 @@ const chai = require('chai'),
if (dialect !== 'mariadb') return; if (dialect !== 'mariadb') return;
describe('[MariaDB Specific] Errors', () => { describe('[MariaDB Specific] Errors', () => {
const validateError = (promise, errClass, errValues) => { const validateError = async (promise, errClass, errValues) => {
const wanted = { ...errValues }; const wanted = { ...errValues };
return expect(promise).to.have.been.rejectedWith(errClass).then(() => await expect(promise).to.have.been.rejectedWith(errClass);
promise.catch(err => Object.keys(wanted).forEach(
k => expect(err[k]).to.eql(wanted[k])))); try {
return await promise;
} catch (err) {
return Object.keys(wanted).forEach(k => expect(err[k]).to.eql(wanted[k]));
}
}; };
describe('ForeignKeyConstraintError', () => { describe('ForeignKeyConstraintError', () => {
...@@ -33,28 +37,26 @@ describe('[MariaDB Specific] Errors', () => { ...@@ -33,28 +37,26 @@ describe('[MariaDB Specific] Errors', () => {
{ foreignKey: 'primaryUserId', as: 'primaryUsers' }); { foreignKey: 'primaryUserId', as: 'primaryUsers' });
}); });
it('in context of DELETE restriction', function() { it('in context of DELETE restriction', async function() {
const ForeignKeyConstraintError = this.sequelize.ForeignKeyConstraintError; const ForeignKeyConstraintError = this.sequelize.ForeignKeyConstraintError;
const ctx = {}; await this.sequelize.sync({ force: true });
return this.sequelize.sync({ force: true }).then(() => {
return Promise.all([ const [user1, task1] = await Promise.all([
this.User.create({ id: 67, username: 'foo' }), this.User.create({ id: 67, username: 'foo' }),
this.Task.create({ id: 52, title: 'task' }) this.Task.create({ id: 52, title: 'task' })
]); ]);
}).then(([user1, task1]) => {
ctx.user1 = user1; await user1.setTasks([task1]);
ctx.task1 = task1;
return user1.setTasks([task1]); await Promise.all([
}).then(() => { validateError(user1.destroy(), ForeignKeyConstraintError, {
return Promise.all([
validateError(ctx.user1.destroy(), ForeignKeyConstraintError, {
fields: ['userId'], fields: ['userId'],
table: 'users', table: 'users',
value: undefined, value: undefined,
index: 'tasksusers_ibfk_1', index: 'tasksusers_ibfk_1',
reltype: 'parent' reltype: 'parent'
}), }),
validateError(ctx.task1.destroy(), ForeignKeyConstraintError, { validateError(task1.destroy(), ForeignKeyConstraintError, {
fields: ['taskId'], fields: ['taskId'],
table: 'tasks', table: 'tasks',
value: undefined, value: undefined,
...@@ -63,20 +65,23 @@ describe('[MariaDB Specific] Errors', () => { ...@@ -63,20 +65,23 @@ describe('[MariaDB Specific] Errors', () => {
}) })
]); ]);
}); });
});
it('in context of missing relation', function() { it('in context of missing relation', async function() {
const ForeignKeyConstraintError = this.sequelize.ForeignKeyConstraintError; const ForeignKeyConstraintError = this.sequelize.ForeignKeyConstraintError;
return this.sequelize.sync({ force: true }).then(() => await this.sequelize.sync({ force: true });
validateError(this.Task.create({ title: 'task', primaryUserId: 5 }),
ForeignKeyConstraintError, { await validateError(
this.Task.create({ title: 'task', primaryUserId: 5 }),
ForeignKeyConstraintError,
{
fields: ['primaryUserId'], fields: ['primaryUserId'],
table: 'users', table: 'users',
value: 5, value: 5,
index: 'tasks_ibfk_1', index: 'tasks_ibfk_1',
reltype: 'child' reltype: 'child'
})); }
);
}); });
}); });
......
...@@ -9,19 +9,13 @@ if (dialect.match(/^mariadb/)) { ...@@ -9,19 +9,13 @@ if (dialect.match(/^mariadb/)) {
describe('QueryInterface', () => { describe('QueryInterface', () => {
describe('databases', () => { describe('databases', () => {
it('should create and drop database', function() { it('should create and drop database', async function() {
return this.sequelize.query('SHOW DATABASES') const res = await this.sequelize.query('SHOW DATABASES');
.then(res => {
const databaseNumber = res[0].length; const databaseNumber = res[0].length;
return this.sequelize.getQueryInterface().createDatabase('myDB') await this.sequelize.getQueryInterface().createDatabase('myDB');
.then(() => { const databases = await this.sequelize.query('SHOW DATABASES');
return this.sequelize.query('SHOW DATABASES');
})
.then(databases => {
expect(databases[0]).to.have.length(databaseNumber + 1); expect(databases[0]).to.have.length(databaseNumber + 1);
return this.sequelize.getQueryInterface().dropDatabase('myDB'); await this.sequelize.getQueryInterface().dropDatabase('myDB');
});
});
}); });
}); });
}); });
......
...@@ -9,24 +9,24 @@ const dialect = Support.getTestDialect(); ...@@ -9,24 +9,24 @@ const dialect = Support.getTestDialect();
if (dialect.match(/^mssql/)) { if (dialect.match(/^mssql/)) {
describe('[MSSQL Specific] Connection Manager', () => { describe('[MSSQL Specific] Connection Manager', () => {
describe('Errors', () => { describe('Errors', () => {
it('ECONNREFUSED', () => { it('ECONNREFUSED', async () => {
const sequelize = Support.createSequelizeInstance({ host: '127.0.0.1', port: 34237 }); const sequelize = Support.createSequelizeInstance({ host: '127.0.0.1', port: 34237 });
return expect(sequelize.connectionManager.getConnection()).to.have.been.rejectedWith(Sequelize.ConnectionRefusedError); await expect(sequelize.connectionManager.getConnection()).to.have.been.rejectedWith(Sequelize.ConnectionRefusedError);
}); });
it('ENOTFOUND', () => { it('ENOTFOUND', async () => {
const sequelize = Support.createSequelizeInstance({ host: 'http://wowow.example.com' }); const sequelize = Support.createSequelizeInstance({ host: 'http://wowow.example.com' });
return expect(sequelize.connectionManager.getConnection()).to.have.been.rejectedWith(Sequelize.HostNotFoundError); await expect(sequelize.connectionManager.getConnection()).to.have.been.rejectedWith(Sequelize.HostNotFoundError);
}); });
it('EHOSTUNREACH', () => { it('EHOSTUNREACH', async () => {
const sequelize = Support.createSequelizeInstance({ host: '255.255.255.255' }); const sequelize = Support.createSequelizeInstance({ host: '255.255.255.255' });
return expect(sequelize.connectionManager.getConnection()).to.have.been.rejectedWith(Sequelize.HostNotReachableError); await expect(sequelize.connectionManager.getConnection()).to.have.been.rejectedWith(Sequelize.HostNotReachableError);
}); });
it('ER_ACCESS_DENIED_ERROR | ELOGIN', () => { it('ER_ACCESS_DENIED_ERROR | ELOGIN', async () => {
const sequelize = new Support.Sequelize('localhost', 'was', 'ddsd', Support.sequelize.options); const sequelize = new Support.Sequelize('localhost', 'was', 'ddsd', Support.sequelize.options);
return expect(sequelize.connectionManager.getConnection()).to.have.been.rejectedWith(Sequelize.AccessDeniedError); await expect(sequelize.connectionManager.getConnection()).to.have.been.rejectedWith(Sequelize.AccessDeniedError);
}); });
}); });
}); });
......
...@@ -11,20 +11,20 @@ const chai = require('chai'), ...@@ -11,20 +11,20 @@ const chai = require('chai'),
if (dialect.match(/^mssql/)) { if (dialect.match(/^mssql/)) {
describe('[MSSQL Specific] Query Queue', () => { describe('[MSSQL Specific] Query Queue', () => {
beforeEach(function() { beforeEach(async function() {
const User = this.User = this.sequelize.define('User', { const User = this.User = this.sequelize.define('User', {
username: DataTypes.STRING username: DataTypes.STRING
}); });
return this.sequelize.sync({ force: true }).then(() => { await this.sequelize.sync({ force: true });
return User.create({ username: 'John' });
}); await User.create({ username: 'John' });
}); });
it('should queue concurrent requests to a connection', function() { it('should queue concurrent requests to a connection', async function() {
const User = this.User; const User = this.User;
return expect(this.sequelize.transaction(t => { await expect(this.sequelize.transaction(async t => {
return Promise.all([ return Promise.all([
User.findOne({ User.findOne({
transaction: t transaction: t
......
...@@ -9,7 +9,7 @@ const chai = require('chai'), ...@@ -9,7 +9,7 @@ const chai = require('chai'),
if (dialect.match(/^mssql/)) { if (dialect.match(/^mssql/)) {
describe('[MSSQL Specific] Regressions', () => { describe('[MSSQL Specific] Regressions', () => {
it('does not duplicate columns in ORDER BY statement, #9008', function() { it('does not duplicate columns in ORDER BY statement, #9008', async function() {
const LoginLog = this.sequelize.define('LoginLog', { const LoginLog = this.sequelize.define('LoginLog', {
ID: { ID: {
field: 'id', field: 'id',
...@@ -45,22 +45,23 @@ if (dialect.match(/^mssql/)) { ...@@ -45,22 +45,23 @@ if (dialect.match(/^mssql/)) {
foreignKey: 'UserID' foreignKey: 'UserID'
}); });
return this.sequelize.sync({ force: true }) await this.sequelize.sync({ force: true });
.then(() => User.bulkCreate([
const [vyom, shakti, nikita, arya] = await User.bulkCreate([
{ UserName: 'Vayom' }, { UserName: 'Vayom' },
{ UserName: 'Shaktimaan' }, { UserName: 'Shaktimaan' },
{ UserName: 'Nikita' }, { UserName: 'Nikita' },
{ UserName: 'Aryamaan' } { UserName: 'Aryamaan' }
], { returning: true })) ], { returning: true });
.then(([vyom, shakti, nikita, arya]) => {
return Promise.all([ await Promise.all([
vyom.createLoginLog(), vyom.createLoginLog(),
shakti.createLoginLog(), shakti.createLoginLog(),
nikita.createLoginLog(), nikita.createLoginLog(),
arya.createLoginLog() arya.createLoginLog()
]); ]);
}).then(() => {
return LoginLog.findAll({ const logs = await LoginLog.findAll({
include: [ include: [
{ {
model: User, model: User,
...@@ -75,41 +76,36 @@ if (dialect.match(/^mssql/)) { ...@@ -75,41 +76,36 @@ if (dialect.match(/^mssql/)) {
offset: 0, offset: 0,
limit: 10 limit: 10
}); });
}).then(logs => {
expect(logs).to.have.length(2); expect(logs).to.have.length(2);
expect(logs[0].User.get('UserName')).to.equal('Shaktimaan'); expect(logs[0].User.get('UserName')).to.equal('Shaktimaan');
expect(logs[1].User.get('UserName')).to.equal('Aryamaan'); expect(logs[1].User.get('UserName')).to.equal('Aryamaan');
}); });
}); });
});
it('sets the varchar(max) length correctly on describeTable', function() { it('sets the varchar(max) length correctly on describeTable', async function() {
const Users = this.sequelize.define('_Users', { const Users = this.sequelize.define('_Users', {
username: Sequelize.STRING('MAX') username: Sequelize.STRING('MAX')
}, { freezeTableName: true }); }, { freezeTableName: true });
return Users.sync({ force: true }).then(() => { await Users.sync({ force: true });
return this.sequelize.getQueryInterface().describeTable('_Users').then(metadata => { const metadata = await this.sequelize.getQueryInterface().describeTable('_Users');
const username = metadata.username; const username = metadata.username;
expect(username.type).to.include('(MAX)'); expect(username.type).to.include('(MAX)');
}); });
});
});
it('sets the char(10) length correctly on describeTable', function() { it('sets the char(10) length correctly on describeTable', async function() {
const Users = this.sequelize.define('_Users', { const Users = this.sequelize.define('_Users', {
username: Sequelize.CHAR(10) username: Sequelize.CHAR(10)
}, { freezeTableName: true }); }, { freezeTableName: true });
return Users.sync({ force: true }).then(() => { await Users.sync({ force: true });
return this.sequelize.getQueryInterface().describeTable('_Users').then(metadata => { const metadata = await this.sequelize.getQueryInterface().describeTable('_Users');
const username = metadata.username; const username = metadata.username;
expect(username.type).to.include('(10)'); expect(username.type).to.include('(10)');
}); });
});
});
it('saves value bigger than 2147483647, #11245', function() { it('saves value bigger than 2147483647, #11245', async function() {
const BigIntTable = this.sequelize.define('BigIntTable', { const BigIntTable = this.sequelize.define('BigIntTable', {
business_id: { business_id: {
type: Sequelize.BIGINT, type: Sequelize.BIGINT,
...@@ -121,19 +117,17 @@ if (dialect.match(/^mssql/)) { ...@@ -121,19 +117,17 @@ if (dialect.match(/^mssql/)) {
const bigIntValue = 2147483648; const bigIntValue = 2147483648;
return BigIntTable.sync({ force: true }) await BigIntTable.sync({ force: true });
.then(() => {
return BigIntTable.create({ await BigIntTable.create({
business_id: bigIntValue business_id: bigIntValue
}); });
})
.then(() => BigIntTable.findOne()) const record = await BigIntTable.findOne();
.then(record => {
expect(Number(record.business_id)).to.equals(bigIntValue); expect(Number(record.business_id)).to.equals(bigIntValue);
}); });
});
it('saves boolean is true, #12090', function() { it('saves boolean is true, #12090', async function() {
const BooleanTable = this.sequelize.define('BooleanTable', { const BooleanTable = this.sequelize.define('BooleanTable', {
status: { status: {
type: Sequelize.BOOLEAN, type: Sequelize.BOOLEAN,
...@@ -145,15 +139,13 @@ if (dialect.match(/^mssql/)) { ...@@ -145,15 +139,13 @@ if (dialect.match(/^mssql/)) {
const value = true; const value = true;
return BooleanTable.sync({ force: true }) await BooleanTable.sync({ force: true });
.then(() => {
return BooleanTable.create({ await BooleanTable.create({
status: value status: value
}); });
})
.then(() => BooleanTable.findOne()) const record = await BooleanTable.findOne();
.then(record => {
expect(record.status).to.equals(value); expect(record.status).to.equals(value);
}); });
});
} }
...@@ -10,30 +10,27 @@ if (dialect === 'mysql') { ...@@ -10,30 +10,27 @@ if (dialect === 'mysql') {
describe('[MYSQL Specific] Associations', () => { describe('[MYSQL Specific] Associations', () => {
describe('many-to-many', () => { describe('many-to-many', () => {
describe('where tables have the same prefix', () => { describe('where tables have the same prefix', () => {
it('should create a table wp_table1wp_table2s', function() { it('should create a table wp_table1wp_table2s', async function() {
const Table2 = this.sequelize.define('wp_table2', { foo: DataTypes.STRING }), const Table2 = this.sequelize.define('wp_table2', { foo: DataTypes.STRING }),
Table1 = this.sequelize.define('wp_table1', { foo: DataTypes.STRING }); Table1 = this.sequelize.define('wp_table1', { foo: DataTypes.STRING });
Table1.belongsToMany(Table2, { through: 'wp_table1swp_table2s' }); Table1.belongsToMany(Table2, { through: 'wp_table1swp_table2s' });
Table2.belongsToMany(Table1, { through: 'wp_table1swp_table2s' }); Table2.belongsToMany(Table1, { through: 'wp_table1swp_table2s' });
return Table1.sync({ force: true }).then(() => { await Table1.sync({ force: true });
return Table2.sync({ force: true }).then(() => { await Table2.sync({ force: true });
expect(this.sequelize.modelManager.getModel('wp_table1swp_table2s')).to.exist; expect(this.sequelize.modelManager.getModel('wp_table1swp_table2s')).to.exist;
}); });
}); });
});
});
describe('when join table name is specified', () => { describe('when join table name is specified', () => {
beforeEach(function() { beforeEach(async function() {
const Table2 = this.sequelize.define('ms_table1', { foo: DataTypes.STRING }), const Table2 = this.sequelize.define('ms_table1', { foo: DataTypes.STRING }),
Table1 = this.sequelize.define('ms_table2', { foo: DataTypes.STRING }); Table1 = this.sequelize.define('ms_table2', { foo: DataTypes.STRING });
Table1.belongsToMany(Table2, { through: 'table1_to_table2' }); Table1.belongsToMany(Table2, { through: 'table1_to_table2' });
Table2.belongsToMany(Table1, { through: 'table1_to_table2' }); Table2.belongsToMany(Table1, { through: 'table1_to_table2' });
return Table1.sync({ force: true }).then(() => { await Table1.sync({ force: true });
return Table2.sync({ force: true }); await Table2.sync({ force: true });
});
}); });
it('should not use only a specified name', function() { it('should not use only a specified name', function() {
...@@ -44,7 +41,7 @@ if (dialect === 'mysql') { ...@@ -44,7 +41,7 @@ if (dialect === 'mysql') {
}); });
describe('HasMany', () => { describe('HasMany', () => {
beforeEach(function() { beforeEach(async function() {
//prevent periods from occurring in the table name since they are used to delimit (table.column) //prevent periods from occurring in the table name since they are used to delimit (table.column)
this.User = this.sequelize.define(`User${Math.ceil(Math.random() * 10000000)}`, { name: DataTypes.STRING }); this.User = this.sequelize.define(`User${Math.ceil(Math.random() * 10000000)}`, { name: DataTypes.STRING });
this.Task = this.sequelize.define(`Task${Math.ceil(Math.random() * 10000000)}`, { name: DataTypes.STRING }); this.Task = this.sequelize.define(`Task${Math.ceil(Math.random() * 10000000)}`, { name: DataTypes.STRING });
...@@ -62,70 +59,48 @@ if (dialect === 'mysql') { ...@@ -62,70 +59,48 @@ if (dialect === 'mysql') {
tasks[i] = { name: `Task${Math.random()}` }; tasks[i] = { name: `Task${Math.random()}` };
} }
return this.sequelize.sync({ force: true }).then(() => { await this.sequelize.sync({ force: true });
return this.User.bulkCreate(users).then(() => { await this.User.bulkCreate(users);
return this.Task.bulkCreate(tasks); await this.Task.bulkCreate(tasks);
});
});
}); });
describe('addDAO / getModel', () => { describe('addDAO / getModel', () => {
beforeEach(function() { beforeEach(async function() {
this.user = null; this.user = null;
this.task = null; this.task = null;
return this.User.findAll().then(_users => { const _users = await this.User.findAll();
return this.Task.findAll().then(_tasks => { const _tasks = await this.Task.findAll();
this.user = _users[0]; this.user = _users[0];
this.task = _tasks[0]; this.task = _tasks[0];
}); });
});
});
it('should correctly add an association to the dao', function() { it('should correctly add an association to the dao', async function() {
return this.user.getTasks().then(_tasks => { expect(await this.user.getTasks()).to.have.length(0);
expect(_tasks.length).to.equal(0); await this.user.addTask(this.task);
return this.user.addTask(this.task).then(() => { expect(await this.user.getTasks()).to.have.length(1);
return this.user.getTasks().then(_tasks => {
expect(_tasks.length).to.equal(1);
});
});
});
}); });
}); });
describe('removeDAO', () => { describe('removeDAO', () => {
beforeEach(function() { beforeEach(async function() {
this.user = null; this.user = null;
this.tasks = null; this.tasks = null;
return this.User.findAll().then(_users => { const _users = await this.User.findAll();
return this.Task.findAll().then(_tasks => { const _tasks = await this.Task.findAll();
this.user = _users[0]; this.user = _users[0];
this.tasks = _tasks; this.tasks = _tasks;
}); });
});
});
it('should correctly remove associated objects', function() { it('should correctly remove associated objects', async function() {
return this.user.getTasks().then(__tasks => { expect(await this.user.getTasks()).to.have.length(0);
expect(__tasks.length).to.equal(0); await this.user.setTasks(this.tasks);
return this.user.setTasks(this.tasks).then(() => { expect(await this.user.getTasks()).to.have.length(this.tasks.length);
return this.user.getTasks().then(_tasks => { await this.user.removeTask(this.tasks[0]);
expect(_tasks.length).to.equal(this.tasks.length); expect(await this.user.getTasks()).to.have.length(this.tasks.length - 1);
return this.user.removeTask(this.tasks[0]).then(() => { await this.user.removeTasks([this.tasks[1], this.tasks[2]]);
return this.user.getTasks().then(_tasks => { expect(await this.user.getTasks()).to.have.length(this.tasks.length - 3);
expect(_tasks.length).to.equal(this.tasks.length - 1);
return this.user.removeTasks([this.tasks[1], this.tasks[2]]).then(() => {
return this.user.getTasks().then(_tasks => {
expect(_tasks).to.have.length(this.tasks.length - 3);
});
});
});
});
});
});
});
}); });
}); });
}); });
......
...@@ -8,31 +8,32 @@ const DataTypes = require('../../../../lib/data-types'); ...@@ -8,31 +8,32 @@ const DataTypes = require('../../../../lib/data-types');
if (dialect === 'mysql') { if (dialect === 'mysql') {
describe('[MYSQL Specific] Connection Manager', () => { describe('[MYSQL Specific] Connection Manager', () => {
it('-FOUND_ROWS can be suppressed to get back legacy behavior', () => { it('-FOUND_ROWS can be suppressed to get back legacy behavior', async () => {
const sequelize = Support.createSequelizeInstance({ dialectOptions: { flags: '' } }); const sequelize = Support.createSequelizeInstance({ dialectOptions: { flags: '' } });
const User = sequelize.define('User', { username: DataTypes.STRING }); const User = sequelize.define('User', { username: DataTypes.STRING });
return User.sync({ force: true }) await User.sync({ force: true });
.then(() => User.create({ id: 1, username: 'jozef' })) await User.create({ id: 1, username: 'jozef' });
.then(() => User.update({ username: 'jozef' }, {
const [affectedCount] = await User.update({ username: 'jozef' }, {
where: { where: {
id: 1 id: 1
} }
})) });
// https://github.com/sequelize/sequelize/issues/7184 // https://github.com/sequelize/sequelize/issues/7184
.then(([affectedCount]) => affectedCount.should.equal(1)); await affectedCount.should.equal(1);
}); });
it('should acquire a valid connection when keepDefaultTimezone is true', () => { it('should acquire a valid connection when keepDefaultTimezone is true', async () => {
const sequelize = Support.createSequelizeInstance({ keepDefaultTimezone: true, pool: { min: 1, max: 1, handleDisconnects: true, idle: 5000 } }); const sequelize = Support.createSequelizeInstance({ keepDefaultTimezone: true, pool: { min: 1, max: 1, handleDisconnects: true, idle: 5000 } });
const cm = sequelize.connectionManager; const cm = sequelize.connectionManager;
return sequelize
.sync() await sequelize.sync();
.then(() => cm.getConnection())
.then(connection => { const connection = await cm.getConnection();
expect(cm.validate(connection)).to.be.ok; expect(cm.validate(connection)).to.be.ok;
return cm.releaseConnection(connection); await cm.releaseConnection(connection);
});
}); });
}); });
} }
...@@ -10,11 +10,16 @@ const DataTypes = require('../../../../lib/data-types'); ...@@ -10,11 +10,16 @@ const DataTypes = require('../../../../lib/data-types');
if (dialect === 'mysql') { if (dialect === 'mysql') {
describe('[MYSQL Specific] Errors', () => { describe('[MYSQL Specific] Errors', () => {
const validateError = (promise, errClass, errValues) => { const validateError = async (promise, errClass, errValues) => {
const wanted = { ...errValues }; const wanted = { ...errValues };
return expect(promise).to.have.been.rejectedWith(errClass).then(() => await expect(promise).to.have.been.rejectedWith(errClass);
promise.catch(err => Object.keys(wanted).forEach(k => expect(err[k]).to.eql(wanted[k]))));
try {
return await promise;
} catch (err) {
return Object.keys(wanted).forEach(k => expect(err[k]).to.eql(wanted[k]));
}
}; };
describe('ForeignKeyConstraintError', () => { describe('ForeignKeyConstraintError', () => {
...@@ -29,27 +34,25 @@ if (dialect === 'mysql') { ...@@ -29,27 +34,25 @@ if (dialect === 'mysql') {
this.Task.belongsTo(this.User, { foreignKey: 'primaryUserId', as: 'primaryUsers' }); this.Task.belongsTo(this.User, { foreignKey: 'primaryUserId', as: 'primaryUsers' });
}); });
it('in context of DELETE restriction', function() { it('in context of DELETE restriction', async function() {
const ctx = {}; await this.sequelize.sync({ force: true });
return this.sequelize.sync({ force: true }).then(() => {
return Promise.all([ const [user1, task1] = await Promise.all([
this.User.create({ id: 67, username: 'foo' }), this.User.create({ id: 67, username: 'foo' }),
this.Task.create({ id: 52, title: 'task' }) this.Task.create({ id: 52, title: 'task' })
]); ]);
}).then(([user1, task1]) => {
ctx.user1 = user1; await user1.setTasks([task1]);
ctx.task1 = task1;
return user1.setTasks([task1]); await Promise.all([
}).then(() => { validateError(user1.destroy(), Sequelize.ForeignKeyConstraintError, {
return Promise.all([
validateError(ctx.user1.destroy(), Sequelize.ForeignKeyConstraintError, {
fields: ['userId'], fields: ['userId'],
table: 'users', table: 'users',
value: undefined, value: undefined,
index: 'tasksusers_ibfk_1', index: 'tasksusers_ibfk_1',
reltype: 'parent' reltype: 'parent'
}), }),
validateError(ctx.task1.destroy(), Sequelize.ForeignKeyConstraintError, { validateError(task1.destroy(), Sequelize.ForeignKeyConstraintError, {
fields: ['taskId'], fields: ['taskId'],
table: 'tasks', table: 'tasks',
value: undefined, value: undefined,
...@@ -58,17 +61,21 @@ if (dialect === 'mysql') { ...@@ -58,17 +61,21 @@ if (dialect === 'mysql') {
}) })
]); ]);
}); });
});
it('in context of missing relation', function() { it('in context of missing relation', async function() {
return this.sequelize.sync({ force: true }).then(() => await this.sequelize.sync({ force: true });
validateError(this.Task.create({ title: 'task', primaryUserId: 5 }), Sequelize.ForeignKeyConstraintError, {
await validateError(
this.Task.create({ title: 'task', primaryUserId: 5 }),
Sequelize.ForeignKeyConstraintError,
{
fields: ['primaryUserId'], fields: ['primaryUserId'],
table: 'users', table: 'users',
value: 5, value: 5,
index: 'tasks_ibfk_1', index: 'tasks_ibfk_1',
reltype: 'child' reltype: 'child'
})); }
);
}); });
}); });
}); });
......
...@@ -11,7 +11,7 @@ describe(Support.getTestDialectTeaser('Warning'), () => { ...@@ -11,7 +11,7 @@ describe(Support.getTestDialectTeaser('Warning'), () => {
// We can only test MySQL warnings when using MySQL. // We can only test MySQL warnings when using MySQL.
if (dialect === 'mysql') { if (dialect === 'mysql') {
describe('logging', () => { describe('logging', () => {
it('logs warnings when there are warnings', () => { it('logs warnings when there are warnings', async () => {
const logger = sinon.spy(console, 'log'); const logger = sinon.spy(console, 'log');
const sequelize = Support.createSequelizeInstance({ const sequelize = Support.createSequelizeInstance({
logging: logger, logging: logger,
...@@ -23,20 +23,16 @@ describe(Support.getTestDialectTeaser('Warning'), () => { ...@@ -23,20 +23,16 @@ describe(Support.getTestDialectTeaser('Warning'), () => {
name: Sequelize.DataTypes.STRING(1, true) name: Sequelize.DataTypes.STRING(1, true)
}); });
return sequelize.sync({ force: true }).then(() => { await sequelize.sync({ force: true });
return sequelize.authenticate(); await sequelize.authenticate();
}).then(() => { await sequelize.query("SET SESSION sql_mode='';");
return sequelize.query("SET SESSION sql_mode='';");
}).then(() => { await Model.create({
return Model.create({
name: 'very-long-long-name' name: 'very-long-long-name'
}); });
}).then(() => {
// last log is warning message // last log is warning message
expect(logger.args[logger.args.length - 1][0]).to.be.match(/^MySQL Warnings \(default\):.*/m); expect(logger.args[logger.args.length - 1][0]).to.be.match(/^MySQL Warnings \(default\):.*/m);
}, () => {
expect.fail();
});
}); });
}); });
} }
......
...@@ -43,7 +43,7 @@ if (dialect.match(/^postgres/)) { ...@@ -43,7 +43,7 @@ if (dialect.match(/^postgres/)) {
describe('HasMany', () => { describe('HasMany', () => {
describe('addDAO / getModel', () => { describe('addDAO / getModel', () => {
beforeEach(function() { beforeEach(async function() {
//prevent periods from occurring in the table name since they are used to delimit (table.column) //prevent periods from occurring in the table name since they are used to delimit (table.column)
this.User = this.sequelize.define(`User${config.rand()}`, { name: DataTypes.STRING }); this.User = this.sequelize.define(`User${config.rand()}`, { name: DataTypes.STRING });
this.Task = this.sequelize.define(`Task${config.rand()}`, { name: DataTypes.STRING }); this.Task = this.sequelize.define(`Task${config.rand()}`, { name: DataTypes.STRING });
...@@ -61,34 +61,24 @@ if (dialect.match(/^postgres/)) { ...@@ -61,34 +61,24 @@ if (dialect.match(/^postgres/)) {
tasks[i] = { name: `Task${Math.random()}` }; tasks[i] = { name: `Task${Math.random()}` };
} }
return this.sequelize.sync({ force: true }).then(() => { await this.sequelize.sync({ force: true });
return this.User.bulkCreate(users).then(() => { await this.User.bulkCreate(users);
return this.Task.bulkCreate(tasks).then(() => { await this.Task.bulkCreate(tasks);
return this.User.findAll().then(_users => { const _users = await this.User.findAll();
return this.Task.findAll().then(_tasks => { const _tasks = await this.Task.findAll();
this.user = _users[0]; this.user = _users[0];
this.task = _tasks[0]; this.task = _tasks[0];
}); });
});
});
});
});
});
it('should correctly add an association to the dao', function() { it('should correctly add an association to the dao', async function() {
return this.user.getTasks().then(_tasks => { expect(await this.user.getTasks()).to.have.length(0);
expect(_tasks).to.have.length(0); await this.user.addTask(this.task);
return this.user.addTask(this.task).then(() => { expect(await this.user.getTasks()).to.have.length(1);
return this.user.getTasks().then(_tasks => {
expect(_tasks).to.have.length(1);
});
});
});
}); });
}); });
describe('removeDAO', () => { describe('removeDAO', () => {
it('should correctly remove associated objects', function() { it('should correctly remove associated objects', async function() {
const users = [], const users = [],
tasks = []; tasks = [];
...@@ -106,39 +96,23 @@ if (dialect.match(/^postgres/)) { ...@@ -106,39 +96,23 @@ if (dialect.match(/^postgres/)) {
tasks[i] = { id: i + 1, name: `Task${Math.random()}` }; tasks[i] = { id: i + 1, name: `Task${Math.random()}` };
} }
return this.sequelize.sync({ force: true }).then(() => { await this.sequelize.sync({ force: true });
return this.User.bulkCreate(users).then(() => { await this.User.bulkCreate(users);
return this.Task.bulkCreate(tasks).then(() => { await this.Task.bulkCreate(tasks);
return this.User.findAll().then(_users => { const _users = await this.User.findAll();
return this.Task.findAll().then(_tasks => { const _tasks = await this.Task.findAll();
this.user = _users[0]; this.user = _users[0];
this.task = _tasks[0]; this.task = _tasks[0];
this.users = _users; this.users = _users;
this.tasks = _tasks; this.tasks = _tasks;
return this.user.getTasks().then(__tasks => { expect(await this.user.getTasks()).to.have.length(0);
expect(__tasks).to.have.length(0); await this.user.setTasks(this.tasks);
return this.user.setTasks(this.tasks).then(() => { expect(await this.user.getTasks()).to.have.length(this.tasks.length);
return this.user.getTasks().then(_tasks => { await this.user.removeTask(this.tasks[0]);
expect(_tasks).to.have.length(this.tasks.length); expect(await this.user.getTasks()).to.have.length(this.tasks.length - 1);
return this.user.removeTask(this.tasks[0]).then(() => { await this.user.removeTasks([this.tasks[1], this.tasks[2]]);
return this.user.getTasks().then(_tasks => { expect(await this.user.getTasks()).to.have.length(this.tasks.length - 3);
expect(_tasks).to.have.length(this.tasks.length - 1);
return this.user.removeTasks([this.tasks[1], this.tasks[2]]).then(() => {
return this.user.getTasks().then(_tasks => {
expect(_tasks).to.have.length(this.tasks.length - 3);
});
});
});
});
});
});
});
});
});
});
});
});
}); });
}); });
}); });
......
...@@ -8,46 +8,38 @@ const chai = require('chai'), ...@@ -8,46 +8,38 @@ const chai = require('chai'),
if (dialect.match(/^postgres/)) { if (dialect.match(/^postgres/)) {
describe('[POSTGRES] Sequelize', () => { describe('[POSTGRES] Sequelize', () => {
function checkTimezoneParsing(baseOptions) { async function checkTimezoneParsing(baseOptions) {
const options = { ...baseOptions, timezone: 'Asia/Kolkata', timestamps: true }; const options = { ...baseOptions, timezone: 'Asia/Kolkata', timestamps: true };
const sequelize = Support.createSequelizeInstance(options); const sequelize = Support.createSequelizeInstance(options);
const tzTable = sequelize.define('tz_table', { foo: DataTypes.STRING }); const tzTable = sequelize.define('tz_table', { foo: DataTypes.STRING });
return tzTable.sync({ force: true }).then(() => { await tzTable.sync({ force: true });
return tzTable.create({ foo: 'test' }).then(row => { const row = await tzTable.create({ foo: 'test' });
expect(row).to.be.not.null; expect(row).to.be.not.null;
});
});
} }
it('should correctly parse the moment based timezone while fetching hstore oids', function() { it('should correctly parse the moment based timezone while fetching hstore oids', async function() {
return checkTimezoneParsing(this.sequelize.options); await checkTimezoneParsing(this.sequelize.options);
}); });
it('should set client_min_messages to warning by default', () => { it('should set client_min_messages to warning by default', async () => {
return Support.sequelize.query('SHOW client_min_messages') const result = await Support.sequelize.query('SHOW client_min_messages');
.then(result => {
expect(result[0].client_min_messages).to.equal('warning'); expect(result[0].client_min_messages).to.equal('warning');
}); });
});
it('should allow overriding client_min_messages', () => { it('should allow overriding client_min_messages', async () => {
const sequelize = Support.createSequelizeInstance({ clientMinMessages: 'ERROR' }); const sequelize = Support.createSequelizeInstance({ clientMinMessages: 'ERROR' });
return sequelize.query('SHOW client_min_messages') const result = await sequelize.query('SHOW client_min_messages');
.then(result => {
expect(result[0].client_min_messages).to.equal('error'); expect(result[0].client_min_messages).to.equal('error');
}); });
});
it('should not set client_min_messages if clientMinMessages is false', () => { it('should not set client_min_messages if clientMinMessages is false', async () => {
const sequelize = Support.createSequelizeInstance({ clientMinMessages: false }); const sequelize = Support.createSequelizeInstance({ clientMinMessages: false });
return sequelize.query('SHOW client_min_messages') const result = await sequelize.query('SHOW client_min_messages');
.then(result => {
// `notice` is Postgres's default // `notice` is Postgres's default
expect(result[0].client_min_messages).to.equal('notice'); expect(result[0].client_min_messages).to.equal('notice');
}); });
}); });
});
describe('Dynamic OIDs', () => { describe('Dynamic OIDs', () => {
const dynamicTypesToCheck = [ const dynamicTypesToCheck = [
...@@ -79,9 +71,9 @@ if (dialect.match(/^postgres/)) { ...@@ -79,9 +71,9 @@ if (dialect.match(/^postgres/)) {
return User.sync({ force: true }); return User.sync({ force: true });
} }
it('should fetch regular dynamic oids and create parsers', () => { it('should fetch regular dynamic oids and create parsers', async () => {
const sequelize = Support.sequelize; const sequelize = Support.sequelize;
return reloadDynamicOIDs(sequelize).then(() => { await reloadDynamicOIDs(sequelize);
dynamicTypesToCheck.forEach(type => { dynamicTypesToCheck.forEach(type => {
expect(type.types.postgres, expect(type.types.postgres,
`DataType.${type.key}.types.postgres`).to.not.be.empty; `DataType.${type.key}.types.postgres`).to.not.be.empty;
...@@ -101,11 +93,10 @@ if (dialect.match(/^postgres/)) { ...@@ -101,11 +93,10 @@ if (dialect.match(/^postgres/)) {
}); });
}); });
});
it('should fetch enum dynamic oids and create parsers', () => { it('should fetch enum dynamic oids and create parsers', async () => {
const sequelize = Support.sequelize; const sequelize = Support.sequelize;
return reloadDynamicOIDs(sequelize).then(() => { await reloadDynamicOIDs(sequelize);
const enumOids = sequelize.connectionManager.enumOids; const enumOids = sequelize.connectionManager.enumOids;
const oidParserMap = sequelize.connectionManager.oidParserMap; const oidParserMap = sequelize.connectionManager.oidParserMap;
...@@ -119,11 +110,10 @@ if (dialect.match(/^postgres/)) { ...@@ -119,11 +110,10 @@ if (dialect.match(/^postgres/)) {
expect(oidParserMap.get(arrayOid), 'oidParserMap.get(enumOids.arrayOids)').to.be.a('function'); expect(oidParserMap.get(arrayOid), 'oidParserMap.get(enumOids.arrayOids)').to.be.a('function');
} }
}); });
});
it('should fetch range dynamic oids and create parsers', () => { it('should fetch range dynamic oids and create parsers', async () => {
const sequelize = Support.sequelize; const sequelize = Support.sequelize;
return reloadDynamicOIDs(sequelize).then(() => { await reloadDynamicOIDs(sequelize);
for (const baseKey in expCastTypes) { for (const baseKey in expCastTypes) {
const name = expCastTypes[baseKey]; const name = expCastTypes[baseKey];
const entry = sequelize.connectionManager.nameOidMap[name]; const entry = sequelize.connectionManager.nameOidMap[name];
...@@ -139,7 +129,6 @@ if (dialect.match(/^postgres/)) { ...@@ -139,7 +129,6 @@ if (dialect.match(/^postgres/)) {
`oidParserMap.get(nameOidMap[${name}].arrayRangeOid)`).to.be.a('function'); `oidParserMap.get(nameOidMap[${name}].arrayRangeOid)`).to.be.a('function');
} }
}); });
});
}); });
} }
...@@ -72,7 +72,7 @@ if (dialect === 'postgres') { ...@@ -72,7 +72,7 @@ if (dialect === 'postgres') {
describe('DATE SQL', () => { describe('DATE SQL', () => {
// create dummy user // create dummy user
it('should be able to create and update records with Infinity/-Infinity', function() { it('should be able to create and update records with Infinity/-Infinity', async function() {
this.sequelize.options.typeValidation = true; this.sequelize.options.typeValidation = true;
const date = new Date(); const date = new Date();
...@@ -97,69 +97,68 @@ if (dialect === 'postgres') { ...@@ -97,69 +97,68 @@ if (dialect === 'postgres') {
timestamps: true timestamps: true
}); });
return User.sync({ await User.sync({
force: true force: true
}).then(() => { });
return User.create({
const user4 = await User.create({
username: 'bob', username: 'bob',
anotherTime: Infinity anotherTime: Infinity
}, { }, {
validate: true validate: true
}); });
}).then(user => {
expect(user.username).to.equal('bob');
expect(user.beforeTime).to.equal(-Infinity);
expect(user.sometime).to.be.withinTime(date, new Date());
expect(user.anotherTime).to.equal(Infinity);
expect(user.afterTime).to.equal(Infinity);
return user.update({ expect(user4.username).to.equal('bob');
expect(user4.beforeTime).to.equal(-Infinity);
expect(user4.sometime).to.be.withinTime(date, new Date());
expect(user4.anotherTime).to.equal(Infinity);
expect(user4.afterTime).to.equal(Infinity);
const user3 = await user4.update({
sometime: Infinity sometime: Infinity
}, { }, {
returning: true returning: true
}); });
}).then(user => {
expect(user.sometime).to.equal(Infinity);
return user.update({ expect(user3.sometime).to.equal(Infinity);
const user2 = await user3.update({
sometime: Infinity sometime: Infinity
}); });
}).then(user => {
expect(user.sometime).to.equal(Infinity);
return user.update({ expect(user2.sometime).to.equal(Infinity);
const user1 = await user2.update({
sometime: this.sequelize.fn('NOW') sometime: this.sequelize.fn('NOW')
}, { }, {
returning: true returning: true
}); });
}).then(user => {
expect(user.sometime).to.be.withinTime(date, new Date()); expect(user1.sometime).to.be.withinTime(date, new Date());
// find // find
return User.findAll(); const users = await User.findAll();
}).then(users => {
expect(users[0].beforeTime).to.equal(-Infinity); expect(users[0].beforeTime).to.equal(-Infinity);
expect(users[0].sometime).to.not.equal(Infinity); expect(users[0].sometime).to.not.equal(Infinity);
expect(users[0].afterTime).to.equal(Infinity); expect(users[0].afterTime).to.equal(Infinity);
return users[0].update({ const user0 = await users[0].update({
sometime: date sometime: date
}); });
}).then(user => {
expect(user.sometime).to.equalTime(date);
return user.update({ expect(user0.sometime).to.equalTime(date);
const user = await user0.update({
sometime: date sometime: date
}); });
}).then(user => {
expect(user.sometime).to.equalTime(date); expect(user.sometime).to.equalTime(date);
}); });
}); });
});
describe('DATEONLY SQL', () => { describe('DATEONLY SQL', () => {
// create dummy user // create dummy user
it('should be able to create and update records with Infinity/-Infinity', function() { it('should be able to create and update records with Infinity/-Infinity', async function() {
this.sequelize.options.typeValidation = true; this.sequelize.options.typeValidation = true;
const date = new Date(); const date = new Date();
...@@ -184,66 +183,65 @@ if (dialect === 'postgres') { ...@@ -184,66 +183,65 @@ if (dialect === 'postgres') {
timestamps: true timestamps: true
}); });
return User.sync({ await User.sync({
force: true force: true
}).then(() => { });
return User.create({
const user4 = await User.create({
username: 'bob', username: 'bob',
anotherTime: Infinity anotherTime: Infinity
}, { }, {
validate: true validate: true
}); });
}).then(user => {
expect(user.username).to.equal('bob');
expect(user.beforeTime).to.equal(-Infinity);
expect(new Date(user.sometime)).to.be.withinDate(date, new Date());
expect(user.anotherTime).to.equal(Infinity);
expect(user.afterTime).to.equal(Infinity);
return user.update({ expect(user4.username).to.equal('bob');
expect(user4.beforeTime).to.equal(-Infinity);
expect(new Date(user4.sometime)).to.be.withinDate(date, new Date());
expect(user4.anotherTime).to.equal(Infinity);
expect(user4.afterTime).to.equal(Infinity);
const user3 = await user4.update({
sometime: Infinity sometime: Infinity
}, { }, {
returning: true returning: true
}); });
}).then(user => {
expect(user.sometime).to.equal(Infinity);
return user.update({ expect(user3.sometime).to.equal(Infinity);
const user2 = await user3.update({
sometime: Infinity sometime: Infinity
}); });
}).then(user => {
expect(user.sometime).to.equal(Infinity);
return user.update({ expect(user2.sometime).to.equal(Infinity);
const user1 = await user2.update({
sometime: this.sequelize.fn('NOW') sometime: this.sequelize.fn('NOW')
}, { }, {
returning: true returning: true
}); });
}).then(user => {
expect(user.sometime).to.not.equal(Infinity); expect(user1.sometime).to.not.equal(Infinity);
expect(new Date(user.sometime)).to.be.withinDate(date, new Date()); expect(new Date(user1.sometime)).to.be.withinDate(date, new Date());
// find // find
return User.findAll(); const users = await User.findAll();
}).then(users => {
expect(users[0].beforeTime).to.equal(-Infinity); expect(users[0].beforeTime).to.equal(-Infinity);
expect(users[0].sometime).to.not.equal(Infinity); expect(users[0].sometime).to.not.equal(Infinity);
expect(users[0].afterTime).to.equal(Infinity); expect(users[0].afterTime).to.equal(Infinity);
return users[0].update({ const user0 = await users[0].update({
sometime: '1969-07-20' sometime: '1969-07-20'
}); });
}).then(user => {
expect(user.sometime).to.equal('1969-07-20');
return user.update({ expect(user0.sometime).to.equal('1969-07-20');
const user = await user0.update({
sometime: '1969-07-20' sometime: '1969-07-20'
}); });
}).then(user => {
expect(user.sometime).to.equal('1969-07-20'); expect(user.sometime).to.equal('1969-07-20');
}); });
}); });
});
}); });
} }
...@@ -11,19 +11,19 @@ const chai = require('chai'), ...@@ -11,19 +11,19 @@ const chai = require('chai'),
if (dialect.match(/^postgres/)) { if (dialect.match(/^postgres/)) {
describe('[POSTGRES Specific] ExclusionConstraintError', () => { describe('[POSTGRES Specific] ExclusionConstraintError', () => {
const constraintName = 'overlap_period'; const constraintName = 'overlap_period';
beforeEach(function() { beforeEach(async function() {
this.Booking = this.sequelize.define('Booking', { this.Booking = this.sequelize.define('Booking', {
roomNo: DataTypes.INTEGER, roomNo: DataTypes.INTEGER,
period: DataTypes.RANGE(DataTypes.DATE) period: DataTypes.RANGE(DataTypes.DATE)
}); });
return this.Booking
.sync({ force: true }) await this.Booking
.then(() => { .sync({ force: true });
return this.sequelize.query(
await this.sequelize.query(
`ALTER TABLE "${this.Booking.tableName}" ADD CONSTRAINT ${constraintName} EXCLUDE USING gist ("roomNo" WITH =, period WITH &&)` `ALTER TABLE "${this.Booking.tableName}" ADD CONSTRAINT ${constraintName} EXCLUDE USING gist ("roomNo" WITH =, period WITH &&)`
); );
}); });
});
it('should contain error specific properties', () => { it('should contain error specific properties', () => {
const errDetails = { const errDetails = {
...@@ -40,24 +40,23 @@ if (dialect.match(/^postgres/)) { ...@@ -40,24 +40,23 @@ if (dialect.match(/^postgres/)) {
}); });
}); });
it('should throw ExclusionConstraintError when "period" value overlaps existing', function() { it('should throw ExclusionConstraintError when "period" value overlaps existing', async function() {
const Booking = this.Booking; const Booking = this.Booking;
return Booking await Booking
.create({ .create({
roomNo: 1, roomNo: 1,
guestName: 'Incognito Visitor', guestName: 'Incognito Visitor',
period: [new Date(2015, 0, 1), new Date(2015, 0, 3)] period: [new Date(2015, 0, 1), new Date(2015, 0, 3)]
}) });
.then(() => {
return expect(Booking await expect(Booking
.create({ .create({
roomNo: 1, roomNo: 1,
guestName: 'Frequent Visitor', guestName: 'Frequent Visitor',
period: [new Date(2015, 0, 2), new Date(2015, 0, 5)] period: [new Date(2015, 0, 2), new Date(2015, 0, 5)]
})).to.eventually.be.rejectedWith(Sequelize.ExclusionConstraintError); })).to.eventually.be.rejectedWith(Sequelize.ExclusionConstraintError);
}); });
});
}); });
} }
...@@ -12,7 +12,7 @@ if (dialect.match(/^postgres/)) { ...@@ -12,7 +12,7 @@ if (dialect.match(/^postgres/)) {
const taskAlias = 'AnActualVeryLongAliasThatShouldBreakthePostgresLimitOfSixtyFourCharacters'; const taskAlias = 'AnActualVeryLongAliasThatShouldBreakthePostgresLimitOfSixtyFourCharacters';
const teamAlias = 'Toto'; const teamAlias = 'Toto';
const executeTest = (options, test) => { const executeTest = async (options, test) => {
const sequelize = Support.createSequelizeInstance(options); const sequelize = Support.createSequelizeInstance(options);
const User = sequelize.define('User', { name: DataTypes.STRING, updatedAt: DataTypes.DATE }, { underscored: true }); const User = sequelize.define('User', { name: DataTypes.STRING, updatedAt: DataTypes.DATE }, { underscored: true });
...@@ -23,12 +23,13 @@ if (dialect.match(/^postgres/)) { ...@@ -23,12 +23,13 @@ if (dialect.match(/^postgres/)) {
User.belongsToMany(Team, { as: teamAlias, foreignKey: 'teamId', through: 'UserTeam' }); User.belongsToMany(Team, { as: teamAlias, foreignKey: 'teamId', through: 'UserTeam' });
Team.belongsToMany(User, { foreignKey: 'userId', through: 'UserTeam' }); Team.belongsToMany(User, { foreignKey: 'userId', through: 'UserTeam' });
return sequelize.sync({ force: true }).then(() => { await sequelize.sync({ force: true });
return Team.create({ name: 'rocket' }).then(team => { const team = await Team.create({ name: 'rocket' });
return Task.create({ title: 'SuperTask' }).then(task => { const task = await Task.create({ title: 'SuperTask' });
return User.create({ name: 'test', task_id: task.id, updatedAt: new Date() }).then(user => { const user = await User.create({ name: 'test', task_id: task.id, updatedAt: new Date() });
return user[`add${teamAlias}`](team).then(() => { await user[`add${teamAlias}`](team);
return User.findOne({
return test(await User.findOne({
include: [ include: [
{ {
model: Task, model: Task,
...@@ -39,32 +40,26 @@ if (dialect.match(/^postgres/)) { ...@@ -39,32 +40,26 @@ if (dialect.match(/^postgres/)) {
as: teamAlias as: teamAlias
} }
] ]
}).then(test); }));
});
});
});
});
});
}; };
it('should throw due to alias being truncated', function() { it('should throw due to alias being truncated', async function() {
const options = { ...this.sequelize.options, minifyAliases: false }; const options = { ...this.sequelize.options, minifyAliases: false };
return executeTest(options, res => { await executeTest(options, res => {
expect(res[taskAlias]).to.not.exist; expect(res[taskAlias]).to.not.exist;
}); });
}); });
it('should be able to retrieve include due to alias minifying', function() { it('should be able to retrieve include due to alias minifying', async function() {
const options = { ...this.sequelize.options, minifyAliases: true }; const options = { ...this.sequelize.options, minifyAliases: true };
return executeTest(options, res => { await executeTest(options, res => {
expect(res[taskAlias].title).to.be.equal('SuperTask'); expect(res[taskAlias].title).to.be.equal('SuperTask');
}); });
}); });
it('should throw due to table name being truncated', () => { it('should throw due to table name being truncated', async () => {
const sequelize = Support.createSequelizeInstance({ minifyAliases: true }); const sequelize = Support.createSequelizeInstance({ minifyAliases: true });
const User = sequelize.define('user_model_name_that_is_long_for_demo_but_also_surpasses_the_character_limit', const User = sequelize.define('user_model_name_that_is_long_for_demo_but_also_surpasses_the_character_limit',
...@@ -95,11 +90,12 @@ if (dialect.match(/^postgres/)) { ...@@ -95,11 +90,12 @@ if (dialect.match(/^postgres/)) {
User.hasMany(Project, { foreignKey: 'userId' }); User.hasMany(Project, { foreignKey: 'userId' });
Project.belongsTo(Company, { foreignKey: 'companyId' }); Project.belongsTo(Company, { foreignKey: 'companyId' });
return sequelize.sync({ force: true }).then(() => { await sequelize.sync({ force: true });
return Company.create({ name: 'Sequelize' }).then(comp => { const comp = await Company.create({ name: 'Sequelize' });
return User.create({ name: 'standard user' }).then(user => { const user = await User.create({ name: 'standard user' });
return Project.create({ name: 'Manhattan', companyId: comp.id, userId: user.id }).then(() => { await Project.create({ name: 'Manhattan', companyId: comp.id, userId: user.id });
return User.findAll({
await User.findAll({
include: { include: {
model: Project, model: Project,
include: Company include: Company
...@@ -107,8 +103,4 @@ if (dialect.match(/^postgres/)) { ...@@ -107,8 +103,4 @@ if (dialect.match(/^postgres/)) {
}); });
}); });
}); });
});
});
});
});
} }
\ No newline at end of file
...@@ -184,9 +184,10 @@ if (dialect.match(/^postgres/)) { ...@@ -184,9 +184,10 @@ if (dialect.match(/^postgres/)) {
expect(range.parse('some_non_array')).to.deep.equal('some_non_array'); expect(range.parse('some_non_array')).to.deep.equal('some_non_array');
}); });
it('should handle native postgres timestamp format', () => { it('should handle native postgres timestamp format', async () => {
// Make sure nameOidMap is loaded // Make sure nameOidMap is loaded
return Support.sequelize.connectionManager.getConnection().then(connection => { const connection = await Support.sequelize.connectionManager.getConnection();
Support.sequelize.connectionManager.releaseConnection(connection); Support.sequelize.connectionManager.releaseConnection(connection);
const tsName = DataTypes.postgres.DATE.types.postgres[0], const tsName = DataTypes.postgres.DATE.types.postgres[0],
...@@ -194,7 +195,6 @@ if (dialect.match(/^postgres/)) { ...@@ -194,7 +195,6 @@ if (dialect.match(/^postgres/)) {
parser = pg.types.getTypeParser(tsOid); parser = pg.types.getTypeParser(tsOid);
expect(range.parse('(2016-01-01 08:00:00-04,)', parser)[0].value.toISOString()).to.equal('2016-01-01T12:00:00.000Z'); expect(range.parse('(2016-01-01 08:00:00-04,)', parser)[0].value.toISOString()).to.equal('2016-01-01T12:00:00.000Z');
}); });
});
}); });
describe('stringify and parse', () => { describe('stringify and parse', () => {
......
...@@ -8,7 +8,7 @@ const chai = require('chai'), ...@@ -8,7 +8,7 @@ const chai = require('chai'),
if (dialect.match(/^postgres/)) { if (dialect.match(/^postgres/)) {
describe('[POSTGRES Specific] Regressions', () => { describe('[POSTGRES Specific] Regressions', () => {
it('properly fetch OIDs after sync, #8749', function() { it('properly fetch OIDs after sync, #8749', async function() {
const User = this.sequelize.define('User', { const User = this.sequelize.define('User', {
active: Sequelize.BOOLEAN active: Sequelize.BOOLEAN
}); });
...@@ -27,24 +27,18 @@ if (dialect.match(/^postgres/)) { ...@@ -27,24 +27,18 @@ if (dialect.match(/^postgres/)) {
User.hasMany(Media); User.hasMany(Media);
Media.belongsTo(User); Media.belongsTo(User);
return this.sequelize await this.sequelize.sync({ force: true });
.sync({ force: true })
.then(() => User.create({ active: true }))
.then(user => {
expect(user.active).to.be.true;
expect(user.get('active')).to.be.true;
return User.findOne(); const user1 = await User.create({ active: true });
}) expect(user1.active).to.be.true;
.then(user => { expect(user1.get('active')).to.be.true;
expect(user.active).to.be.true;
expect(user.get('active')).to.be.true;
return User.findOne({ raw: true }); const user0 = await User.findOne();
}) expect(user0.active).to.be.true;
.then(user => { expect(user0.get('active')).to.be.true;
const user = await User.findOne({ raw: true });
expect(user.active).to.be.true; expect(user.active).to.be.true;
}); });
}); });
});
} }
...@@ -18,22 +18,21 @@ if (dialect === 'sqlite') { ...@@ -18,22 +18,21 @@ if (dialect === 'sqlite') {
jetpack.remove(directoryName); jetpack.remove(directoryName);
}); });
it('close connection and remove journal and wal files', function() { it('close connection and remove journal and wal files', async function() {
const sequelize = Support.createSequelizeInstance({ const sequelize = Support.createSequelizeInstance({
storage: jetpack.path(fileName) storage: jetpack.path(fileName)
}); });
const User = sequelize.define('User', { username: DataTypes.STRING }); const User = sequelize.define('User', { username: DataTypes.STRING });
return User await User.sync({ force: true });
.sync({ force: true })
.then(() => sequelize.query('PRAGMA journal_mode = WAL')) await sequelize.query('PRAGMA journal_mode = WAL');
.then(() => User.create({ username: 'user1' })) await User.create({ username: 'user1' });
.then(() => {
return sequelize.transaction(transaction => { await sequelize.transaction(transaction => {
return User.create({ username: 'user2' }, { transaction }); return User.create({ username: 'user2' }, { transaction });
}); });
})
.then(async () => {
expect(jetpack.exists(fileName)).to.be.equal('file'); expect(jetpack.exists(fileName)).to.be.equal('file');
expect(jetpack.exists(`${fileName}-shm`), 'shm file should exists').to.be.equal('file'); expect(jetpack.exists(`${fileName}-shm`), 'shm file should exists').to.be.equal('file');
expect(jetpack.exists(`${fileName}-wal`), 'wal file should exists').to.be.equal('file'); expect(jetpack.exists(`${fileName}-wal`), 'wal file should exists').to.be.equal('file');
...@@ -47,23 +46,20 @@ if (dialect === 'sqlite') { ...@@ -47,23 +46,20 @@ if (dialect === 'sqlite') {
expect(jetpack.exists(`${fileName}-shm`), 'shm file should exists').to.be.equal('file'); expect(jetpack.exists(`${fileName}-shm`), 'shm file should exists').to.be.equal('file');
expect(jetpack.exists(`${fileName}-wal`), 'wal file should exists').to.be.equal('file'); expect(jetpack.exists(`${fileName}-wal`), 'wal file should exists').to.be.equal('file');
return sequelize.close(); await sequelize.close();
})
.then(() => {
expect(jetpack.exists(fileName)).to.be.equal('file'); expect(jetpack.exists(fileName)).to.be.equal('file');
expect(jetpack.exists(`${fileName}-shm`), 'shm file exists').to.be.false; expect(jetpack.exists(`${fileName}-shm`), 'shm file exists').to.be.false;
expect(jetpack.exists(`${fileName}-wal`), 'wal file exists').to.be.false; expect(jetpack.exists(`${fileName}-wal`), 'wal file exists').to.be.false;
return this.sequelize.query('PRAGMA journal_mode = DELETE'); await this.sequelize.query('PRAGMA journal_mode = DELETE');
});
}); });
it('automatic path provision for `options.storage`', () => { it('automatic path provision for `options.storage`', async () => {
return Support.createSequelizeInstance({ storage: nestedFileName }) await Support.createSequelizeInstance({ storage: nestedFileName })
.define('User', { username: DataTypes.STRING }) .define('User', { username: DataTypes.STRING })
.sync({ force: true }).then(() => { .sync({ force: true });
expect(jetpack.exists(nestedFileName)).to.be.equal('file'); expect(jetpack.exists(nestedFileName)).to.be.equal('file');
}); });
}); });
});
} }
...@@ -14,14 +14,14 @@ if (dialect === 'sqlite') { ...@@ -14,14 +14,14 @@ if (dialect === 'sqlite') {
this.sequelize.options.storage = ':memory:'; this.sequelize.options.storage = ':memory:';
}); });
beforeEach(function() { beforeEach(async function() {
this.sequelize.options.storage = dbFile; this.sequelize.options.storage = dbFile;
this.User = this.sequelize.define('User', { this.User = this.sequelize.define('User', {
age: DataTypes.INTEGER, age: DataTypes.INTEGER,
name: DataTypes.STRING, name: DataTypes.STRING,
bio: DataTypes.TEXT bio: DataTypes.TEXT
}); });
return this.User.sync({ force: true }); await this.User.sync({ force: true });
}); });
storages.forEach(storage => { storages.forEach(storage => {
...@@ -33,140 +33,131 @@ if (dialect === 'sqlite') { ...@@ -33,140 +33,131 @@ if (dialect === 'sqlite') {
}); });
describe('create', () => { describe('create', () => {
it('creates a table entry', function() { it('creates a table entry', async function() {
return this.User.create({ age: 21, name: 'John Wayne', bio: 'noot noot' }).then(user => { const user = await this.User.create({ age: 21, name: 'John Wayne', bio: 'noot noot' });
expect(user.age).to.equal(21); expect(user.age).to.equal(21);
expect(user.name).to.equal('John Wayne'); expect(user.name).to.equal('John Wayne');
expect(user.bio).to.equal('noot noot'); expect(user.bio).to.equal('noot noot');
return this.User.findAll().then(users => { const users = await this.User.findAll();
const usernames = users.map(user => { const usernames = users.map(user => {
return user.name; return user.name;
}); });
expect(usernames).to.contain('John Wayne'); expect(usernames).to.contain('John Wayne');
}); });
});
});
it('should allow the creation of an object with options as attribute', function() { it('should allow the creation of an object with options as attribute', async function() {
const Person = this.sequelize.define('Person', { const Person = this.sequelize.define('Person', {
name: DataTypes.STRING, name: DataTypes.STRING,
options: DataTypes.TEXT options: DataTypes.TEXT
}); });
return Person.sync({ force: true }).then(() => { await Person.sync({ force: true });
const options = JSON.stringify({ foo: 'bar', bar: 'foo' }); const options = JSON.stringify({ foo: 'bar', bar: 'foo' });
return Person.create({ const people = await Person.create({
name: 'John Doe', name: 'John Doe',
options options
}).then(people => {
expect(people.options).to.deep.equal(options);
});
}); });
expect(people.options).to.deep.equal(options);
}); });
it('should allow the creation of an object with a boolean (true) as attribute', function() { it('should allow the creation of an object with a boolean (true) as attribute', async function() {
const Person = this.sequelize.define('Person', { const Person = this.sequelize.define('Person', {
name: DataTypes.STRING, name: DataTypes.STRING,
has_swag: DataTypes.BOOLEAN has_swag: DataTypes.BOOLEAN
}); });
return Person.sync({ force: true }).then(() => { await Person.sync({ force: true });
return Person.create({
const people = await Person.create({
name: 'John Doe', name: 'John Doe',
has_swag: true has_swag: true
}).then(people => {
expect(people.has_swag).to.be.ok;
});
}); });
expect(people.has_swag).to.be.ok;
}); });
it('should allow the creation of an object with a boolean (false) as attribute', function() { it('should allow the creation of an object with a boolean (false) as attribute', async function() {
const Person = this.sequelize.define('Person', { const Person = this.sequelize.define('Person', {
name: DataTypes.STRING, name: DataTypes.STRING,
has_swag: DataTypes.BOOLEAN has_swag: DataTypes.BOOLEAN
}); });
return Person.sync({ force: true }).then(() => { await Person.sync({ force: true });
return Person.create({
const people = await Person.create({
name: 'John Doe', name: 'John Doe',
has_swag: false has_swag: false
}).then(people => {
expect(people.has_swag).to.not.be.ok;
});
}); });
expect(people.has_swag).to.not.be.ok;
}); });
}); });
describe('.findOne', () => { describe('.findOne', () => {
beforeEach(function() { beforeEach(async function() {
return this.User.create({ name: 'user', bio: 'footbar' }); await this.User.create({ name: 'user', bio: 'footbar' });
}); });
it('finds normal lookups', function() { it('finds normal lookups', async function() {
return this.User.findOne({ where: { name: 'user' } }).then(user => { const user = await this.User.findOne({ where: { name: 'user' } });
expect(user.name).to.equal('user'); expect(user.name).to.equal('user');
}); });
});
it.skip('should make aliased attributes available', function() { it.skip('should make aliased attributes available', async function() { // eslint-disable-line mocha/no-skipped-tests
return this.User.findOne({ const user = await this.User.findOne({
where: { name: 'user' }, where: { name: 'user' },
attributes: ['id', ['name', 'username']] attributes: ['id', ['name', 'username']]
}).then(user => {
expect(user.username).to.equal('user');
}); });
expect(user.username).to.equal('user');
}); });
}); });
describe('.all', () => { describe('.all', () => {
beforeEach(function() { beforeEach(async function() {
return this.User.bulkCreate([ await this.User.bulkCreate([
{ name: 'user', bio: 'foobar' }, { name: 'user', bio: 'foobar' },
{ name: 'user', bio: 'foobar' } { name: 'user', bio: 'foobar' }
]); ]);
}); });
it('should return all users', function() { it('should return all users', async function() {
return this.User.findAll().then(users => { const users = await this.User.findAll();
expect(users).to.have.length(2); expect(users).to.have.length(2);
}); });
}); });
});
describe('.min', () => { describe('.min', () => {
it('should return the min value', function() { it('should return the min value', async function() {
const users = []; const users = [];
for (let i = 2; i < 5; i++) { for (let i = 2; i < 5; i++) {
users[users.length] = { age: i }; users[users.length] = { age: i };
} }
return this.User.bulkCreate(users).then(() => { await this.User.bulkCreate(users);
return this.User.min('age').then(min => { const min = await this.User.min('age');
expect(min).to.equal(2); expect(min).to.equal(2);
}); });
}); });
});
});
describe('.max', () => { describe('.max', () => {
it('should return the max value', function() { it('should return the max value', async function() {
const users = []; const users = [];
for (let i = 2; i <= 5; i++) { for (let i = 2; i <= 5; i++) {
users[users.length] = { age: i }; users[users.length] = { age: i };
} }
return this.User.bulkCreate(users).then(() => { await this.User.bulkCreate(users);
return this.User.max('age').then(min => { const min = await this.User.max('age');
expect(min).to.equal(5); expect(min).to.equal(5);
}); });
}); });
}); });
}); });
}); });
});
});
} }
...@@ -10,7 +10,7 @@ const chai = require('chai'), ...@@ -10,7 +10,7 @@ const chai = require('chai'),
if (dialect === 'sqlite') { if (dialect === 'sqlite') {
describe('[SQLITE Specific] DAO', () => { describe('[SQLITE Specific] DAO', () => {
beforeEach(function() { beforeEach(async function() {
this.User = this.sequelize.define('User', { this.User = this.sequelize.define('User', {
username: DataTypes.STRING, username: DataTypes.STRING,
emergency_contact: DataTypes.JSON, emergency_contact: DataTypes.JSON,
...@@ -28,90 +28,90 @@ if (dialect === 'sqlite') { ...@@ -28,90 +28,90 @@ if (dialect === 'sqlite') {
}); });
this.User.hasMany(this.Project); this.User.hasMany(this.Project);
return this.sequelize.sync({ force: true }); await this.sequelize.sync({ force: true });
}); });
describe('findAll', () => { describe('findAll', () => {
it('handles dates correctly', function() { it('handles dates correctly', async function() {
const user = this.User.build({ username: 'user' }); const user = this.User.build({ username: 'user' });
user.dataValues.createdAt = new Date(2011, 4, 4); user.dataValues.createdAt = new Date(2011, 4, 4);
return user.save().then(() => { await user.save();
return this.User.create({ username: 'new user' }).then(() => { await this.User.create({ username: 'new user' });
return this.User.findAll({
const users = await this.User.findAll({
where: { createdAt: { [Op.gt]: new Date(2012, 1, 1) } } where: { createdAt: { [Op.gt]: new Date(2012, 1, 1) } }
}).then(users => {
expect(users).to.have.length(1);
});
});
}); });
expect(users).to.have.length(1);
}); });
it('handles dates with aliasses correctly #3611', function() { it('handles dates with aliasses correctly #3611', async function() {
return this.User.create({ await this.User.create({
dateField: new Date(2010, 10, 10) dateField: new Date(2010, 10, 10)
}).then(() => { });
return this.User.findAll().then(obj => obj[0]);
}).then(user => { const obj = await this.User.findAll();
const user = await obj[0];
expect(user.get('dateField')).to.be.an.instanceof(Date); expect(user.get('dateField')).to.be.an.instanceof(Date);
expect(user.get('dateField')).to.equalTime(new Date(2010, 10, 10)); expect(user.get('dateField')).to.equalTime(new Date(2010, 10, 10));
}); });
});
it('handles dates in includes correctly #2644', function() { it('handles dates in includes correctly #2644', async function() {
return this.User.create({ await this.User.create({
projects: [ projects: [
{ dateField: new Date(1990, 5, 5) } { dateField: new Date(1990, 5, 5) }
] ]
}, { include: [this.Project] }).then(() => { }, { include: [this.Project] });
return this.User.findAll({
const obj = await this.User.findAll({
include: [this.Project] include: [this.Project]
}).then(obj => obj[0]); });
}).then(user => {
const user = await obj[0];
expect(user.projects[0].get('dateField')).to.be.an.instanceof(Date); expect(user.projects[0].get('dateField')).to.be.an.instanceof(Date);
expect(user.projects[0].get('dateField')).to.equalTime(new Date(1990, 5, 5)); expect(user.projects[0].get('dateField')).to.equalTime(new Date(1990, 5, 5));
}); });
}); });
});
describe('json', () => { describe('json', () => {
it('should be able to retrieve a row with json_extract function', function() { it('should be able to retrieve a row with json_extract function', async function() {
return Promise.all([ await Promise.all([
this.User.create({ username: 'swen', emergency_contact: { name: 'kate' } }), this.User.create({ username: 'swen', emergency_contact: { name: 'kate' } }),
this.User.create({ username: 'anna', emergency_contact: { name: 'joe' } }) this.User.create({ username: 'anna', emergency_contact: { name: 'joe' } })
]).then(() => { ]);
return this.User.findOne({
const user = await this.User.findOne({
where: Sequelize.json('json_extract(emergency_contact, \'$.name\')', 'kate'), where: Sequelize.json('json_extract(emergency_contact, \'$.name\')', 'kate'),
attributes: ['username', 'emergency_contact'] attributes: ['username', 'emergency_contact']
}); });
}).then(user => {
expect(user.emergency_contact.name).to.equal('kate'); expect(user.emergency_contact.name).to.equal('kate');
}); });
});
it('should be able to retrieve a row by json_type function', function() { it('should be able to retrieve a row by json_type function', async function() {
return Promise.all([ await Promise.all([
this.User.create({ username: 'swen', emergency_contact: { name: 'kate' } }), this.User.create({ username: 'swen', emergency_contact: { name: 'kate' } }),
this.User.create({ username: 'anna', emergency_contact: ['kate', 'joe'] }) this.User.create({ username: 'anna', emergency_contact: ['kate', 'joe'] })
]).then(() => { ]);
return this.User.findOne({
const user = await this.User.findOne({
where: Sequelize.json('json_type(emergency_contact)', 'array'), where: Sequelize.json('json_type(emergency_contact)', 'array'),
attributes: ['username', 'emergency_contact'] attributes: ['username', 'emergency_contact']
}); });
}).then(user => {
expect(user.username).to.equal('anna'); expect(user.username).to.equal('anna');
}); });
}); });
});
describe('regression tests', () => { describe('regression tests', () => {
it('do not crash while parsing unique constraint errors', function() { it('do not crash while parsing unique constraint errors', async function() {
const Payments = this.sequelize.define('payments', {}); const Payments = this.sequelize.define('payments', {});
return Payments.sync({ force: true }).then(() => { await Payments.sync({ force: true });
return expect(Payments.bulkCreate([{ id: 1 }, { id: 1 }], { ignoreDuplicates: false })).to.eventually.be.rejected;
}); await expect(Payments.bulkCreate([{ id: 1 }, { id: 1 }], { ignoreDuplicates: false })).to.eventually.be.rejected;
}); });
}); });
}); });
......
...@@ -8,7 +8,7 @@ const chai = require('chai'), ...@@ -8,7 +8,7 @@ const chai = require('chai'),
if (dialect === 'sqlite') { if (dialect === 'sqlite') {
describe('[SQLITE Specific] sqlite_master raw queries', () => { describe('[SQLITE Specific] sqlite_master raw queries', () => {
beforeEach(function() { beforeEach(async function() {
this.sequelize.define('SomeTable', { this.sequelize.define('SomeTable', {
someColumn: DataTypes.INTEGER someColumn: DataTypes.INTEGER
}, { }, {
...@@ -16,12 +16,11 @@ if (dialect === 'sqlite') { ...@@ -16,12 +16,11 @@ if (dialect === 'sqlite') {
timestamps: false timestamps: false
}); });
return this.sequelize.sync({ force: true }); await this.sequelize.sync({ force: true });
}); });
it('should be able to select with tbl_name filter', function() { it('should be able to select with tbl_name filter', async function() {
return this.sequelize.query('SELECT * FROM sqlite_master WHERE tbl_name=\'SomeTable\'') const result = await this.sequelize.query('SELECT * FROM sqlite_master WHERE tbl_name=\'SomeTable\'');
.then(result => {
const rows = result[0]; const rows = result[0];
expect(rows).to.have.length(1); expect(rows).to.have.length(1);
const row = rows[0]; const row = rows[0];
...@@ -30,11 +29,9 @@ if (dialect === 'sqlite') { ...@@ -30,11 +29,9 @@ if (dialect === 'sqlite') {
expect(row).to.have.property('tbl_name', 'SomeTable'); expect(row).to.have.property('tbl_name', 'SomeTable');
expect(row).to.have.property('sql'); expect(row).to.have.property('sql');
}); });
});
it('should be able to select *', function() { it('should be able to select *', async function() {
return this.sequelize.query('SELECT * FROM sqlite_master') const result = await this.sequelize.query('SELECT * FROM sqlite_master');
.then(result => {
const rows = result[0]; const rows = result[0];
expect(rows).to.have.length(2); expect(rows).to.have.length(2);
rows.forEach(row => { rows.forEach(row => {
...@@ -45,11 +42,9 @@ if (dialect === 'sqlite') { ...@@ -45,11 +42,9 @@ if (dialect === 'sqlite') {
expect(row).to.have.property('sql'); expect(row).to.have.property('sql');
}); });
}); });
});
it('should be able to select just "sql" column and get rows back', function() { it('should be able to select just "sql" column and get rows back', async function() {
return this.sequelize.query('SELECT sql FROM sqlite_master WHERE tbl_name=\'SomeTable\'') const result = await this.sequelize.query('SELECT sql FROM sqlite_master WHERE tbl_name=\'SomeTable\'');
.then(result => {
const rows = result[0]; const rows = result[0];
expect(rows).to.have.length(1); expect(rows).to.have.length(1);
const row = rows[0]; const row = rows[0];
...@@ -57,5 +52,4 @@ if (dialect === 'sqlite') { ...@@ -57,5 +52,4 @@ if (dialect === 'sqlite') {
'CREATE TABLE `SomeTable` (`id` INTEGER PRIMARY KEY AUTOINCREMENT, `someColumn` INTEGER)'); 'CREATE TABLE `SomeTable` (`id` INTEGER PRIMARY KEY AUTOINCREMENT, `someColumn` INTEGER)');
}); });
}); });
});
} }
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!