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

Commit 783fc806 by Simon Schick Committed by Sushant

chore: replace lodash and es5 constructs to use es6 (#10043)

1 parent 08ab29cd
...@@ -181,8 +181,7 @@ Task.bulkCreate([ ...@@ -181,8 +181,7 @@ Task.bulkCreate([
{ status: 'inactive' }, /* set attributes' value */ { status: 'inactive' }, /* set attributes' value */
{ where: { subject: 'programming' }} /* where criteria */ { where: { subject: 'programming' }} /* where criteria */
); );
}).spread((affectedCount, affectedRows) => { }).then(([affectedCount, affectedRows]) => {
// .update returns two values in an array, therefore we use .spread
// Notice that affectedRows will only be defined in dialects which support returning: true // Notice that affectedRows will only be defined in dialects which support returning: true
// affectedCount will be 2 // affectedCount will be 2
......
...@@ -793,4 +793,3 @@ sequelize.define('user', {}, { ...@@ -793,4 +793,3 @@ sequelize.define('user', {}, {
[0]: /manual/tutorial/models-definition.html#configuration [0]: /manual/tutorial/models-definition.html#configuration
[3]: https://github.com/chriso/validator.js [3]: https://github.com/chriso/validator.js
[5]: /docs/final/misc#asynchronicity [5]: /docs/final/misc#asynchronicity
[6]: http://bluebirdjs.com/docs/api/spread.html
...@@ -38,7 +38,7 @@ Let's assume we have an empty database with a `User` model which has a `username ...@@ -38,7 +38,7 @@ Let's assume we have an empty database with a `User` model which has a `username
```js ```js
User User
.findOrCreate({where: {username: 'sdepold'}, defaults: {job: 'Technical Lead JavaScript'}}) .findOrCreate({where: {username: 'sdepold'}, defaults: {job: 'Technical Lead JavaScript'}})
.spread((user, created) => { .then(([user, created]) => {
console.log(user.get({ console.log(user.get({
plain: true plain: true
})) }))
...@@ -65,7 +65,7 @@ The code created a new instance. So when we already have an instance ... ...@@ -65,7 +65,7 @@ The code created a new instance. So when we already have an instance ...
```js ```js
User.create({ username: 'fnord', job: 'omnomnom' }) User.create({ username: 'fnord', job: 'omnomnom' })
.then(() => User.findOrCreate({where: {username: 'fnord'}, defaults: {job: 'something else'}})) .then(() => User.findOrCreate({where: {username: 'fnord'}, defaults: {job: 'something else'}}))
.spread((user, created) => { .then(([user, created]) => {
console.log(user.get({ console.log(user.get({
plain: true plain: true
})) }))
......
...@@ -5,7 +5,7 @@ As there are often use cases in which it is just easier to execute raw / already ...@@ -5,7 +5,7 @@ As there are often use cases in which it is just easier to execute raw / already
By default the function will return two arguments - a results array, and an object containing metadata (affected rows etc.). Note that since this is a raw query, the metadata (property names etc.) is dialect specific. Some dialects return the metadata "within" the results object (as properties on an array). However, two arguments will always be returned, but for MSSQL and MySQL it will be two references to the same object. By default the function will return two arguments - a results array, and an object containing metadata (affected rows etc.). Note that since this is a raw query, the metadata (property names etc.) is dialect specific. Some dialects return the metadata "within" the results object (as properties on an array). However, two arguments will always be returned, but for MSSQL and MySQL it will be two references to the same object.
```js ```js
sequelize.query("UPDATE users SET y = 42 WHERE x = 12").spread((results, metadata) => { sequelize.query("UPDATE users SET y = 42 WHERE x = 12").then(([results, metadata]) => {
// Results will be an empty array and metadata will contain the number of affected rows. // Results will be an empty array and metadata will contain the number of affected rows.
}) })
``` ```
......
...@@ -121,7 +121,7 @@ Project.scope('defaultScope', 'deleted').findAll(); ...@@ -121,7 +121,7 @@ Project.scope('defaultScope', 'deleted').findAll();
SELECT * FROM projects WHERE active = true AND deleted = true SELECT * FROM projects WHERE active = true AND deleted = true
``` ```
When invoking several scopes, keys from subsequent scopes will overwrite previous ones (similar to [_.assign](https://lodash.com/docs#assign)). Consider two scopes: When invoking several scopes, keys from subsequent scopes will overwrite previous ones (similar to [Object.assign](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/assign). Consider two scopes:
```js ```js
{ {
......
...@@ -73,7 +73,7 @@ class BelongsToMany extends Association { ...@@ -73,7 +73,7 @@ class BelongsToMany extends Association {
this.associationType = 'BelongsToMany'; this.associationType = 'BelongsToMany';
this.targetAssociation = null; this.targetAssociation = null;
this.sequelize = source.sequelize; this.sequelize = source.sequelize;
this.through = _.assign({}, this.options.through); this.through = Object.assign({}, this.options.through);
this.isMultiAssociation = true; this.isMultiAssociation = true;
this.doubleLinked = false; this.doubleLinked = false;
...@@ -162,7 +162,7 @@ class BelongsToMany extends Association { ...@@ -162,7 +162,7 @@ class BelongsToMany extends Association {
if (typeof this.through.model === 'string') { if (typeof this.through.model === 'string') {
if (!this.sequelize.isDefined(this.through.model)) { if (!this.sequelize.isDefined(this.through.model)) {
this.through.model = this.sequelize.define(this.through.model, {}, _.extend(this.options, { this.through.model = this.sequelize.define(this.through.model, {}, Object.assign(this.options, {
tableName: this.through.model, tableName: this.through.model,
indexes: [], //we don't want indexes here (as referenced in #2416) indexes: [], //we don't want indexes here (as referenced in #2416)
paranoid: false, // A paranoid join table does not make sense paranoid: false, // A paranoid join table does not make sense
...@@ -297,8 +297,8 @@ class BelongsToMany extends Association { ...@@ -297,8 +297,8 @@ class BelongsToMany extends Association {
if (!targetAttribute.onUpdate) targetAttribute.onUpdate = 'CASCADE'; if (!targetAttribute.onUpdate) targetAttribute.onUpdate = 'CASCADE';
} }
this.through.model.rawAttributes[this.foreignKey] = _.extend(this.through.model.rawAttributes[this.foreignKey], sourceAttribute); this.through.model.rawAttributes[this.foreignKey] = Object.assign(this.through.model.rawAttributes[this.foreignKey], sourceAttribute);
this.through.model.rawAttributes[this.otherKey] = _.extend(this.through.model.rawAttributes[this.otherKey], targetAttribute); this.through.model.rawAttributes[this.otherKey] = Object.assign(this.through.model.rawAttributes[this.otherKey], targetAttribute);
this.through.model.refreshAttributes(); this.through.model.refreshAttributes();
...@@ -396,7 +396,7 @@ class BelongsToMany extends Association { ...@@ -396,7 +396,7 @@ class BelongsToMany extends Association {
throughWhere[association.foreignKey] = instance.get(association.source.primaryKeyAttribute); throughWhere[association.foreignKey] = instance.get(association.source.primaryKeyAttribute);
if (through.scope) { if (through.scope) {
_.assign(throughWhere, through.scope); Object.assign(throughWhere, through.scope);
} }
//If a user pass a where on the options through options, make an "and" with the current throughWhere //If a user pass a where on the options through options, make an "and" with the current throughWhere
...@@ -474,7 +474,7 @@ class BelongsToMany extends Association { ...@@ -474,7 +474,7 @@ class BelongsToMany extends Association {
instances = [instances]; instances = [instances];
} }
options = _.assign({ options = Object.assign({
raw: true raw: true
}, options, { }, options, {
scope: false scope: false
...@@ -562,7 +562,7 @@ class BelongsToMany extends Association { ...@@ -562,7 +562,7 @@ class BelongsToMany extends Association {
where[foreignIdentifier] = newObj.get(targetKey); where[foreignIdentifier] = newObj.get(targetKey);
if (Object.keys(attributes).length) { if (Object.keys(attributes).length) {
promises.push(association.through.model.update(attributes, _.extend(options, {where}))); promises.push(association.through.model.update(attributes, Object.assign(options, {where})));
} }
} }
} }
...@@ -584,13 +584,13 @@ class BelongsToMany extends Association { ...@@ -584,13 +584,13 @@ class BelongsToMany extends Association {
attributes = _.defaults(attributes, unassociatedObject[association.through.model.name], defaultAttributes); attributes = _.defaults(attributes, unassociatedObject[association.through.model.name], defaultAttributes);
_.assign(attributes, association.through.scope); Object.assign(attributes, association.through.scope);
attributes = Object.assign(attributes, association.through.scope); attributes = Object.assign(attributes, association.through.scope);
return attributes; return attributes;
}); });
promises.push(association.through.model.bulkCreate(bulk, _.assign({ validate: true }, options))); promises.push(association.through.model.bulkCreate(bulk, Object.assign({ validate: true }, options)));
} }
return Utils.Promise.all(promises); return Utils.Promise.all(promises);
...@@ -635,7 +635,7 @@ class BelongsToMany extends Association { ...@@ -635,7 +635,7 @@ class BelongsToMany extends Association {
where[identifier] = sourceInstance.get(sourceKey); where[identifier] = sourceInstance.get(sourceKey);
where[foreignIdentifier] = newInstances.map(newInstance => newInstance.get(targetKey)); where[foreignIdentifier] = newInstances.map(newInstance => newInstance.get(targetKey));
_.assign(where, association.through.scope); Object.assign(where, association.through.scope);
const updateAssociations = currentRows => { const updateAssociations = currentRows => {
const promises = []; const promises = [];
...@@ -664,12 +664,12 @@ class BelongsToMany extends Association { ...@@ -664,12 +664,12 @@ class BelongsToMany extends Association {
attributes[identifier] = sourceInstance.get(sourceKey); attributes[identifier] = sourceInstance.get(sourceKey);
attributes[foreignIdentifier] = unassociatedObject.get(targetKey); attributes[foreignIdentifier] = unassociatedObject.get(targetKey);
_.assign(attributes, association.through.scope); Object.assign(attributes, association.through.scope);
return attributes; return attributes;
}); });
promises.push(association.through.model.bulkCreate(bulk, _.assign({ validate: true }, options))); promises.push(association.through.model.bulkCreate(bulk, Object.assign({ validate: true }, options)));
} }
for (const assoc of changedAssociations) { for (const assoc of changedAssociations) {
...@@ -684,7 +684,7 @@ class BelongsToMany extends Association { ...@@ -684,7 +684,7 @@ class BelongsToMany extends Association {
where[identifier] = sourceInstance.get(sourceKey); where[identifier] = sourceInstance.get(sourceKey);
where[foreignIdentifier] = assoc.get(targetKey); where[foreignIdentifier] = assoc.get(targetKey);
promises.push(association.through.model.update(attributes, _.extend(options, {where}))); promises.push(association.through.model.update(attributes, Object.assign(options, {where})));
} }
return Utils.Promise.all(promises); return Utils.Promise.all(promises);
...@@ -692,7 +692,7 @@ class BelongsToMany extends Association { ...@@ -692,7 +692,7 @@ class BelongsToMany extends Association {
return association.through.model.findAll(_.defaults({where, raw: true}, options)) return association.through.model.findAll(_.defaults({where, raw: true}, options))
.then(currentRows => updateAssociations(currentRows)) .then(currentRows => updateAssociations(currentRows))
.spread(associations => associations) .then(([associations]) => associations)
.catch(error => { .catch(error => {
if (error instanceof EmptyResultError) return updateAssociations(); if (error instanceof EmptyResultError) return updateAssociations();
throw error; throw error;
...@@ -745,7 +745,7 @@ class BelongsToMany extends Association { ...@@ -745,7 +745,7 @@ class BelongsToMany extends Association {
} }
if (association.scope) { if (association.scope) {
_.assign(values, association.scope); Object.assign(values, association.scope);
if (options.fields) { if (options.fields) {
Array.prototype.push.apply(options.fields, Object.keys(association.scope)); Array.prototype.push.apply(options.fields, Object.keys(association.scope));
} }
......
...@@ -202,7 +202,7 @@ class BelongsTo extends Association { ...@@ -202,7 +202,7 @@ class BelongsTo extends Association {
if (options.save === false) return; if (options.save === false) return;
options = _.extend({ options = Object.assign({
fields: [this.foreignKey], fields: [this.foreignKey],
allowNull: [this.foreignKey], allowNull: [this.foreignKey],
association: true association: true
......
...@@ -182,7 +182,7 @@ class HasMany extends Association { ...@@ -182,7 +182,7 @@ class HasMany extends Association {
options = Utils.cloneDeep(options); options = Utils.cloneDeep(options);
if (this.scope) { if (this.scope) {
_.assign(where, this.scope); Object.assign(where, this.scope);
} }
if (instances) { if (instances) {
...@@ -282,7 +282,7 @@ class HasMany extends Association { ...@@ -282,7 +282,7 @@ class HasMany extends Association {
targetInstances = [targetInstances]; targetInstances = [targetInstances];
} }
options = _.assign({}, options, { options = Object.assign({}, options, {
scope: false, scope: false,
raw: true raw: true
}); });
...@@ -363,7 +363,7 @@ class HasMany extends Association { ...@@ -363,7 +363,7 @@ class HasMany extends Association {
update = {}; update = {};
update[this.foreignKey] = sourceInstance.get(this.sourceKey); update[this.foreignKey] = sourceInstance.get(this.sourceKey);
_.assign(update, this.scope); Object.assign(update, this.scope);
updateWhere[this.target.primaryKeyAttribute] = unassociatedObjects.map(unassociatedObject => updateWhere[this.target.primaryKeyAttribute] = unassociatedObjects.map(unassociatedObject =>
unassociatedObject[this.target.primaryKeyAttribute] unassociatedObject[this.target.primaryKeyAttribute]
); );
...@@ -399,7 +399,7 @@ class HasMany extends Association { ...@@ -399,7 +399,7 @@ class HasMany extends Association {
targetInstances = this.toInstanceArray(targetInstances); targetInstances = this.toInstanceArray(targetInstances);
update[this.foreignKey] = sourceInstance.get(this.sourceKey); update[this.foreignKey] = sourceInstance.get(this.sourceKey);
_.assign(update, this.scope); Object.assign(update, this.scope);
where[this.target.primaryKeyAttribute] = targetInstances.map(unassociatedObject => where[this.target.primaryKeyAttribute] = targetInstances.map(unassociatedObject =>
unassociatedObject.get(this.target.primaryKeyAttribute) unassociatedObject.get(this.target.primaryKeyAttribute)
......
...@@ -155,7 +155,7 @@ class HasOne extends Association { ...@@ -155,7 +155,7 @@ class HasOne extends Association {
} }
if (this.scope) { if (this.scope) {
_.assign(where, this.scope); Object.assign(where, this.scope);
} }
options.where = options.where ? options.where = options.where ?
...@@ -192,7 +192,7 @@ class HasOne extends Association { ...@@ -192,7 +192,7 @@ class HasOne extends Association {
set(sourceInstance, associatedInstance, options) { set(sourceInstance, associatedInstance, options) {
let alreadyAssociated; let alreadyAssociated;
options = _.assign({}, options, { options = Object.assign({}, options, {
scope: false scope: false
}); });
...@@ -204,7 +204,7 @@ class HasOne extends Association { ...@@ -204,7 +204,7 @@ class HasOne extends Association {
if (oldInstance && !alreadyAssociated) { if (oldInstance && !alreadyAssociated) {
oldInstance[this.foreignKey] = null; oldInstance[this.foreignKey] = null;
return oldInstance.save(_.extend({}, options, { return oldInstance.save(Object.assign({}, options, {
fields: [this.foreignKey], fields: [this.foreignKey],
allowNull: [this.foreignKey], allowNull: [this.foreignKey],
association: true association: true
...@@ -220,7 +220,7 @@ class HasOne extends Association { ...@@ -220,7 +220,7 @@ class HasOne extends Association {
}); });
} }
_.assign(associatedInstance, this.scope); Object.assign(associatedInstance, this.scope);
associatedInstance.set(this.foreignKey, sourceInstance.get(this.sourceKeyAttribute)); associatedInstance.set(this.foreignKey, sourceInstance.get(this.sourceKeyAttribute));
return associatedInstance.save(options); return associatedInstance.save(options);
......
...@@ -24,7 +24,7 @@ const Mixin = { ...@@ -24,7 +24,7 @@ const Mixin = {
options.hooks = options.hooks === undefined ? false : Boolean(options.hooks); options.hooks = options.hooks === undefined ? false : Boolean(options.hooks);
options.useHooks = options.hooks; options.useHooks = options.hooks;
options = _.extend(options, _.omit(source.options, ['hooks'])); options = Object.assign(options, _.omit(source.options, ['hooks']));
if (options.useHooks) { if (options.useHooks) {
this.runHooks('beforeAssociate', {source, target, type: HasMany}, options); this.runHooks('beforeAssociate', {source, target, type: HasMany}, options);
...@@ -55,7 +55,7 @@ const Mixin = { ...@@ -55,7 +55,7 @@ const Mixin = {
options.hooks = options.hooks === undefined ? false : Boolean(options.hooks); options.hooks = options.hooks === undefined ? false : Boolean(options.hooks);
options.useHooks = options.hooks; options.useHooks = options.hooks;
options.timestamps = options.timestamps === undefined ? this.sequelize.options.timestamps : options.timestamps; options.timestamps = options.timestamps === undefined ? this.sequelize.options.timestamps : options.timestamps;
options = _.extend(options, _.omit(source.options, ['hooks', 'timestamps', 'scopes', 'defaultScope'])); options = Object.assign(options, _.omit(source.options, ['hooks', 'timestamps', 'scopes', 'defaultScope']));
if (options.useHooks) { if (options.useHooks) {
this.runHooks('beforeAssociate', {source, target, type: BelongsToMany}, options); this.runHooks('beforeAssociate', {source, target, type: BelongsToMany}, options);
...@@ -109,7 +109,7 @@ function singleLinked(Type) { ...@@ -109,7 +109,7 @@ function singleLinked(Type) {
this.runHooks('beforeAssociate', {source, target, type: Type}, options); this.runHooks('beforeAssociate', {source, target, type: Type}, options);
} }
// the id is in the foreign table // the id is in the foreign table
const association = new Type(source, target, _.extend(options, source.options)); const association = new Type(source, target, Object.assign(options, source.options));
source.associations[association.associationAccessor] = association; source.associations[association.associationAccessor] = association;
association._injectAttributes(); association._injectAttributes();
......
...@@ -780,7 +780,7 @@ RANGE.prototype.toCastType = function toCastType() { ...@@ -780,7 +780,7 @@ RANGE.prototype.toCastType = function toCastType() {
return pgRangeCastTypes[this._subtype.toLowerCase()]; return pgRangeCastTypes[this._subtype.toLowerCase()];
}; };
RANGE.prototype.validate = function validate(value) { RANGE.prototype.validate = function validate(value) {
if (!_.isArray(value)) { if (!Array.isArray(value)) {
throw new sequelizeErrors.ValidationError(util.format('%j is not a valid range', value)); throw new sequelizeErrors.ValidationError(util.format('%j is not a valid range', value));
} }
...@@ -963,7 +963,7 @@ ARRAY.prototype.toSql = function toSql() { ...@@ -963,7 +963,7 @@ ARRAY.prototype.toSql = function toSql() {
return this.type.toSql() + '[]'; return this.type.toSql() + '[]';
}; };
ARRAY.prototype.validate = function validate(value) { ARRAY.prototype.validate = function validate(value) {
if (!_.isArray(value)) { if (!Array.isArray(value)) {
throw new sequelizeErrors.ValidationError(util.format('%j is not a valid array', value)); throw new sequelizeErrors.ValidationError(util.format('%j is not a valid array', value));
} }
......
...@@ -1799,7 +1799,7 @@ class QueryGenerator { ...@@ -1799,7 +1799,7 @@ class QueryGenerator {
return; return;
} }
nestedIncludes = [_.extend({}, child, { include: nestedIncludes, attributes: [] })]; nestedIncludes = [Object.assign({}, child, { include: nestedIncludes, attributes: [] })];
child = parent; child = parent;
} }
...@@ -1876,7 +1876,7 @@ class QueryGenerator { ...@@ -1876,7 +1876,7 @@ class QueryGenerator {
* are preserved. * are preserved.
*/ */
_getRequiredClosure(include) { _getRequiredClosure(include) {
const copy = _.extend({}, include, {attributes: [], include: []}); const copy = Object.assign({}, include, {attributes: [], include: []});
if (Array.isArray(include.include)) { if (Array.isArray(include.include)) {
copy.include = include.include copy.include = include.include
...@@ -2261,7 +2261,7 @@ class QueryGenerator { ...@@ -2261,7 +2261,7 @@ class QueryGenerator {
Utils.getOperators(value).forEach(op => { Utils.getOperators(value).forEach(op => {
const where = {}; const where = {};
where[op] = value[op]; where[op] = value[op];
items.push(this.whereItemQuery(key, where, _.assign({}, options, {json: false}))); items.push(this.whereItemQuery(key, where, Object.assign({}, options, {json: false})));
}); });
_.forOwn(value, (item, prop) => { _.forOwn(value, (item, prop) => {
...@@ -2550,7 +2550,7 @@ class QueryGenerator { ...@@ -2550,7 +2550,7 @@ class QueryGenerator {
} }
} }
_.assignIn(QueryGenerator.prototype, require('./query-generator/operators')); Object.assign(QueryGenerator.prototype, require('./query-generator/operators'));
_.assignIn(QueryGenerator.prototype, require('./query-generator/transaction')); Object.assign(QueryGenerator.prototype, require('./query-generator/transaction'));
module.exports = QueryGenerator; module.exports = QueryGenerator;
...@@ -51,7 +51,7 @@ const OperatorHelpers = { ...@@ -51,7 +51,7 @@ const OperatorHelpers = {
if (!aliases || _.isEmpty(aliases)) { if (!aliases || _.isEmpty(aliases)) {
this.OperatorsAliasMap = false; this.OperatorsAliasMap = false;
} else { } else {
this.OperatorsAliasMap = _.assign({}, aliases); this.OperatorsAliasMap = Object.assign({}, aliases);
} }
}, },
......
...@@ -16,7 +16,7 @@ const throwMethodUndefined = function(methodName) { ...@@ -16,7 +16,7 @@ const throwMethodUndefined = function(methodName) {
class MSSQLQueryGenerator extends AbstractQueryGenerator { class MSSQLQueryGenerator extends AbstractQueryGenerator {
createDatabaseQuery(databaseName, options) { createDatabaseQuery(databaseName, options) {
options = _.extend({ options = Object.assign({
collate: null collate: null
}, options || {}); }, options || {});
......
...@@ -24,7 +24,7 @@ const removeColumn = function(tableName, attributeName, options) { ...@@ -24,7 +24,7 @@ const removeColumn = function(tableName, attributeName, options) {
const findConstraintSql = this.QueryGenerator.getDefaultConstraintQuery(tableName, attributeName); const findConstraintSql = this.QueryGenerator.getDefaultConstraintQuery(tableName, attributeName);
return this.sequelize.query(findConstraintSql, options) return this.sequelize.query(findConstraintSql, options)
.spread(results => { .then(([results]) => {
if (!results.length) { if (!results.length) {
// No default constraint found -- we can cleanly remove the column // No default constraint found -- we can cleanly remove the column
return; return;
...@@ -36,7 +36,7 @@ const removeColumn = function(tableName, attributeName, options) { ...@@ -36,7 +36,7 @@ const removeColumn = function(tableName, attributeName, options) {
const findForeignKeySql = this.QueryGenerator.getForeignKeyQuery(tableName, attributeName); const findForeignKeySql = this.QueryGenerator.getForeignKeyQuery(tableName, attributeName);
return this.sequelize.query(findForeignKeySql, options); return this.sequelize.query(findForeignKeySql, options);
}) })
.spread(results => { .then(([results]) => {
if (!results.length) { if (!results.length) {
// No foreign key constraints found, so we can remove the column // No foreign key constraints found, so we can remove the column
return; return;
...@@ -49,7 +49,7 @@ const removeColumn = function(tableName, attributeName, options) { ...@@ -49,7 +49,7 @@ const removeColumn = function(tableName, attributeName, options) {
const primaryKeyConstraintSql = this.QueryGenerator.getPrimaryKeyConstraintQuery(tableName, attributeName); const primaryKeyConstraintSql = this.QueryGenerator.getPrimaryKeyConstraintQuery(tableName, attributeName);
return this.sequelize.query(primaryKeyConstraintSql, options); return this.sequelize.query(primaryKeyConstraintSql, options);
}) })
.spread(result => { .then(([result]) => {
if (!result.length) { if (!result.length) {
return; return;
} }
......
...@@ -15,7 +15,7 @@ class Query extends AbstractQuery { ...@@ -15,7 +15,7 @@ class Query extends AbstractQuery {
this.instance = options.instance; this.instance = options.instance;
this.model = options.model; this.model = options.model;
this.sequelize = sequelize; this.sequelize = sequelize;
this.options = _.extend({ this.options = Object.assign({
logging: console.log, logging: console.log,
plain: false, plain: false,
raw: false raw: false
......
...@@ -17,7 +17,7 @@ class MySQLQueryGenerator extends AbstractQueryGenerator { ...@@ -17,7 +17,7 @@ class MySQLQueryGenerator extends AbstractQueryGenerator {
} }
createDatabaseQuery(databaseName, options) { createDatabaseQuery(databaseName, options) {
options = _.extend({ options = Object.assign({
charset: null, charset: null,
collate: null collate: null
}, options || {}); }, options || {});
...@@ -56,7 +56,7 @@ class MySQLQueryGenerator extends AbstractQueryGenerator { ...@@ -56,7 +56,7 @@ class MySQLQueryGenerator extends AbstractQueryGenerator {
} }
createTableQuery(tableName, attributes, options) { createTableQuery(tableName, attributes, options) {
options = _.extend({ options = Object.assign({
engine: 'InnoDB', engine: 'InnoDB',
charset: null, charset: null,
rowFormat: null rowFormat: null
...@@ -204,7 +204,7 @@ class MySQLQueryGenerator extends AbstractQueryGenerator { ...@@ -204,7 +204,7 @@ class MySQLQueryGenerator extends AbstractQueryGenerator {
// Parse nested object // Parse nested object
if (smth.conditions) { if (smth.conditions) {
const conditions = _.map(this.parseConditionObject(smth.conditions), condition => const conditions = _.map(this.parseConditionObject(smth.conditions), condition =>
`${this.quoteIdentifier(_.first(condition.path))}->>'\$.${_.tail(condition.path).join('.')}' = '${condition.value}'` `${this.quoteIdentifier(condition.path[0])}->>'\$.${_.tail(condition.path).join('.')}' = '${condition.value}'`
); );
return conditions.join(' and '); return conditions.join(' and ');
......
...@@ -8,7 +8,6 @@ ...@@ -8,7 +8,6 @@
@private @private
*/ */
const _ = require('lodash');
const Promise = require('../../promise'); const Promise = require('../../promise');
const sequelizeErrors = require('../../errors'); const sequelizeErrors = require('../../errors');
...@@ -29,9 +28,9 @@ function removeColumn(tableName, columnName, options) { ...@@ -29,9 +28,9 @@ function removeColumn(tableName, columnName, options) {
tableName, tableName,
schema: this.sequelize.config.database schema: this.sequelize.config.database
}, columnName), }, columnName),
_.assign({ raw: true }, options) Object.assign({ raw: true }, options)
) )
.spread(results => { .then(([results]) => {
//Exclude primary key constraint //Exclude primary key constraint
if (!results.length || results[0].constraint_name === 'PRIMARY') { if (!results.length || results[0].constraint_name === 'PRIMARY') {
// No foreign key constraints found, so we can remove the column // No foreign key constraints found, so we can remove the column
...@@ -39,12 +38,12 @@ function removeColumn(tableName, columnName, options) { ...@@ -39,12 +38,12 @@ function removeColumn(tableName, columnName, options) {
} }
return Promise.map(results, constraint => this.sequelize.query( return Promise.map(results, constraint => this.sequelize.query(
this.QueryGenerator.dropForeignKeyQuery(tableName, constraint.constraint_name), this.QueryGenerator.dropForeignKeyQuery(tableName, constraint.constraint_name),
_.assign({ raw: true }, options) Object.assign({ raw: true }, options)
)); ));
}) })
.then(() => this.sequelize.query( .then(() => this.sequelize.query(
this.QueryGenerator.removeColumnQuery(tableName, columnName), this.QueryGenerator.removeColumnQuery(tableName, columnName),
_.assign({ raw: true }, options) Object.assign({ raw: true }, options)
)); ));
} }
......
...@@ -16,7 +16,7 @@ class Query extends AbstractQuery { ...@@ -16,7 +16,7 @@ class Query extends AbstractQuery {
this.model = options.model; this.model = options.model;
this.sequelize = sequelize; this.sequelize = sequelize;
this.uuid = uuidv4(); this.uuid = uuidv4();
this.options = _.extend({ this.options = Object.assign({
logging: console.log, logging: console.log,
plain: false, plain: false,
raw: false, raw: false,
......
...@@ -13,7 +13,7 @@ class PostgresQueryGenerator extends AbstractQueryGenerator { ...@@ -13,7 +13,7 @@ class PostgresQueryGenerator extends AbstractQueryGenerator {
} }
createDatabaseQuery(databaseName, options) { createDatabaseQuery(databaseName, options) {
options = _.extend({ options = Object.assign({
encoding: null, encoding: null,
collate: null collate: null
}, options || {}); }, options || {});
...@@ -56,7 +56,7 @@ class PostgresQueryGenerator extends AbstractQueryGenerator { ...@@ -56,7 +56,7 @@ class PostgresQueryGenerator extends AbstractQueryGenerator {
} }
createTableQuery(tableName, attributes, options) { createTableQuery(tableName, attributes, options) {
options = _.extend({}, options || {}); options = Object.assign({}, options || {});
//Postgres 9.0 does not support CREATE TABLE IF NOT EXISTS, 9.1 and above do //Postgres 9.0 does not support CREATE TABLE IF NOT EXISTS, 9.1 and above do
const databaseVersion = _.get(this, 'sequelize.options.databaseVersion', 0); const databaseVersion = _.get(this, 'sequelize.options.databaseVersion', 0);
...@@ -122,7 +122,7 @@ class PostgresQueryGenerator extends AbstractQueryGenerator { ...@@ -122,7 +122,7 @@ class PostgresQueryGenerator extends AbstractQueryGenerator {
describeTableQuery(tableName, schema) { describeTableQuery(tableName, schema) {
if (!schema) schema = 'public'; if (!schema) schema = 'public';
return 'SELECT ' + return 'SELECT ' +
'pk.constraint_type as "Constraint",' + 'pk.constraint_type as "Constraint",' +
'c.column_name as "Field", ' + 'c.column_name as "Field", ' +
...@@ -217,7 +217,7 @@ class PostgresQueryGenerator extends AbstractQueryGenerator { ...@@ -217,7 +217,7 @@ class PostgresQueryGenerator extends AbstractQueryGenerator {
// Parse nested object // Parse nested object
if (smth.conditions) { if (smth.conditions) {
const conditions = _.map(this.parseConditionObject(smth.conditions), condition => const conditions = _.map(this.parseConditionObject(smth.conditions), condition =>
`${this.jsonPathExtractionQuery(_.first(condition.path), _.tail(condition.path))} = '${condition.value}'` `${this.jsonPathExtractionQuery(condition.path[0], _.tail(condition.path))} = '${condition.value}'`
); );
return conditions.join(' AND '); return conditions.join(' AND ');
...@@ -672,7 +672,7 @@ class PostgresQueryGenerator extends AbstractQueryGenerator { ...@@ -672,7 +672,7 @@ class PostgresQueryGenerator extends AbstractQueryGenerator {
} }
expandFunctionParamList(params) { expandFunctionParamList(params) {
if (_.isUndefined(params) || !_.isArray(params)) { if (_.isUndefined(params) || !Array.isArray(params)) {
throw new Error('expandFunctionParamList: function parameters array required, including an empty one for no arguments'); throw new Error('expandFunctionParamList: function parameters array required, including an empty one for no arguments');
} }
...@@ -738,7 +738,7 @@ class PostgresQueryGenerator extends AbstractQueryGenerator { ...@@ -738,7 +738,7 @@ class PostgresQueryGenerator extends AbstractQueryGenerator {
let eventSpec = EVENT_MAP[fireValue]; let eventSpec = EVENT_MAP[fireValue];
if (eventSpec === 'UPDATE') { if (eventSpec === 'UPDATE') {
if (_.isArray(fireValue) && fireValue.length > 0) { if (Array.isArray(fireValue) && fireValue.length > 0) {
eventSpec += ' OF ' + fireValue.join(', '); eventSpec += ' OF ' + fireValue.join(', ');
} }
} }
......
...@@ -44,7 +44,7 @@ function ensureEnums(tableName, attributes, options, model) { ...@@ -44,7 +44,7 @@ function ensureEnums(tableName, attributes, options, model) {
sql = this.QueryGenerator.pgListEnums(tableName, attribute.field || keys[i], options); sql = this.QueryGenerator.pgListEnums(tableName, attribute.field || keys[i], options);
promises.push(this.sequelize.query( promises.push(this.sequelize.query(
sql, sql,
_.assign({}, options, { plain: true, raw: true, type: QueryTypes.SELECT }) Object.assign({}, options, { plain: true, raw: true, type: QueryTypes.SELECT })
)); ));
} }
} }
...@@ -67,7 +67,7 @@ function ensureEnums(tableName, attributes, options, model) { ...@@ -67,7 +67,7 @@ function ensureEnums(tableName, attributes, options, model) {
sql = this.QueryGenerator.pgEnum(tableName, attribute.field || keys[i], enumType, options); sql = this.QueryGenerator.pgEnum(tableName, attribute.field || keys[i], enumType, options);
promises.push(this.sequelize.query( promises.push(this.sequelize.query(
sql, sql,
_.assign({}, options, { raw: true }) Object.assign({}, options, { raw: true })
)); ));
} else if (!!results[enumIdx] && !!model) { } else if (!!results[enumIdx] && !!model) {
const enumVals = this.QueryGenerator.fromArray(results[enumIdx].enum_value); const enumVals = this.QueryGenerator.fromArray(results[enumIdx].enum_value);
...@@ -106,4 +106,4 @@ function ensureEnums(tableName, attributes, options, model) { ...@@ -106,4 +106,4 @@ function ensureEnums(tableName, attributes, options, model) {
} }
exports.ensureEnums = ensureEnums; exports.ensureEnums = ensureEnums;
\ No newline at end of file
...@@ -15,7 +15,7 @@ class Query extends AbstractQuery { ...@@ -15,7 +15,7 @@ class Query extends AbstractQuery {
this.sequelize = sequelize; this.sequelize = sequelize;
this.instance = options.instance; this.instance = options.instance;
this.model = options.model; this.model = options.model;
this.options = _.extend({ this.options = Object.assign({
logging: console.log, logging: console.log,
plain: false, plain: false,
raw: false raw: false
......
...@@ -27,7 +27,7 @@ function parseRangeBound(bound, parseType) { ...@@ -27,7 +27,7 @@ function parseRangeBound(bound, parseType) {
function stringify(data) { function stringify(data) {
if (data === null) return null; if (data === null) return null;
if (!_.isArray(data)) throw new Error('range must be an array'); if (!Array.isArray(data)) throw new Error('range must be an array');
if (!data.length) return 'empty'; if (!data.length) return 'empty';
if (data.length !== 2) throw new Error('range array length must be 0 (empty) or 2 (lower and upper bounds)'); if (data.length !== 2) throw new Error('range array length must be 0 (empty) or 2 (lower and upper bounds)');
......
...@@ -151,7 +151,7 @@ class SQLiteQueryGenerator extends MySqlQueryGenerator { ...@@ -151,7 +151,7 @@ class SQLiteQueryGenerator extends MySqlQueryGenerator {
// Parse nested object // Parse nested object
if (smth.conditions) { if (smth.conditions) {
const conditions = this.parseConditionObject(smth.conditions).map(condition => const conditions = this.parseConditionObject(smth.conditions).map(condition =>
`${this.jsonPathExtractionQuery(_.first(condition.path), _.tail(condition.path))} = '${condition.value}'` `${this.jsonPathExtractionQuery(condition.path[0], _.tail(condition.path))} = '${condition.value}'`
); );
return conditions.join(' AND '); return conditions.join(' AND ');
......
...@@ -35,7 +35,7 @@ function removeColumn(tableName, attributeName, options) { ...@@ -35,7 +35,7 @@ function removeColumn(tableName, attributeName, options) {
const sql = this.QueryGenerator.removeColumnQuery(tableName, fields); const sql = this.QueryGenerator.removeColumnQuery(tableName, fields);
const subQueries = sql.split(';').filter(q => q !== ''); const subQueries = sql.split(';').filter(q => q !== '');
return Promise.each(subQueries, subQuery => this.sequelize.query(subQuery + ';', _.assign({raw: true}, options))); return Promise.each(subQueries, subQuery => this.sequelize.query(subQuery + ';', Object.assign({raw: true}, options)));
}); });
} }
exports.removeColumn = removeColumn; exports.removeColumn = removeColumn;
...@@ -63,7 +63,7 @@ function changeColumn(tableName, attributes, options) { ...@@ -63,7 +63,7 @@ function changeColumn(tableName, attributes, options) {
const sql = this.QueryGenerator.removeColumnQuery(tableName, fields); const sql = this.QueryGenerator.removeColumnQuery(tableName, fields);
const subQueries = sql.split(';').filter(q => q !== ''); const subQueries = sql.split(';').filter(q => q !== '');
return Promise.each(subQueries, subQuery => this.sequelize.query(subQuery + ';', _.assign({raw: true}, options))); return Promise.each(subQueries, subQuery => this.sequelize.query(subQuery + ';', Object.assign({raw: true}, options)));
}); });
} }
exports.changeColumn = changeColumn; exports.changeColumn = changeColumn;
...@@ -92,7 +92,7 @@ function renameColumn(tableName, attrNameBefore, attrNameAfter, options) { ...@@ -92,7 +92,7 @@ function renameColumn(tableName, attrNameBefore, attrNameAfter, options) {
const sql = this.QueryGenerator.renameColumnQuery(tableName, attrNameBefore, attrNameAfter, fields); const sql = this.QueryGenerator.renameColumnQuery(tableName, attrNameBefore, attrNameAfter, fields);
const subQueries = sql.split(';').filter(q => q !== ''); const subQueries = sql.split(';').filter(q => q !== '');
return Promise.each(subQueries, subQuery => this.sequelize.query(subQuery + ';', _.assign({raw: true}, options))); return Promise.each(subQueries, subQuery => this.sequelize.query(subQuery + ';', Object.assign({raw: true}, options)));
}); });
} }
exports.renameColumn = renameColumn; exports.renameColumn = renameColumn;
...@@ -134,7 +134,7 @@ function removeConstraint(tableName, constraintName, options) { ...@@ -134,7 +134,7 @@ function removeConstraint(tableName, constraintName, options) {
const sql = this.QueryGenerator._alterConstraintQuery(tableName, fields, createTableSql); const sql = this.QueryGenerator._alterConstraintQuery(tableName, fields, createTableSql);
const subQueries = sql.split(';').filter(q => q !== ''); const subQueries = sql.split(';').filter(q => q !== '');
return Promise.each(subQueries, subQuery => this.sequelize.query(subQuery + ';', _.assign({raw: true}, options))); return Promise.each(subQueries, subQuery => this.sequelize.query(subQuery + ';', Object.assign({raw: true}, options)));
}); });
} }
exports.removeConstraint = removeConstraint; exports.removeConstraint = removeConstraint;
...@@ -144,7 +144,7 @@ function addConstraint(tableName, options) { ...@@ -144,7 +144,7 @@ function addConstraint(tableName, options) {
const describeCreateTableSql = this.QueryGenerator.describeCreateTableQuery(tableName); const describeCreateTableSql = this.QueryGenerator.describeCreateTableQuery(tableName);
let createTableSql; let createTableSql;
return this.sequelize.query(describeCreateTableSql, _.assign({}, options, { type: QueryTypes.SELECT, raw: true })) return this.sequelize.query(describeCreateTableSql, Object.assign({}, options, { type: QueryTypes.SELECT, raw: true }))
.then(constraints => { .then(constraints => {
const sql = constraints[0].sql; const sql = constraints[0].sql;
const index = sql.length - 1; const index = sql.length - 1;
...@@ -158,7 +158,7 @@ function addConstraint(tableName, options) { ...@@ -158,7 +158,7 @@ function addConstraint(tableName, options) {
const sql = this.QueryGenerator._alterConstraintQuery(tableName, fields, createTableSql); const sql = this.QueryGenerator._alterConstraintQuery(tableName, fields, createTableSql);
const subQueries = sql.split(';').filter(q => q !== ''); const subQueries = sql.split(';').filter(q => q !== '');
return Promise.each(subQueries, subQuery => this.sequelize.query(subQuery + ';', _.assign({raw: true}, options))); return Promise.each(subQueries, subQuery => this.sequelize.query(subQuery + ';', Object.assign({raw: true}, options)));
}); });
} }
exports.addConstraint = addConstraint; exports.addConstraint = addConstraint;
......
...@@ -18,11 +18,11 @@ class Query extends AbstractQuery { ...@@ -18,11 +18,11 @@ class Query extends AbstractQuery {
this.sequelize = sequelize; this.sequelize = sequelize;
this.instance = options.instance; this.instance = options.instance;
this.model = options.model; this.model = options.model;
this.options = _.extend({ this.options = Object.assign({
logging: console.log, logging: console.log,
plain: false, plain: false,
raw: false raw: false
}, options || {}); }, options);
this.checkLoggingOption(); this.checkLoggingOption();
} }
......
...@@ -81,7 +81,7 @@ const Hooks = { ...@@ -81,7 +81,7 @@ const Hooks = {
_setupHooks(hooks) { _setupHooks(hooks) {
this.options.hooks = {}; this.options.hooks = {};
_.map(hooks || {}, (hooksArray, hookName) => { _.map(hooks || {}, (hooksArray, hookName) => {
if (!_.isArray(hooksArray)) hooksArray = [hooksArray]; if (!Array.isArray(hooksArray)) hooksArray = [hooksArray];
hooksArray.forEach(hookFn => this.addHook(hookName, hookFn)); hooksArray.forEach(hookFn => this.addHook(hookName, hookFn));
}); });
}, },
......
...@@ -70,7 +70,7 @@ class Model { ...@@ -70,7 +70,7 @@ class Model {
* @param {Array} [options.include] an array of include options - Used to build prefetched/included model instances. See `set` * @param {Array} [options.include] an array of include options - Used to build prefetched/included model instances. See `set`
*/ */
constructor(values = {}, options = {}) { constructor(values = {}, options = {}) {
options = _.extend({ options = Object.assign({
isNewRecord: true, isNewRecord: true,
_schema: this.constructor._schema, _schema: this.constructor._schema,
_schemaDelimiter: this.constructor._schemaDelimiter _schemaDelimiter: this.constructor._schemaDelimiter
...@@ -912,7 +912,7 @@ class Model { ...@@ -912,7 +912,7 @@ class Model {
// error check options // error check options
_.each(options.validate, (validator, validatorType) => { _.each(options.validate, (validator, validatorType) => {
if (_.includes(_.keys(attributes), validatorType)) { if (_.includes(Object.keys(attributes), validatorType)) {
throw new Error('A model validator function must not have the same name as a field. Model: ' + this.name + ', field/validation name: ' + validatorType); throw new Error('A model validator function must not have the same name as a field. Model: ' + this.name + ', field/validation name: ' + validatorType);
} }
...@@ -1234,7 +1234,7 @@ class Model { ...@@ -1234,7 +1234,7 @@ class Model {
* @returns {Promise<Model>} * @returns {Promise<Model>}
*/ */
static sync(options) { static sync(options) {
options = _.extend({}, this.options, options); options = Object.assign({}, this.options, options);
options.hooks = options.hooks === undefined ? true : !!options.hooks; options.hooks = options.hooks === undefined ? true : !!options.hooks;
const attributes = this.tableAttributes; const attributes = this.tableAttributes;
...@@ -1318,7 +1318,7 @@ class Model { ...@@ -1318,7 +1318,7 @@ class Model {
return Promise.map(indexes, index => this.QueryInterface.addIndex( return Promise.map(indexes, index => this.QueryInterface.addIndex(
this.getTableName(options), this.getTableName(options),
_.assign({ Object.assign({
logging: options.logging, logging: options.logging,
benchmark: options.benchmark, benchmark: options.benchmark,
transaction: options.transaction transaction: options.transaction
...@@ -1420,7 +1420,7 @@ class Model { ...@@ -1420,7 +1420,7 @@ class Model {
* @param {boolean} [options.override=false] override old scope if already defined * @param {boolean} [options.override=false] override old scope if already defined
*/ */
static addScope(name, scope, options) { static addScope(name, scope, options) {
options = _.assign({ options = Object.assign({
override: false override: false
}, options); }, options);
...@@ -1815,7 +1815,7 @@ class Model { ...@@ -1815,7 +1815,7 @@ class Model {
} }
return memo; return memo;
}, []), }, []),
_.assign( Object.assign(
{}, {},
_.omit(options, 'include', 'attributes', 'order', 'where', 'limit', 'offset', 'plain', 'scope'), _.omit(options, 'include', 'attributes', 'order', 'where', 'limit', 'offset', 'plain', 'scope'),
{include: include.include || []} {include: include.include || []}
...@@ -1823,7 +1823,7 @@ class Model { ...@@ -1823,7 +1823,7 @@ class Model {
); );
} }
return include.association.get(results, _.assign( return include.association.get(results, Object.assign(
{}, {},
_.omit(options, ['include', 'attributes', 'originalAttributes', 'order', 'where', 'limit', 'offset', 'plain', 'group']), _.omit(options, ['include', 'attributes', 'originalAttributes', 'order', 'where', 'limit', 'offset', 'plain', 'group']),
_.omit(include, ['parent', 'association', 'as', 'originalAttributes']) _.omit(include, ['parent', 'association', 'as', 'originalAttributes'])
...@@ -2061,10 +2061,11 @@ class Model { ...@@ -2061,10 +2061,11 @@ class Model {
return Promise.all([ return Promise.all([
this.count(countOptions), this.count(countOptions),
this.findAll(options) this.findAll(options)
]).spread((count, rows) => ({ ])
count, .then(([count, rows]) => ({
rows: count === 0 ? [] : rows count,
})); rows: count === 0 ? [] : rows
}));
} }
/** /**
...@@ -2129,7 +2130,7 @@ class Model { ...@@ -2129,7 +2130,7 @@ class Model {
} }
static bulkBuild(valueSets, options) { // testhint options:none static bulkBuild(valueSets, options) { // testhint options:none
options = _.extend({ options = Object.assign({
isNewRecord: true isNewRecord: true
}, options || {}); }, options || {});
...@@ -2187,7 +2188,7 @@ class Model { ...@@ -2187,7 +2188,7 @@ class Model {
/** /**
* Find a row that matches the query, or build (but don't save) the row if none is found. * Find a row that matches the query, or build (but don't save) the row if none is found.
* The successful result of the promise will be (instance, built) - Make sure to use .spread() * The successful result of the promise will be (instance, built)
* *
* @param {Object} options find options * @param {Object} options find options
* @param {Object} options.where A hash of search attributes. * @param {Object} options.where A hash of search attributes.
...@@ -2224,7 +2225,7 @@ class Model { ...@@ -2224,7 +2225,7 @@ class Model {
/** /**
* Find a row that matches the query, or build and save the row if none is found * Find a row that matches the query, or build and save the row if none is found
* The successful result of the promise will be (instance, created) - Make sure to use .spread() * The successful result of the promise will be (instance, created)
* *
* If no transaction is passed in the `options` object, a new transaction will be created internally, to prevent the race condition where a matching row is created by another connection after the find but before the insert call. * If no transaction is passed in the `options` object, a new transaction will be created internally, to prevent the race condition where a matching row is created by another connection after the find but before the insert call.
* However, it is not always possible to handle this case in SQLite, specifically if one transaction inserts and another tries to select before the first one has committed. In this case, an instance of sequelize. TimeoutError will be thrown instead. * However, it is not always possible to handle this case in SQLite, specifically if one transaction inserts and another tries to select before the first one has committed. In this case, an instance of sequelize. TimeoutError will be thrown instead.
...@@ -2247,7 +2248,7 @@ class Model { ...@@ -2247,7 +2248,7 @@ class Model {
); );
} }
options = _.assign({}, options); options = Object.assign({}, options);
if (options.defaults) { if (options.defaults) {
const defaults = Object.keys(options.defaults); const defaults = Object.keys(options.defaults);
...@@ -2296,7 +2297,7 @@ class Model { ...@@ -2296,7 +2297,7 @@ class Model {
return [instance, true]; return [instance, true];
}).catch(sequelizeErrors.UniqueConstraintError, err => { }).catch(sequelizeErrors.UniqueConstraintError, err => {
const flattenedWhere = Utils.flattenObjectDeep(options.where); const flattenedWhere = Utils.flattenObjectDeep(options.where);
const flattenedWhereKeys = _.map(_.keys(flattenedWhere), name => _.last(_.split(name, '.'))); const flattenedWhereKeys = _.map(Object.keys(flattenedWhere), name => _.last(_.split(name, '.')));
const whereFields = flattenedWhereKeys.map(name => _.get(this.rawAttributes, `${name}.field`, name)); const whereFields = flattenedWhereKeys.map(name => _.get(this.rawAttributes, `${name}.field`, name));
const defaultFields = options.defaults && Object.keys(options.defaults) const defaultFields = options.defaults && Object.keys(options.defaults)
.filter(name => this.rawAttributes[name]) .filter(name => this.rawAttributes[name])
...@@ -2443,19 +2444,22 @@ class Model { ...@@ -2443,19 +2444,22 @@ class Model {
if (options.hooks) { if (options.hooks) {
return this.runHooks('beforeUpsert', values, options); return this.runHooks('beforeUpsert', values, options);
} }
}).then(() => { })
return this.QueryInterface.upsert(this.getTableName(options), insertValues, updateValues, instance.where(), this, options); .then(() => {
}).spread((created, primaryKey) => { return this.QueryInterface.upsert(this.getTableName(options), insertValues, updateValues, instance.where(), this, options);
if (options.returning === true && primaryKey) { })
return this.findByPk(primaryKey, options).then(record => [record, created]); .then(([created, primaryKey]) => {
} if (options.returning === true && primaryKey) {
return this.findByPk(primaryKey, options).then(record => [record, created]);
}
return created; return created;
}).tap(result => { })
if (options.hooks) { .tap(result => {
return this.runHooks('afterUpsert', result, options); if (options.hooks) {
} return this.runHooks('afterUpsert', result, options);
}); }
});
}); });
} }
...@@ -2489,7 +2493,7 @@ class Model { ...@@ -2489,7 +2493,7 @@ class Model {
return Promise.resolve([]); return Promise.resolve([]);
} }
options = _.extend({ options = Object.assign({
validate: false, validate: false,
hooks: true, hooks: true,
individualHooks: false, individualHooks: false,
...@@ -2508,7 +2512,7 @@ class Model { ...@@ -2508,7 +2512,7 @@ class Model {
} }
if (options.updateOnDuplicate !== undefined) { if (options.updateOnDuplicate !== undefined) {
if (_.isArray(options.updateOnDuplicate) && options.updateOnDuplicate.length) { if (Array.isArray(options.updateOnDuplicate) && options.updateOnDuplicate.length) {
options.updateOnDuplicate = _.intersection( options.updateOnDuplicate = _.intersection(
_.without(Object.keys(this.tableAttributes), this._timestampAttributes.createdAt), _.without(Object.keys(this.tableAttributes), this._timestampAttributes.createdAt),
options.updateOnDuplicate options.updateOnDuplicate
...@@ -2679,7 +2683,7 @@ class Model { ...@@ -2679,7 +2683,7 @@ class Model {
throw new Error('Missing where or truncate attribute in the options parameter of model.destroy.'); throw new Error('Missing where or truncate attribute in the options parameter of model.destroy.');
} }
if (!options.truncate && !_.isPlainObject(options.where) && !_.isArray(options.where) && !(options.where instanceof Utils.SequelizeMethod)) { if (!options.truncate && !_.isPlainObject(options.where) && !Array.isArray(options.where) && !(options.where instanceof Utils.SequelizeMethod)) {
throw new Error('Expected plain object, array or sequelize method in the options.where parameter of model.destroy.'); throw new Error('Expected plain object, array or sequelize method in the options.where parameter of model.destroy.');
} }
...@@ -2760,7 +2764,7 @@ class Model { ...@@ -2760,7 +2764,7 @@ class Model {
static restore(options) { static restore(options) {
if (!this._timestampAttributes.deletedAt) throw new Error('Model is not paranoid'); if (!this._timestampAttributes.deletedAt) throw new Error('Model is not paranoid');
options = _.extend({ options = Object.assign({
hooks: true, hooks: true,
individualHooks: false individualHooks: false
}, options || {}); }, options || {});
...@@ -2883,7 +2887,7 @@ class Model { ...@@ -2883,7 +2887,7 @@ class Model {
build.set(this._timestampAttributes.updatedAt, values[this._timestampAttributes.updatedAt], { raw: true }); build.set(this._timestampAttributes.updatedAt, values[this._timestampAttributes.updatedAt], { raw: true });
if (options.sideEffects) { if (options.sideEffects) {
values = _.assign(values, _.pick(build.get(), build.changed())); values = Object.assign(values, _.pick(build.get(), build.changed()));
options.fields = _.union(options.fields, Object.keys(values)); options.fields = _.union(options.fields, Object.keys(values));
} }
...@@ -2925,7 +2929,7 @@ class Model { ...@@ -2925,7 +2929,7 @@ class Model {
return Promise.map(instances, instance => { return Promise.map(instances, instance => {
// Record updates in instances dataValues // Record updates in instances dataValues
_.extend(instance.dataValues, values); Object.assign(instance.dataValues, values);
// Set the changed fields on the instance // Set the changed fields on the instance
_.forIn(valuesUse, (newValue, attr) => { _.forIn(valuesUse, (newValue, attr) => {
if (newValue !== instance._previousDataValues[attr]) { if (newValue !== instance._previousDataValues[attr]) {
...@@ -3028,7 +3032,7 @@ class Model { ...@@ -3028,7 +3032,7 @@ class Model {
* @returns {Promise} hash of attributes and their types * @returns {Promise} hash of attributes and their types
*/ */
static describe(schema, options) { static describe(schema, options) {
return this.QueryInterface.describeTable(this.tableName, _.assign({schema: schema || this._schema || undefined}, options)); return this.QueryInterface.describeTable(this.tableName, Object.assign({schema: schema || this._schema || undefined}, options));
} }
static _getDefaultTimestamp(attr) { static _getDefaultTimestamp(attr) {
...@@ -3139,12 +3143,12 @@ class Model { ...@@ -3139,12 +3143,12 @@ class Model {
Utils.mapOptionFieldNames(options, this); Utils.mapOptionFieldNames(options, this);
const where = _.extend({}, options.where); const where = Object.assign({}, options.where);
let values = {}; let values = {};
if (_.isString(fields)) { if (_.isString(fields)) {
values[fields] = options.by; values[fields] = options.by;
} else if (_.isArray(fields)) { } else if (Array.isArray(fields)) {
_.each(fields, field => { _.each(fields, field => {
values[field] = options.by; values[field] = options.by;
}); });
...@@ -3216,7 +3220,7 @@ class Model { ...@@ -3216,7 +3220,7 @@ class Model {
static _optionsMustContainWhere(options) { static _optionsMustContainWhere(options) {
assert(options && options.where, 'Missing where attribute in the options parameter'); assert(options && options.where, 'Missing where attribute in the options parameter');
assert(_.isPlainObject(options.where) || _.isArray(options.where) || options.where instanceof Utils.SequelizeMethod, assert(_.isPlainObject(options.where) || Array.isArray(options.where) || options.where instanceof Utils.SequelizeMethod,
'Expected plain object, array or sequelize method in the options.where parameter'); 'Expected plain object, array or sequelize method in the options.where parameter');
} }
...@@ -3392,7 +3396,7 @@ class Model { ...@@ -3392,7 +3396,7 @@ class Model {
// If raw, and we're not dealing with includes or special attributes, just set it straight on the dataValues object // If raw, and we're not dealing with includes or special attributes, just set it straight on the dataValues object
if (options.raw && !(this._options && this._options.include) && !(options && options.attributes) && !this.constructor._hasBooleanAttributes && !this.constructor._hasDateAttributes) { if (options.raw && !(this._options && this._options.include) && !(options && options.attributes) && !this.constructor._hasBooleanAttributes && !this.constructor._hasDateAttributes) {
if (Object.keys(this.dataValues).length) { if (Object.keys(this.dataValues).length) {
this.dataValues = _.extend(this.dataValues, values); this.dataValues = Object.assign(this.dataValues, values);
} else { } else {
this.dataValues = values; this.dataValues = values;
} }
...@@ -3771,10 +3775,7 @@ class Model { ...@@ -3771,10 +3775,7 @@ class Model {
} }
return this.constructor.QueryInterface[query].apply(this.constructor.QueryInterface, args) return this.constructor.QueryInterface[query].apply(this.constructor.QueryInterface, args)
.then(results => { .then(([result, rowsUpdated])=> {
const result = _.head(results);
const rowsUpdated = results[1];
if (versionAttr) { if (versionAttr) {
// Check to see that a row was updated, otherwise it's an optimistic locking error. // Check to see that a row was updated, otherwise it's an optimistic locking error.
if (rowsUpdated < 1) { if (rowsUpdated < 1) {
...@@ -3798,9 +3799,9 @@ class Model { ...@@ -3798,9 +3799,9 @@ class Model {
delete values[this.constructor.rawAttributes[attr].field]; delete values[this.constructor.rawAttributes[attr].field];
} }
} }
values = _.extend(values, result.dataValues); values = Object.assign(values, result.dataValues);
result.dataValues = _.extend(result.dataValues, values); result.dataValues = Object.assign(result.dataValues, values);
return result; return result;
}) })
.tap(() => { .tap(() => {
...@@ -3831,12 +3832,12 @@ class Model { ...@@ -3831,12 +3832,12 @@ class Model {
values[include.association.foreignKey] = this.get(this.constructor.primaryKeyAttribute, {raw: true}); values[include.association.foreignKey] = this.get(this.constructor.primaryKeyAttribute, {raw: true});
values[include.association.otherKey] = instance.get(instance.constructor.primaryKeyAttribute, {raw: true}); values[include.association.otherKey] = instance.get(instance.constructor.primaryKeyAttribute, {raw: true});
// Include values defined in the scope of the association // Include values defined in the scope of the association
_.assign(values, include.association.through.scope); Object.assign(values, include.association.through.scope);
return include.association.throughModel.create(values, includeOptions); return include.association.throughModel.create(values, includeOptions);
}); });
} else { } else {
instance.set(include.association.foreignKey, this.get(include.association.sourceKey || this.constructor.primaryKeyAttribute, {raw: true})); instance.set(include.association.foreignKey, this.get(include.association.sourceKey || this.constructor.primaryKeyAttribute, {raw: true}));
_.assign(instance, include.association.scope); Object.assign(instance, include.association.scope);
return instance.save(includeOptions); return instance.save(includeOptions);
} }
}); });
...@@ -3963,7 +3964,7 @@ class Model { ...@@ -3963,7 +3964,7 @@ class Model {
* @returns {Promise} * @returns {Promise}
*/ */
destroy(options) { destroy(options) {
options = _.extend({ options = Object.assign({
hooks: true, hooks: true,
force: false force: false
}, options); }, options);
...@@ -3988,8 +3989,7 @@ class Model { ...@@ -3988,8 +3989,7 @@ class Model {
return this.constructor.QueryInterface.update( return this.constructor.QueryInterface.update(
this, this.constructor.getTableName(options), values, where, _.defaults({ hooks: false, model: this.constructor }, options) this, this.constructor.getTableName(options), values, where, _.defaults({ hooks: false, model: this.constructor }, options)
).then(results => { ).then(([results, rowsUpdated]) => {
const rowsUpdated = results[1];
if (this.constructor._versionAttribute && rowsUpdated < 1) { if (this.constructor._versionAttribute && rowsUpdated < 1) {
throw new sequelizeErrors.OptimisticLockError({ throw new sequelizeErrors.OptimisticLockError({
modelName: this.constructor.name, modelName: this.constructor.name,
...@@ -3997,10 +3997,10 @@ class Model { ...@@ -3997,10 +3997,10 @@ class Model {
where where
}); });
} }
return _.head(results); return results;
}); });
} else { } else {
return this.constructor.QueryInterface.delete(this, this.constructor.getTableName(options), where, _.assign({ type: QueryTypes.DELETE, limit: null }, options)); return this.constructor.QueryInterface.delete(this, this.constructor.getTableName(options), where, Object.assign({ type: QueryTypes.DELETE, limit: null }, options));
} }
}).tap(() => { }).tap(() => {
// Run after hook // Run after hook
...@@ -4042,7 +4042,7 @@ class Model { ...@@ -4042,7 +4042,7 @@ class Model {
restore(options) { restore(options) {
if (!this.constructor._timestampAttributes.deletedAt) throw new Error('Model is not paranoid'); if (!this.constructor._timestampAttributes.deletedAt) throw new Error('Model is not paranoid');
options = _.extend({ options = Object.assign({
hooks: true, hooks: true,
force: false force: false
}, options); }, options);
...@@ -4058,7 +4058,7 @@ class Model { ...@@ -4058,7 +4058,7 @@ class Model {
const deletedAtDefaultValue = deletedAtAttribute.hasOwnProperty('defaultValue') ? deletedAtAttribute.defaultValue : null; const deletedAtDefaultValue = deletedAtAttribute.hasOwnProperty('defaultValue') ? deletedAtAttribute.defaultValue : null;
this.setDataValue(deletedAtCol, deletedAtDefaultValue); this.setDataValue(deletedAtCol, deletedAtDefaultValue);
return this.save(_.extend({}, options, {hooks: false, omitNull: false})); return this.save(Object.assign({}, options, {hooks: false, omitNull: false}));
}).tap(() => { }).tap(() => {
// Run after hook // Run after hook
if (options.hooks) { if (options.hooks) {
...@@ -4101,7 +4101,7 @@ class Model { ...@@ -4101,7 +4101,7 @@ class Model {
const identifier = this.where(); const identifier = this.where();
options = Utils.cloneDeep(options); options = Utils.cloneDeep(options);
options.where = _.extend({}, options.where, identifier); options.where = Object.assign({}, options.where, identifier);
options.instance = this; options.instance = this;
return this.constructor.increment(fields, options).return(this); return this.constructor.increment(fields, options).return(this);
...@@ -4293,7 +4293,7 @@ class Model { ...@@ -4293,7 +4293,7 @@ class Model {
static belongsTo(target, options) {} // eslint-disable-line static belongsTo(target, options) {} // eslint-disable-line
} }
_.extend(Model, associationsMixin); Object.assign(Model, associationsMixin);
Hooks.applyTo(Model); Hooks.applyTo(Model);
module.exports = Model; module.exports = Model;
...@@ -110,7 +110,7 @@ class QueryInterface { ...@@ -110,7 +110,7 @@ class QueryInterface {
* @returns {Promise<Array>} * @returns {Promise<Array>}
*/ */
showAllSchemas(options) { showAllSchemas(options) {
options = _.assign({}, options, { options = Object.assign({}, options, {
raw: true, raw: true,
type: this.sequelize.QueryTypes.SELECT type: this.sequelize.QueryTypes.SELECT
}); });
...@@ -134,7 +134,7 @@ class QueryInterface { ...@@ -134,7 +134,7 @@ class QueryInterface {
databaseVersion(options) { databaseVersion(options) {
return this.sequelize.query( return this.sequelize.query(
this.QueryGenerator.versionQuery(), this.QueryGenerator.versionQuery(),
_.assign({}, options, { type: QueryTypes.VERSION }) Object.assign({}, options, { type: QueryTypes.VERSION })
); );
} }
...@@ -270,7 +270,7 @@ class QueryInterface { ...@@ -270,7 +270,7 @@ class QueryInterface {
if (instanceTable.rawAttributes[keys[i]].type instanceof DataTypes.ENUM) { if (instanceTable.rawAttributes[keys[i]].type instanceof DataTypes.ENUM) {
sql = this.QueryGenerator.pgEnumDrop(getTableName, keys[i]); sql = this.QueryGenerator.pgEnumDrop(getTableName, keys[i]);
options.supportsSearchPath = false; options.supportsSearchPath = false;
promises.push(this.sequelize.query(sql, _.assign({}, options, { raw: true }))); promises.push(this.sequelize.query(sql, Object.assign({}, options, { raw: true })));
} }
} }
} }
...@@ -295,7 +295,7 @@ class QueryInterface { ...@@ -295,7 +295,7 @@ class QueryInterface {
const dropAllTables = tableNames => Promise.each(tableNames, tableName => { const dropAllTables = tableNames => Promise.each(tableNames, tableName => {
// if tableName is not in the Array of tables names then don't drop it // if tableName is not in the Array of tables names then don't drop it
if (skip.indexOf(tableName.tableName || tableName) === -1) { if (skip.indexOf(tableName.tableName || tableName) === -1) {
return this.dropTable(tableName, _.assign({}, options, { cascade: true }) ); return this.dropTable(tableName, Object.assign({}, options, { cascade: true }) );
} }
}); });
...@@ -352,7 +352,7 @@ class QueryInterface { ...@@ -352,7 +352,7 @@ class QueryInterface {
return this.sequelize.query( return this.sequelize.query(
this.QueryGenerator.pgEnumDrop(null, null, this.QueryGenerator.pgEscapeAndQuote(enumName)), this.QueryGenerator.pgEnumDrop(null, null, this.QueryGenerator.pgEscapeAndQuote(enumName)),
_.assign({}, options, { raw: true }) Object.assign({}, options, { raw: true })
); );
} }
...@@ -373,7 +373,7 @@ class QueryInterface { ...@@ -373,7 +373,7 @@ class QueryInterface {
return this.pgListEnums(null, options).map(result => this.sequelize.query( return this.pgListEnums(null, options).map(result => this.sequelize.query(
this.QueryGenerator.pgEnumDrop(null, null, this.QueryGenerator.pgEscapeAndQuote(result.enum_name)), this.QueryGenerator.pgEnumDrop(null, null, this.QueryGenerator.pgEscapeAndQuote(result.enum_name)),
_.assign({}, options, { raw: true }) Object.assign({}, options, { raw: true })
)); ));
} }
...@@ -389,7 +389,7 @@ class QueryInterface { ...@@ -389,7 +389,7 @@ class QueryInterface {
pgListEnums(tableName, options) { pgListEnums(tableName, options) {
options = options || {}; options = options || {};
const sql = this.QueryGenerator.pgListEnums(tableName); const sql = this.QueryGenerator.pgListEnums(tableName);
return this.sequelize.query(sql, _.assign({}, options, { plain: false, raw: true, type: QueryTypes.SELECT })); return this.sequelize.query(sql, Object.assign({}, options, { plain: false, raw: true, type: QueryTypes.SELECT }));
} }
/** /**
...@@ -418,7 +418,7 @@ class QueryInterface { ...@@ -418,7 +418,7 @@ class QueryInterface {
* @private * @private
*/ */
showAllTables(options) { showAllTables(options) {
options = _.assign({}, options, { options = Object.assign({}, options, {
raw: true, raw: true,
type: QueryTypes.SHOWTABLES type: QueryTypes.SHOWTABLES
}); });
...@@ -472,7 +472,7 @@ class QueryInterface { ...@@ -472,7 +472,7 @@ class QueryInterface {
return this.sequelize.query( return this.sequelize.query(
sql, sql,
_.assign({}, options, { type: QueryTypes.DESCRIBE }) Object.assign({}, options, { type: QueryTypes.DESCRIBE })
).then(data => { ).then(data => {
// If no data is returned from the query, then the table name may be wrong. // If no data is returned from the query, then the table name may be wrong.
// Query generators that use information_schema for retrieving table info will just return an empty result set, // Query generators that use information_schema for retrieving table info will just return an empty result set,
...@@ -650,7 +650,7 @@ class QueryInterface { ...@@ -650,7 +650,7 @@ class QueryInterface {
options = Utils.cloneDeep(options); options = Utils.cloneDeep(options);
options.fields = attributes; options.fields = attributes;
const sql = this.QueryGenerator.addIndexQuery(tableName, options, rawTablename); const sql = this.QueryGenerator.addIndexQuery(tableName, options, rawTablename);
return this.sequelize.query(sql, _.assign({}, options, { supportsSearchPath: false })); return this.sequelize.query(sql, Object.assign({}, options, { supportsSearchPath: false }));
} }
/** /**
...@@ -664,7 +664,7 @@ class QueryInterface { ...@@ -664,7 +664,7 @@ class QueryInterface {
*/ */
showIndex(tableName, options) { showIndex(tableName, options) {
const sql = this.QueryGenerator.showIndexesQuery(tableName, options); const sql = this.QueryGenerator.showIndexesQuery(tableName, options);
return this.sequelize.query(sql, _.assign({}, options, { type: QueryTypes.SHOWINDEXES })); return this.sequelize.query(sql, Object.assign({}, options, { type: QueryTypes.SHOWINDEXES }));
} }
getForeignKeysForTables(tableNames, options) { getForeignKeysForTables(tableNames, options) {
...@@ -672,7 +672,7 @@ class QueryInterface { ...@@ -672,7 +672,7 @@ class QueryInterface {
return Promise.resolve({}); return Promise.resolve({});
} }
options = _.assign({}, options || {}, { type: QueryTypes.FOREIGNKEYS }); options = Object.assign({}, options || {}, { type: QueryTypes.FOREIGNKEYS });
return Promise.map(tableNames, tableName => return Promise.map(tableNames, tableName =>
this.sequelize.query(this.QueryGenerator.getForeignKeysQuery(tableName, this.sequelize.config.database), options) this.sequelize.query(this.QueryGenerator.getForeignKeysQuery(tableName, this.sequelize.config.database), options)
...@@ -684,7 +684,7 @@ class QueryInterface { ...@@ -684,7 +684,7 @@ class QueryInterface {
tableName = tableName.schema + '.' + tableName.tableName; tableName = tableName.schema + '.' + tableName.tableName;
} }
result[tableName] = _.isArray(results[i]) result[tableName] = Array.isArray(results[i])
? results[i].map(r => r.constraint_name) ? results[i].map(r => r.constraint_name)
: [results[i] && results[i].constraint_name]; : [results[i] && results[i].constraint_name];
...@@ -1010,7 +1010,7 @@ class QueryInterface { ...@@ -1010,7 +1010,7 @@ class QueryInterface {
* @example * @example
* queryInterface.bulkUpdate('roles', { * queryInterface.bulkUpdate('roles', {
* label: 'admin', * label: 'admin',
* }, { * }, {
* userType: 3, * userType: 3,
* }, * },
* ); * );
...@@ -1369,7 +1369,7 @@ class QueryInterface { ...@@ -1369,7 +1369,7 @@ class QueryInterface {
return Promise.resolve(); return Promise.resolve();
} }
options = _.assign({}, options, { options = Object.assign({}, options, {
transaction: transaction.parent || transaction transaction: transaction.parent || transaction
}); });
...@@ -1387,7 +1387,7 @@ class QueryInterface { ...@@ -1387,7 +1387,7 @@ class QueryInterface {
throw new Error('Unable to start a transaction without transaction object!'); throw new Error('Unable to start a transaction without transaction object!');
} }
options = _.assign({}, options, { options = Object.assign({}, options, {
transaction: transaction.parent || transaction transaction: transaction.parent || transaction
}); });
options.transaction.name = transaction.parent ? transaction.name : undefined; options.transaction.name = transaction.parent ? transaction.name : undefined;
...@@ -1397,7 +1397,7 @@ class QueryInterface { ...@@ -1397,7 +1397,7 @@ class QueryInterface {
} }
deferConstraints(transaction, options) { deferConstraints(transaction, options) {
options = _.assign({}, options, { options = Object.assign({}, options, {
transaction: transaction.parent || transaction transaction: transaction.parent || transaction
}); });
...@@ -1419,7 +1419,7 @@ class QueryInterface { ...@@ -1419,7 +1419,7 @@ class QueryInterface {
return Promise.resolve(); return Promise.resolve();
} }
options = _.assign({}, options, { options = Object.assign({}, options, {
transaction: transaction.parent || transaction, transaction: transaction.parent || transaction,
supportsSearchPath: false supportsSearchPath: false
}); });
...@@ -1437,7 +1437,7 @@ class QueryInterface { ...@@ -1437,7 +1437,7 @@ class QueryInterface {
throw new Error('Unable to rollback a transaction without transaction object!'); throw new Error('Unable to rollback a transaction without transaction object!');
} }
options = _.assign({}, options, { options = Object.assign({}, options, {
transaction: transaction.parent || transaction, transaction: transaction.parent || transaction,
supportsSearchPath: false supportsSearchPath: false
}); });
......
...@@ -134,7 +134,7 @@ class Sequelize { ...@@ -134,7 +134,7 @@ class Sequelize {
if (urlParts.query) { if (urlParts.query) {
if (options.dialectOptions) if (options.dialectOptions)
_.assign(options.dialectOptions, urlParts.query); Object.assign(options.dialectOptions, urlParts.query);
else else
options.dialectOptions = urlParts.query; options.dialectOptions = urlParts.query;
} }
...@@ -413,12 +413,12 @@ class Sequelize { ...@@ -413,12 +413,12 @@ class Sequelize {
/** /**
* Execute a query on the DB, with the possibility to bypass all the sequelize goodness. * Execute a query on the DB, with the possibility to bypass all the sequelize goodness.
* *
* By default, the function will return two arguments: an array of results, and a metadata object, containing number of affected rows etc. Use `.spread` to access the results. * By default, the function will return two arguments: an array of results, and a metadata object, containing number of affected rows etc.
* *
* If you are running a type of query where you don't need the metadata, for example a `SELECT` query, you can pass in a query type to make sequelize format the results: * If you are running a type of query where you don't need the metadata, for example a `SELECT` query, you can pass in a query type to make sequelize format the results:
* *
* ```js * ```js
* sequelize.query('SELECT...').spread((results, metadata) => { * sequelize.query('SELECT...').then(([results, metadata]) => {
* // Raw query - use spread * // Raw query - use spread
* }); * });
* *
...@@ -454,8 +454,8 @@ class Sequelize { ...@@ -454,8 +454,8 @@ class Sequelize {
*/ */
query(sql, options) { query(sql, options) {
options = _.assign({}, this.options.query, options); options = Object.assign({}, this.options.query, options);
const retryOptions = _.assignIn({}, this.options.retry, options.retry || {}); const retryOptions = Object.assign({}, this.options.retry, options.retry || {});
let bindParameters; let bindParameters;
...@@ -591,7 +591,7 @@ class Sequelize { ...@@ -591,7 +591,7 @@ class Sequelize {
set(variables, options) { set(variables, options) {
// Prepare options // Prepare options
options = _.extend({}, this.options.set, typeof options === 'object' && options || {}); options = Object.assign({}, this.options.set, typeof options === 'object' && options);
if (this.options.dialect !== 'mysql') { if (this.options.dialect !== 'mysql') {
throw new Error('sequelize.set is only supported for mysql'); throw new Error('sequelize.set is only supported for mysql');
...@@ -801,7 +801,7 @@ class Sequelize { ...@@ -801,7 +801,7 @@ class Sequelize {
* @returns {Promise} * @returns {Promise}
*/ */
authenticate(options) { authenticate(options) {
options = _.assign({ options = Object.assign({
raw: true, raw: true,
plain: true, plain: true,
type: QueryTypes.SELECT type: QueryTypes.SELECT
......
'use strict'; 'use strict';
const _ = require('lodash');
const Promise = require('./promise'); const Promise = require('./promise');
/** /**
...@@ -29,7 +28,7 @@ class Transaction { ...@@ -29,7 +28,7 @@ class Transaction {
// get dialect specific transaction options // get dialect specific transaction options
const generateTransactionId = this.sequelize.dialect.QueryGenerator.generateTransactionId; const generateTransactionId = this.sequelize.dialect.QueryGenerator.generateTransactionId;
this.options = _.extend({ this.options = Object.assign({
type: sequelize.options.transactionType, type: sequelize.options.transactionType,
isolationLevel: sequelize.options.isolationLevel, isolationLevel: sequelize.options.isolationLevel,
readOnly: false readOnly: false
......
...@@ -265,7 +265,7 @@ function toDefaultValue(value, dialect) { ...@@ -265,7 +265,7 @@ function toDefaultValue(value, dialect) {
return uuidv4(); return uuidv4();
} else if (value instanceof DataTypes.NOW) { } else if (value instanceof DataTypes.NOW) {
return now(dialect); return now(dialect);
} else if (_.isPlainObject(value) || _.isArray(value)) { } else if (_.isPlainObject(value) || Array.isArray(value)) {
return _.clone(value); return _.clone(value);
} else { } else {
return value; return value;
...@@ -516,7 +516,7 @@ exports.getOperators = getOperators; ...@@ -516,7 +516,7 @@ exports.getOperators = getOperators;
* @private * @private
*/ */
function getComplexKeys(obj) { function getComplexKeys(obj) {
return getOperators(obj).concat(_.keys(obj)); return getOperators(obj).concat(Object.keys(obj));
} }
exports.getComplexKeys = getComplexKeys; exports.getComplexKeys = getComplexKeys;
...@@ -596,10 +596,10 @@ function defaults(object) { ...@@ -596,10 +596,10 @@ function defaults(object) {
getComplexKeys(source).forEach(key => { getComplexKeys(source).forEach(key => {
const value = object[key]; const value = object[key];
if ( if (
value === undefined || value === undefined ||
_.eq(value, Object.prototype[key]) && _.eq(value, Object.prototype[key]) &&
!Object.prototype.hasOwnProperty.call(object, key) !Object.prototype.hasOwnProperty.call(object, key)
) { ) {
object[key] = source[key]; object[key] = source[key];
} }
......
'use strict'; 'use strict';
const util = require('util'); const util = require('util');
const _ = require('lodash');
/** /**
* like util.inherits, but also copies over static properties. Inherit child constructor * like util.inherits, but also copies over static properties. Inherit child constructor
...@@ -14,7 +13,7 @@ const _ = require('lodash'); ...@@ -14,7 +13,7 @@ const _ = require('lodash');
*/ */
function inherits(constructor, superConstructor) { function inherits(constructor, superConstructor) {
util.inherits(constructor, superConstructor); // Instance (prototype) methods util.inherits(constructor, superConstructor); // Instance (prototype) methods
_.extend(constructor, superConstructor); // Static methods Object.assign(constructor, superConstructor); // Static methods
} }
module.exports = inherits; module.exports = inherits;
......
...@@ -10,15 +10,14 @@ ...@@ -10,15 +10,14 @@
const depd = require('depd'); const depd = require('depd');
const debug = require('debug'); const debug = require('debug');
const _ = require('lodash');
class Logger { class Logger {
constructor(config) { constructor(config) {
this.config = _.extend({ this.config = Object.assign({
context: 'sequelize', context: 'sequelize',
debug: true debug: true
}, config || {}); }, config);
this.depd = depd(this.config.context); this.depd = depd(this.config.context);
this.debug = debug(this.config.context); this.debug = debug(this.config.context);
......
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!