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

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'), () => {
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') {
return;
}
......@@ -91,21 +91,19 @@ describe(Support.getTestDialectTeaser('Connection Manager'), () => {
const _getConnection = connectionManager.getConnection.bind(connectionManager, queryOptions);
return _getConnection()
.then(_getConnection)
.then(_getConnection)
.then(() => {
chai.expect(connectStub.callCount).to.equal(4);
// First call is the get connection for DB versions - ignore
const calls = connectStub.getCalls();
chai.expect(calls[1].args[0].host).to.eql('slave1');
chai.expect(calls[2].args[0].host).to.eql('slave2');
chai.expect(calls[3].args[0].host).to.eql('slave1');
});
await _getConnection();
await _getConnection();
await _getConnection();
chai.expect(connectStub.callCount).to.equal(4);
// First call is the get connection for DB versions - ignore
const calls = connectStub.getCalls();
chai.expect(calls[1].args[0].host).to.eql('slave1');
chai.expect(calls[2].args[0].host).to.eql('slave2');
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 sequelize = Support.createSequelizeInstance();
const connectionManager = new ConnectionManager(sequelize.dialect, sequelize);
......@@ -126,14 +124,12 @@ describe(Support.getTestDialectTeaser('Connection Manager'), () => {
useMaster: true
};
return connectionManager.getConnection(queryOptions)
.then(() => {
chai.expect(deprecationStub).to.have.been.calledOnce;
});
await connectionManager.getConnection(queryOptions);
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 };
master.host = 'the-boss';
......@@ -161,15 +157,13 @@ describe(Support.getTestDialectTeaser('Connection Manager'), () => {
useMaster: true
};
return connectionManager.getConnection(queryOptions)
.then(() => {
chai.expect(connectStub).to.have.been.calledTwice; // Once to get DB version, and once to actually get the connection.
const calls = connectStub.getCalls();
chai.expect(calls[1].args[0].host).to.eql('the-boss');
});
await connectionManager.getConnection(queryOptions);
chai.expect(connectStub).to.have.been.calledTwice; // Once to get DB version, and once to actually get the connection.
const calls = connectStub.getCalls();
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 = {
replication: null
};
......@@ -181,9 +175,8 @@ describe(Support.getTestDialectTeaser('Connection Manager'), () => {
const poolDrainSpy = sandbox.spy(connectionManager.pool, 'drain');
const poolClearSpy = sandbox.spy(connectionManager.pool, 'destroyAllNow');
return connectionManager.close().then(() => {
expect(poolDrainSpy.calledOnce).to.be.true;
expect(poolClearSpy.calledOnce).to.be.true;
});
await connectionManager.close();
expect(poolDrainSpy.calledOnce).to.be.true;
expect(poolClearSpy.calledOnce).to.be.true;
});
});
......@@ -11,33 +11,30 @@ if (dialect !== 'mariadb') return;
describe('[MariaDB Specific] Associations', () => {
describe('many-to-many', () => {
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 }),
Table1 = this.sequelize.define('wp_table1',
{ foo: DataTypes.STRING });
Table1.belongsToMany(Table2, { through: 'wp_table1swp_table2s' });
Table2.belongsToMany(Table1, { through: 'wp_table1swp_table2s' });
return Table1.sync({ force: true }).then(() => {
return Table2.sync({ force: true }).then(() => {
expect(this.sequelize.modelManager.getModel(
'wp_table1swp_table2s')).to.exist;
});
});
await Table1.sync({ force: true });
await Table2.sync({ force: true });
expect(this.sequelize.modelManager.getModel(
'wp_table1swp_table2s')).to.exist;
});
});
describe('when join table name is specified', () => {
beforeEach(function() {
beforeEach(async function() {
const Table2 = this.sequelize.define('ms_table1', { foo: DataTypes.STRING }),
Table1 = this.sequelize.define('ms_table2',
{ foo: DataTypes.STRING });
Table1.belongsToMany(Table2, { through: 'table1_to_table2' });
Table2.belongsToMany(Table1, { through: 'table1_to_table2' });
return Table1.sync({ force: true }).then(() => {
return Table2.sync({ force: true });
});
await Table1.sync({ force: true });
await Table2.sync({ force: true });
});
it('should not use only a specified name', function() {
......@@ -50,7 +47,7 @@ describe('[MariaDB Specific] Associations', () => {
});
describe('HasMany', () => {
beforeEach(function() {
beforeEach(async function() {
//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.Task = this.sequelize.define(`Task${Math.ceil(Math.random() * 10000000)}`, { name: DataTypes.STRING });
......@@ -68,10 +65,9 @@ describe('[MariaDB Specific] Associations', () => {
tasks[i] = { name: `Task${Math.random()}` };
}
return this.sequelize.sync({ force: true })
.then(() => this.User.bulkCreate(users))
.then(() => this.Task.bulkCreate(tasks));
await this.sequelize.sync({ force: true });
await this.User.bulkCreate(users);
await this.Task.bulkCreate(tasks);
});
});
......
......@@ -13,17 +13,15 @@ if (dialect !== 'mariadb') {
describe('[MARIADB Specific] Connection Manager', () => {
it('has existing init SQL', () => {
it('has existing init SQL', async () => {
const sequelize = Support.createSequelizeInstance(
{ dialectOptions: { initSql: 'SET @myUserVariable=\'myValue\'' } });
return sequelize.query('SELECT @myUserVariable')
.then(res => {
expect(res[0]).to.deep.equal([{ '@myUserVariable': 'myValue' }]);
sequelize.close();
});
const res = await sequelize.query('SELECT @myUserVariable');
expect(res[0]).to.deep.equal([{ '@myUserVariable': 'myValue' }]);
sequelize.close();
});
it('has existing init SQL array', () => {
it('has existing init SQL array', async () => {
const sequelize = Support.createSequelizeInstance(
{
dialectOptions: {
......@@ -31,12 +29,10 @@ describe('[MARIADB Specific] Connection Manager', () => {
'SET @myUserVariable2=\'myValue\'']
}
});
return sequelize.query('SELECT @myUserVariable1, @myUserVariable2')
.then(res => {
expect(res[0]).to.deep.equal(
[{ '@myUserVariable1': 'myValue', '@myUserVariable2': 'myValue' }]);
sequelize.close();
});
const res = await sequelize.query('SELECT @myUserVariable1, @myUserVariable2');
expect(res[0]).to.deep.equal(
[{ '@myUserVariable1': 'myValue', '@myUserVariable2': 'myValue' }]);
sequelize.close();
});
......@@ -44,29 +40,29 @@ describe('[MARIADB Specific] Connection Manager', () => {
describe('Errors', () => {
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 } });
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 });
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' });
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' });
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);
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'),
if (dialect !== 'mariadb') return;
describe('[MariaDB Specific] DAO', () => {
beforeEach(function() {
beforeEach(async function() {
this.sequelize.options.quoteIdentifiers = true;
this.User = this.sequelize.define('User', {
username: DataTypes.STRING,
email: DataTypes.STRING,
location: DataTypes.GEOMETRY()
});
return this.User.sync({ force: true });
await this.User.sync({ force: true });
});
afterEach(function() {
......@@ -24,112 +24,99 @@ describe('[MariaDB Specific] DAO', () => {
describe('integers', () => {
describe('integer', () => {
beforeEach(function() {
beforeEach(async function() {
this.User = this.sequelize.define('User', {
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;
return User.create({ aNumber: 2147483647 }).then(user => {
expect(user.aNumber).to.equal(2147483647);
return User.findOne({ where: { aNumber: 2147483647 } }).then(_user => {
expect(_user.aNumber).to.equal(2147483647);
});
});
const user = await User.create({ aNumber: 2147483647 });
expect(user.aNumber).to.equal(2147483647);
const _user = await User.findOne({ where: { aNumber: 2147483647 } });
expect(_user.aNumber).to.equal(2147483647);
});
it('negative', function() {
it('negative', async function() {
const User = this.User;
return User.create({ aNumber: -2147483647 }).then(user => {
expect(user.aNumber).to.equal(-2147483647);
return User.findOne({ where: { aNumber: -2147483647 } }).then(_user => {
expect(_user.aNumber).to.equal(-2147483647);
});
});
const user = await User.create({ aNumber: -2147483647 });
expect(user.aNumber).to.equal(-2147483647);
const _user = await User.findOne({ where: { aNumber: -2147483647 } });
expect(_user.aNumber).to.equal(-2147483647);
});
});
describe('bigint', () => {
beforeEach(function() {
beforeEach(async function() {
this.User = this.sequelize.define('User', {
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;
return User.create({ aNumber: '9223372036854775807' }).then(user => {
expect(user.aNumber).to.equal('9223372036854775807');
return User.findOne({ where: { aNumber: '9223372036854775807' } }).then(
_user => {
return expect(_user.aNumber.toString()).to.equal(
'9223372036854775807');
});
});
const user = await User.create({ aNumber: '9223372036854775807' });
expect(user.aNumber).to.equal('9223372036854775807');
const _user = await User.findOne({ where: { aNumber: '9223372036854775807' } });
await expect(_user.aNumber.toString()).to.equal('9223372036854775807');
});
it('negative', function() {
it('negative', async function() {
const User = this.User;
return User.create({ aNumber: '-9223372036854775807' }).then(user => {
expect(user.aNumber).to.equal('-9223372036854775807');
return User.findOne(
{ where: { aNumber: '-9223372036854775807' } }).then(_user => {
return expect(_user.aNumber.toString()).to.equal(
'-9223372036854775807');
});
});
const user = await User.create({ aNumber: '-9223372036854775807' });
expect(user.aNumber).to.equal('-9223372036854775807');
const _user = await User.findOne(
{ where: { aNumber: '-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] };
return this.User.create(
{ username: 'user', email: 'foo@bar.com', location: point }).then(
newUser => {
expect(newUser.location).to.deep.eql(point);
});
const newUser = await this.User.create(
{ username: 'user', email: 'foo@bar.com', location: 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 point1 = { type: 'Point', coordinates: [39.807222, -76.984722] };
const point2 = { type: 'Point', coordinates: [39.828333, -77.232222] };
return User.create(
{ username: 'user', email: 'foo@bar.com', location: point1 })
.then(oldUser => {
return User.update({ location: point2 },
{ where: { username: oldUser.username } })
.then(() => {
return User.findOne({ where: { username: oldUser.username } });
})
.then(updatedUser => {
expect(updatedUser.location).to.deep.eql(point2);
});
});
const oldUser = await User.create(
{ username: 'user', email: 'foo@bar.com', location: point1 });
await User.update({ location: point2 },
{ where: { username: oldUser.username } });
const updatedUser = await User.findOne({ where: { username: oldUser.username } });
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 point = { type: 'Point', coordinates: [39.807222, -76.984722] };
return User.create(
{ username: 'user', email: 'foo@bar.com', location: point }).then(
user => {
return User.findOne({ where: { username: user.username } });
}).then(user => {
expect(user.location).to.deep.eql(point);
});
const user0 = await User.create(
{ username: 'user', email: 'foo@bar.com', location: point });
const user = await User.findOne({ where: { username: user0.username } });
expect(user.location).to.deep.eql(point);
});
});
......
......@@ -9,12 +9,16 @@ const chai = require('chai'),
if (dialect !== 'mariadb') return;
describe('[MariaDB Specific] Errors', () => {
const validateError = (promise, errClass, errValues) => {
const validateError = async (promise, errClass, errValues) => {
const wanted = { ...errValues };
return expect(promise).to.have.been.rejectedWith(errClass).then(() =>
promise.catch(err => Object.keys(wanted).forEach(
k => expect(err[k]).to.eql(wanted[k]))));
await expect(promise).to.have.been.rejectedWith(errClass);
try {
return await promise;
} catch (err) {
return Object.keys(wanted).forEach(k => expect(err[k]).to.eql(wanted[k]));
}
};
describe('ForeignKeyConstraintError', () => {
......@@ -33,50 +37,51 @@ describe('[MariaDB Specific] Errors', () => {
{ 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 ctx = {};
return this.sequelize.sync({ force: true }).then(() => {
return Promise.all([
this.User.create({ id: 67, username: 'foo' }),
this.Task.create({ id: 52, title: 'task' })
]);
}).then(([user1, task1]) => {
ctx.user1 = user1;
ctx.task1 = task1;
return user1.setTasks([task1]);
}).then(() => {
return Promise.all([
validateError(ctx.user1.destroy(), ForeignKeyConstraintError, {
fields: ['userId'],
table: 'users',
value: undefined,
index: 'tasksusers_ibfk_1',
reltype: 'parent'
}),
validateError(ctx.task1.destroy(), ForeignKeyConstraintError, {
fields: ['taskId'],
table: 'tasks',
value: undefined,
index: 'tasksusers_ibfk_2',
reltype: 'parent'
})
]);
});
await this.sequelize.sync({ force: true });
const [user1, task1] = await Promise.all([
this.User.create({ id: 67, username: 'foo' }),
this.Task.create({ id: 52, title: 'task' })
]);
await user1.setTasks([task1]);
await Promise.all([
validateError(user1.destroy(), ForeignKeyConstraintError, {
fields: ['userId'],
table: 'users',
value: undefined,
index: 'tasksusers_ibfk_1',
reltype: 'parent'
}),
validateError(task1.destroy(), ForeignKeyConstraintError, {
fields: ['taskId'],
table: 'tasks',
value: undefined,
index: 'tasksusers_ibfk_2',
reltype: 'parent'
})
]);
});
it('in context of missing relation', function() {
it('in context of missing relation', async function() {
const ForeignKeyConstraintError = this.sequelize.ForeignKeyConstraintError;
return this.sequelize.sync({ force: true }).then(() =>
validateError(this.Task.create({ title: 'task', primaryUserId: 5 }),
ForeignKeyConstraintError, {
fields: ['primaryUserId'],
table: 'users',
value: 5,
index: 'tasks_ibfk_1',
reltype: 'child'
}));
await this.sequelize.sync({ force: true });
await validateError(
this.Task.create({ title: 'task', primaryUserId: 5 }),
ForeignKeyConstraintError,
{
fields: ['primaryUserId'],
table: 'users',
value: 5,
index: 'tasks_ibfk_1',
reltype: 'child'
}
);
});
});
......
......@@ -9,19 +9,13 @@ if (dialect.match(/^mariadb/)) {
describe('QueryInterface', () => {
describe('databases', () => {
it('should create and drop database', function() {
return this.sequelize.query('SHOW DATABASES')
.then(res => {
const databaseNumber = res[0].length;
return this.sequelize.getQueryInterface().createDatabase('myDB')
.then(() => {
return this.sequelize.query('SHOW DATABASES');
})
.then(databases => {
expect(databases[0]).to.have.length(databaseNumber + 1);
return this.sequelize.getQueryInterface().dropDatabase('myDB');
});
});
it('should create and drop database', async function() {
const res = await this.sequelize.query('SHOW DATABASES');
const databaseNumber = res[0].length;
await this.sequelize.getQueryInterface().createDatabase('myDB');
const databases = await this.sequelize.query('SHOW DATABASES');
expect(databases[0]).to.have.length(databaseNumber + 1);
await this.sequelize.getQueryInterface().dropDatabase('myDB');
});
});
});
......
......@@ -9,24 +9,24 @@ const dialect = Support.getTestDialect();
if (dialect.match(/^mssql/)) {
describe('[MSSQL Specific] Connection Manager', () => {
describe('Errors', () => {
it('ECONNREFUSED', () => {
it('ECONNREFUSED', async () => {
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' });
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' });
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);
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'),
if (dialect.match(/^mssql/)) {
describe('[MSSQL Specific] Query Queue', () => {
beforeEach(function() {
beforeEach(async function() {
const User = this.User = this.sequelize.define('User', {
username: DataTypes.STRING
});
return this.sequelize.sync({ force: true }).then(() => {
return User.create({ username: 'John' });
});
await this.sequelize.sync({ force: true });
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;
return expect(this.sequelize.transaction(t => {
await expect(this.sequelize.transaction(async t => {
return Promise.all([
User.findOne({
transaction: t
......
......@@ -9,7 +9,7 @@ const chai = require('chai'),
if (dialect.match(/^mssql/)) {
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', {
ID: {
field: 'id',
......@@ -45,71 +45,67 @@ if (dialect.match(/^mssql/)) {
foreignKey: 'UserID'
});
return this.sequelize.sync({ force: true })
.then(() => User.bulkCreate([
{ UserName: 'Vayom' },
{ UserName: 'Shaktimaan' },
{ UserName: 'Nikita' },
{ UserName: 'Aryamaan' }
], { returning: true }))
.then(([vyom, shakti, nikita, arya]) => {
return Promise.all([
vyom.createLoginLog(),
shakti.createLoginLog(),
nikita.createLoginLog(),
arya.createLoginLog()
]);
}).then(() => {
return LoginLog.findAll({
include: [
{
model: User,
where: {
UserName: {
[Op.like]: '%maan%'
}
}
await this.sequelize.sync({ force: true });
const [vyom, shakti, nikita, arya] = await User.bulkCreate([
{ UserName: 'Vayom' },
{ UserName: 'Shaktimaan' },
{ UserName: 'Nikita' },
{ UserName: 'Aryamaan' }
], { returning: true });
await Promise.all([
vyom.createLoginLog(),
shakti.createLoginLog(),
nikita.createLoginLog(),
arya.createLoginLog()
]);
const logs = await LoginLog.findAll({
include: [
{
model: User,
where: {
UserName: {
[Op.like]: '%maan%'
}
],
order: [[User, 'UserName', 'DESC']],
offset: 0,
limit: 10
});
}).then(logs => {
expect(logs).to.have.length(2);
expect(logs[0].User.get('UserName')).to.equal('Shaktimaan');
expect(logs[1].User.get('UserName')).to.equal('Aryamaan');
});
}
}
],
order: [[User, 'UserName', 'DESC']],
offset: 0,
limit: 10
});
expect(logs).to.have.length(2);
expect(logs[0].User.get('UserName')).to.equal('Shaktimaan');
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', {
username: Sequelize.STRING('MAX')
}, { freezeTableName: true });
return Users.sync({ force: true }).then(() => {
return this.sequelize.getQueryInterface().describeTable('_Users').then(metadata => {
const username = metadata.username;
expect(username.type).to.include('(MAX)');
});
});
await Users.sync({ force: true });
const metadata = await this.sequelize.getQueryInterface().describeTable('_Users');
const username = metadata.username;
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', {
username: Sequelize.CHAR(10)
}, { freezeTableName: true });
return Users.sync({ force: true }).then(() => {
return this.sequelize.getQueryInterface().describeTable('_Users').then(metadata => {
const username = metadata.username;
expect(username.type).to.include('(10)');
});
});
await Users.sync({ force: true });
const metadata = await this.sequelize.getQueryInterface().describeTable('_Users');
const username = metadata.username;
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', {
business_id: {
type: Sequelize.BIGINT,
......@@ -121,19 +117,17 @@ if (dialect.match(/^mssql/)) {
const bigIntValue = 2147483648;
return BigIntTable.sync({ force: true })
.then(() => {
return BigIntTable.create({
business_id: bigIntValue
});
})
.then(() => BigIntTable.findOne())
.then(record => {
expect(Number(record.business_id)).to.equals(bigIntValue);
});
await BigIntTable.sync({ force: true });
await BigIntTable.create({
business_id: bigIntValue
});
const record = await BigIntTable.findOne();
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', {
status: {
type: Sequelize.BOOLEAN,
......@@ -145,15 +139,13 @@ if (dialect.match(/^mssql/)) {
const value = true;
return BooleanTable.sync({ force: true })
.then(() => {
return BooleanTable.create({
status: value
});
})
.then(() => BooleanTable.findOne())
.then(record => {
expect(record.status).to.equals(value);
});
await BooleanTable.sync({ force: true });
await BooleanTable.create({
status: value
});
const record = await BooleanTable.findOne();
expect(record.status).to.equals(value);
});
}
......@@ -10,30 +10,27 @@ if (dialect === 'mysql') {
describe('[MYSQL Specific] Associations', () => {
describe('many-to-many', () => {
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 }),
Table1 = this.sequelize.define('wp_table1', { foo: DataTypes.STRING });
Table1.belongsToMany(Table2, { through: 'wp_table1swp_table2s' });
Table2.belongsToMany(Table1, { through: 'wp_table1swp_table2s' });
return Table1.sync({ force: true }).then(() => {
return Table2.sync({ force: true }).then(() => {
expect(this.sequelize.modelManager.getModel('wp_table1swp_table2s')).to.exist;
});
});
await Table1.sync({ force: true });
await Table2.sync({ force: true });
expect(this.sequelize.modelManager.getModel('wp_table1swp_table2s')).to.exist;
});
});
describe('when join table name is specified', () => {
beforeEach(function() {
beforeEach(async function() {
const Table2 = this.sequelize.define('ms_table1', { foo: DataTypes.STRING }),
Table1 = this.sequelize.define('ms_table2', { foo: DataTypes.STRING });
Table1.belongsToMany(Table2, { through: 'table1_to_table2' });
Table2.belongsToMany(Table1, { through: 'table1_to_table2' });
return Table1.sync({ force: true }).then(() => {
return Table2.sync({ force: true });
});
await Table1.sync({ force: true });
await Table2.sync({ force: true });
});
it('should not use only a specified name', function() {
......@@ -44,7 +41,7 @@ if (dialect === 'mysql') {
});
describe('HasMany', () => {
beforeEach(function() {
beforeEach(async function() {
//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.Task = this.sequelize.define(`Task${Math.ceil(Math.random() * 10000000)}`, { name: DataTypes.STRING });
......@@ -62,70 +59,48 @@ if (dialect === 'mysql') {
tasks[i] = { name: `Task${Math.random()}` };
}
return this.sequelize.sync({ force: true }).then(() => {
return this.User.bulkCreate(users).then(() => {
return this.Task.bulkCreate(tasks);
});
});
await this.sequelize.sync({ force: true });
await this.User.bulkCreate(users);
await this.Task.bulkCreate(tasks);
});
describe('addDAO / getModel', () => {
beforeEach(function() {
beforeEach(async function() {
this.user = null;
this.task = null;
return this.User.findAll().then(_users => {
return this.Task.findAll().then(_tasks => {
this.user = _users[0];
this.task = _tasks[0];
});
});
const _users = await this.User.findAll();
const _tasks = await this.Task.findAll();
this.user = _users[0];
this.task = _tasks[0];
});
it('should correctly add an association to the dao', function() {
return this.user.getTasks().then(_tasks => {
expect(_tasks.length).to.equal(0);
return this.user.addTask(this.task).then(() => {
return this.user.getTasks().then(_tasks => {
expect(_tasks.length).to.equal(1);
});
});
});
it('should correctly add an association to the dao', async function() {
expect(await this.user.getTasks()).to.have.length(0);
await this.user.addTask(this.task);
expect(await this.user.getTasks()).to.have.length(1);
});
});
describe('removeDAO', () => {
beforeEach(function() {
beforeEach(async function() {
this.user = null;
this.tasks = null;
return this.User.findAll().then(_users => {
return this.Task.findAll().then(_tasks => {
this.user = _users[0];
this.tasks = _tasks;
});
});
const _users = await this.User.findAll();
const _tasks = await this.Task.findAll();
this.user = _users[0];
this.tasks = _tasks;
});
it('should correctly remove associated objects', function() {
return this.user.getTasks().then(__tasks => {
expect(__tasks.length).to.equal(0);
return this.user.setTasks(this.tasks).then(() => {
return this.user.getTasks().then(_tasks => {
expect(_tasks.length).to.equal(this.tasks.length);
return this.user.removeTask(this.tasks[0]).then(() => {
return this.user.getTasks().then(_tasks => {
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);
});
});
});
});
});
});
});
it('should correctly remove associated objects', async function() {
expect(await this.user.getTasks()).to.have.length(0);
await this.user.setTasks(this.tasks);
expect(await this.user.getTasks()).to.have.length(this.tasks.length);
await this.user.removeTask(this.tasks[0]);
expect(await this.user.getTasks()).to.have.length(this.tasks.length - 1);
await this.user.removeTasks([this.tasks[1], this.tasks[2]]);
expect(await this.user.getTasks()).to.have.length(this.tasks.length - 3);
});
});
});
......
......@@ -8,31 +8,32 @@ const DataTypes = require('../../../../lib/data-types');
if (dialect === 'mysql') {
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 User = sequelize.define('User', { username: DataTypes.STRING });
return User.sync({ force: true })
.then(() => User.create({ id: 1, username: 'jozef' }))
.then(() => User.update({ username: 'jozef' }, {
where: {
id: 1
}
}))
// https://github.com/sequelize/sequelize/issues/7184
.then(([affectedCount]) => affectedCount.should.equal(1));
await User.sync({ force: true });
await User.create({ id: 1, username: 'jozef' });
const [affectedCount] = await User.update({ username: 'jozef' }, {
where: {
id: 1
}
});
// https://github.com/sequelize/sequelize/issues/7184
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 cm = sequelize.connectionManager;
return sequelize
.sync()
.then(() => cm.getConnection())
.then(connection => {
expect(cm.validate(connection)).to.be.ok;
return cm.releaseConnection(connection);
});
await sequelize.sync();
const connection = await cm.getConnection();
expect(cm.validate(connection)).to.be.ok;
await cm.releaseConnection(connection);
});
});
}
......@@ -10,11 +10,16 @@ const DataTypes = require('../../../../lib/data-types');
if (dialect === 'mysql') {
describe('[MYSQL Specific] Errors', () => {
const validateError = (promise, errClass, errValues) => {
const validateError = async (promise, errClass, errValues) => {
const wanted = { ...errValues };
return expect(promise).to.have.been.rejectedWith(errClass).then(() =>
promise.catch(err => Object.keys(wanted).forEach(k => expect(err[k]).to.eql(wanted[k]))));
await expect(promise).to.have.been.rejectedWith(errClass);
try {
return await promise;
} catch (err) {
return Object.keys(wanted).forEach(k => expect(err[k]).to.eql(wanted[k]));
}
};
describe('ForeignKeyConstraintError', () => {
......@@ -29,46 +34,48 @@ if (dialect === 'mysql') {
this.Task.belongsTo(this.User, { foreignKey: 'primaryUserId', as: 'primaryUsers' });
});
it('in context of DELETE restriction', function() {
const ctx = {};
return this.sequelize.sync({ force: true }).then(() => {
return Promise.all([
this.User.create({ id: 67, username: 'foo' }),
this.Task.create({ id: 52, title: 'task' })
]);
}).then(([user1, task1]) => {
ctx.user1 = user1;
ctx.task1 = task1;
return user1.setTasks([task1]);
}).then(() => {
return Promise.all([
validateError(ctx.user1.destroy(), Sequelize.ForeignKeyConstraintError, {
fields: ['userId'],
table: 'users',
value: undefined,
index: 'tasksusers_ibfk_1',
reltype: 'parent'
}),
validateError(ctx.task1.destroy(), Sequelize.ForeignKeyConstraintError, {
fields: ['taskId'],
table: 'tasks',
value: undefined,
index: 'tasksusers_ibfk_2',
reltype: 'parent'
})
]);
});
it('in context of DELETE restriction', async function() {
await this.sequelize.sync({ force: true });
const [user1, task1] = await Promise.all([
this.User.create({ id: 67, username: 'foo' }),
this.Task.create({ id: 52, title: 'task' })
]);
await user1.setTasks([task1]);
await Promise.all([
validateError(user1.destroy(), Sequelize.ForeignKeyConstraintError, {
fields: ['userId'],
table: 'users',
value: undefined,
index: 'tasksusers_ibfk_1',
reltype: 'parent'
}),
validateError(task1.destroy(), Sequelize.ForeignKeyConstraintError, {
fields: ['taskId'],
table: 'tasks',
value: undefined,
index: 'tasksusers_ibfk_2',
reltype: 'parent'
})
]);
});
it('in context of missing relation', function() {
return this.sequelize.sync({ force: true }).then(() =>
validateError(this.Task.create({ title: 'task', primaryUserId: 5 }), Sequelize.ForeignKeyConstraintError, {
it('in context of missing relation', async function() {
await this.sequelize.sync({ force: true });
await validateError(
this.Task.create({ title: 'task', primaryUserId: 5 }),
Sequelize.ForeignKeyConstraintError,
{
fields: ['primaryUserId'],
table: 'users',
value: 5,
index: 'tasks_ibfk_1',
reltype: 'child'
}));
}
);
});
});
});
......
......@@ -11,7 +11,7 @@ describe(Support.getTestDialectTeaser('Warning'), () => {
// We can only test MySQL warnings when using MySQL.
if (dialect === 'mysql') {
describe('logging', () => {
it('logs warnings when there are warnings', () => {
it('logs warnings when there are warnings', async () => {
const logger = sinon.spy(console, 'log');
const sequelize = Support.createSequelizeInstance({
logging: logger,
......@@ -23,20 +23,16 @@ describe(Support.getTestDialectTeaser('Warning'), () => {
name: Sequelize.DataTypes.STRING(1, true)
});
return sequelize.sync({ force: true }).then(() => {
return sequelize.authenticate();
}).then(() => {
return sequelize.query("SET SESSION sql_mode='';");
}).then(() => {
return Model.create({
name: 'very-long-long-name'
});
}).then(() => {
// last log is warning message
expect(logger.args[logger.args.length - 1][0]).to.be.match(/^MySQL Warnings \(default\):.*/m);
}, () => {
expect.fail();
await sequelize.sync({ force: true });
await sequelize.authenticate();
await sequelize.query("SET SESSION sql_mode='';");
await Model.create({
name: 'very-long-long-name'
});
// last log is warning message
expect(logger.args[logger.args.length - 1][0]).to.be.match(/^MySQL Warnings \(default\):.*/m);
});
});
}
......
......@@ -43,7 +43,7 @@ if (dialect.match(/^postgres/)) {
describe('HasMany', () => {
describe('addDAO / getModel', () => {
beforeEach(function() {
beforeEach(async function() {
//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.Task = this.sequelize.define(`Task${config.rand()}`, { name: DataTypes.STRING });
......@@ -61,35 +61,25 @@ if (dialect.match(/^postgres/)) {
tasks[i] = { name: `Task${Math.random()}` };
}
return this.sequelize.sync({ force: true }).then(() => {
return this.User.bulkCreate(users).then(() => {
return this.Task.bulkCreate(tasks).then(() => {
return this.User.findAll().then(_users => {
return this.Task.findAll().then(_tasks => {
this.user = _users[0];
this.task = _tasks[0];
});
});
});
});
});
await this.sequelize.sync({ force: true });
await this.User.bulkCreate(users);
await this.Task.bulkCreate(tasks);
const _users = await this.User.findAll();
const _tasks = await this.Task.findAll();
this.user = _users[0];
this.task = _tasks[0];
});
it('should correctly add an association to the dao', function() {
return this.user.getTasks().then(_tasks => {
expect(_tasks).to.have.length(0);
return this.user.addTask(this.task).then(() => {
return this.user.getTasks().then(_tasks => {
expect(_tasks).to.have.length(1);
});
});
});
it('should correctly add an association to the dao', async function() {
expect(await this.user.getTasks()).to.have.length(0);
await this.user.addTask(this.task);
expect(await this.user.getTasks()).to.have.length(1);
});
});
describe('removeDAO', () => {
it('should correctly remove associated objects', function() {
const users = [],
it('should correctly remove associated objects', async function() {
const users = [],
tasks = [];
//prevent periods from occurring in the table name since they are used to delimit (table.column)
......@@ -106,39 +96,23 @@ if (dialect.match(/^postgres/)) {
tasks[i] = { id: i + 1, name: `Task${Math.random()}` };
}
return this.sequelize.sync({ force: true }).then(() => {
return this.User.bulkCreate(users).then(() => {
return this.Task.bulkCreate(tasks).then(() => {
return this.User.findAll().then(_users => {
return this.Task.findAll().then(_tasks => {
this.user = _users[0];
this.task = _tasks[0];
this.users = _users;
this.tasks = _tasks;
return this.user.getTasks().then(__tasks => {
expect(__tasks).to.have.length(0);
return this.user.setTasks(this.tasks).then(() => {
return this.user.getTasks().then(_tasks => {
expect(_tasks).to.have.length(this.tasks.length);
return this.user.removeTask(this.tasks[0]).then(() => {
return this.user.getTasks().then(_tasks => {
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);
});
});
});
});
});
});
});
});
});
});
});
});
await this.sequelize.sync({ force: true });
await this.User.bulkCreate(users);
await this.Task.bulkCreate(tasks);
const _users = await this.User.findAll();
const _tasks = await this.Task.findAll();
this.user = _users[0];
this.task = _tasks[0];
this.users = _users;
this.tasks = _tasks;
expect(await this.user.getTasks()).to.have.length(0);
await this.user.setTasks(this.tasks);
expect(await this.user.getTasks()).to.have.length(this.tasks.length);
await this.user.removeTask(this.tasks[0]);
expect(await this.user.getTasks()).to.have.length(this.tasks.length - 1);
await this.user.removeTasks([this.tasks[1], this.tasks[2]]);
expect(await this.user.getTasks()).to.have.length(this.tasks.length - 3);
});
});
});
......
......@@ -8,44 +8,36 @@ const chai = require('chai'),
if (dialect.match(/^postgres/)) {
describe('[POSTGRES] Sequelize', () => {
function checkTimezoneParsing(baseOptions) {
async function checkTimezoneParsing(baseOptions) {
const options = { ...baseOptions, timezone: 'Asia/Kolkata', timestamps: true };
const sequelize = Support.createSequelizeInstance(options);
const tzTable = sequelize.define('tz_table', { foo: DataTypes.STRING });
return tzTable.sync({ force: true }).then(() => {
return tzTable.create({ foo: 'test' }).then(row => {
expect(row).to.be.not.null;
});
});
await tzTable.sync({ force: true });
const row = await tzTable.create({ foo: 'test' });
expect(row).to.be.not.null;
}
it('should correctly parse the moment based timezone while fetching hstore oids', function() {
return checkTimezoneParsing(this.sequelize.options);
it('should correctly parse the moment based timezone while fetching hstore oids', async function() {
await checkTimezoneParsing(this.sequelize.options);
});
it('should set client_min_messages to warning by default', () => {
return Support.sequelize.query('SHOW client_min_messages')
.then(result => {
expect(result[0].client_min_messages).to.equal('warning');
});
it('should set client_min_messages to warning by default', async () => {
const result = await Support.sequelize.query('SHOW client_min_messages');
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' });
return sequelize.query('SHOW client_min_messages')
.then(result => {
expect(result[0].client_min_messages).to.equal('error');
});
const result = await sequelize.query('SHOW client_min_messages');
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 });
return sequelize.query('SHOW client_min_messages')
.then(result => {
// `notice` is Postgres's default
expect(result[0].client_min_messages).to.equal('notice');
});
const result = await sequelize.query('SHOW client_min_messages');
// `notice` is Postgres's default
expect(result[0].client_min_messages).to.equal('notice');
});
});
......@@ -79,66 +71,63 @@ if (dialect.match(/^postgres/)) {
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;
return reloadDynamicOIDs(sequelize).then(() => {
dynamicTypesToCheck.forEach(type => {
expect(type.types.postgres,
`DataType.${type.key}.types.postgres`).to.not.be.empty;
await reloadDynamicOIDs(sequelize);
dynamicTypesToCheck.forEach(type => {
expect(type.types.postgres,
`DataType.${type.key}.types.postgres`).to.not.be.empty;
for (const name of type.types.postgres) {
const entry = sequelize.connectionManager.nameOidMap[name];
const oidParserMap = sequelize.connectionManager.oidParserMap;
for (const name of type.types.postgres) {
const entry = sequelize.connectionManager.nameOidMap[name];
const oidParserMap = sequelize.connectionManager.oidParserMap;
expect(entry.oid, `nameOidMap[${name}].oid`).to.be.a('number');
expect(entry.arrayOid, `nameOidMap[${name}].arrayOid`).to.be.a('number');
expect(entry.oid, `nameOidMap[${name}].oid`).to.be.a('number');
expect(entry.arrayOid, `nameOidMap[${name}].arrayOid`).to.be.a('number');
expect(oidParserMap.get(entry.oid),
`oidParserMap.get(nameOidMap[${name}].oid)`).to.be.a('function');
expect(oidParserMap.get(entry.arrayOid),
`oidParserMap.get(nameOidMap[${name}].arrayOid)`).to.be.a('function');
}
expect(oidParserMap.get(entry.oid),
`oidParserMap.get(nameOidMap[${name}].oid)`).to.be.a('function');
expect(oidParserMap.get(entry.arrayOid),
`oidParserMap.get(nameOidMap[${name}].arrayOid)`).to.be.a('function');
}
});
});
});
it('should fetch enum dynamic oids and create parsers', () => {
it('should fetch enum dynamic oids and create parsers', async () => {
const sequelize = Support.sequelize;
return reloadDynamicOIDs(sequelize).then(() => {
const enumOids = sequelize.connectionManager.enumOids;
const oidParserMap = sequelize.connectionManager.oidParserMap;
expect(enumOids.oids, 'enumOids.oids').to.not.be.empty;
expect(enumOids.arrayOids, 'enumOids.arrayOids').to.not.be.empty;
for (const oid of enumOids.oids) {
expect(oidParserMap.get(oid), 'oidParserMap.get(enumOids.oids)').to.be.a('function');
}
for (const arrayOid of enumOids.arrayOids) {
expect(oidParserMap.get(arrayOid), 'oidParserMap.get(enumOids.arrayOids)').to.be.a('function');
}
});
await reloadDynamicOIDs(sequelize);
const enumOids = sequelize.connectionManager.enumOids;
const oidParserMap = sequelize.connectionManager.oidParserMap;
expect(enumOids.oids, 'enumOids.oids').to.not.be.empty;
expect(enumOids.arrayOids, 'enumOids.arrayOids').to.not.be.empty;
for (const oid of enumOids.oids) {
expect(oidParserMap.get(oid), 'oidParserMap.get(enumOids.oids)').to.be.a('function');
}
for (const arrayOid of enumOids.arrayOids) {
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;
return reloadDynamicOIDs(sequelize).then(() => {
for (const baseKey in expCastTypes) {
const name = expCastTypes[baseKey];
const entry = sequelize.connectionManager.nameOidMap[name];
const oidParserMap = sequelize.connectionManager.oidParserMap;
for (const key of ['rangeOid', 'arrayRangeOid']) {
expect(entry[key], `nameOidMap[${name}][${key}]`).to.be.a('number');
}
await reloadDynamicOIDs(sequelize);
for (const baseKey in expCastTypes) {
const name = expCastTypes[baseKey];
const entry = sequelize.connectionManager.nameOidMap[name];
const oidParserMap = sequelize.connectionManager.oidParserMap;
expect(oidParserMap.get(entry.rangeOid),
`oidParserMap.get(nameOidMap[${name}].rangeOid)`).to.be.a('function');
expect(oidParserMap.get(entry.arrayRangeOid),
`oidParserMap.get(nameOidMap[${name}].arrayRangeOid)`).to.be.a('function');
for (const key of ['rangeOid', 'arrayRangeOid']) {
expect(entry[key], `nameOidMap[${name}][${key}]`).to.be.a('number');
}
});
expect(oidParserMap.get(entry.rangeOid),
`oidParserMap.get(nameOidMap[${name}].rangeOid)`).to.be.a('function');
expect(oidParserMap.get(entry.arrayRangeOid),
`oidParserMap.get(nameOidMap[${name}].arrayRangeOid)`).to.be.a('function');
}
});
});
......
......@@ -72,7 +72,7 @@ if (dialect === 'postgres') {
describe('DATE SQL', () => {
// 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;
const date = new Date();
......@@ -97,69 +97,68 @@ if (dialect === 'postgres') {
timestamps: true
});
return User.sync({
await User.sync({
force: true
}).then(() => {
return User.create({
username: 'bob',
anotherTime: Infinity
}, {
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({
sometime: Infinity
}, {
returning: true
});
}).then(user => {
expect(user.sometime).to.equal(Infinity);
return user.update({
sometime: Infinity
});
}).then(user => {
expect(user.sometime).to.equal(Infinity);
return user.update({
sometime: this.sequelize.fn('NOW')
}, {
returning: true
});
}).then(user => {
expect(user.sometime).to.be.withinTime(date, new Date());
// find
return User.findAll();
}).then(users => {
expect(users[0].beforeTime).to.equal(-Infinity);
expect(users[0].sometime).to.not.equal(Infinity);
expect(users[0].afterTime).to.equal(Infinity);
return users[0].update({
sometime: date
});
}).then(user => {
expect(user.sometime).to.equalTime(date);
return user.update({
sometime: date
});
}).then(user => {
expect(user.sometime).to.equalTime(date);
});
const user4 = await User.create({
username: 'bob',
anotherTime: Infinity
}, {
validate: true
});
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
}, {
returning: true
});
expect(user3.sometime).to.equal(Infinity);
const user2 = await user3.update({
sometime: Infinity
});
expect(user2.sometime).to.equal(Infinity);
const user1 = await user2.update({
sometime: this.sequelize.fn('NOW')
}, {
returning: true
});
expect(user1.sometime).to.be.withinTime(date, new Date());
// find
const users = await User.findAll();
expect(users[0].beforeTime).to.equal(-Infinity);
expect(users[0].sometime).to.not.equal(Infinity);
expect(users[0].afterTime).to.equal(Infinity);
const user0 = await users[0].update({
sometime: date
});
expect(user0.sometime).to.equalTime(date);
const user = await user0.update({
sometime: date
});
expect(user.sometime).to.equalTime(date);
});
});
describe('DATEONLY SQL', () => {
// 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;
const date = new Date();
......@@ -184,64 +183,63 @@ if (dialect === 'postgres') {
timestamps: true
});
return User.sync({
await User.sync({
force: true
}).then(() => {
return User.create({
username: 'bob',
anotherTime: Infinity
}, {
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({
sometime: Infinity
}, {
returning: true
});
}).then(user => {
expect(user.sometime).to.equal(Infinity);
return user.update({
sometime: Infinity
});
}).then(user => {
expect(user.sometime).to.equal(Infinity);
return user.update({
sometime: this.sequelize.fn('NOW')
}, {
returning: true
});
}).then(user => {
expect(user.sometime).to.not.equal(Infinity);
expect(new Date(user.sometime)).to.be.withinDate(date, new Date());
// find
return User.findAll();
}).then(users => {
expect(users[0].beforeTime).to.equal(-Infinity);
expect(users[0].sometime).to.not.equal(Infinity);
expect(users[0].afterTime).to.equal(Infinity);
return users[0].update({
sometime: '1969-07-20'
});
}).then(user => {
expect(user.sometime).to.equal('1969-07-20');
return user.update({
sometime: '1969-07-20'
});
}).then(user => {
expect(user.sometime).to.equal('1969-07-20');
});
const user4 = await User.create({
username: 'bob',
anotherTime: Infinity
}, {
validate: true
});
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
}, {
returning: true
});
expect(user3.sometime).to.equal(Infinity);
const user2 = await user3.update({
sometime: Infinity
});
expect(user2.sometime).to.equal(Infinity);
const user1 = await user2.update({
sometime: this.sequelize.fn('NOW')
}, {
returning: true
});
expect(user1.sometime).to.not.equal(Infinity);
expect(new Date(user1.sometime)).to.be.withinDate(date, new Date());
// find
const users = await User.findAll();
expect(users[0].beforeTime).to.equal(-Infinity);
expect(users[0].sometime).to.not.equal(Infinity);
expect(users[0].afterTime).to.equal(Infinity);
const user0 = await users[0].update({
sometime: '1969-07-20'
});
expect(user0.sometime).to.equal('1969-07-20');
const user = await user0.update({
sometime: '1969-07-20'
});
expect(user.sometime).to.equal('1969-07-20');
});
});
......
......@@ -11,18 +11,18 @@ const chai = require('chai'),
if (dialect.match(/^postgres/)) {
describe('[POSTGRES Specific] ExclusionConstraintError', () => {
const constraintName = 'overlap_period';
beforeEach(function() {
beforeEach(async function() {
this.Booking = this.sequelize.define('Booking', {
roomNo: DataTypes.INTEGER,
period: DataTypes.RANGE(DataTypes.DATE)
});
return this.Booking
.sync({ force: true })
.then(() => {
return this.sequelize.query(
`ALTER TABLE "${this.Booking.tableName}" ADD CONSTRAINT ${constraintName} EXCLUDE USING gist ("roomNo" WITH =, period WITH &&)`
);
});
await this.Booking
.sync({ force: true });
await this.sequelize.query(
`ALTER TABLE "${this.Booking.tableName}" ADD CONSTRAINT ${constraintName} EXCLUDE USING gist ("roomNo" WITH =, period WITH &&)`
);
});
it('should contain error specific properties', () => {
......@@ -40,23 +40,22 @@ 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;
return Booking
await Booking
.create({
roomNo: 1,
guestName: 'Incognito Visitor',
period: [new Date(2015, 0, 1), new Date(2015, 0, 3)]
})
.then(() => {
return expect(Booking
.create({
roomNo: 1,
guestName: 'Frequent Visitor',
period: [new Date(2015, 0, 2), new Date(2015, 0, 5)]
})).to.eventually.be.rejectedWith(Sequelize.ExclusionConstraintError);
});
await expect(Booking
.create({
roomNo: 1,
guestName: 'Frequent Visitor',
period: [new Date(2015, 0, 2), new Date(2015, 0, 5)]
})).to.eventually.be.rejectedWith(Sequelize.ExclusionConstraintError);
});
});
......
......@@ -12,7 +12,7 @@ if (dialect.match(/^postgres/)) {
const taskAlias = 'AnActualVeryLongAliasThatShouldBreakthePostgresLimitOfSixtyFourCharacters';
const teamAlias = 'Toto';
const executeTest = (options, test) => {
const executeTest = async (options, test) => {
const sequelize = Support.createSequelizeInstance(options);
const User = sequelize.define('User', { name: DataTypes.STRING, updatedAt: DataTypes.DATE }, { underscored: true });
......@@ -23,48 +23,43 @@ if (dialect.match(/^postgres/)) {
User.belongsToMany(Team, { as: teamAlias, foreignKey: 'teamId', through: 'UserTeam' });
Team.belongsToMany(User, { foreignKey: 'userId', through: 'UserTeam' });
return sequelize.sync({ force: true }).then(() => {
return Team.create({ name: 'rocket' }).then(team => {
return Task.create({ title: 'SuperTask' }).then(task => {
return User.create({ name: 'test', task_id: task.id, updatedAt: new Date() }).then(user => {
return user[`add${teamAlias}`](team).then(() => {
return User.findOne({
include: [
{
model: Task,
as: taskAlias
},
{
model: Team,
as: teamAlias
}
]
}).then(test);
});
});
});
});
});
await sequelize.sync({ force: true });
const team = await Team.create({ name: 'rocket' });
const task = await Task.create({ title: 'SuperTask' });
const user = await User.create({ name: 'test', task_id: task.id, updatedAt: new Date() });
await user[`add${teamAlias}`](team);
return test(await User.findOne({
include: [
{
model: Task,
as: taskAlias
},
{
model: Team,
as: teamAlias
}
]
}));
};
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 };
return executeTest(options, res => {
await executeTest(options, res => {
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 };
return executeTest(options, res => {
await executeTest(options, res => {
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 User = sequelize.define('user_model_name_that_is_long_for_demo_but_also_surpasses_the_character_limit',
......@@ -95,19 +90,16 @@ if (dialect.match(/^postgres/)) {
User.hasMany(Project, { foreignKey: 'userId' });
Project.belongsTo(Company, { foreignKey: 'companyId' });
return sequelize.sync({ force: true }).then(() => {
return Company.create({ name: 'Sequelize' }).then(comp => {
return User.create({ name: 'standard user' }).then(user => {
return Project.create({ name: 'Manhattan', companyId: comp.id, userId: user.id }).then(() => {
return User.findAll({
include: {
model: Project,
include: Company
}
});
});
});
});
await sequelize.sync({ force: true });
const comp = await Company.create({ name: 'Sequelize' });
const user = await User.create({ name: 'standard user' });
await Project.create({ name: 'Manhattan', companyId: comp.id, userId: user.id });
await User.findAll({
include: {
model: Project,
include: Company
}
});
});
});
......
......@@ -184,16 +184,16 @@ if (dialect.match(/^postgres/)) {
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
return Support.sequelize.connectionManager.getConnection().then(connection => {
Support.sequelize.connectionManager.releaseConnection(connection);
const connection = await Support.sequelize.connectionManager.getConnection();
const tsName = DataTypes.postgres.DATE.types.postgres[0],
tsOid = Support.sequelize.connectionManager.nameOidMap[tsName].oid,
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');
});
Support.sequelize.connectionManager.releaseConnection(connection);
const tsName = DataTypes.postgres.DATE.types.postgres[0],
tsOid = Support.sequelize.connectionManager.nameOidMap[tsName].oid,
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');
});
});
......
......@@ -8,7 +8,7 @@ const chai = require('chai'),
if (dialect.match(/^postgres/)) {
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', {
active: Sequelize.BOOLEAN
});
......@@ -27,24 +27,18 @@ if (dialect.match(/^postgres/)) {
User.hasMany(Media);
Media.belongsTo(User);
return this.sequelize
.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();
})
.then(user => {
expect(user.active).to.be.true;
expect(user.get('active')).to.be.true;
return User.findOne({ raw: true });
})
.then(user => {
expect(user.active).to.be.true;
});
await this.sequelize.sync({ force: true });
const user1 = await User.create({ active: true });
expect(user1.active).to.be.true;
expect(user1.get('active')).to.be.true;
const user0 = await User.findOne();
expect(user0.active).to.be.true;
expect(user0.get('active')).to.be.true;
const user = await User.findOne({ raw: true });
expect(user.active).to.be.true;
});
});
}
......@@ -18,52 +18,48 @@ if (dialect === 'sqlite') {
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({
storage: jetpack.path(fileName)
});
const User = sequelize.define('User', { username: DataTypes.STRING });
return User
.sync({ force: true })
.then(() => sequelize.query('PRAGMA journal_mode = WAL'))
.then(() => User.create({ username: 'user1' }))
.then(() => {
return sequelize.transaction(transaction => {
return User.create({ username: 'user2' }, { transaction });
});
})
.then(async () => {
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}-wal`), 'wal file should exists').to.be.equal('file');
await User.sync({ force: true });
// move wal file content to main database
// so those files can be removed on connection close
// https://www.sqlite.org/wal.html#ckpt
await sequelize.query('PRAGMA wal_checkpoint');
await sequelize.query('PRAGMA journal_mode = WAL');
await User.create({ username: 'user1' });
// wal, shm files exist after checkpoint
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');
await sequelize.transaction(transaction => {
return User.create({ username: 'user2' }, { transaction });
});
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}-wal`), 'wal file should exists').to.be.equal('file');
// move wal file content to main database
// so those files can be removed on connection close
// https://www.sqlite.org/wal.html#ckpt
await sequelize.query('PRAGMA wal_checkpoint');
return sequelize.close();
})
.then(() => {
expect(jetpack.exists(fileName)).to.be.equal('file');
expect(jetpack.exists(`${fileName}-shm`), 'shm file exists').to.be.false;
expect(jetpack.exists(`${fileName}-wal`), 'wal file exists').to.be.false;
// wal, shm files exist after checkpoint
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');
return this.sequelize.query('PRAGMA journal_mode = DELETE');
});
await sequelize.close();
expect(jetpack.exists(fileName)).to.be.equal('file');
expect(jetpack.exists(`${fileName}-shm`), 'shm file exists').to.be.false;
expect(jetpack.exists(`${fileName}-wal`), 'wal file exists').to.be.false;
await this.sequelize.query('PRAGMA journal_mode = DELETE');
});
it('automatic path provision for `options.storage`', () => {
return Support.createSequelizeInstance({ storage: nestedFileName })
it('automatic path provision for `options.storage`', async () => {
await Support.createSequelizeInstance({ storage: nestedFileName })
.define('User', { username: DataTypes.STRING })
.sync({ force: true }).then(() => {
expect(jetpack.exists(nestedFileName)).to.be.equal('file');
});
.sync({ force: true });
expect(jetpack.exists(nestedFileName)).to.be.equal('file');
});
});
}
......@@ -14,14 +14,14 @@ if (dialect === 'sqlite') {
this.sequelize.options.storage = ':memory:';
});
beforeEach(function() {
beforeEach(async function() {
this.sequelize.options.storage = dbFile;
this.User = this.sequelize.define('User', {
age: DataTypes.INTEGER,
name: DataTypes.STRING,
bio: DataTypes.TEXT
});
return this.User.sync({ force: true });
await this.User.sync({ force: true });
});
storages.forEach(storage => {
......@@ -33,137 +33,128 @@ if (dialect === 'sqlite') {
});
describe('create', () => {
it('creates a table entry', function() {
return this.User.create({ age: 21, name: 'John Wayne', bio: 'noot noot' }).then(user => {
expect(user.age).to.equal(21);
expect(user.name).to.equal('John Wayne');
expect(user.bio).to.equal('noot noot');
return this.User.findAll().then(users => {
const usernames = users.map(user => {
return user.name;
});
expect(usernames).to.contain('John Wayne');
});
it('creates a table entry', async function() {
const user = await this.User.create({ age: 21, name: 'John Wayne', bio: 'noot noot' });
expect(user.age).to.equal(21);
expect(user.name).to.equal('John Wayne');
expect(user.bio).to.equal('noot noot');
const users = await this.User.findAll();
const usernames = users.map(user => {
return user.name;
});
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', {
name: DataTypes.STRING,
options: DataTypes.TEXT
});
return Person.sync({ force: true }).then(() => {
const options = JSON.stringify({ foo: 'bar', bar: 'foo' });
await Person.sync({ force: true });
const options = JSON.stringify({ foo: 'bar', bar: 'foo' });
return Person.create({
name: 'John Doe',
options
}).then(people => {
expect(people.options).to.deep.equal(options);
});
const people = await Person.create({
name: 'John Doe',
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', {
name: DataTypes.STRING,
has_swag: DataTypes.BOOLEAN
});
return Person.sync({ force: true }).then(() => {
return Person.create({
name: 'John Doe',
has_swag: true
}).then(people => {
expect(people.has_swag).to.be.ok;
});
await Person.sync({ force: true });
const people = await Person.create({
name: 'John Doe',
has_swag: true
});
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', {
name: DataTypes.STRING,
has_swag: DataTypes.BOOLEAN
});
return Person.sync({ force: true }).then(() => {
return Person.create({
name: 'John Doe',
has_swag: false
}).then(people => {
expect(people.has_swag).to.not.be.ok;
});
await Person.sync({ force: true });
const people = await Person.create({
name: 'John Doe',
has_swag: false
});
expect(people.has_swag).to.not.be.ok;
});
});
describe('.findOne', () => {
beforeEach(function() {
return this.User.create({ name: 'user', bio: 'footbar' });
beforeEach(async function() {
await this.User.create({ name: 'user', bio: 'footbar' });
});
it('finds normal lookups', function() {
return this.User.findOne({ where: { name: 'user' } }).then(user => {
expect(user.name).to.equal('user');
});
it('finds normal lookups', async function() {
const user = await this.User.findOne({ where: { name: 'user' } });
expect(user.name).to.equal('user');
});
it.skip('should make aliased attributes available', function() {
return this.User.findOne({
it.skip('should make aliased attributes available', async function() { // eslint-disable-line mocha/no-skipped-tests
const user = await this.User.findOne({
where: { name: 'user' },
attributes: ['id', ['name', 'username']]
}).then(user => {
expect(user.username).to.equal('user');
});
expect(user.username).to.equal('user');
});
});
describe('.all', () => {
beforeEach(function() {
return this.User.bulkCreate([
beforeEach(async function() {
await this.User.bulkCreate([
{ name: 'user', bio: 'foobar' },
{ name: 'user', bio: 'foobar' }
]);
});
it('should return all users', function() {
return this.User.findAll().then(users => {
expect(users).to.have.length(2);
});
it('should return all users', async function() {
const users = await this.User.findAll();
expect(users).to.have.length(2);
});
});
describe('.min', () => {
it('should return the min value', function() {
it('should return the min value', async function() {
const users = [];
for (let i = 2; i < 5; i++) {
users[users.length] = { age: i };
}
return this.User.bulkCreate(users).then(() => {
return this.User.min('age').then(min => {
expect(min).to.equal(2);
});
});
await this.User.bulkCreate(users);
const min = await this.User.min('age');
expect(min).to.equal(2);
});
});
describe('.max', () => {
it('should return the max value', function() {
it('should return the max value', async function() {
const users = [];
for (let i = 2; i <= 5; i++) {
users[users.length] = { age: i };
}
return this.User.bulkCreate(users).then(() => {
return this.User.max('age').then(min => {
expect(min).to.equal(5);
});
});
await this.User.bulkCreate(users);
const min = await this.User.max('age');
expect(min).to.equal(5);
});
});
});
......
......@@ -10,7 +10,7 @@ const chai = require('chai'),
if (dialect === 'sqlite') {
describe('[SQLITE Specific] DAO', () => {
beforeEach(function() {
beforeEach(async function() {
this.User = this.sequelize.define('User', {
username: DataTypes.STRING,
emergency_contact: DataTypes.JSON,
......@@ -28,90 +28,90 @@ if (dialect === 'sqlite') {
});
this.User.hasMany(this.Project);
return this.sequelize.sync({ force: true });
await this.sequelize.sync({ force: true });
});
describe('findAll', () => {
it('handles dates correctly', function() {
it('handles dates correctly', async function() {
const user = this.User.build({ username: 'user' });
user.dataValues.createdAt = new Date(2011, 4, 4);
return user.save().then(() => {
return this.User.create({ username: 'new user' }).then(() => {
return this.User.findAll({
where: { createdAt: { [Op.gt]: new Date(2012, 1, 1) } }
}).then(users => {
expect(users).to.have.length(1);
});
});
await user.save();
await this.User.create({ username: 'new user' });
const users = await this.User.findAll({
where: { createdAt: { [Op.gt]: new Date(2012, 1, 1) } }
});
expect(users).to.have.length(1);
});
it('handles dates with aliasses correctly #3611', function() {
return this.User.create({
it('handles dates with aliasses correctly #3611', async function() {
await this.User.create({
dateField: new Date(2010, 10, 10)
}).then(() => {
return this.User.findAll().then(obj => obj[0]);
}).then(user => {
expect(user.get('dateField')).to.be.an.instanceof(Date);
expect(user.get('dateField')).to.equalTime(new Date(2010, 10, 10));
});
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.equalTime(new Date(2010, 10, 10));
});
it('handles dates in includes correctly #2644', function() {
return this.User.create({
it('handles dates in includes correctly #2644', async function() {
await this.User.create({
projects: [
{ dateField: new Date(1990, 5, 5) }
]
}, { include: [this.Project] }).then(() => {
return this.User.findAll({
include: [this.Project]
}).then(obj => obj[0]);
}).then(user => {
expect(user.projects[0].get('dateField')).to.be.an.instanceof(Date);
expect(user.projects[0].get('dateField')).to.equalTime(new Date(1990, 5, 5));
}, { include: [this.Project] });
const obj = await this.User.findAll({
include: [this.Project]
});
const user = await obj[0];
expect(user.projects[0].get('dateField')).to.be.an.instanceof(Date);
expect(user.projects[0].get('dateField')).to.equalTime(new Date(1990, 5, 5));
});
});
describe('json', () => {
it('should be able to retrieve a row with json_extract function', function() {
return Promise.all([
it('should be able to retrieve a row with json_extract function', async function() {
await Promise.all([
this.User.create({ username: 'swen', emergency_contact: { name: 'kate' } }),
this.User.create({ username: 'anna', emergency_contact: { name: 'joe' } })
]).then(() => {
return this.User.findOne({
where: Sequelize.json('json_extract(emergency_contact, \'$.name\')', 'kate'),
attributes: ['username', 'emergency_contact']
});
}).then(user => {
expect(user.emergency_contact.name).to.equal('kate');
]);
const user = await this.User.findOne({
where: Sequelize.json('json_extract(emergency_contact, \'$.name\')', 'kate'),
attributes: ['username', 'emergency_contact']
});
expect(user.emergency_contact.name).to.equal('kate');
});
it('should be able to retrieve a row by json_type function', function() {
return Promise.all([
it('should be able to retrieve a row by json_type function', async function() {
await Promise.all([
this.User.create({ username: 'swen', emergency_contact: { name: 'kate' } }),
this.User.create({ username: 'anna', emergency_contact: ['kate', 'joe'] })
]).then(() => {
return this.User.findOne({
where: Sequelize.json('json_type(emergency_contact)', 'array'),
attributes: ['username', 'emergency_contact']
});
}).then(user => {
expect(user.username).to.equal('anna');
]);
const user = await this.User.findOne({
where: Sequelize.json('json_type(emergency_contact)', 'array'),
attributes: ['username', 'emergency_contact']
});
expect(user.username).to.equal('anna');
});
});
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', {});
return Payments.sync({ force: true }).then(() => {
return expect(Payments.bulkCreate([{ id: 1 }, { id: 1 }], { ignoreDuplicates: false })).to.eventually.be.rejected;
});
await Payments.sync({ force: true });
await expect(Payments.bulkCreate([{ id: 1 }, { id: 1 }], { ignoreDuplicates: false })).to.eventually.be.rejected;
});
});
});
......
......@@ -8,7 +8,7 @@ const chai = require('chai'),
if (dialect === 'sqlite') {
describe('[SQLITE Specific] sqlite_master raw queries', () => {
beforeEach(function() {
beforeEach(async function() {
this.sequelize.define('SomeTable', {
someColumn: DataTypes.INTEGER
}, {
......@@ -16,46 +16,40 @@ if (dialect === 'sqlite') {
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() {
return this.sequelize.query('SELECT * FROM sqlite_master WHERE tbl_name=\'SomeTable\'')
.then(result => {
const rows = result[0];
expect(rows).to.have.length(1);
const row = rows[0];
expect(row).to.have.property('type', 'table');
expect(row).to.have.property('name', 'SomeTable');
expect(row).to.have.property('tbl_name', 'SomeTable');
expect(row).to.have.property('sql');
});
it('should be able to select with tbl_name filter', async function() {
const result = await this.sequelize.query('SELECT * FROM sqlite_master WHERE tbl_name=\'SomeTable\'');
const rows = result[0];
expect(rows).to.have.length(1);
const row = rows[0];
expect(row).to.have.property('type', 'table');
expect(row).to.have.property('name', 'SomeTable');
expect(row).to.have.property('tbl_name', 'SomeTable');
expect(row).to.have.property('sql');
});
it('should be able to select *', function() {
return this.sequelize.query('SELECT * FROM sqlite_master')
.then(result => {
const rows = result[0];
expect(rows).to.have.length(2);
rows.forEach(row => {
expect(row).to.have.property('type');
expect(row).to.have.property('name');
expect(row).to.have.property('tbl_name');
expect(row).to.have.property('rootpage');
expect(row).to.have.property('sql');
});
});
it('should be able to select *', async function() {
const result = await this.sequelize.query('SELECT * FROM sqlite_master');
const rows = result[0];
expect(rows).to.have.length(2);
rows.forEach(row => {
expect(row).to.have.property('type');
expect(row).to.have.property('name');
expect(row).to.have.property('tbl_name');
expect(row).to.have.property('rootpage');
expect(row).to.have.property('sql');
});
});
it('should be able to select just "sql" column and get rows back', function() {
return this.sequelize.query('SELECT sql FROM sqlite_master WHERE tbl_name=\'SomeTable\'')
.then(result => {
const rows = result[0];
expect(rows).to.have.length(1);
const row = rows[0];
expect(row).to.have.property('sql',
'CREATE TABLE `SomeTable` (`id` INTEGER PRIMARY KEY AUTOINCREMENT, `someColumn` INTEGER)');
});
it('should be able to select just "sql" column and get rows back', async function() {
const result = await this.sequelize.query('SELECT sql FROM sqlite_master WHERE tbl_name=\'SomeTable\'');
const rows = result[0];
expect(rows).to.have.length(1);
const row = rows[0];
expect(row).to.have.property('sql',
'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!