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

Commit 9f7b51ef by Simon Schick

refactor: use default parameters

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