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

Commit 6640ba2a by Simon Schick Committed by GitHub

refactor: use object spread instead of Object.assign (#12213)

1 parent 777ec098
......@@ -94,7 +94,8 @@
"no-unused-expressions": "error",
"no-sequences": "error",
"no-self-compare": "error",
"no-case-declarations": "off"
"no-case-declarations": "off",
"prefer-object-spread": "error"
},
"settings": {
"jsdoc": {
......
......@@ -73,7 +73,7 @@ class BelongsToMany extends Association {
this.associationType = 'BelongsToMany';
this.targetAssociation = null;
this.sequelize = source.sequelize;
this.through = Object.assign({}, this.options.through);
this.through = { ...this.options.through };
this.isMultiAssociation = true;
this.doubleLinked = false;
......@@ -153,7 +153,7 @@ class BelongsToMany extends Association {
}
}
this.options = Object.assign(this.options, _.pick(this.through.model.options, [
Object.assign(this.options, _.pick(this.through.model.options, [
'timestamps', 'createdAt', 'updatedAt', 'deletedAt', 'paranoid'
]));
......@@ -335,8 +335,8 @@ class BelongsToMany extends Association {
if (!targetAttribute.onUpdate) targetAttribute.onUpdate = 'CASCADE';
}
this.through.model.rawAttributes[this.foreignKey] = Object.assign(this.through.model.rawAttributes[this.foreignKey], sourceAttribute);
this.through.model.rawAttributes[this.otherKey] = Object.assign(this.through.model.rawAttributes[this.otherKey], targetAttribute);
Object.assign(this.through.model.rawAttributes[this.foreignKey], sourceAttribute);
Object.assign(this.through.model.rawAttributes[this.otherKey], targetAttribute);
this.through.model.refreshAttributes();
......@@ -513,13 +513,13 @@ class BelongsToMany extends Association {
instances = [instances];
}
options = Object.assign({
raw: true
}, options, {
options = {
raw: true,
...options,
scope: false,
attributes: [this.targetKey],
joinTableAttributes: []
});
};
const instancePrimaryKeys = instances.map(instance => {
if (instance instanceof this.target) {
......@@ -562,16 +562,16 @@ class BelongsToMany extends Association {
const targetKey = this.targetKey;
const identifier = this.identifier;
const foreignIdentifier = this.foreignIdentifier;
let where = {};
if (newAssociatedObjects === null) {
newAssociatedObjects = [];
} else {
newAssociatedObjects = this.toInstanceArray(newAssociatedObjects);
}
where[identifier] = sourceInstance.get(sourceKey);
where = Object.assign(where, this.through.scope);
const where = {
[identifier]: sourceInstance.get(sourceKey),
...this.through.scope
};
const updateAssociations = currentRows => {
const obsoleteAssociations = [];
......@@ -613,10 +613,11 @@ class BelongsToMany extends Association {
if (obsoleteAssociations.length > 0) {
promises.push(
this.through.model.destroy(_.defaults({
where: Object.assign({
where: {
[identifier]: sourceInstance.get(sourceKey),
[foreignIdentifier]: obsoleteAssociations.map(obsoleteAssociation => obsoleteAssociation[foreignIdentifier])
}, this.through.scope)
[foreignIdentifier]: obsoleteAssociations.map(obsoleteAssociation => obsoleteAssociation[foreignIdentifier]),
...this.through.scope
}
}, options))
);
}
......@@ -631,12 +632,11 @@ class BelongsToMany extends Association {
attributes = _.defaults(attributes, unassociatedObject[this.through.model.name], defaultAttributes);
Object.assign(attributes, this.through.scope);
attributes = Object.assign(attributes, this.through.scope);
return attributes;
});
promises.push(this.through.model.bulkCreate(bulk, Object.assign({ validate: true }, options)));
promises.push(this.through.model.bulkCreate(bulk, { validate: true, ...options }));
}
return Promise.all(promises);
......@@ -680,11 +680,10 @@ class BelongsToMany extends Association {
const where = {
[identifier]: sourceInstance.get(sourceKey),
[foreignIdentifier]: newInstances.map(newInstance => newInstance.get(targetKey))
[foreignIdentifier]: newInstances.map(newInstance => newInstance.get(targetKey)),
...association.through.scope
};
Object.assign(where, association.through.scope);
const updateAssociations = currentRows => {
const promises = [];
const unassociatedObjects = [];
......@@ -717,7 +716,7 @@ class BelongsToMany extends Association {
return attributes;
});
promises.push(association.through.model.bulkCreate(bulk, Object.assign({ validate: true }, options)));
promises.push(association.through.model.bulkCreate(bulk, { validate: true, ...options }));
}
for (const assoc of changedAssociations) {
......
......@@ -201,11 +201,12 @@ class BelongsTo extends Association {
if (options.save === false) return;
options = Object.assign({
options = {
fields: [this.foreignKey],
allowNull: [this.foreignKey],
association: true
}, options);
association: true,
...options
};
// passes the changed field to save, so only that field get updated.
return await sourceInstance.save(options);
......
......@@ -180,7 +180,7 @@ class HasMany extends Association {
instances = undefined;
}
options = Object.assign({}, options);
options = { ...options };
if (this.scope) {
Object.assign(where, this.scope);
......@@ -284,11 +284,12 @@ class HasMany extends Association {
targetInstances = [targetInstances];
}
options = Object.assign({}, options, {
options = {
...options,
scope: false,
attributes: [this.target.primaryKeyAttribute],
raw: true
});
};
where[Op.or] = targetInstances.map(instance => {
if (instance instanceof this.target) {
......@@ -399,12 +400,13 @@ class HasMany extends Association {
async add(sourceInstance, targetInstances, options = {}) {
if (!targetInstances) return Promise.resolve();
const update = {};
targetInstances = this.toInstanceArray(targetInstances);
update[this.foreignKey] = sourceInstance.get(this.sourceKey);
Object.assign(update, this.scope);
const update = {
[this.foreignKey]: sourceInstance.get(this.sourceKey),
...this.scope
};
const where = {
[this.target.primaryKeyAttribute]: targetInstances.map(unassociatedObject =>
......
......@@ -190,9 +190,7 @@ class HasOne extends Association {
* @returns {Promise}
*/
async set(sourceInstance, associatedInstance, options) {
options = Object.assign({}, options, {
scope: false
});
options = { ...options, scope: false };
const oldInstance = await sourceInstance[this.accessors.get](options);
// TODO Use equals method once #5605 is resolved
......@@ -203,11 +201,12 @@ class HasOne extends Association {
if (oldInstance && !alreadyAssociated) {
oldInstance[this.foreignKey] = null;
await oldInstance.save(Object.assign({}, options, {
await oldInstance.save({
...options,
fields: [this.foreignKey],
allowNull: [this.foreignKey],
association: true
}));
});
}
if (associatedInstance && !alreadyAssociated) {
if (!(associatedInstance instanceof this.target)) {
......
......@@ -24,7 +24,7 @@ const Mixin = {
options.hooks = options.hooks === undefined ? false : Boolean(options.hooks);
options.useHooks = options.hooks;
options = Object.assign(options, _.omit(source.options, ['hooks']));
Object.assign(options, _.omit(source.options, ['hooks']));
if (options.useHooks) {
this.runHooks('beforeAssociate', { source, target, type: HasMany }, options);
......@@ -55,7 +55,7 @@ const Mixin = {
options.hooks = options.hooks === undefined ? false : Boolean(options.hooks);
options.useHooks = options.hooks;
options.timestamps = options.timestamps === undefined ? this.sequelize.options.timestamps : options.timestamps;
options = Object.assign(options, _.omit(source.options, ['hooks', 'timestamps', 'scopes', 'defaultScope']));
Object.assign(options, _.omit(source.options, ['hooks', 'timestamps', 'scopes', 'defaultScope']));
if (options.useHooks) {
this.runHooks('beforeAssociate', { source, target, type: BelongsToMany }, options);
......
......@@ -1204,7 +1204,7 @@ class QueryGenerator {
if (!mainTable.as) {
mainTable.as = mainTable.quotedName;
}
const where = Object.assign({}, options.where);
const where = { ...options.where };
let groupedLimitOrder,
whereKey,
include,
......@@ -1224,9 +1224,10 @@ class QueryGenerator {
association: options.groupedLimit.on.manyFromSource,
duplicating: false, // The UNION'ed query may contain duplicates, but each sub-query cannot
required: true,
where: Object.assign({
[Op.placeholder]: true
}, options.groupedLimit.through && options.groupedLimit.through.where)
where: {
[Op.placeholder]: true,
...options.groupedLimit.through && options.groupedLimit.through.where
}
}],
model
});
......@@ -1932,7 +1933,7 @@ class QueryGenerator {
return;
}
nestedIncludes = [Object.assign({}, child, { include: nestedIncludes, attributes: [] })];
nestedIncludes = [{ ...child, include: nestedIncludes, attributes: [] }];
child = parent;
}
......@@ -2009,7 +2010,7 @@ class QueryGenerator {
* are preserved.
*/
_getRequiredClosure(include) {
const copy = Object.assign({}, include, { attributes: [], include: [] });
const copy = { ...include, attributes: [], include: [] };
if (Array.isArray(include.include)) {
copy.include = include.include
......@@ -2265,7 +2266,7 @@ class QueryGenerator {
const tmp = {};
const field = options.model.rawAttributes[keyParts[0]];
_.set(tmp, keyParts.slice(1), value);
return this.whereItemQuery(field.field || keyParts[0], tmp, Object.assign({ field }, options));
return this.whereItemQuery(field.field || keyParts[0], tmp, { field, ...options });
}
}
......@@ -2429,7 +2430,7 @@ class QueryGenerator {
const where = {
[op]: value[op]
};
items.push(this.whereItemQuery(key, where, Object.assign({}, options, { json: false })));
items.push(this.whereItemQuery(key, where, { ...options, json: false }));
});
_.forOwn(value, (item, prop) => {
......
......@@ -51,7 +51,7 @@ const OperatorHelpers = {
if (!aliases || _.isEmpty(aliases)) {
this.OperatorsAliasMap = false;
} else {
this.OperatorsAliasMap = Object.assign({}, aliases);
this.OperatorsAliasMap = { ...aliases };
}
},
......
......@@ -15,12 +15,13 @@ class AbstractQuery {
this.instance = options.instance;
this.model = options.model;
this.sequelize = sequelize;
this.options = Object.assign({
this.options = {
plain: false,
raw: false,
// eslint-disable-next-line no-console
logging: console.log
}, options || {});
logging: console.log,
...options
};
this.checkLoggingOption();
}
......
......@@ -68,13 +68,10 @@ class ConnectionManager extends AbstractConnectionManager {
typeCast: ConnectionManager._typecast.bind(this),
bigNumberStrings: false,
supportBigNumbers: true,
foundRows: false
foundRows: false,
...config.dialectOptions
};
if (config.dialectOptions) {
Object.assign(connectionConfig, config.dialectOptions);
}
if (!this.sequelize.config.keepDefaultTimezone) {
// set timezone for this connection
if (connectionConfig.initSql) {
......
......@@ -5,10 +5,11 @@ const Utils = require('./../../utils');
class MariaDBQueryGenerator extends MySQLQueryGenerator {
createSchema(schema, options) {
options = Object.assign({
options = {
charset: null,
collate: null
}, options || {});
collate: null,
...options
};
return Utils.joinSQLFragments([
'CREATE SCHEMA IF NOT EXISTS',
......
......@@ -14,7 +14,7 @@ const debug = logger.debugContext('sql:mariadb');
class Query extends AbstractQuery {
constructor(connection, sequelize, options) {
super(connection, sequelize, Object.assign({ showWarnings: false }, options));
super(connection, sequelize, { showWarnings: false, ...options });
}
static formatBindParameters(sql, values, dialect) {
......
......@@ -16,9 +16,7 @@ const throwMethodUndefined = function(methodName) {
class MSSQLQueryGenerator extends AbstractQueryGenerator {
createDatabaseQuery(databaseName, options) {
options = Object.assign({
collate: null
}, options || {});
options = { collate: null, ...options };
const collation = options.collate ? `COLLATE ${this.escape(options.collate)}` : '';
......@@ -838,14 +836,14 @@ class MSSQLQueryGenerator extends AbstractQueryGenerator {
selectFromTableFragment(options, model, attributes, tables, mainTableAs, where) {
this._throwOnEmptyAttributes(attributes, { modelName: model && model.name, as: mainTableAs });
const dbVersion = this.sequelize.options.databaseVersion;
const isSQLServer2008 = semver.valid(dbVersion) && semver.lt(dbVersion, '11.0.0');
if (isSQLServer2008 && options.offset) {
// For earlier versions of SQL server, we need to nest several queries
// in order to emulate the OFFSET behavior.
//
//
// 1. The outermost query selects all items from the inner query block.
// This is due to a limitation in SQL server with the use of computed
// columns (e.g. SELECT ROW_NUMBER()...AS x) in WHERE clauses.
......
......@@ -21,7 +21,7 @@
@private
*/
const removeColumn = async function(qi, tableName, attributeName, options) {
options = Object.assign({ raw: true }, options || {});
options = { raw: true, ...options };
const findConstraintSql = qi.QueryGenerator.getDefaultConstraintQuery(tableName, attributeName);
const [results0] = await qi.sequelize.query(findConstraintSql, options);
......
......@@ -54,7 +54,7 @@ class ConnectionManager extends AbstractConnectionManager {
* @private
*/
async connect(config) {
const connectionConfig = Object.assign({
const connectionConfig = {
host: config.host,
port: config.port,
user: config.username,
......@@ -64,8 +64,9 @@ class ConnectionManager extends AbstractConnectionManager {
timezone: this.sequelize.options.timezone,
typeCast: ConnectionManager._typecast.bind(this),
bigNumberStrings: false,
supportBigNumbers: true
}, config.dialectOptions);
supportBigNumbers: true,
...config.dialectOptions
};
try {
const connection = await new Promise((resolve, reject) => {
......
......@@ -31,17 +31,19 @@ class MySQLQueryGenerator extends AbstractQueryGenerator {
constructor(options) {
super(options);
this.OperatorMap = Object.assign({}, this.OperatorMap, {
this.OperatorMap = {
...this.OperatorMap,
[Op.regexp]: 'REGEXP',
[Op.notRegexp]: 'NOT REGEXP'
});
};
}
createDatabaseQuery(databaseName, options) {
options = Object.assign({
options = {
charset: null,
collate: null
}, options || {});
collate: null,
...options
};
return Utils.joinSQLFragments([
'CREATE DATABASE IF NOT EXISTS',
......@@ -69,11 +71,12 @@ class MySQLQueryGenerator extends AbstractQueryGenerator {
}
createTableQuery(tableName, attributes, options) {
options = Object.assign({
options = {
engine: 'InnoDB',
charset: null,
rowFormat: null
}, options || {});
rowFormat: null,
...options
};
const primaryKeys = [];
const foreignKeys = {};
......
......@@ -28,20 +28,20 @@ async function removeColumn(qi, tableName, columnName, options) {
tableName,
schema: qi.sequelize.config.database
}, columnName),
Object.assign({ raw: true }, options)
{ raw: true, ...options }
);
//Exclude primary key constraint
if (results.length && results[0].constraint_name !== 'PRIMARY') {
await Promise.all(results.map(constraint => qi.sequelize.query(
qi.QueryGenerator.dropForeignKeyQuery(tableName, constraint.constraint_name),
Object.assign({ raw: true }, options)
{ raw: true, ...options }
)));
}
return await qi.sequelize.query(
qi.QueryGenerator.removeColumnQuery(tableName, columnName),
Object.assign({ raw: true }, options)
{ raw: true, ...options }
);
}
......@@ -60,8 +60,10 @@ async function removeConstraint(qi, tableName, constraintName, options) {
schema: qi.sequelize.config.database
}, constraintName);
const constraints = await qi.sequelize.query(sql, Object.assign({}, options,
{ type: qi.sequelize.QueryTypes.SHOWCONSTRAINTS }));
const constraints = await qi.sequelize.query(sql, {
...options,
type: qi.sequelize.QueryTypes.SHOWCONSTRAINTS
});
const constraint = constraints[0];
let query;
......
......@@ -10,7 +10,7 @@ const debug = logger.debugContext('sql:mysql');
class Query extends AbstractQuery {
constructor(connection, sequelize, options) {
super(connection, sequelize, Object.assign({ showWarnings: false }, options));
super(connection, sequelize, { showWarnings: false, ...options });
}
static formatBindParameters(sql, values, dialect) {
......
......@@ -13,10 +13,11 @@ class PostgresQueryGenerator extends AbstractQueryGenerator {
}
createDatabaseQuery(databaseName, options) {
options = Object.assign({
options = {
encoding: null,
collate: null
}, options || {});
collate: null,
...options
};
const values = {
database: this.quoteTable(databaseName),
......@@ -56,7 +57,7 @@ class PostgresQueryGenerator extends AbstractQueryGenerator {
}
createTableQuery(tableName, attributes, options) {
options = Object.assign({}, options || {});
options = { ...options };
//Postgres 9.0 does not support CREATE TABLE IF NOT EXISTS, 9.1 and above do
const databaseVersion = _.get(this, 'sequelize.options.databaseVersion', 0);
......@@ -600,7 +601,7 @@ class PostgresQueryGenerator extends AbstractQueryGenerator {
for (const key in attributes) {
const attribute = attributes[key];
result[attribute.field || key] = this.attributeToSQL(attribute, Object.assign({ key }, options || {}));
result[attribute.field || key] = this.attributeToSQL(attribute, { key, ...options });
}
return result;
......
......@@ -44,7 +44,7 @@ async function ensureEnums(qi, tableName, attributes, options, model) {
sql = qi.QueryGenerator.pgListEnums(tableName, attribute.field || keys[i], options);
promises.push(qi.sequelize.query(
sql,
Object.assign({}, options, { plain: true, raw: true, type: QueryTypes.SELECT })
{ ...options, plain: true, raw: true, type: QueryTypes.SELECT }
));
}
}
......@@ -89,7 +89,7 @@ async function ensureEnums(qi, tableName, attributes, options, model) {
// If the enum type doesn't exist then create it
if (!results[enumIdx]) {
promises.push(() => {
return qi.sequelize.query(qi.QueryGenerator.pgEnum(tableName, field, enumType, options), Object.assign({}, options, { raw: true }));
return qi.sequelize.query(qi.QueryGenerator.pgEnum(tableName, field, enumType, options), { ...options, raw: true });
});
} else if (!!results[enumIdx] && !!model) {
const enumVals = qi.QueryGenerator.fromArray(results[enumIdx].enum_value);
......
......@@ -35,7 +35,7 @@ async function removeColumn(qi, tableName, attributeName, options) {
const sql = qi.QueryGenerator.removeColumnQuery(tableName, fields);
const subQueries = sql.split(';').filter(q => q !== '');
for (const subQuery of subQueries) await qi.sequelize.query(`${subQuery};`, Object.assign({ raw: true }, options));
for (const subQuery of subQueries) await qi.sequelize.query(`${subQuery};`, { raw: true, ...options });
}
exports.removeColumn = removeColumn;
......@@ -63,7 +63,7 @@ async function changeColumn(qi, tableName, attributes, options) {
const sql = qi.QueryGenerator.removeColumnQuery(tableName, fields);
const subQueries = sql.split(';').filter(q => q !== '');
for (const subQuery of subQueries) await qi.sequelize.query(`${subQuery};`, Object.assign({ raw: true }, options));
for (const subQuery of subQueries) await qi.sequelize.query(`${subQuery};`, { raw: true, ...options });
}
exports.changeColumn = changeColumn;
......@@ -92,7 +92,7 @@ async function renameColumn(qi, tableName, attrNameBefore, attrNameAfter, option
const sql = qi.QueryGenerator.renameColumnQuery(tableName, attrNameBefore, attrNameAfter, fields);
const subQueries = sql.split(';').filter(q => q !== '');
for (const subQuery of subQueries) await qi.sequelize.query(`${subQuery};`, Object.assign({ raw: true }, options));
for (const subQuery of subQueries) await qi.sequelize.query(`${subQuery};`, { raw: true, ...options });
}
exports.renameColumn = renameColumn;
......@@ -139,7 +139,7 @@ async function removeConstraint(qi, tableName, constraintName, options) {
const sql = qi.QueryGenerator._alterConstraintQuery(tableName, fields, createTableSql);
const subQueries = sql.split(';').filter(q => q !== '');
for (const subQuery of subQueries) await qi.sequelize.query(`${subQuery};`, Object.assign({ raw: true }, options));
for (const subQuery of subQueries) await qi.sequelize.query(`${subQuery};`, { raw: true, ...options });
}
exports.removeConstraint = removeConstraint;
......@@ -154,7 +154,7 @@ async function addConstraint(qi, tableName, options) {
const constraintSnippet = qi.QueryGenerator.getConstraintSnippet(tableName, options);
const describeCreateTableSql = qi.QueryGenerator.describeCreateTableQuery(tableName);
const constraints = await qi.sequelize.query(describeCreateTableSql, Object.assign({}, options, { type: QueryTypes.SELECT, raw: true }));
const constraints = await qi.sequelize.query(describeCreateTableSql, { ...options, type: QueryTypes.SELECT, raw: true });
let sql = constraints[0].sql;
const index = sql.length - 1;
//Replace ending ')' with constraint snippet - Simulates String.replaceAt
......@@ -165,7 +165,7 @@ async function addConstraint(qi, tableName, options) {
sql = qi.QueryGenerator._alterConstraintQuery(tableName, fields, createTableSql);
const subQueries = sql.split(';').filter(q => q !== '');
for (const subQuery of subQueries) await qi.sequelize.query(`${subQuery};`, Object.assign({ raw: true }, options));
for (const subQuery of subQueries) await qi.sequelize.query(`${subQuery};`, { raw: true, ...options });
}
exports.addConstraint = addConstraint;
......
......@@ -109,10 +109,11 @@ class QueryInterface {
* @returns {Promise<Array>}
*/
async showAllSchemas(options) {
options = Object.assign({}, options, {
options = {
...options,
raw: true,
type: this.sequelize.QueryTypes.SELECT
});
};
const showSchemasSql = this.QueryGenerator.showSchemasQuery(options);
......@@ -133,7 +134,7 @@ class QueryInterface {
async databaseVersion(options) {
return await this.sequelize.query(
this.QueryGenerator.versionQuery(),
Object.assign({}, options, { type: QueryTypes.VERSION })
{ ...options, type: QueryTypes.VERSION }
);
}
......@@ -266,7 +267,7 @@ class QueryInterface {
if (instanceTable.rawAttributes[keys[i]].type instanceof DataTypes.ENUM) {
sql = this.QueryGenerator.pgEnumDrop(getTableName, keys[i]);
options.supportsSearchPath = false;
promises.push(this.sequelize.query(sql, Object.assign({}, options, { raw: true })));
promises.push(this.sequelize.query(sql, { ...options, raw: true }));
}
}
}
......@@ -293,7 +294,7 @@ class QueryInterface {
for (const tableName of tableNames) {
// if tableName is not in the Array of tables names then don't drop it
if (!skip.includes(tableName.tableName || tableName)) {
await this.dropTable(tableName, Object.assign({}, options, { cascade: true }) );
await this.dropTable(tableName, { ...options, cascade: true } );
}
}
};
......@@ -345,7 +346,7 @@ class QueryInterface {
return this.sequelize.query(
this.QueryGenerator.pgEnumDrop(null, null, this.QueryGenerator.pgEscapeAndQuote(enumName)),
Object.assign({}, options, { raw: true })
{ ...options, raw: true }
);
}
......@@ -368,7 +369,7 @@ class QueryInterface {
return await Promise.all(enums.map(result => this.sequelize.query(
this.QueryGenerator.pgEnumDrop(null, null, this.QueryGenerator.pgEscapeAndQuote(result.enum_name)),
Object.assign({}, options, { raw: true })
{ ...options, raw: true }
)));
}
......@@ -384,7 +385,7 @@ class QueryInterface {
pgListEnums(tableName, options) {
options = options || {};
const sql = this.QueryGenerator.pgListEnums(tableName);
return this.sequelize.query(sql, Object.assign({}, options, { plain: false, raw: true, type: QueryTypes.SELECT }));
return this.sequelize.query(sql, { ...options, plain: false, raw: true, type: QueryTypes.SELECT });
}
/**
......@@ -413,10 +414,11 @@ class QueryInterface {
* @private
*/
async showAllTables(options) {
options = Object.assign({}, options, {
options = {
...options,
raw: true,
type: QueryTypes.SHOWTABLES
});
};
const showTablesSql = this.QueryGenerator.showTablesQuery(this.sequelize.config.database);
const tableNames = await this.sequelize.query(showTablesSql, options);
......@@ -465,7 +467,7 @@ class QueryInterface {
}
const sql = this.QueryGenerator.describeTableQuery(tableName, schema, schemaDelimiter);
options = Object.assign({}, options, { type: QueryTypes.DESCRIBE });
options = { ...options, type: QueryTypes.DESCRIBE };
try {
const data = await this.sequelize.query(sql, options);
......@@ -655,7 +657,7 @@ class QueryInterface {
options = Utils.cloneDeep(options);
options.fields = attributes;
const sql = this.QueryGenerator.addIndexQuery(tableName, options, rawTablename);
return await this.sequelize.query(sql, Object.assign({}, options, { supportsSearchPath: false }));
return await this.sequelize.query(sql, { ...options, supportsSearchPath: false });
}
/**
......@@ -669,7 +671,7 @@ class QueryInterface {
*/
async showIndex(tableName, options) {
const sql = this.QueryGenerator.showIndexesQuery(tableName, options);
return await this.sequelize.query(sql, Object.assign({}, options, { type: QueryTypes.SHOWINDEXES }));
return await this.sequelize.query(sql, { ...options, type: QueryTypes.SHOWINDEXES });
}
......@@ -686,7 +688,7 @@ class QueryInterface {
return {};
}
options = Object.assign({}, options || {}, { type: QueryTypes.FOREIGNKEYS });
options = { ...options, type: QueryTypes.FOREIGNKEYS };
const results = await Promise.all(tableNames.map(tableName =>
this.sequelize.query(this.QueryGenerator.getForeignKeysQuery(tableName, this.sequelize.config.database), options)));
......@@ -722,9 +724,7 @@ class QueryInterface {
* @returns {Promise}
*/
async getForeignKeyReferencesForTable(tableName, options) {
const queryOptions = Object.assign({}, options, {
type: QueryTypes.FOREIGNKEYS
});
const queryOptions = { ...options, type: QueryTypes.FOREIGNKEYS };
const catalogName = this.sequelize.config.database;
switch (this.sequelize.options.dialect) {
case 'sqlite':
......@@ -853,7 +853,7 @@ class QueryInterface {
async showConstraint(tableName, constraintName, options) {
const sql = this.QueryGenerator.showConstraintsQuery(tableName, constraintName);
return await this.sequelize.query(sql, Object.assign({}, options, { type: QueryTypes.SHOWCONSTRAINTS }));
return await this.sequelize.query(sql, { ...options, type: QueryTypes.SHOWCONSTRAINTS });
}
/**
......@@ -1115,7 +1115,7 @@ class QueryInterface {
}
async select(model, tableName, optionsArg) {
const options = Object.assign({}, optionsArg, { type: QueryTypes.SELECT, model });
const options = { ...optionsArg, type: QueryTypes.SELECT, model };
return await this.sequelize.query(
this.QueryGenerator.selectQuery(tableName, options, model),
......@@ -1376,9 +1376,7 @@ class QueryInterface {
return;
}
options = Object.assign({}, options, {
transaction: transaction.parent || transaction
});
options = { ...options, transaction: transaction.parent || transaction };
const sql = this.QueryGenerator.setIsolationLevelQuery(value, {
parent: transaction.parent
......@@ -1394,9 +1392,7 @@ class QueryInterface {
throw new Error('Unable to start a transaction without transaction object!');
}
options = Object.assign({}, options, {
transaction: transaction.parent || transaction
});
options = { ...options, transaction: transaction.parent || transaction };
options.transaction.name = transaction.parent ? transaction.name : undefined;
const sql = this.QueryGenerator.startTransactionQuery(transaction);
......@@ -1404,9 +1400,7 @@ class QueryInterface {
}
async deferConstraints(transaction, options) {
options = Object.assign({}, options, {
transaction: transaction.parent || transaction
});
options = { ...options, transaction: transaction.parent || transaction };
const sql = this.QueryGenerator.deferConstraintsQuery(options);
......@@ -1424,11 +1418,12 @@ class QueryInterface {
return;
}
options = Object.assign({}, options, {
options = {
...options,
transaction: transaction.parent || transaction,
supportsSearchPath: false,
completesTransaction: true
});
};
const sql = this.QueryGenerator.commitTransactionQuery(transaction);
const promise = this.sequelize.query(sql, options);
......@@ -1443,11 +1438,12 @@ class QueryInterface {
throw new Error('Unable to rollback a transaction without transaction object!');
}
options = Object.assign({}, options, {
options = {
...options,
transaction: transaction.parent || transaction,
supportsSearchPath: false,
completesTransaction: true
});
};
options.transaction.name = transaction.parent ? transaction.name : undefined;
const sql = this.QueryGenerator.rollbackTransactionQuery(transaction);
const promise = this.sequelize.query(sql, options);
......
......@@ -231,7 +231,7 @@ class Sequelize {
Sequelize.runHooks('beforeInit', config, options);
this.options = Object.assign({
this.options = {
dialect: null,
dialectModule: null,
dialectModulePath: null,
......@@ -264,8 +264,9 @@ class Sequelize {
typeValidation: false,
benchmark: false,
minifyAliases: false,
logQueryParameters: false
}, options || {});
logQueryParameters: false,
...options
};
if (!this.options.dialect) {
throw new Error('Dialect needs to be explicitly supplied as of v4.0.0');
......@@ -504,7 +505,7 @@ class Sequelize {
*/
async query(sql, options) {
options = Object.assign({}, this.options.query, options);
options = { ...this.options.query, ...options };
if (options.instance && !options.model) {
options.model = options.instance.constructor;
......@@ -596,7 +597,7 @@ class Sequelize {
}
};
const retryOptions = Object.assign({}, this.options.retry, options.retry || {});
const retryOptions = { ...this.options.retry, ...options.retry };
return retry(async () => {
if (options.transaction === undefined && Sequelize._cls) {
......@@ -636,7 +637,7 @@ class Sequelize {
async set(variables, options) {
// Prepare options
options = Object.assign({}, this.options.set, typeof options === 'object' && options);
options = { ...this.options.set, ...typeof options === 'object' && options };
if (this.options.dialect !== 'mysql') {
throw new Error('sequelize.set is only supported for mysql');
......@@ -849,11 +850,12 @@ class Sequelize {
* @returns {Promise}
*/
async authenticate(options) {
options = Object.assign({
options = {
raw: true,
plain: true,
type: QueryTypes.SELECT
}, options);
type: QueryTypes.SELECT,
...options
};
await this.query('SELECT 1+1 AS result', options);
......
......@@ -26,11 +26,12 @@ class Transaction {
// get dialect specific transaction options
const generateTransactionId = this.sequelize.dialect.QueryGenerator.generateTransactionId;
this.options = Object.assign({
this.options = {
type: sequelize.options.transactionType,
isolationLevel: sequelize.options.isolationLevel,
readOnly: false
}, options || {});
readOnly: false,
...options
};
this.parent = this.options.transaction;
......
......@@ -14,10 +14,11 @@ const util = require('util');
class Logger {
constructor(config) {
this.config = Object.assign({
this.config = {
context: 'sequelize',
debug: true
}, config);
debug: true,
...config
};
}
warn(message) {
......
......@@ -10,7 +10,7 @@ if (dialect !== 'mariadb') return;
describe('[MariaDB Specific] Errors', () => {
const validateError = (promise, errClass, errValues) => {
const wanted = Object.assign({}, errValues);
const wanted = { ...errValues };
return expect(promise).to.have.been.rejectedWith(errClass).then(() =>
promise.catch(err => Object.keys(wanted).forEach(
......
......@@ -11,7 +11,7 @@ if (dialect === 'mysql') {
describe('[MYSQL Specific] Errors', () => {
const validateError = (promise, errClass, errValues) => {
const wanted = Object.assign({}, errValues);
const wanted = { ...errValues };
return expect(promise).to.have.been.rejectedWith(errClass).then(() =>
promise.catch(err => Object.keys(wanted).forEach(k => expect(err[k]).to.eql(wanted[k]))));
......
......@@ -9,7 +9,7 @@ const chai = require('chai'),
if (dialect.match(/^postgres/)) {
describe('[POSTGRES] Sequelize', () => {
function checkTimezoneParsing(baseOptions) {
const options = Object.assign({}, baseOptions, { timezone: 'Asia/Kolkata', timestamps: true });
const options = { ...baseOptions, timezone: 'Asia/Kolkata', timestamps: true };
const sequelize = Support.createSequelizeInstance(options);
const tzTable = sequelize.define('tz_table', { foo: DataTypes.STRING });
......
......@@ -49,7 +49,7 @@ if (dialect.match(/^postgres/)) {
};
it('should throw due to alias being truncated', function() {
const options = Object.assign({}, this.sequelize.options, { minifyAliases: false });
const options = { ...this.sequelize.options, minifyAliases: false };
return executeTest(options, res => {
expect(res[taskAlias]).to.not.exist;
......@@ -57,7 +57,7 @@ if (dialect.match(/^postgres/)) {
});
it('should be able to retrieve include due to alias minifying', function() {
const options = Object.assign({}, this.sequelize.options, { minifyAliases: true });
const options = { ...this.sequelize.options, minifyAliases: true };
return executeTest(options, res => {
expect(res[taskAlias].title).to.be.equal('SuperTask');
......
......@@ -62,12 +62,12 @@ describe(Support.getTestDialectTeaser('Sequelize'), () => {
if (dialect === 'postgres') {
const getConnectionUri = o => `${o.protocol}://${o.username}:${o.password}@${o.host}${o.port ? `:${o.port}` : ''}/${o.database}`;
it('should work with connection strings (postgres protocol)', () => {
const connectionUri = getConnectionUri(Object.assign(config[dialect], { protocol: 'postgres' }));
const connectionUri = getConnectionUri({ ...config[dialect], protocol: 'postgres' });
// postgres://...
new Sequelize(connectionUri);
});
it('should work with connection strings (postgresql protocol)', () => {
const connectionUri = getConnectionUri(Object.assign(config[dialect], { protocol: 'postgresql' }));
const connectionUri = getConnectionUri({ ...config[dialect], protocol: 'postgresql' });
// postgresql://...
new Sequelize(connectionUri);
});
......@@ -84,7 +84,7 @@ describe(Support.getTestDialectTeaser('Sequelize'), () => {
describe('with an invalid connection', () => {
beforeEach(function() {
const options = Object.assign({}, this.sequelize.options, { port: '99999' });
const options = { ...this.sequelize.options, port: '99999' };
this.sequelizeWithInvalidConnection = new Sequelize('wat', 'trololo', 'wow', options);
});
......@@ -341,7 +341,7 @@ describe(Support.getTestDialectTeaser('Sequelize'), () => {
}, {
timestamps: false
});
return this.User.sync({ force: true });
});
it('add parameters in log sql', function() {
......@@ -365,7 +365,7 @@ describe(Support.getTestDialectTeaser('Sequelize'), () => {
expect(updateSql).to.match(/; ("li", 1|{"(\$1|0)":"li","(\$2|1)":1})/);
});
});
it('add parameters in log sql when use bind value', function() {
let logSql;
const typeCast = dialect === 'postgres' ? '::text' : '';
......@@ -375,7 +375,7 @@ describe(Support.getTestDialectTeaser('Sequelize'), () => {
});
});
});
});
it('executes select queries correctly', function() {
......
......@@ -18,7 +18,7 @@ describe(Support.getTestDialectTeaser('Sequelize'), () => {
options = options || {};
const taskTableName = options.taskTableName || `tasks_${config.rand()}`;
const transactionOptions = Object.assign({}, { deferrable: Sequelize.Deferrable.SET_DEFERRED }, options);
const transactionOptions = { deferrable: Sequelize.Deferrable.SET_DEFERRED, ...options };
const userTableName = `users_${config.rand()}`;
const User = this.sequelize.define(
......
......@@ -77,7 +77,7 @@ const Support = {
if (fs.existsSync(p)) {
fs.unlinkSync(p);
}
const options = Object.assign({}, sequelize.options, { storage: p }),
const options = { ...sequelize.options, storage: p },
_sequelize = new Sequelize(sequelize.config.database, null, null, options);
return _sequelize.sync({ force: true }).then(() => _sequelize);
......
......@@ -834,7 +834,7 @@ if (dialect === 'mariadb') {
}
// Options would normally be set by the query interface that instantiates the query-generator, but here we specify it explicitly
this.queryGenerator.options = Object.assign({}, this.queryGenerator.options, test.context && test.context.options || {});
this.queryGenerator.options = { ...this.queryGenerator.options, ...test.context && test.context.options };
const conditions = this.queryGenerator[suiteTitle](...test.arguments);
expect(conditions).to.deep.equal(test.expectation);
......
......@@ -785,7 +785,7 @@ if (dialect === 'mysql') {
}
// Options would normally be set by the query interface that instantiates the query-generator, but here we specify it explicitly
this.queryGenerator.options = Object.assign({}, this.queryGenerator.options, test.context && test.context.options || {});
this.queryGenerator.options = { ...this.queryGenerator.options, ...test.context && test.context.options };
const conditions = this.queryGenerator[suiteTitle](...test.arguments);
expect(conditions).to.deep.equal(test.expectation);
......
......@@ -1280,7 +1280,7 @@ if (dialect.startsWith('postgres')) {
}
// Options would normally be set by the query interface that instantiates the query-generator, but here we specify it explicitly
this.queryGenerator.options = Object.assign({}, this.queryGenerator.options, test.context && test.context.options || {});
this.queryGenerator.options = { ...this.queryGenerator.options, ...test.context && test.context.options };
const conditions = this.queryGenerator[suiteTitle](...test.arguments);
expect(conditions).to.deep.equal(test.expectation);
......
......@@ -645,7 +645,7 @@ if (dialect === 'sqlite') {
}
// Options would normally be set by the query interface that instantiates the query-generator, but here we specify it explicitly
this.queryGenerator.options = Object.assign({}, this.queryGenerator.options, test.context && test.context.options || {});
this.queryGenerator.options = { ...this.queryGenerator.options, ...test.context && test.context.options };
const conditions = this.queryGenerator[suiteTitle](...test.arguments);
expect(conditions).to.deep.equal(test.expectation);
......
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!