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

Commit 9f7b51ef by Simon Schick

refactor: use default parameters

1 parent 740fed0a
......@@ -54,6 +54,7 @@
"./docs/resources.md",
"./docs/typescript.md",
"./docs/upgrade-to-v5.md",
"./docs/upgrade-to-v6.md",
"./docs/legacy.md",
"./docs/whos-using.md",
"./docs/legal.md"
......
......@@ -20,9 +20,9 @@ Sequelize follows [SEMVER](http://semver.org). Supports Node v6 and above to use
New to Sequelize? Take a look at the [Tutorials and Guides](http://docs.sequelizejs.com/). You might also be interested in the [API Reference](http://docs.sequelizejs.com/identifiers).
## v5 Release
## v6 Release
You can find the upgrade guide and changelog [here](http://docs.sequelizejs.com/manual/upgrade-to-v5.html).
You can find the upgrade guide and changelog [here](http://docs.sequelizejs.com/manual/upgrade-to-v6.html).
## Table of Contents
- [Installation](#installation)
......@@ -33,7 +33,7 @@ You can find the upgrade guide and changelog [here](http://docs.sequelizejs.com/
## Installation
```bash
$ npm install --save sequelize # This will install v5
$ npm install --save sequelize # This will install v6
# And one of the following:
$ npm install --save pg pg-hstore # Postgres
......@@ -44,7 +44,8 @@ $ npm install --save tedious # Microsoft SQL Server
```
## Documentation
- [v5 Documentation](http://docs.sequelizejs.com)
- [v6 Documentation](http://docs.sequelizejs.com)
- [v5 Documentation](https://github.com/sequelize/sequelize/blob/v5/docs)
- [v4 Documentation](https://github.com/sequelize/sequelize/blob/v4/docs)
- [v3 Documentation](https://sequelize.readthedocs.io/en/v3/)
- [Contributing](https://github.com/sequelize/sequelize/blob/master/CONTRIBUTING.md)
......
# Upgrade to v5
# Upgrade to v6
Sequelize v5 is the next major release after v4
Sequelize v6 is the next major release after v4
## Breaking Changes
......
......@@ -376,8 +376,8 @@ class BelongsToMany extends Association {
*
* @returns {Promise<Array<Model>>}
*/
get(instance, options) {
options = Utils.cloneDeep(options) || {};
get(instance, options = {}) {
options = Utils.cloneDeep(options);
const through = this.through;
let scopeWhere;
......@@ -514,9 +514,7 @@ class BelongsToMany extends Association {
*
* @returns {Promise}
*/
set(sourceInstance, newAssociatedObjects, options) {
options = options || {};
set(sourceInstance, newAssociatedObjects, options = {}) {
const sourceKey = this.source.primaryKeyAttribute;
const targetKey = this.target.primaryKeyAttribute;
const identifier = this.identifier;
......@@ -625,21 +623,20 @@ class BelongsToMany extends Association {
options = { ...options };
const association = this;
const sourceKey = association.source.primaryKeyAttribute;
const targetKey = association.target.primaryKeyAttribute;
const identifier = association.identifier;
const foreignIdentifier = association.foreignIdentifier;
const sourceKey = this.source.primaryKeyAttribute;
const targetKey = this.target.primaryKeyAttribute;
const identifier = this.identifier;
const foreignIdentifier = this.foreignIdentifier;
const defaultAttributes = options.through || {};
newInstances = association.toInstanceArray(newInstances);
newInstances = this.toInstanceArray(newInstances);
const where = {
[identifier]: sourceInstance.get(sourceKey),
[foreignIdentifier]: newInstances.map(newInstance => newInstance.get(targetKey))
};
Object.assign(where, association.through.scope);
Object.assign(where, this.through.scope);
const updateAssociations = currentRows => {
const promises = [];
......@@ -651,7 +648,7 @@ class BelongsToMany extends Association {
if (!existingAssociation) {
unassociatedObjects.push(obj);
} else {
const throughAttributes = obj[association.through.model.name];
const throughAttributes = obj[this.through.model.name];
const attributes = { ...defaultAttributes, ...throughAttributes };
if (Object.keys(attributes).some(attribute => attributes[attribute] !== existingAssociation[attribute])) {
......@@ -662,23 +659,23 @@ class BelongsToMany extends Association {
if (unassociatedObjects.length > 0) {
const bulk = unassociatedObjects.map(unassociatedObject => {
const throughAttributes = unassociatedObject[association.through.model.name];
const throughAttributes = unassociatedObject[this.through.model.name];
return {
...defaultAttributes,
...throughAttributes,
[identifier]: sourceInstance.get(sourceKey),
[foreignIdentifier]: unassociatedObject.get(targetKey),
...association.through.scope
...this.through.scope
};
});
promises.push(association.through.model.bulkCreate(bulk, Object.assign({ validate: true }, options)));
promises.push(this.through.model.bulkCreate(bulk, Object.assign({ validate: true }, options)));
}
for (const assoc of changedAssociations) {
const attributes = { ...defaultAttributes, ...assoc[association.through.model.name] };
const attributes = { ...defaultAttributes, ...assoc[this.through.model.name] };
promises.push(association.through.model.update(attributes, Object.assign(options, {
promises.push(this.through.model.update(attributes, Object.assign(options, {
where: {
[identifier]: sourceInstance.get(sourceKey),
[foreignIdentifier]: assoc.get(targetKey)
......@@ -689,7 +686,7 @@ class BelongsToMany extends Association {
return Utils.Promise.all(promises);
};
return association.through.model.findAll({ ...options, where, raw: true })
return this.through.model.findAll({ ...options, where, raw: true })
.then(currentRows => updateAssociations(currentRows))
.then(([associations]) => associations)
.catch(error => {
......@@ -707,19 +704,15 @@ class BelongsToMany extends Association {
*
* @returns {Promise}
*/
remove(sourceInstance, oldAssociatedObjects, options) {
const association = this;
options = options || {};
oldAssociatedObjects = association.toInstanceArray(oldAssociatedObjects);
remove(sourceInstance, oldAssociatedObjects, options = {}) {
oldAssociatedObjects = this.toInstanceArray(oldAssociatedObjects);
const where = {
[association.identifier]: sourceInstance.get(association.source.primaryKeyAttribute),
[association.foreignIdentifier]: oldAssociatedObjects.map(newInstance => newInstance.get(association.target.primaryKeyAttribute))
[this.identifier]: sourceInstance.get(this.source.primaryKeyAttribute),
[this.foreignIdentifier]: oldAssociatedObjects.map(newInstance => newInstance.get(this.target.primaryKeyAttribute))
};
return association.through.model.destroy({ ...options, where });
return this.through.model.destroy({ ...options, where });
}
/**
......@@ -732,28 +725,23 @@ class BelongsToMany extends Association {
*
* @returns {Promise}
*/
create(sourceInstance, values, options) {
const association = this;
options = options || {};
values = values || {};
create(sourceInstance, values = {}, options = {}) {
if (Array.isArray(options)) {
options = {
fields: options
};
}
if (association.scope) {
Object.assign(values, association.scope);
if (this.scope) {
Object.assign(values, this.scope);
if (options.fields) {
options.fields = options.fields.concat(Object.keys(association.scope));
options.fields = options.fields.concat(Object.keys(this.scope));
}
}
// Create the related model instance
return association.target.create(values, options).then(newAssociatedObject =>
sourceInstance[association.accessors.add](newAssociatedObject, _.omit(options, ['fields'])).return(newAssociatedObject)
return this.target.create(values, options).then(newAssociatedObject =>
sourceInstance[this.accessors.add](newAssociatedObject, _.omit(options, ['fields'])).return(newAssociatedObject)
);
}
......
......@@ -225,10 +225,7 @@ class BelongsTo extends Association {
*
* @returns {Promise<Model>} The created target model
*/
create(sourceInstance, values, options) {
values = values || {};
options = options || {};
create(sourceInstance, values = {}, options = {}) {
return this.target.create(values, options)
.then(newAssociatedObject => sourceInstance[this.accessors.set](newAssociatedObject, options)
.then(() => newAssociatedObject)
......
......@@ -244,10 +244,7 @@ class HasOne extends Association {
*
* @returns {Promise<Model>} The created target model
*/
create(sourceInstance, values, options) {
values = values || {};
options = options || {};
create(sourceInstance, values = {}, options = {}) {
if (this.scope) {
for (const attribute of Object.keys(this.scope)) {
values[attribute] = this.scope[attribute];
......
......@@ -52,9 +52,7 @@ exports.addForeignKeyConstraints = addForeignKeyConstraints;
* @param {Object} aliases Mapping between model and association method names
*
*/
function mixinMethods(association, obj, methods, aliases) {
aliases = aliases || {};
function mixinMethods(association, obj, methods, aliases = {}) {
for (const method of methods) {
// don't override custom methods
if (!obj.hasOwnProperty(association.accessors[method])) {
......
......@@ -160,7 +160,7 @@ class ConnectionManager {
// Apply defaults to each read config
config.replication.read = config.replication.read.map(readConfig => ({
...configWithoutReplication,
readConfig
...readConfig
})
);
......@@ -244,8 +244,7 @@ class ConnectionManager {
*
* @returns {Promise<Connection>}
*/
getConnection(options) {
options = options || {};
getConnection(options = {}) {
let promise;
if (this.sequelize.options.databaseVersion === 0) {
......
......@@ -41,9 +41,7 @@ class QueryGenerator {
this._templateSettings = require('lodash').runInContext().templateSettings;
}
extractTableDetails(tableName, options) {
options = options || {};
tableName = tableName || {};
extractTableDetails(tableName = {}, options = {}) {
return {
schema: tableName.schema || options.schema || 'public',
tableName: _.isPlainObject(tableName) ? tableName.tableName : tableName,
......@@ -261,10 +259,7 @@ class QueryGenerator {
*
* @private
*/
bulkInsertQuery(tableName, fieldValueHashes, options, fieldMappedAttributes) {
options = options || {};
fieldMappedAttributes = fieldMappedAttributes || {};
bulkInsertQuery(tableName, fieldValueHashes, options = {}, fieldMappedAttributes = {}) {
const tuples = [];
const serials = {};
const allAttributes = [];
......@@ -437,7 +432,7 @@ class QueryGenerator {
* @param {Object} options
* @param {Object} attributes
*/
arithmeticQuery(operator, tableName, attrValueHash, where, options, attributes) {
arithmeticQuery(operator, tableName, attrValueHash, where, options, attributes = {}) {
options = {
returning: true,
...options
......@@ -463,7 +458,6 @@ class QueryGenerator {
values.push(`${this.quoteIdentifier(key)}=${this.quoteIdentifier(key)}${operator} ${this.escape(value)}`);
}
attributes = attributes || {};
for (const key in attributes) {
const value = attributes[key];
values.push(`${this.quoteIdentifier(key)}=${this.escape(value)}`);
......@@ -491,9 +485,7 @@ class QueryGenerator {
- rawTablename, the name of the table, without schema. Used to create the name of the index
@private
*/
addIndexQuery(tableName, attributes, options, rawTablename) {
options = options || {};
addIndexQuery(tableName, attributes, options = {}, rawTablename) {
if (!Array.isArray(attributes)) {
options = attributes;
attributes = undefined;
......@@ -592,8 +584,7 @@ class QueryGenerator {
return _.compact(ind).join(' ');
}
addConstraintQuery(tableName, options) {
options = options || {};
addConstraintQuery(tableName, options = {}) {
const constraintSnippet = this.getConstraintSnippet(tableName, options);
if (typeof tableName === 'string') {
......@@ -947,9 +938,7 @@ class QueryGenerator {
Escape a value (e.g. a string, number or date)
@private
*/
escape(value, field, options) {
options = options || {};
escape(value, field, options = {}) {
if (value !== null && value !== undefined) {
if (value instanceof Utils.SequelizeMethod) {
return this.handleSequelizeMethod(value);
......@@ -985,9 +974,7 @@ class QueryGenerator {
Returns a bind parameter representation of a value (e.g. a string, number or date)
@private
*/
format(value, field, options, bindParam) {
options = options || {};
format(value, field, options = {}, bindParam) {
if (value !== null && value !== undefined) {
if (value instanceof Utils.SequelizeMethod) {
throw new Error('Cannot pass SequelizeMethod as a bind parameter - use escape instead');
......@@ -1096,8 +1083,7 @@ class QueryGenerator {
- offset -> An offset value to start from. Only useable with limit!
@private
*/
selectQuery(tableName, options, model) {
options = options || {};
selectQuery(tableName, options = {}, model) {
const limit = options.limit;
const mainQueryItems = [];
const subQueryItems = [];
......@@ -2445,7 +2431,7 @@ class QueryGenerator {
Takes something and transforms it into values of a where condition.
@private
*/
getWhereConditions(smth, tableName, factory, options, prepend) {
getWhereConditions(smth, tableName, factory, options = {}, prepend = true) {
const where = {};
if (Array.isArray(tableName)) {
......@@ -2455,12 +2441,6 @@ class QueryGenerator {
}
}
options = options || {};
if (prepend === undefined) {
prepend = true;
}
if (smth && smth instanceof Utils.SequelizeMethod) { // Checking a property is cheaper than a lot of instanceof calls
return this.handleSequelizeMethod(smth, tableName, factory, options, prepend);
}
......
......@@ -32,10 +32,10 @@ const postgresReservedWords = 'all,analyse,analyze,and,any,array,as,asc,asymmetr
* @returns {string}
* @private
*/
function quoteIdentifier(dialect, identifier, options) {
function quoteIdentifier(dialect, identifier, options = {}) {
if (identifier === '*') return identifier;
options = Utils.defaults(options || {}, {
options = Utils.defaults(options, {
force: false,
quoteIdentifiers: true
});
......
......@@ -20,7 +20,7 @@ class AbstractQuery {
raw: false,
// eslint-disable-next-line no-console
logging: console.log
}, options || {});
}, options);
this.checkLoggingOption();
}
......@@ -44,12 +44,11 @@ class AbstractQuery {
* @param {Object} [options]
* @private
*/
static formatBindParameters(sql, values, dialect, replacementFunc, options) {
static formatBindParameters(sql, values, dialect, replacementFunc, options = {}) {
if (!values) {
return [sql, []];
}
options = options || {};
if (typeof replacementFunc !== 'function') {
options = replacementFunc || {};
replacementFunc = undefined;
......
......@@ -8,10 +8,11 @@ const util = require('util');
class MariaDBQueryGenerator extends MySQLQueryGenerator {
createSchema(schema, options) {
options = Object.assign({
options = {
charset: null,
collate: null
}, options || {});
collate: null,
...options
};
const charset = options.charset ? ` DEFAULT CHARACTER SET ${this.escape(options.charset)}` : '';
const collate = options.collate ? ` DEFAULT COLLATE ${this.escape(options.collate)}` : '';
......
......@@ -16,10 +16,10 @@ 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)}` : '';
return [
......@@ -301,17 +301,13 @@ class MSSQLQueryGenerator extends AbstractQueryGenerator {
return `EXEC sp_rename '${this.quoteTable(tableName)}.${attrBefore}', '${newName}', 'COLUMN';`;
}
bulkInsertQuery(tableName, attrValueHashes, options, attributes) {
bulkInsertQuery(tableName, attrValueHashes, options = {}, attributes = {}) {
const quotedTable = this.quoteTable(tableName);
options = options || {};
attributes = attributes || {};
const tuples = [];
const allAttributes = [];
const allQueries = [];
let needIdentityInsertWrapper = false,
outputFragment = '';
......
......@@ -20,8 +20,8 @@
@private
*/
const removeColumn = function(qi, tableName, attributeName, options) {
options = Object.assign({ raw: true }, options || {});
const removeColumn = function(qi, tableName, attributeName, options = {}) {
options = Object.assign({ raw: true }, options);
const findConstraintSql = qi.QueryGenerator.getDefaultConstraintQuery(tableName, attributeName);
return qi.sequelize.query(findConstraintSql, options)
......
......@@ -35,11 +35,11 @@ class MySQLQueryGenerator extends AbstractQueryGenerator {
});
}
createDatabaseQuery(databaseName, options) {
createDatabaseQuery(databaseName, options = {}) {
options = Object.assign({
charset: null,
collate: null
}, options || {});
}, options);
const database = this.quoteIdentifier(databaseName);
const charset = options.charset ? ` DEFAULT CHARACTER SET ${this.escape(options.charset)}` : '';
......@@ -64,12 +64,12 @@ class MySQLQueryGenerator extends AbstractQueryGenerator {
return 'SELECT VERSION() as `version`';
}
createTableQuery(tableName, attributes, options) {
createTableQuery(tableName, attributes, options = {}) {
options = Object.assign({
engine: 'InnoDB',
charset: null,
rowFormat: null
}, options || {});
}, options);
const primaryKeys = [];
const foreignKeys = {};
......@@ -310,8 +310,8 @@ class MySQLQueryGenerator extends AbstractQueryGenerator {
return query + limit;
}
showIndexesQuery(tableName, options) {
return `SHOW INDEX FROM ${this.quoteTable(tableName)}${(options || {}).database ? ` FROM \`${options.database}\`` : ''}`;
showIndexesQuery(tableName, options = {}) {
return `SHOW INDEX FROM ${this.quoteTable(tableName)}${options.database ? ` FROM \`${options.database}\`` : ''}`;
}
showConstraintsQuery(table, constraintName) {
......
......@@ -21,9 +21,7 @@ const sequelizeErrors = require('../../errors');
@private
*/
function removeColumn(qi, tableName, columnName, options) {
options = options || {};
function removeColumn(qi, tableName, columnName, options = {}) {
return qi.sequelize.query(
qi.QueryGenerator.getForeignKeyQuery(tableName.tableName ? tableName : {
tableName,
......
......@@ -12,11 +12,11 @@ class PostgresQueryGenerator extends AbstractQueryGenerator {
return `SET search_path to ${searchPath};`;
}
createDatabaseQuery(databaseName, options) {
createDatabaseQuery(databaseName, options = {}) {
options = Object.assign({
encoding: null,
collate: null
}, options || {});
}, options);
const values = {
database: this.quoteTable(databaseName),
......@@ -55,8 +55,8 @@ class PostgresQueryGenerator extends AbstractQueryGenerator {
return 'SHOW SERVER_VERSION';
}
createTableQuery(tableName, attributes, options) {
options = Object.assign({}, options || {});
createTableQuery(tableName, attributes, options = {}) {
options = Object.assign({}, 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);
......@@ -109,8 +109,7 @@ class PostgresQueryGenerator extends AbstractQueryGenerator {
return `CREATE TABLE ${databaseVersion === 0 || semver.gte(databaseVersion, '9.1.0') ? 'IF NOT EXISTS ' : ''}${quotedTable} (${attributesClause})${comments}${columnComments};`;
}
dropTableQuery(tableName, options) {
options = options || {};
dropTableQuery(tableName, options = {}) {
return `DROP TABLE IF EXISTS ${this.quoteTable(tableName)}${options.cascade ? ' CASCADE' : ''};`;
}
......@@ -716,9 +715,7 @@ class PostgresQueryGenerator extends AbstractQueryGenerator {
}).join(' OR ');
}
pgEnumName(tableName, attr, options) {
options = options || {};
pgEnumName(tableName, attr, options = {}) {
const tableDetails = this.extractTableDetails(tableName, options);
let enumName = Utils.addTicks(Utils.generateEnumName(tableDetails.tableName, attr), '"');
......@@ -730,7 +727,7 @@ class PostgresQueryGenerator extends AbstractQueryGenerator {
return enumName;
}
pgListEnums(tableName, attrName, options) {
pgListEnums(tableName, attrName, options = {}) {
let enumName = '';
const tableDetails = this.extractTableDetails(tableName, options);
......
......@@ -41,8 +41,7 @@ class ConnectionManager extends AbstractConnectionManager {
parserStore.clear();
}
getConnection(options) {
options = options || {};
getConnection(options = {}) {
options.uuid = options.uuid || 'default';
options.inMemory = (this.sequelize.options.storage || this.sequelize.options.host || ':memory:') === ':memory:' ? 1 : 0;
......
......@@ -20,9 +20,7 @@ class SQLiteQueryGenerator extends MySqlQueryGenerator {
return 'SELECT sqlite_version() as `version`';
}
createTableQuery(tableName, attributes, options) {
options = options || {};
createTableQuery(tableName, attributes, options = {}) {
const primaryKeys = [];
const needsMultiplePrimaryKeys = Object.values(attributes).filter(definition => definition.includes('PRIMARY KEY')).length > 1;
const attrArray = [];
......
......@@ -26,9 +26,7 @@ const QueryTypes = require('../../query-types');
@since 1.6.0
@private
*/
function removeColumn(qi, tableName, attributeName, options) {
options = options || {};
function removeColumn(qi, tableName, attributeName, options = {}) {
return qi.describeTable(tableName, options).then(fields => {
delete fields[attributeName];
......@@ -54,10 +52,8 @@ exports.removeColumn = removeColumn;
@since 1.6.0
@private
*/
function changeColumn(qi, tableName, attributes, options) {
function changeColumn(qi, tableName, attributes, options = {}) {
const attributeName = Object.keys(attributes)[0];
options = options || {};
return qi.describeTable(tableName, options).then(fields => {
fields[attributeName] = attributes[attributeName];
......@@ -84,9 +80,7 @@ exports.changeColumn = changeColumn;
@since 1.6.0
@private
*/
function renameColumn(qi, tableName, attrNameBefore, attrNameAfter, options) {
options = options || {};
function renameColumn(qi, tableName, attrNameBefore, attrNameAfter, options = {}) {
return qi.describeTable(tableName, options).then(fields => {
fields[attrNameAfter] = { ...fields[attrNameBefore] };
delete fields[attrNameBefore];
......
......@@ -6,8 +6,7 @@ const DatabaseError = require('./../database-error');
* Thrown when an exclusion constraint is violated in the database
*/
class ExclusionConstraintError extends DatabaseError {
constructor(options) {
options = options || {};
constructor(options = {}) {
options.parent = options.parent || { sql: '' };
super(options.parent);
......
......@@ -6,8 +6,7 @@ const DatabaseError = require('./../database-error');
* Thrown when a foreign key constraint is violated in the database
*/
class ForeignKeyConstraintError extends DatabaseError {
constructor(options) {
options = options || {};
constructor(options = {}) {
options.parent = options.parent || { sql: '' };
super(options.parent);
......
......@@ -6,8 +6,7 @@ const DatabaseError = require('./../database-error');
* Thrown when constraint name is not found in the database
*/
class UnknownConstraintError extends DatabaseError {
constructor(options) {
options = options || {};
constructor(options = {}) {
options.parent = options.parent || { sql: '' };
super(options.parent);
......
......@@ -6,8 +6,7 @@ const BaseError = require('./base-error');
* Thrown when attempting to update a stale model instance
*/
class OptimisticLockError extends BaseError {
constructor(options) {
options = options || {};
constructor(options = {}) {
options.message = options.message || `Attempting to update a stale model instance: ${options.modelName}`;
super(options.message);
this.name = 'SequelizeOptimisticLockError';
......
......@@ -6,8 +6,7 @@ const ValidationError = require('./../validation-error');
* Thrown when a unique constraint is violated in the database
*/
class UniqueConstraintError extends ValidationError {
constructor(options) {
options = options || {};
constructor(options = {}) {
options.parent = options.parent || { sql: '' };
options.message = options.message || options.parent.message || 'Validation Error';
options.errors = options.errors || {};
......
......@@ -79,9 +79,9 @@ const Hooks = {
* @memberof Sequelize
* @memberof Sequelize.Model
*/
_setupHooks(hooks) {
_setupHooks(hooks = {}) {
this.options.hooks = {};
_.map(hooks || {}, (hooksArray, hookName) => {
_.map(hooks, (hooksArray, hookName) => {
if (!Array.isArray(hooksArray)) hooksArray = [hooksArray];
hooksArray.forEach(hookFn => this.addHook(hookName, hookFn));
});
......
......@@ -88,7 +88,7 @@ class Model {
isNewRecord: true,
_schema: this.constructor._schema,
_schemaDelimiter: this.constructor._schemaDelimiter
}, options || {});
}, options);
if (options.attributes) {
options.attributes = options.attributes.map(attribute => Array.isArray(attribute) ? attribute[1] : attribute);
......@@ -106,7 +106,7 @@ class Model {
this._previousDataValues = {};
this._changed = {};
this._modelOptions = this.constructor.options;
this._options = options || {};
this._options = options;
/**
* Returns true if this instance has not yet been persisted to the database
......@@ -492,10 +492,9 @@ class Model {
})(this, includes);
}
static _validateIncludedElements(options, tableNames) {
static _validateIncludedElements(options, tableNames = {}) {
if (!options.model) options.model = this;
tableNames = tableNames || {};
options.includeNames = [];
options.includeMap = {};
......@@ -1868,7 +1867,7 @@ class Model {
return Promise.resolve(null);
}
options = Utils.cloneDeep(options) || {};
options = Utils.cloneDeep(options);
if (typeof param === 'number' || typeof param === 'string' || Buffer.isBuffer(param)) {
options.where = {
......@@ -2166,7 +2165,7 @@ class Model {
static bulkBuild(valueSets, options) {
options = Object.assign({
isNewRecord: true
}, options || {});
}, options);
if (!options.includeValidated) {
this._conformIncludes(options, this);
......@@ -2211,7 +2210,7 @@ class Model {
*
*/
static create(values, options) {
options = Utils.cloneDeep(options || {});
options = Utils.cloneDeep(options);
return this.build(values, {
isNewRecord: true,
......@@ -2437,7 +2436,7 @@ class Model {
hooks: true,
returning: false,
validate: true
}, Utils.cloneDeep(options || {}));
}, Utils.cloneDeep(options));
options.model = this;
......@@ -2697,7 +2696,7 @@ class Model {
* {@link Model.destroy} for more information
*/
static truncate(options) {
options = Utils.cloneDeep(options) || {};
options = Utils.cloneDeep(options);
options.truncate = true;
return this.destroy(options);
}
......@@ -2813,7 +2812,7 @@ class Model {
options = Object.assign({
hooks: true,
individualHooks: false
}, options || {});
}, options);
options.type = QueryTypes.RAW;
options.model = this;
......@@ -3165,9 +3164,7 @@ class Model {
*
* @returns {Promise<Model[],?number>} returns an array of affected rows and affected count with `options.returning: true`, whenever supported by dialect
*/
static increment(fields, options) {
options = options || {};
static increment(fields, options = {}) {
this._injectScope(options);
this._optionsMustContainWhere(options);
......@@ -3986,13 +3983,12 @@ class Model {
*
* @returns {Promise<Model>}
*/
update(values, options) {
update(values, options = {}) {
// Clone values so it doesn't get modified for caller scope and ignore undefined values
values = _.omitBy(values, value => value === undefined);
const changedBefore = this.changed() || [];
options = options || {};
if (Array.isArray(options)) options = { fields: options };
options = Utils.cloneDeep(options);
......
......@@ -37,8 +37,7 @@ class QueryInterface {
*
* @returns {Promise}
*/
createDatabase(database, options) {
options = options || {};
createDatabase(database, options = {}) {
const sql = this.QueryGenerator.createDatabaseQuery(database, options);
return this.sequelize.query(sql, options);
}
......@@ -51,8 +50,7 @@ class QueryInterface {
*
* @returns {Promise}
*/
dropDatabase(database, options) {
options = options || {};
dropDatabase(database, options = {}) {
const sql = this.QueryGenerator.dropDatabaseQuery(database);
return this.sequelize.query(sql, options);
}
......@@ -65,8 +63,7 @@ class QueryInterface {
*
* @returns {Promise}
*/
createSchema(schema, options) {
options = options || {};
createSchema(schema, options = {}) {
const sql = this.QueryGenerator.createSchema(schema);
return this.sequelize.query(sql, options);
}
......@@ -79,8 +76,7 @@ class QueryInterface {
*
* @returns {Promise}
*/
dropSchema(schema, options) {
options = options || {};
dropSchema(schema, options = {}) {
const sql = this.QueryGenerator.dropSchema(schema);
return this.sequelize.query(sql, options);
}
......@@ -92,9 +88,7 @@ class QueryInterface {
*
* @returns {Promise}
*/
dropAllSchemas(options) {
options = options || {};
dropAllSchemas(options = {}) {
if (!this.QueryGenerator._dialect.supports.schemas) {
return this.sequelize.drop(options);
}
......@@ -287,8 +281,7 @@ class QueryInterface {
*
* @returns {Promise}
*/
dropAllTables(options) {
options = options || {};
dropAllTables(options = {}) {
const skip = options.skip || [];
const dropAllTables = tableNames => Promise.each(tableNames, tableName => {
......@@ -340,13 +333,11 @@ class QueryInterface {
* @returns {Promise}
* @private
*/
dropEnum(enumName, options) {
dropEnum(enumName, options = {}) {
if (this.sequelize.getDialect() !== 'postgres') {
return Promise.resolve();
}
options = options || {};
return this.sequelize.query(
this.QueryGenerator.pgEnumDrop(null, null, this.QueryGenerator.pgEscapeAndQuote(enumName)),
Object.assign({}, options, { raw: true })
......@@ -361,14 +352,12 @@ class QueryInterface {
* @returns {Promise}
* @private
*/
dropAllEnums(options) {
dropAllEnums(options = {}) {
if (this.sequelize.getDialect() !== 'postgres') {
return Promise.resolve();
}
options = options || {};
return this.pgListEnums(null, options).map(result => this.sequelize.query(
return this.pgListEnums(undefined, options).map(result => this.sequelize.query(
this.QueryGenerator.pgEnumDrop(null, null, this.QueryGenerator.pgEscapeAndQuote(result.enum_name)),
Object.assign({}, options, { raw: true })
));
......@@ -383,8 +372,7 @@ class QueryInterface {
* @returns {Promise}
* @private
*/
pgListEnums(tableName, options) {
options = options || {};
pgListEnums(tableName, options = {}) {
const sql = this.QueryGenerator.pgListEnums(tableName);
return this.sequelize.query(sql, Object.assign({}, options, { plain: false, raw: true, type: QueryTypes.SELECT }));
}
......@@ -398,8 +386,7 @@ class QueryInterface {
*
* @returns {Promise}
*/
renameTable(before, after, options) {
options = options || {};
renameTable(before, after, options = {}) {
const sql = this.QueryGenerator.renameTableQuery(before, after);
return this.sequelize.query(sql, options);
}
......@@ -504,12 +491,11 @@ class QueryInterface {
*
* @returns {Promise}
*/
addColumn(table, key, attribute, options) {
addColumn(table, key, attribute, options = {}) {
if (!table || !key || !attribute) {
throw new Error('addColumn takes at least 3 arguments (table, attribute name, attribute definition)');
}
options = options || {};
attribute = this.sequelize.normalizeAttribute(attribute);
return this.sequelize.query(this.QueryGenerator.addColumnQuery(table, key, attribute), options);
}
......@@ -523,8 +509,7 @@ class QueryInterface {
*
* @returns {Promise}
*/
removeColumn(tableName, attributeName, options) {
options = options || {};
removeColumn(tableName, attributeName, options = {}) {
switch (this.sequelize.options.dialect) {
case 'sqlite':
// sqlite needs some special treatment as it cannot drop a column
......@@ -551,9 +536,8 @@ class QueryInterface {
*
* @returns {Promise}
*/
changeColumn(tableName, attributeName, dataTypeOrOptions, options) {
changeColumn(tableName, attributeName, dataTypeOrOptions, options = {}) {
const attributes = {};
options = options || {};
if (Object.values(DataTypes).includes(dataTypeOrOptions)) {
attributes[attributeName] = { type: dataTypeOrOptions, allowNull: true };
......@@ -586,8 +570,7 @@ class QueryInterface {
*
* @returns {Promise}
*/
renameColumn(tableName, attrNameBefore, attrNameAfter, options) {
options = options || {};
renameColumn(tableName, attrNameBefore, attrNameAfter, options = {}) {
return this.describeTable(tableName, options).then(data => {
if (!data[attrNameBefore]) {
throw new Error(`Table ${tableName} doesn't have the column ${attrNameBefore}`);
......@@ -678,7 +661,7 @@ class QueryInterface {
return Promise.resolve({});
}
options = Object.assign({}, options || {}, { type: QueryTypes.FOREIGNKEYS });
options = Object.assign({}, options, { type: QueryTypes.FOREIGNKEYS });
return Promise.map(tableNames, tableName =>
this.sequelize.query(this.QueryGenerator.getForeignKeysQuery(tableName, this.sequelize.config.database), options)
......@@ -750,8 +733,7 @@ class QueryInterface {
*
* @returns {Promise}
*/
removeIndex(tableName, indexNameOrAttributes, options) {
options = options || {};
removeIndex(tableName, indexNameOrAttributes, options = {}) {
const sql = this.QueryGenerator.removeIndexQuery(tableName, indexNameOrAttributes);
return this.sequelize.query(sql, options);
}
......@@ -858,8 +840,7 @@ class QueryInterface {
*
* @returns {Promise}
*/
removeConstraint(tableName, constraintName, options) {
options = options || {};
removeConstraint(tableName, constraintName, options = {}) {
switch (this.sequelize.options.dialect) {
case 'mysql':
......@@ -1001,7 +982,7 @@ class QueryInterface {
}
update(instance, tableName, values, identifier, options) {
options = { ...options || {} };
options = { ...options };
options.hasTrigger = !!(instance && instance._modelOptions && instance._modelOptions.hasTrigger);
const sql = this.QueryGenerator.updateQuery(tableName, values, identifier, options, instance.constructor.rawAttributes);
......@@ -1191,18 +1172,16 @@ class QueryInterface {
});
}
createTrigger(tableName, triggerName, timingType, fireOnArray, functionName, functionParams, optionsArray, options) {
createTrigger(tableName, triggerName, timingType, fireOnArray, functionName, functionParams, optionsArray, options = {}) {
const sql = this.QueryGenerator.createTrigger(tableName, triggerName, timingType, fireOnArray, functionName, functionParams, optionsArray);
options = options || {};
if (sql) {
return this.sequelize.query(sql, options);
}
return Promise.resolve();
}
dropTrigger(tableName, triggerName, options) {
dropTrigger(tableName, triggerName, options = {}) {
const sql = this.QueryGenerator.dropTrigger(tableName, triggerName);
options = options || {};
if (sql) {
return this.sequelize.query(sql, options);
......@@ -1210,9 +1189,8 @@ class QueryInterface {
return Promise.resolve();
}
renameTrigger(tableName, oldTriggerName, newTriggerName, options) {
renameTrigger(tableName, oldTriggerName, newTriggerName, options = {}) {
const sql = this.QueryGenerator.renameTrigger(tableName, oldTriggerName, newTriggerName);
options = options || {};
if (sql) {
return this.sequelize.query(sql, options);
......@@ -1248,9 +1226,8 @@ class QueryInterface {
*
* @returns {Promise}
*/
createFunction(functionName, params, returnType, language, body, optionsArray, options) {
createFunction(functionName, params, returnType, language, body, optionsArray, options = {}) {
const sql = this.QueryGenerator.createFunction(functionName, params, returnType, language, body, optionsArray);
options = options || {};
if (sql) {
return this.sequelize.query(sql, options);
......@@ -1276,9 +1253,8 @@ class QueryInterface {
*
* @returns {Promise}
*/
dropFunction(functionName, params, options) {
dropFunction(functionName, params, options = {}) {
const sql = this.QueryGenerator.dropFunction(functionName, params);
options = options || {};
if (sql) {
return this.sequelize.query(sql, options);
......@@ -1306,9 +1282,8 @@ class QueryInterface {
*
* @returns {Promise}
*/
renameFunction(oldFunctionName, params, newFunctionName, options) {
renameFunction(oldFunctionName, params, newFunctionName, options = {}) {
const sql = this.QueryGenerator.renameFunction(oldFunctionName, params, newFunctionName);
options = options || {};
if (sql) {
return this.sequelize.query(sql, options);
......
......@@ -255,7 +255,7 @@ class Sequelize {
databaseVersion: 0,
typeValidation: false,
benchmark: false
}, options || {});
}, options);
if (!this.options.dialect) {
throw new Error('Dialect needs to be explicitly supplied as of v4.0.0');
......
......@@ -20,7 +20,7 @@ class Transaction {
* @param {string} options.isolationLevel=true Sets the isolation level of the transaction.
* @param {string} options.deferrable Sets the constraints to be deferred or immediately checked.
*/
constructor(sequelize, options) {
constructor(sequelize, options = {}) {
this.sequelize = sequelize;
this.savepoints = [];
this._afterCommitHooks = [];
......@@ -32,7 +32,7 @@ class Transaction {
type: sequelize.options.transactionType,
isolationLevel: sequelize.options.isolationLevel,
readOnly: false
}, options || {});
}, options);
this.parent = this.options.transaction;
this.id = this.parent ? this.parent.id : generateTransactionId();
......
......@@ -124,8 +124,7 @@ function formatNamedParameters(sql, parameters, dialect) {
exports.formatNamedParameters = formatNamedParameters;
function cloneDeep(obj) {
obj = obj || {};
return _.cloneDeepWith(obj, elem => {
return _.cloneDeepWith(obj || {}, elem => {
// Do not try to customize cloning of arrays or POJOs
if (Array.isArray(elem) || _.isPlainObject(elem)) {
return undefined;
......@@ -295,10 +294,9 @@ function defaultValueSchemable(value) {
}
exports.defaultValueSchemable = defaultValueSchemable;
function removeNullValuesFromHash(hash, omitNull, options) {
function removeNullValuesFromHash(hash, omitNull, options = {}) {
let result = hash;
options = options || {};
options.allowNull = options.allowNull || [];
if (omitNull) {
......
......@@ -14,9 +14,7 @@ if (!Support.sequelize.dialect.supports.deferrableConstraints) {
describe(Support.getTestDialectTeaser('Sequelize'), () => {
describe('Deferrable', () => {
beforeEach(function() {
this.run = function(deferrable, options) {
options = options || {};
this.run = function(deferrable, options = {}) {
const taskTableName = options.taskTableName || `tasks_${config.rand()}`;
const transactionOptions = Object.assign({}, { deferrable: Sequelize.Deferrable.SET_DEFERRED }, options);
const userTableName = `users_${config.rand()}`;
......
......@@ -48,8 +48,7 @@ const Support = {
return Sequelize.Promise.resolve(sequelize);
},
createSequelizeInstance(options) {
options = options || {};
createSequelizeInstance(options = {}) {
options.dialect = this.getTestDialect();
const config = Config[options.dialect];
......@@ -83,8 +82,7 @@ const Support = {
return config;
},
getSequelizeInstance(db, user, pass, options) {
options = options || {};
getSequelizeInstance(db, user, pass, options = {}) {
options.dialect = options.dialect || this.getTestDialect();
return new Sequelize(db, user, pass, options);
},
......
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!