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

Commit 891de8e1 by Simon Schick Committed by Sushant

refactor: cleanup association and spread use (#10276)

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