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

Commit 891de8e1 by Simon Schick Committed by Sushant

refactor: cleanup association and spread use (#10276)

1 parent 66a45336
......@@ -56,7 +56,7 @@ User
},
true ]
In the example above, the "spread" on line 39 divides the array into its 2 parts and passes them as arguments to the callback function defined beginning at line 39, which treats them as "user" and "created" in this case. (So "user" will be the object from index 0 of the returned array and "created" will equal "true".)
In the example above, the array spread on line 3 divides the array into its 2 parts and passes them as arguments to the callback function defined beginning at line 39, which treats them as "user" and "created" in this case. (So "user" will be the object from index 0 of the returned array and "created" will equal "true".)
*/
})
```
......@@ -82,7 +82,7 @@ User.create({ username: 'fnord', job: 'omnomnom' })
},
false
]
The array returned by findOrCreate gets spread into its 2 parts by the "spread" on line 69, and the parts will be passed as 2 arguments to the callback function beginning on line 69, which will then treat them as "user" and "created" in this case. (So "user" will be the object from index 0 of the returned array and "created" will equal "false".)
The array returned by findOrCreate gets spread into its 2 parts by the array spread on line 3, and the parts will be passed as 2 arguments to the callback function beginning on line 69, which will then treat them as "user" and "created" in this case. (So "user" will be the object from index 0 of the returned array and "created" will equal "false".)
*/
})
```
......
......@@ -375,13 +375,12 @@ class BelongsToMany extends Association {
get(instance, options) {
options = Utils.cloneDeep(options) || {};
const association = this;
const through = association.through;
const through = this.through;
let scopeWhere;
let throughWhere;
if (association.scope) {
scopeWhere = _.clone(association.scope);
if (this.scope) {
scopeWhere = _.clone(this.scope);
}
options.where = {
......@@ -393,7 +392,7 @@ class BelongsToMany extends Association {
if (Object(through.model) === through.model) {
throughWhere = {};
throughWhere[association.foreignKey] = instance.get(association.source.primaryKeyAttribute);
throughWhere[this.foreignKey] = instance.get(this.source.primaryKeyAttribute);
if (through.scope) {
Object.assign(throughWhere, through.scope);
......@@ -408,14 +407,14 @@ class BelongsToMany extends Association {
options.include = options.include || [];
options.include.push({
association: association.oneFromTarget,
association: this.oneFromTarget,
attributes: options.joinTableAttributes,
required: true,
where: throughWhere
});
}
let model = association.target;
let model = this.target;
if (options.hasOwnProperty('scope')) {
if (!options.scope) {
model = model.unscoped();
......@@ -442,19 +441,18 @@ class BelongsToMany extends Association {
* @returns {Promise<number>}
*/
count(instance, options) {
const association = this;
const model = association.target;
const model = this.target;
const sequelize = model.sequelize;
options = Utils.cloneDeep(options);
options.attributes = [
[sequelize.fn('COUNT', sequelize.col([association.target.name, model.primaryKeyField].join('.'))), 'count']
[sequelize.fn('COUNT', sequelize.col([this.target.name, model.primaryKeyField].join('.'))), 'count']
];
options.joinTableAttributes = [];
options.raw = true;
options.plain = true;
return association.get(instance, options).then(result => parseInt(result.count, 10));
return this.get(instance, options).then(result => parseInt(result.count, 10));
}
/**
......@@ -467,7 +465,6 @@ class BelongsToMany extends Association {
* @returns {Promise<boolean>}
*/
has(sourceInstance, instances, options) {
const association = this;
const where = {};
if (!Array.isArray(instances)) {
......@@ -481,11 +478,11 @@ class BelongsToMany extends Association {
});
where[Op.or] = instances.map(instance => {
if (instance instanceof association.target) {
if (instance instanceof this.target) {
return instance.where();
}
return {
[association.target.primaryKeyAttribute]: instance
[this.target.primaryKeyAttribute]: instance
};
});
......@@ -496,7 +493,7 @@ class BelongsToMany extends Association {
]
};
return association.get(sourceInstance, options).then(associatedObjects => associatedObjects.length === instances.length);
return this.get(sourceInstance, options).then(associatedObjects => associatedObjects.length === instances.length);
}
/**
......@@ -514,21 +511,20 @@ class BelongsToMany extends Association {
set(sourceInstance, newAssociatedObjects, options) {
options = options || {};
const association = this;
const sourceKey = association.source.primaryKeyAttribute;
const targetKey = association.target.primaryKeyAttribute;
const identifier = association.identifier;
const foreignIdentifier = association.foreignIdentifier;
const sourceKey = this.source.primaryKeyAttribute;
const targetKey = this.target.primaryKeyAttribute;
const identifier = this.identifier;
const foreignIdentifier = this.foreignIdentifier;
let where = {};
if (newAssociatedObjects === null) {
newAssociatedObjects = [];
} else {
newAssociatedObjects = association.toInstanceArray(newAssociatedObjects);
newAssociatedObjects = this.toInstanceArray(newAssociatedObjects);
}
where[identifier] = sourceInstance.get(sourceKey);
where = Object.assign(where, association.through.scope);
where = Object.assign(where, this.through.scope);
const updateAssociations = currentRows => {
const obsoleteAssociations = [];
......@@ -536,7 +532,7 @@ class BelongsToMany extends Association {
const defaultAttributes = options.through || {};
const unassociatedObjects = newAssociatedObjects.filter(obj =>
!_.find(currentRows, currentRow => currentRow[foreignIdentifier] === obj.get(targetKey))
!currentRows.some(currentRow => currentRow[foreignIdentifier] === obj.get(targetKey))
);
for (const currentRow of currentRows) {
......@@ -545,30 +541,38 @@ class BelongsToMany extends Association {
if (!newObj) {
obsoleteAssociations.push(currentRow);
} else {
let throughAttributes = newObj[association.through.model.name];
let throughAttributes = newObj[this.through.model.name];
// Quick-fix for subtle bug when using existing objects that might have the through model attached (not as an attribute object)
if (throughAttributes instanceof association.through.model) {
if (throughAttributes instanceof this.through.model) {
throughAttributes = {};
}
const where = {};
const attributes = _.defaults({}, throughAttributes, defaultAttributes);
where[identifier] = sourceInstance.get(sourceKey);
where[foreignIdentifier] = newObj.get(targetKey);
if (Object.keys(attributes).length) {
promises.push(association.through.model.update(attributes, Object.assign(options, { where })));
promises.push(
this.through.model.update(attributes, Object.assign(options, {
where: {
[identifier]: sourceInstance.get(sourceKey),
[foreignIdentifier]: newObj.get(targetKey)
}
}
))
);
}
}
}
if (obsoleteAssociations.length > 0) {
let where = {};
where[identifier] = sourceInstance.get(sourceKey);
where[foreignIdentifier] = obsoleteAssociations.map(obsoleteAssociation => obsoleteAssociation[foreignIdentifier]);
where = Object.assign(where, association.through.scope);
promises.push(association.through.model.destroy(_.defaults({ where }, options)));
const where = Object.assign({
[identifier]: sourceInstance.get(sourceKey),
[foreignIdentifier]: obsoleteAssociations.map(obsoleteAssociation => obsoleteAssociation[foreignIdentifier])
}, this.through.scope);
promises.push(
this.through.model.destroy(_.defaults({
where
}, options))
);
}
if (unassociatedObjects.length > 0) {
......@@ -578,21 +582,21 @@ class BelongsToMany extends Association {
attributes[identifier] = sourceInstance.get(sourceKey);
attributes[foreignIdentifier] = unassociatedObject.get(targetKey);
attributes = _.defaults(attributes, unassociatedObject[association.through.model.name], defaultAttributes);
attributes = _.defaults(attributes, unassociatedObject[this.through.model.name], defaultAttributes);
Object.assign(attributes, association.through.scope);
attributes = Object.assign(attributes, association.through.scope);
Object.assign(attributes, this.through.scope);
attributes = Object.assign(attributes, this.through.scope);
return attributes;
});
promises.push(association.through.model.bulkCreate(bulk, Object.assign({ validate: true }, options)));
promises.push(this.through.model.bulkCreate(bulk, Object.assign({ validate: true }, options)));
}
return Utils.Promise.all(promises);
};
return association.through.model.findAll(_.defaults({ where, raw: true }, options))
return this.through.model.findAll(_.defaults({ where, raw: true }, options))
.then(currentRows => updateAssociations(currentRows))
.catch(error => {
if (error instanceof EmptyResultError) return updateAssociations([]);
......@@ -627,9 +631,10 @@ class BelongsToMany extends Association {
newInstances = association.toInstanceArray(newInstances);
const where = {};
where[identifier] = sourceInstance.get(sourceKey);
where[foreignIdentifier] = newInstances.map(newInstance => newInstance.get(targetKey));
const where = {
[identifier]: sourceInstance.get(sourceKey),
[foreignIdentifier]: newInstances.map(newInstance => newInstance.get(targetKey))
};
Object.assign(where, association.through.scope);
......@@ -638,7 +643,7 @@ class BelongsToMany extends Association {
const unassociatedObjects = [];
const changedAssociations = [];
for (const obj of newInstances) {
const existingAssociation = _.find(currentRows, current => current[foreignIdentifier] === obj.get(targetKey));
const existingAssociation = currentRows && currentRows.find(current => current[foreignIdentifier] === obj.get(targetKey));
if (!existingAssociation) {
unassociatedObjects.push(obj);
......@@ -671,14 +676,15 @@ class BelongsToMany extends Association {
for (const assoc of changedAssociations) {
let throughAttributes = assoc[association.through.model.name];
const attributes = _.defaults({}, throughAttributes, defaultAttributes);
const where = {};
// Quick-fix for subtle bug when using existing objects that might have the through model attached (not as an attribute object)
if (throughAttributes instanceof association.through.model) {
throughAttributes = {};
}
const where = {
[identifier]: sourceInstance.get(sourceKey),
[foreignIdentifier]: assoc.get(targetKey)
};
where[identifier] = sourceInstance.get(sourceKey);
where[foreignIdentifier] = assoc.get(targetKey);
promises.push(association.through.model.update(attributes, Object.assign(options, { where })));
}
......@@ -711,9 +717,10 @@ class BelongsToMany extends Association {
oldAssociatedObjects = association.toInstanceArray(oldAssociatedObjects);
const where = {};
where[association.identifier] = sourceInstance.get(association.source.primaryKeyAttribute);
where[association.foreignIdentifier] = oldAssociatedObjects.map(newInstance => newInstance.get(association.target.primaryKeyAttribute));
const where = {
[association.identifier]: sourceInstance.get(association.source.primaryKeyAttribute),
[association.foreignIdentifier]: oldAssociatedObjects.map(newInstance => newInstance.get(association.target.primaryKeyAttribute))
};
return association.through.model.destroy(_.defaults({ where }, options));
}
......
......@@ -342,11 +342,12 @@ class HasMany extends Association {
update = {};
update[this.foreignKey] = null;
updateWhere = {};
updateWhere = {
[this.target.primaryKeyAttribute]: obsoleteAssociations.map(associatedObject =>
associatedObject[this.target.primaryKeyAttribute]
)
};
updateWhere[this.target.primaryKeyAttribute] = obsoleteAssociations.map(associatedObject =>
associatedObject[this.target.primaryKeyAttribute]
);
promises.push(this.target.unscoped().update(
update,
......@@ -393,16 +394,17 @@ class HasMany extends Association {
if (!targetInstances) return Utils.Promise.resolve();
const update = {};
const where = {};
targetInstances = this.toInstanceArray(targetInstances);
update[this.foreignKey] = sourceInstance.get(this.sourceKey);
Object.assign(update, this.scope);
where[this.target.primaryKeyAttribute] = targetInstances.map(unassociatedObject =>
unassociatedObject.get(this.target.primaryKeyAttribute)
);
const where = {
[this.target.primaryKeyAttribute]: targetInstances.map(unassociatedObject =>
unassociatedObject.get(this.target.primaryKeyAttribute)
)
};
return this.target.unscoped().update(update, _.defaults({ where }, options)).return(sourceInstance);
}
......@@ -417,17 +419,18 @@ class HasMany extends Association {
* @returns {Promise}
*/
remove(sourceInstance, targetInstances, options = {}) {
const update = {};
const where = {};
const update = {
[this.foreignKey]: null
};
targetInstances = this.toInstanceArray(targetInstances);
update[this.foreignKey] = null;
where[this.foreignKey] = sourceInstance.get(this.sourceKey);
where[this.target.primaryKeyAttribute] = targetInstances.map(targetInstance =>
targetInstance.get(this.target.primaryKeyAttribute)
);
const where = {
[this.foreignKey]: sourceInstance.get(this.sourceKey),
[this.target.primaryKeyAttribute]: targetInstances.map(targetInstance =>
targetInstance.get(this.target.primaryKeyAttribute)
)
};
return this.target.unscoped().update(update, _.defaults({ where }, options)).return(this);
}
......
......@@ -198,7 +198,7 @@ class HasOne extends Association {
return sourceInstance[this.accessors.get](options).then(oldInstance => {
// TODO Use equals method once #5605 is resolved
alreadyAssociated = oldInstance && associatedInstance && _.every(this.target.primaryKeyAttributes, attribute =>
alreadyAssociated = oldInstance && associatedInstance && this.target.primaryKeyAttributes.every(attribute =>
oldInstance.get(attribute, { raw: true }) === (associatedInstance.get ? associatedInstance.get(attribute, { raw: true }) : associatedInstance)
);
......
......@@ -1126,7 +1126,7 @@ class QueryGenerator {
if (subQuery && attributes.main) {
for (const keyAtt of mainTable.model.primaryKeyAttributes) {
// Check if mainAttributes contain the primary key of the model either as a field or an aliased field
if (!_.find(attributes.main, attr => keyAtt === attr || keyAtt === attr[0] || keyAtt === attr[1])) {
if (!attributes.main.some(attr => keyAtt === attr || keyAtt === attr[0] || keyAtt === attr[1])) {
attributes.main.push(mainTable.model.rawAttributes[keyAtt].field ? [keyAtt, mainTable.model.rawAttributes[keyAtt].field] : keyAtt);
}
}
......@@ -2217,8 +2217,9 @@ class QueryGenerator {
}
Utils.getOperators(value).forEach(op => {
const where = {};
where[op] = value[op];
const where = {
[op]: value[op]
};
items.push(this.whereItemQuery(key, where, Object.assign({}, options, { json: false })));
});
......
......@@ -48,10 +48,7 @@ class ConnectionManager extends AbstractConnectionManager {
if (config.dialectOptions.domain) {
connectionConfig.domain = config.dialectOptions.domain;
}
for (const key of Object.keys(config.dialectOptions)) {
connectionConfig.options[key] = config.dialectOptions[key];
}
Object.assign(connectionConfig.options, config.dialectOptions);
}
return new Promise((resolve, reject) => {
......
......@@ -53,7 +53,7 @@ class ConnectionManager extends AbstractConnectionManager {
* @private
*/
connect(config) {
const connectionConfig = {
const connectionConfig = Object.assign({
host: config.host,
port: config.port,
user: config.username,
......@@ -64,13 +64,7 @@ class ConnectionManager extends AbstractConnectionManager {
typeCast: ConnectionManager._typecast.bind(this),
bigNumberStrings: false,
supportBigNumbers: true
};
if (config.dialectOptions) {
for (const key of Object.keys(config.dialectOptions)) {
connectionConfig[key] = config.dialectOptions[key];
}
}
}, config.dialectOptions);
return new Promise((resolve, reject) => {
const connection = this.lib.createConnection(connectionConfig);
......
......@@ -286,9 +286,8 @@ class Model {
if (definition && definition.autoIncrement) {
if (this.autoIncrementAttribute) {
throw new Error('Invalid Instance definition. Only one autoincrement field allowed.');
} else {
this.autoIncrementAttribute = name;
}
this.autoIncrementAttribute = name;
}
}
}
......@@ -444,7 +443,7 @@ class Model {
predicate.as = as;
}
if (_.find(includes, predicate)) {
if (_.some(includes, predicate)) {
return;
}
......@@ -576,7 +575,7 @@ class Model {
if (include.attributes.length) {
_.each(include.model.primaryKeys, (attr, key) => {
// Include the primary key if it's not already included - take into account that the pk might be aliased (due to a .field prop)
if (!_.some(include.attributes, includeAttr => {
if (!include.attributes.some(includeAttr => {
if (attr.field !== key) {
return Array.isArray(includeAttr) && includeAttr[0] === attr.field && includeAttr[1] === key;
}
......@@ -1848,8 +1847,9 @@ class Model {
options = Utils.cloneDeep(options) || {};
if (typeof param === 'number' || typeof param === 'string' || Buffer.isBuffer(param)) {
options.where = {};
options.where[this.primaryKeyAttribute] = param;
options.where = {
[this.primaryKeyAttribute]: param
};
} else {
throw new Error(`Argument passed to findByPk is invalid: ${param}`);
}
......@@ -2716,9 +2716,10 @@ class Model {
const attrValueHash = {};
const deletedAtAttribute = this.rawAttributes[this._timestampAttributes.deletedAt];
const field = this.rawAttributes[this._timestampAttributes.deletedAt].field;
const where = {};
const where = {
[field]: deletedAtAttribute.hasOwnProperty('defaultValue') ? deletedAtAttribute.defaultValue : null
};
where[field] = deletedAtAttribute.hasOwnProperty('defaultValue') ? deletedAtAttribute.defaultValue : null;
attrValueHash[field] = Utils.now(this.sequelize.options.dialect);
return this.QueryInterface.bulkUpdate(this.getTableName(options), attrValueHash, Object.assign(where, options.where), options, this.rawAttributes);
......@@ -4142,18 +4143,18 @@ class Model {
return false;
}
return _.every(this.constructor.primaryKeyAttributes, attribute => this.get(attribute, { raw: true }) === other.get(attribute, { raw: true }));
return this.constructor.primaryKeyAttributes.every(attribute => this.get(attribute, { raw: true }) === other.get(attribute, { raw: true }));
}
/**
* Check if this is equal to one of `others` by calling equals
*
* @param {Array<<Model>>} others An array of instances to check against
* @param {Array<Model>} others An array of instances to check against
*
* @returns {boolean}
*/
equalsOneOf(others) {
return _.some(others, other => this.equals(other));
return others.some(other => this.equals(other));
}
setValidators(attribute, validators) {
......
......@@ -421,7 +421,7 @@ class Sequelize {
*
* ```js
* sequelize.query('SELECT...').then(([results, metadata]) => {
* // Raw query - use spread
* // Raw query - use then plus array spread
* });
*
* sequelize.query('SELECT...', { type: sequelize.QueryTypes.SELECT }).then(results => {
......
......@@ -1106,8 +1106,8 @@ describe(Support.getTestDialectTeaser('BelongsToMany'), () => {
return user.getTasks();
}).then(tasks => {
expect(tasks).to.have.length(2);
expect(_.find(tasks, item => { return item.title === 'get started'; })).to.be.ok;
expect(_.find(tasks, item => { return item.title === 'get done'; })).to.be.ok;
expect(tasks.some(item => { return item.title === 'get started'; })).to.be.ok;
expect(tasks.some(item => { return item.title === 'get done'; })).to.be.ok;
});
});
......
......@@ -495,7 +495,7 @@ describe(Support.getTestDialectTeaser('DataTypes'), () => {
return Model.sync({ force: true })
.then(() => Model.create({ interval: [1, 4] }) )
.then(() => Model.findAll() )
.spread(m => {
.then(([m]) => {
expect(m.interval[0].value).to.be.eql(1);
expect(m.interval[1].value).to.be.eql(4);
});
......
......@@ -14,14 +14,13 @@ describe('[MariaDB Specific] Associations', () => {
it('should create a table wp_table1wp_table2s', function() {
const Table2 = this.sequelize.define('wp_table2', { foo: DataTypes.STRING }),
Table1 = this.sequelize.define('wp_table1',
{ foo: DataTypes.STRING }),
self = this;
{ 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(self.sequelize.modelManager.getModel(
expect(this.sequelize.modelManager.getModel(
'wp_table1swp_table2s')).to.exist;
});
});
......@@ -61,21 +60,17 @@ describe('[MariaDB Specific] Associations', () => {
this.User.belongsToMany(this.Task, { as: 'Tasks', through: 'UserTasks' });
this.Task.belongsToMany(this.User, { as: 'Users', through: 'UserTasks' });
const self = this,
users = [],
tasks = [];
const users = [];
const tasks = [];
for (let i = 0; i < 5; ++i) {
users[users.length] = { name: `User${Math.random()}` };
}
for (let x = 0; x < 5; ++x) {
tasks[tasks.length] = { name: `Task${Math.random()}` };
users[i] = { name: `User${Math.random()}` };
tasks[i] = { name: `Task${Math.random()}` };
}
return this.sequelize.sync({ force: true })
.then(() => self.User.bulkCreate(users))
.then(() => self.Task.bulkCreate(tasks));
.then(() => this.User.bulkCreate(users))
.then(() => this.Task.bulkCreate(tasks));
});
......
......@@ -34,28 +34,27 @@ describe('[MariaDB Specific] Errors', () => {
});
it('in context of DELETE restriction', function() {
const self = this,
ForeignKeyConstraintError = this.sequelize.ForeignKeyConstraintError;
return this.sequelize.sync({ force: true }).bind({}).then(() => {
const ForeignKeyConstraintError = this.sequelize.ForeignKeyConstraintError;
const ctx = {};
return this.sequelize.sync({ force: true }).then(() => {
return Promise.all([
self.User.create({ id: 67, username: 'foo' }),
self.Task.create({ id: 52, title: 'task' })
this.User.create({ id: 67, username: 'foo' }),
this.Task.create({ id: 52, title: 'task' })
]);
}).spread(function(user1, task1) {
this.user1 = user1;
this.task1 = task1;
}).then(([user1, task1]) => {
ctx.user1 = user1;
ctx.task1 = task1;
return user1.setTasks([task1]);
}).then(function() {
}).then(() => {
return Promise.all([
validateError(this.user1.destroy(), ForeignKeyConstraintError, {
validateError(ctx.user1.destroy(), ForeignKeyConstraintError, {
fields: ['userId'],
table: 'users',
value: undefined,
index: 'tasksusers_ibfk_1',
reltype: 'parent'
}),
validateError(this.task1.destroy(), ForeignKeyConstraintError, {
validateError(ctx.task1.destroy(), ForeignKeyConstraintError, {
fields: ['taskId'],
table: 'tasks',
value: undefined,
......@@ -67,11 +66,10 @@ describe('[MariaDB Specific] Errors', () => {
});
it('in context of missing relation', function() {
const self = this,
ForeignKeyConstraintError = this.sequelize.ForeignKeyConstraintError;
const ForeignKeyConstraintError = this.sequelize.ForeignKeyConstraintError;
return this.sequelize.sync({ force: true }).then(() =>
validateError(self.Task.create({ title: 'task', primaryUserId: 5 }),
validateError(this.Task.create({ title: 'task', primaryUserId: 5 }),
ForeignKeyConstraintError, {
fields: ['primaryUserId'],
table: 'users',
......
......@@ -58,11 +58,8 @@ if (dialect === 'mysql') {
tasks = [];
for (let i = 0; i < 5; ++i) {
users[users.length] = { name: `User${Math.random()}` };
}
for (let x = 0; x < 5; ++x) {
tasks[tasks.length] = { name: `Task${Math.random()}` };
users[i] = { name: `User${Math.random()}` };
tasks[i] = { name: `Task${Math.random()}` };
}
return this.sequelize.sync({ force: true }).then(() => {
......
......@@ -20,7 +20,7 @@ if (dialect === 'mysql') {
}
}))
// https://github.com/sequelize/sequelize/issues/7184
.spread(affectedCount => affectedCount.should.equal(1));
.then(([affectedCount]) => affectedCount.should.equal(1));
});
it('should acquire a valid connection when keepDefaultTimezone is true', () => {
......
......@@ -57,11 +57,8 @@ if (dialect.match(/^postgres/)) {
tasks = [];
for (let i = 0; i < 5; ++i) {
users[users.length] = { name: `User${Math.random()}` };
}
for (let x = 0; x < 5; ++x) {
tasks[tasks.length] = { name: `Task${Math.random()}` };
users[i] = { name: `User${Math.random()}` };
tasks[i] = { name: `Task${Math.random()}` };
}
return this.sequelize.sync({ force: true }).then(() => {
......@@ -105,11 +102,8 @@ if (dialect.match(/^postgres/)) {
this.Task.belongsToMany(this.User, { as: 'Users', through: 'usertasks' });
for (let i = 0; i < 5; ++i) {
users[users.length] = { id: i + 1, name: `User${Math.random()}` };
}
for (let x = 0; x < 5; ++x) {
tasks[tasks.length] = { id: x + 1, name: `Task${Math.random()}` };
users[i] = { id: i + 1, name: `User${Math.random()}` };
tasks[i] = { id: i + 1, name: `Task${Math.random()}` };
}
return this.sequelize.sync({ force: true }).then(() => {
......
......@@ -469,7 +469,7 @@ describe(Support.getTestDialectTeaser('Includes with schemas'), () => {
users[2].setItemB(items[3]),
users[2].setOrder(orders[0])
]);
}).spread(() => {
}).then(() => {
return User.findAll({
'include': [
{ 'model': Item, 'as': 'itemA', where: { test: 'abc' } },
......@@ -515,7 +515,7 @@ describe(Support.getTestDialectTeaser('Includes with schemas'), () => {
{ name: 'B' },
{ name: 'C' }
])
]).spread(() => {
]).then(() => {
return Promise.all([
Product.findAll(),
Tag.findAll()
......@@ -529,7 +529,7 @@ describe(Support.getTestDialectTeaser('Includes with schemas'), () => {
products[2].addTag(tags[1], { through: { priority: 1 } }),
products[2].addTag(tags[2], { through: { priority: 2 } })
]);
}).spread(() => {
}).then(() => {
return Product.findAll({
include: [
{ model: Tag }
......
......@@ -106,7 +106,7 @@ describe(Support.getTestDialectTeaser('Instance'), () => {
const users = [];
for (let i = 0; i < 10; i++) {
users[users.length] = { username: 'user' };
users[i] = { username: 'user' };
}
return this.User.bulkCreate(users).then(() => {
......
......@@ -443,7 +443,7 @@ describe(Support.getTestDialectTeaser('DAO'), () => {
expect(user.changed()).not.to.be.ok;
});
}).then(() => {
return User.bulkCreate([{ name: 'Jan Meier' }]).spread(user => {
return User.bulkCreate([{ name: 'Jan Meier' }]).then(([user]) => {
expect(user.changed('name')).to.be.false;
expect(user.changed()).not.to.be.ok;
});
......
......@@ -740,16 +740,16 @@ describe(Support.getTestDialectTeaser('Model'), () => {
return User.create({ username: 'foo' }, { transaction: t }).then(() => {
return User.findOrBuild({
where: { username: 'foo' }
}).spread(user1 => {
}).then(([user1]) => {
return User.findOrBuild({
where: { username: 'foo' },
transaction: t
}).spread(user2 => {
}).then(([user2]) => {
return User.findOrBuild({
where: { username: 'foo' },
defaults: { foo: 'asd' },
transaction: t
}).spread(user3 => {
}).then(([user3]) => {
expect(user1.isNewRecord).to.be.true;
expect(user2.isNewRecord).to.be.false;
expect(user3.isNewRecord).to.be.false;
......@@ -999,7 +999,7 @@ describe(Support.getTestDialectTeaser('Model'), () => {
});
}).then(() => {
return User.findAll();
}).spread(user => {
}).then(([user]) => {
expect(user.username).to.equal('kurt');
});
});
......@@ -1035,7 +1035,7 @@ describe(Support.getTestDialectTeaser('Model'), () => {
});
}).then(() => {
return User.findAll();
}).spread(user => {
}).then(([user]) => {
expect(user.illness_pain).to.be.equal(5);
});
});
......@@ -1070,7 +1070,7 @@ describe(Support.getTestDialectTeaser('Model'), () => {
});
}).then(() => {
return User.findAll();
}).spread(user => {
}).then(([user]) => {
expect(user.illness_pain).to.be.equal(10);
});
});
......@@ -1123,10 +1123,10 @@ describe(Support.getTestDialectTeaser('Model'), () => {
{ username: 'Bob', secretValue: '43' }];
return this.User.bulkCreate(data).then(() => {
return this.User.update({ username: 'Bill' }, { where: { secretValue: '42' } }).spread(affectedRows => {
return this.User.update({ username: 'Bill' }, { where: { secretValue: '42' } }).then(([affectedRows]) => {
expect(affectedRows).to.equal(2);
}).then(() => {
return this.User.update({ username: 'Bill' }, { where: { secretValue: '44' } }).spread(affectedRows => {
return this.User.update({ username: 'Bill' }, { where: { secretValue: '44' } }).then(([affectedRows]) => {
expect(affectedRows).to.equal(0);
});
});
......@@ -1221,7 +1221,7 @@ describe(Support.getTestDialectTeaser('Model'), () => {
{ username: 'Peter', secretValue: '42' }];
return this.User.bulkCreate(data).then(() => {
return this.User.update({ secretValue: '43' }, { where: { username: 'Peter' }, limit: 1 }).spread(affectedRows => {
return this.User.update({ secretValue: '43' }, { where: { username: 'Peter' }, limit: 1 }).then(([affectedRows]) => {
expect(affectedRows).to.equal(1);
});
});
......@@ -1607,7 +1607,7 @@ describe(Support.getTestDialectTeaser('Model'), () => {
return User.destroy({ where: { username: ['Tony', 'Max'] }, force: true });
}).then(() => {
return this.sequelize.query('SELECT * FROM paranoidusers', { raw: true });
}).spread(users => {
}).then(([users]) => {
expect(users).to.have.length(1);
expect(users[0].username).to.equal('Tobi');
});
......
......@@ -612,7 +612,7 @@ describe(Support.getTestDialectTeaser('Model'), () => {
expect(m.secret).to.be.eql(M1.secret);
return Maya.bulkCreate([M2]);
}).spread(m => {
}).then(([m]) => {
// only attributes are returned, no fields are mixed
expect(m.createdAt).to.be.ok;
......
......@@ -355,13 +355,13 @@ describe(Support.getTestDialectTeaser('Model'), () => {
return this.User.findOrCreate({
where: data,
defaults: {}
}).spread(user => {
}).then(([user]) => {
expect(user.dataValues.sequelize_caught_exception).to.be.undefined;
}).then(() => {
return this.User.findOrCreate({
where: data,
defaults: {}
}).spread(user => {
}).then(([user]) => {
expect(user.dataValues.sequelize_caught_exception).to.be.undefined;
});
});
......
......@@ -34,7 +34,7 @@ describe(Support.getTestDialectTeaser('Model'), () => {
project.addLevelTwo(level21),
project.addLevelTwo(level22)
]);
}).spread(() => {
}).then(() => {
// one include case
return Project.findAll({
where: { name: 'testProject' },
......
......@@ -115,7 +115,7 @@ describe(Support.getTestDialectTeaser('Model'), () => {
});
it('should have no problem performing findOrCreate', function() {
return this.ScopeMe.findOrCreate({ where: { username: 'fake' } }).spread(user => {
return this.ScopeMe.findOrCreate({ where: { username: 'fake' } }).then(([user]) => {
expect(user.username).to.equal('fake');
});
});
......
......@@ -435,7 +435,7 @@ describe(Support.getTestDialectTeaser('QueryInterface'), () => {
this.queryInterface.QueryGenerator.getForeignKeyQuery('hosts', 'admin'),
{}
)
.spread(fk => {
.then(([fk]) => {
expect(fks[0]).to.deep.eql(fk[0]);
});
}
......
......@@ -326,7 +326,7 @@ describe(Support.getTestDialectTeaser('Sequelize'), () => {
it('executes select queries correctly', function() {
return this.sequelize.query(this.insertQuery).then(() => {
return this.sequelize.query(`select * from ${qq(this.User.tableName)}`);
}).spread(users => {
}).then(([users]) => {
expect(users.map(u => { return u.username; })).to.include('john');
});
});
......@@ -337,7 +337,7 @@ describe(Support.getTestDialectTeaser('Sequelize'), () => {
seq.options.quoteIdentifiers = false;
return seq.query(this.insertQuery).then(() => {
return seq.query(`select * from ${qq(this.User.tableName)}`);
}).spread(users => {
}).then(([users]) => {
expect(users.map(u => { return u.username; })).to.include('john');
});
});
......@@ -347,7 +347,7 @@ describe(Support.getTestDialectTeaser('Sequelize'), () => {
return this.sequelize.query(this.insertQuery);
}).then(() => {
return this.sequelize.query(`select username as ${qq('user.username')} from ${qq(this.User.tableName)}`);
}).spread(users => {
}).then(([users]) => {
expect(users).to.deep.equal([{ 'user.username': 'john' }]);
});
});
......@@ -715,7 +715,7 @@ describe(Support.getTestDialectTeaser('Sequelize'), () => {
datetime = 'GETDATE()';
}
return this.sequelize.query(`SELECT ${datetime} AS t`).spread(result => {
return this.sequelize.query(`SELECT ${datetime} AS t`).then(([result]) => {
expect(moment(result[0].t).isValid()).to.be.true;
});
});
......
......@@ -179,7 +179,7 @@ describe(Support.getTestDialectTeaser('Utils'), () => {
}
}, type)), 'count-engines-wings']
]
}).spread(airplane => {
}).then(([airplane]) => {
expect(parseInt(airplane.get('count'))).to.equal(3);
expect(parseInt(airplane.get('count-engines'))).to.equal(1);
expect(parseInt(airplane.get('count-engines-wings'))).to.equal(2);
......@@ -204,7 +204,7 @@ describe(Support.getTestDialectTeaser('Utils'), () => {
}
}), 'count-engines-wings']
]
}).spread(airplane => {
}).then(([airplane]) => {
expect(parseInt(airplane.get('count'))).to.equal(3);
expect(parseInt(airplane.get('count-engines'))).to.equal(1);
expect(parseInt(airplane.get('count-engines-wings'))).to.equal(2);
......
......@@ -146,15 +146,16 @@ describe(Support.getTestDialectTeaser('hasMany'), () => {
it('should fetch associations for a single instance', () => {
const findAll = stub(Task, 'findAll').returns(Promise.resolve([
Task.build({}),
Task.build({})
])),
where = {};
Task.build({}),
Task.build({})
]));
User.Tasks = User.hasMany(Task, { foreignKey });
const actual = User.Tasks.get(User.build({ id: idA }));
where[foreignKey] = idA;
const where = {
[foreignKey]: idA
};
expect(findAll).to.have.been.calledOnce;
expect(findAll.firstCall.args[0].where).to.deep.equal(where);
......
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!