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

Commit c1ac5433 by Simon Schick Committed by Sushant

refactor: reduce code complexity (#10120)

1 parent b896ba4d
...@@ -25,17 +25,17 @@ ...@@ -25,17 +25,17 @@
"keyword-spacing": "error", "keyword-spacing": "error",
"no-console": "off", "no-console": "off",
"no-extra-parens": "warn", "no-extra-parens": "error",
"valid-jsdoc": "off", "valid-jsdoc": "off",
"new-cap": [ "new-cap": [
"warn", "error",
{ {
"properties": false "properties": false
} }
], ],
"no-extra-boolean-cast": "warn", "no-extra-boolean-cast": "error",
"strict": [ "strict": [
"warn", "error",
"global" "global"
], ],
"no-var": "error", "no-var": "error",
...@@ -45,7 +45,7 @@ ...@@ -45,7 +45,7 @@
"always" "always"
], ],
"space-before-function-paren": [ "space-before-function-paren": [
"warn", "error",
"never" "never"
], ],
"space-before-blocks": "error", "space-before-blocks": "error",
...@@ -55,7 +55,7 @@ ...@@ -55,7 +55,7 @@
"as-needed" "as-needed"
], ],
"comma-style": [ "comma-style": [
"warn", "error",
"last" "last"
], ],
"no-bitwise": "off", "no-bitwise": "off",
...@@ -84,7 +84,7 @@ ...@@ -84,7 +84,7 @@
"no-irregular-whitespace": "error", "no-irregular-whitespace": "error",
"max-depth": [ "max-depth": [
"error", "error",
8 6
], ],
"quotes": [ "quotes": [
"error", "error",
...@@ -96,11 +96,13 @@ ...@@ -96,11 +96,13 @@
"linebreak-style": "error", "linebreak-style": "error",
"no-loop-func": "warn", "no-loop-func": "warn",
"object-shorthand": "error", "object-shorthand": "error",
"one-var-declaration-per-line": "warn", "one-var-declaration-per-line": "error",
"comma-dangle": "warn", "comma-dangle": "error",
"no-shadow": "warn", "no-shadow": "warn",
"camelcase": "warn", "camelcase": "warn",
"prefer-template": "error" "prefer-template": "error",
"no-else-return": ["error", { "allowElseIf": false }],
"no-lonely-if": "error"
}, },
"parserOptions": { "parserOptions": {
"ecmaVersion": 6, "ecmaVersion": 6,
......
docs
esdoc
examples
test
scripts
README.md
.watchr.js
changelog.md
Makefile
coverage*
.github
.vscode
appveyor-setup.ps1
appveyor.yml
codecov.yml
docker-compose.yml
mkdocs.yml
.dockerignore
.editorconfig
.travis.yml
package-lock.json
...@@ -483,11 +483,10 @@ class BelongsToMany extends Association { ...@@ -483,11 +483,10 @@ class BelongsToMany extends Association {
where[Op.or] = instances.map(instance => { where[Op.or] = instances.map(instance => {
if (instance instanceof association.target) { if (instance instanceof association.target) {
return instance.where(); return instance.where();
} else {
const where = {};
where[association.target.primaryKeyAttribute] = instance;
return where;
} }
return {
[association.target.primaryKeyAttribute]: instance
};
}); });
options.where = { options.where = {
......
...@@ -153,10 +153,9 @@ class BelongsTo extends Association { ...@@ -153,10 +153,9 @@ class BelongsTo extends Association {
} else { } else {
if (this.targetKeyIsPrimary && !options.where) { if (this.targetKeyIsPrimary && !options.where) {
return Target.findByPk(instance.get(this.foreignKey), options); return Target.findByPk(instance.get(this.foreignKey), options);
} else {
where[this.targetKey] = instance.get(this.foreignKey);
options.limit = null;
} }
where[this.targetKey] = instance.get(this.foreignKey);
options.limit = null;
} }
options.where = options.where ? options.where = options.where ?
......
...@@ -290,11 +290,10 @@ class HasMany extends Association { ...@@ -290,11 +290,10 @@ class HasMany extends Association {
where[Op.or] = targetInstances.map(instance => { where[Op.or] = targetInstances.map(instance => {
if (instance instanceof this.target) { if (instance instanceof this.target) {
return instance.where(); return instance.where();
} else {
const _where = {};
_where[this.target.primaryKeyAttribute] = instance;
return _where;
} }
return {
[this.target.primaryKeyAttribute]: instance
};
}); });
options.where = { options.where = {
......
...@@ -86,9 +86,8 @@ const Mixin = { ...@@ -86,9 +86,8 @@ const Mixin = {
verifyAssociationAlias(association, alias) { verifyAssociationAlias(association, alias) {
if (alias) { if (alias) {
return association.as === alias; return association.as === alias;
} else {
return !association.isAliased;
} }
return !association.isAliased;
} }
}; };
......
...@@ -548,15 +548,11 @@ DATE.prototype._isChanged = function _isChanged(value, originalValue) { ...@@ -548,15 +548,11 @@ DATE.prototype._isChanged = function _isChanged(value, originalValue) {
DATE.prototype._applyTimezone = function _applyTimezone(date, options) { DATE.prototype._applyTimezone = function _applyTimezone(date, options) {
if (options.timezone) { if (options.timezone) {
if (momentTz.tz.zone(options.timezone)) { if (momentTz.tz.zone(options.timezone)) {
date = momentTz(date).tz(options.timezone); return momentTz(date).tz(options.timezone);
} else {
date = moment(date).utcOffset(options.timezone);
} }
} else { return date = moment(date).utcOffset(options.timezone);
date = momentTz(date);
} }
return momentTz(date);
return date;
}; };
DATE.prototype._stringify = function _stringify(date, options) { DATE.prototype._stringify = function _stringify(date, options) {
......
...@@ -170,9 +170,8 @@ class ConnectionManager { ...@@ -170,9 +170,8 @@ class ConnectionManager {
useMaster = _.isUndefined(useMaster) ? false : useMaster; useMaster = _.isUndefined(useMaster) ? false : useMaster;
if (queryType === 'SELECT' && !useMaster) { if (queryType === 'SELECT' && !useMaster) {
return this.pool.read.acquire(); return this.pool.read.acquire();
} else {
return this.pool.write.acquire();
} }
return this.pool.write.acquire();
}, },
destroy: connection => { destroy: connection => {
this.pool[connection.queryType].destroy(connection); this.pool[connection.queryType].destroy(connection);
......
...@@ -716,7 +716,8 @@ class QueryGenerator { ...@@ -716,7 +716,8 @@ class QueryGenerator {
// just quote as identifiers if string // just quote as identifiers if string
if (typeof collection === 'string') { if (typeof collection === 'string') {
return this.quoteIdentifiers(collection); return this.quoteIdentifiers(collection);
} else if (Array.isArray(collection)) { }
if (Array.isArray(collection)) {
// iterate through the collection and mutate objects into associations // iterate through the collection and mutate objects into associations
collection.forEach((item, index) => { collection.forEach((item, index) => {
const previous = collection[index - 1]; const previous = collection[index - 1];
...@@ -888,9 +889,8 @@ class QueryGenerator { ...@@ -888,9 +889,8 @@ class QueryGenerator {
quoteAttribute(attribute, model) { quoteAttribute(attribute, model) {
if (model && attribute in model.rawAttributes) { if (model && attribute in model.rawAttributes) {
return this.quoteIdentifier(attribute); return this.quoteIdentifier(attribute);
} else {
return this.quoteIdentifiers(attribute);
} }
return this.quoteIdentifiers(attribute);
} }
/** /**
...@@ -944,20 +944,19 @@ class QueryGenerator { ...@@ -944,20 +944,19 @@ class QueryGenerator {
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);
} else { }
if (field && field.type) { if (field && field.type) {
this.validate(value, field, options); this.validate(value, field, options);
if (field.type.stringify) { if (field.type.stringify) {
// Users shouldn't have to worry about these args - just give them a function that takes a single arg // Users shouldn't have to worry about these args - just give them a function that takes a single arg
const simpleEscape = _.partialRight(SqlString.escape, this.options.timezone, this.dialect); const simpleEscape = _.partialRight(SqlString.escape, this.options.timezone, this.dialect);
value = field.type.stringify(value, { escape: simpleEscape, field, timezone: this.options.timezone, operation: options.operation }); value = field.type.stringify(value, { escape: simpleEscape, field, timezone: this.options.timezone, operation: options.operation });
if (field.type.escape === false) { if (field.type.escape === false) {
// The data-type already did the required escaping // The data-type already did the required escaping
return value; return value;
}
} }
} }
} }
...@@ -983,13 +982,12 @@ class QueryGenerator { ...@@ -983,13 +982,12 @@ class QueryGenerator {
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');
} else { }
if (field && field.type) { if (field && field.type) {
this.validate(value, field, options); this.validate(value, field, options);
if (field.type.bindParam) { if (field.type.bindParam) {
return field.type.bindParam(value, { escape: _.identity, field, timezone: this.options.timezone, operation: options.operation, bindParam }); return field.type.bindParam(value, { escape: _.identity, field, timezone: this.options.timezone, operation: options.operation, bindParam });
}
} }
} }
} }
...@@ -1968,15 +1966,14 @@ class QueryGenerator { ...@@ -1968,15 +1966,14 @@ class QueryGenerator {
return this.whereItemQuery(smth.attribute, value, { return this.whereItemQuery(smth.attribute, value, {
model: factory model: factory
}); });
}
if (typeof value === 'boolean') {
value = this.booleanValue(value);
} else { } else {
if (typeof value === 'boolean') { value = this.escape(value);
value = this.booleanValue(value);
} else {
value = this.escape(value);
}
return value === 'NULL' ? `${key} IS NULL` : [key, value].join(` ${smth.comparator} `);
} }
return value === 'NULL' ? `${key} IS NULL` : [key, value].join(` ${smth.comparator} `);
} }
if (smth instanceof Utils.Literal) { if (smth instanceof Utils.Literal) {
return smth.val; return smth.val;
...@@ -2145,9 +2142,8 @@ class QueryGenerator { ...@@ -2145,9 +2142,8 @@ class QueryGenerator {
if (isPlainObject) { if (isPlainObject) {
if (this.OperatorMap[valueKeys[0]]) { if (this.OperatorMap[valueKeys[0]]) {
return this._whereParseSingleValueObject(key, field, valueKeys[0], value[valueKeys[0]], options); return this._whereParseSingleValueObject(key, field, valueKeys[0], value[valueKeys[0]], options);
} else {
return this._whereParseSingleValueObject(key, field, this.OperatorMap[Op.eq], value, options);
} }
return this._whereParseSingleValueObject(key, field, this.OperatorMap[Op.eq], value, options);
} }
if (key === Op.placeholder) { if (key === Op.placeholder) {
......
...@@ -63,10 +63,8 @@ function quoteIdentifier(dialect, identifier, options) { ...@@ -63,10 +63,8 @@ function quoteIdentifier(dialect, identifier, options) {
// impossible to write queries in portable SQL if tables are created in // impossible to write queries in portable SQL if tables are created in
// this way. Hence, we strip quotes if we don't want case sensitivity. // this way. Hence, we strip quotes if we don't want case sensitivity.
return rawIdentifier; return rawIdentifier;
} else {
return Utils.addTicks(rawIdentifier, '"');
} }
return Utils.addTicks(rawIdentifier, '"');
case 'mssql': case 'mssql':
return `[${identifier.replace(/[\[\]']+/g, '')}]`; return `[${identifier.replace(/[\[\]']+/g, '')}]`;
......
...@@ -49,16 +49,14 @@ class AbstractQuery { ...@@ -49,16 +49,14 @@ class AbstractQuery {
return undefined; return undefined;
}; };
} }
} else { } else if (options.skipValueReplace) {
if (options.skipValueReplace) { const origReplacementFunc = replacementFunc;
const origReplacementFunc = replacementFunc; replacementFunc = (match, key, values, timeZone, dialect, options) => {
replacementFunc = (match, key, values, timeZone, dialect, options) => { if (origReplacementFunc(match, key, values, timeZone, dialect, options) !== undefined) {
if (origReplacementFunc(match, key, values, timeZone, dialect, options) !== undefined) { return match;
return match; }
} return undefined;
return undefined; };
};
}
} }
const timeZone = null; const timeZone = null;
...@@ -75,10 +73,8 @@ class AbstractQuery { ...@@ -75,10 +73,8 @@ class AbstractQuery {
key = key - 1; key = key - 1;
replVal = replacementFunc(match, key, values, timeZone, dialect, options); replVal = replacementFunc(match, key, values, timeZone, dialect, options);
} }
} else { } else if (!key.match(/^\d*$/)) {
if (!key.match(/^\d*$/)) { replVal = replacementFunc(match, key, values, timeZone, dialect, options);
replVal = replacementFunc(match, key, values, timeZone, dialect, options);
}
} }
if (replVal === undefined) { if (replVal === undefined) {
throw new Error(`Named bind parameter "${match}" has no value in the given object.`); throw new Error(`Named bind parameter "${match}" has no value in the given object.`);
...@@ -562,21 +558,19 @@ class AbstractQuery { ...@@ -562,21 +558,19 @@ class AbstractQuery {
} else { } else {
topExists = true; topExists = true;
} }
} else { } else if (!resultMap[itemHash]) {
if (!resultMap[itemHash]) { $parent = resultMap[parentHash];
$parent = resultMap[parentHash]; $lastKeyPrefix = lastKeyPrefix(prevKey);
$lastKeyPrefix = lastKeyPrefix(prevKey);
if (includeMap[prevKey].association.isSingleAssociation) { if (includeMap[prevKey].association.isSingleAssociation) {
if ($parent) { if ($parent) {
$parent[$lastKeyPrefix] = resultMap[itemHash] = values; $parent[$lastKeyPrefix] = resultMap[itemHash] = values;
}
} else {
if (!$parent[$lastKeyPrefix]) {
$parent[$lastKeyPrefix] = [];
}
$parent[$lastKeyPrefix].push(resultMap[itemHash] = values);
} }
} else {
if (!$parent[$lastKeyPrefix]) {
$parent[$lastKeyPrefix] = [];
}
$parent[$lastKeyPrefix].push(resultMap[itemHash] = values);
} }
} }
...@@ -651,21 +645,19 @@ class AbstractQuery { ...@@ -651,21 +645,19 @@ class AbstractQuery {
} else { } else {
topExists = true; topExists = true;
} }
} else { } else if (!resultMap[itemHash]) {
if (!resultMap[itemHash]) { $parent = resultMap[parentHash];
$parent = resultMap[parentHash]; $lastKeyPrefix = lastKeyPrefix(prevKey);
$lastKeyPrefix = lastKeyPrefix(prevKey);
if (includeMap[prevKey].association.isSingleAssociation) { if (includeMap[prevKey].association.isSingleAssociation) {
if ($parent) { if ($parent) {
$parent[$lastKeyPrefix] = resultMap[itemHash] = values; $parent[$lastKeyPrefix] = resultMap[itemHash] = values;
} }
} else { } else {
if (!$parent[$lastKeyPrefix]) { if (!$parent[$lastKeyPrefix]) {
$parent[$lastKeyPrefix] = []; $parent[$lastKeyPrefix] = [];
}
$parent[$lastKeyPrefix].push(resultMap[itemHash] = values);
} }
$parent[$lastKeyPrefix].push(resultMap[itemHash] = values);
} }
} }
if (!topExists) { if (!topExists) {
......
...@@ -80,18 +80,16 @@ module.exports = BaseTypes => { ...@@ -80,18 +80,16 @@ module.exports = BaseTypes => {
STRING.prototype.toSql = function toSql() { STRING.prototype.toSql = function toSql() {
if (!this._binary) { if (!this._binary) {
return `NVARCHAR(${this._length})`; return `NVARCHAR(${this._length})`;
} else {
return `BINARY(${this._length})`;
} }
return `BINARY(${this._length})`;
}; };
STRING.prototype.escape = false; STRING.prototype.escape = false;
STRING.prototype._stringify = function _stringify(value, options) { STRING.prototype._stringify = function _stringify(value, options) {
if (this._binary) { if (this._binary) {
return BLOB.prototype._stringify(value); return BLOB.prototype._stringify(value);
} else {
return options.escape(value);
} }
return options.escape(value);
}; };
STRING.prototype._bindParam = function _bindParam(value, options) { STRING.prototype._bindParam = function _bindParam(value, options) {
return options.bindParam(this._binary ? Buffer.from(value) : value); return options.bindParam(this._binary ? Buffer.from(value) : value);
......
...@@ -551,9 +551,8 @@ class MSSQLQueryGenerator extends AbstractQueryGenerator { ...@@ -551,9 +551,8 @@ class MSSQLQueryGenerator extends AbstractQueryGenerator {
return this.escape(value); return this.escape(value);
}).join(', ') }))`; }).join(', ') }))`;
return template; return template;
} else {
template = attribute.type.toString();
} }
template = attribute.type.toString();
if (attribute.allowNull === false) { if (attribute.allowNull === false) {
template += ' NOT NULL'; template += ' NOT NULL';
...@@ -825,9 +824,8 @@ class MSSQLQueryGenerator extends AbstractQueryGenerator { ...@@ -825,9 +824,8 @@ class MSSQLQueryGenerator extends AbstractQueryGenerator {
` AS ${tmpTable} WHERE row_num > ${offset})` + ` AS ${tmpTable} WHERE row_num > ${offset})` +
` AS ${tmpTable}`; ` AS ${tmpTable}`;
return fragment; return fragment;
} else {
mainFragment = `SELECT ${topFragment}${attributes.join(', ')} FROM ${tables}`;
} }
mainFragment = `SELECT ${topFragment}${attributes.join(', ')} FROM ${tables}`;
} }
if (mainTableAs) { if (mainTableAs) {
......
...@@ -195,7 +195,8 @@ class MySQLQueryGenerator extends AbstractQueryGenerator { ...@@ -195,7 +195,8 @@ class MySQLQueryGenerator extends AbstractQueryGenerator {
); );
return conditions.join(' and '); return conditions.join(' and ');
} else if (smth.path) { }
if (smth.path) {
let str; let str;
// Allow specifying conditions using the sqlite json functions // Allow specifying conditions using the sqlite json functions
......
...@@ -198,9 +198,8 @@ class Query extends AbstractQuery { ...@@ -198,9 +198,8 @@ class Query extends AbstractQuery {
const targetAttr = attrsMap[key]; const targetAttr = attrsMap[key];
if (typeof targetAttr === 'string' && targetAttr !== key) { if (typeof targetAttr === 'string' && targetAttr !== key) {
return targetAttr; return targetAttr;
} else {
return key;
} }
return key;
}); });
}); });
} }
......
...@@ -88,9 +88,8 @@ module.exports = BaseTypes => { ...@@ -88,9 +88,8 @@ module.exports = BaseTypes => {
STRING.prototype.toSql = function toSql() { STRING.prototype.toSql = function toSql() {
if (this._binary) { if (this._binary) {
return `VARCHAR BINARY(${this._length})`; return `VARCHAR BINARY(${this._length})`;
} else {
return BaseTypes.STRING.prototype.toSql.call(this);
} }
return BaseTypes.STRING.prototype.toSql.call(this);
}; };
function TEXT(length) { function TEXT(length) {
...@@ -126,9 +125,8 @@ module.exports = BaseTypes => { ...@@ -126,9 +125,8 @@ module.exports = BaseTypes => {
CHAR.prototype.toSql = function toSql() { CHAR.prototype.toSql = function toSql() {
if (this._binary) { if (this._binary) {
return `CHAR BINARY(${this._length})`; return `CHAR BINARY(${this._length})`;
} else {
return BaseTypes.CHAR.prototype.toSql.call(this);
} }
return BaseTypes.CHAR.prototype.toSql.call(this);
}; };
function NUMBER(options) { function NUMBER(options) {
......
...@@ -122,13 +122,12 @@ function removeConstraint(tableName, constraintName, options) { ...@@ -122,13 +122,12 @@ function removeConstraint(tableName, constraintName, options) {
createTableSql += ';'; createTableSql += ';';
return this.describeTable(tableName, options); return this.describeTable(tableName, options);
} else {
throw new sequelizeErrors.UnknownConstraintError({
message: `Constraint ${constraintName} on table ${tableName} does not exist`,
constraint: constraintName,
table: tableName
});
} }
throw new sequelizeErrors.UnknownConstraintError({
message: `Constraint ${constraintName} on table ${tableName} does not exist`,
constraint: constraintName,
table: tableName
});
}) })
.then(fields => { .then(fields => {
const sql = this.QueryGenerator._alterConstraintQuery(tableName, fields, createTableSql); const sql = this.QueryGenerator._alterConstraintQuery(tableName, fields, createTableSql);
......
...@@ -293,7 +293,7 @@ class Query extends AbstractQuery { ...@@ -293,7 +293,7 @@ class Query extends AbstractQuery {
} }
// If we already have the metadata for the table, there's no need to ask for it again // If we already have the metadata for the table, there's no need to ask for it again
tableNames = _.filter(tableNames, tableName => !(tableName in columnTypes) && tableName !== 'sqlite_master'); tableNames = tableNames.filter(tableName => !(tableName in columnTypes) && tableName !== 'sqlite_master');
if (!tableNames.length) { if (!tableNames.length) {
return executeSql(); return executeSql();
......
...@@ -327,7 +327,7 @@ class ValidationErrorItem { ...@@ -327,7 +327,7 @@ class ValidationErrorItem {
if (ValidationErrorItem.Origins[ type ]) { if (ValidationErrorItem.Origins[ type ]) {
this.origin = type; this.origin = type;
} else { } else {
const lowercaseType = (`${type}`).toLowerCase().trim(); const lowercaseType = `${type}`.toLowerCase().trim();
const realType = ValidationErrorItem.TypeStringMap[ lowercaseType ]; const realType = ValidationErrorItem.TypeStringMap[ lowercaseType ];
if (realType && ValidationErrorItem.Origins[ realType ]) { if (realType && ValidationErrorItem.Origins[ realType ]) {
......
...@@ -256,11 +256,10 @@ class InstanceValidator { ...@@ -256,11 +256,10 @@ class InstanceValidator {
} }
return validatorFunction() return validatorFunction()
.catch(e => this._pushError(false, errorKey, e, optValue, validatorType)); .catch(e => this._pushError(false, errorKey, e, optValue, validatorType));
} else {
return Promise
.try(() => validator.call(this.modelInstance, invokeArgs))
.catch(e => this._pushError(false, errorKey, e, optValue, validatorType));
} }
return Promise
.try(() => validator.call(this.modelInstance, invokeArgs))
.catch(e => this._pushError(false, errorKey, e, optValue, validatorType));
} }
/** /**
......
...@@ -1420,10 +1420,8 @@ class Model { ...@@ -1420,10 +1420,8 @@ class Model {
if (options) { if (options) {
if (typeof options === 'string') { if (typeof options === 'string') {
clone._schemaDelimiter = options; clone._schemaDelimiter = options;
} else { } else if (options.schemaDelimiter) {
if (options.schemaDelimiter) { clone._schemaDelimiter = options.schemaDelimiter;
clone._schemaDelimiter = options.schemaDelimiter;
}
} }
} }
...@@ -1554,16 +1552,14 @@ class Model { ...@@ -1554,16 +1552,14 @@ class Model {
} else { } else {
scope = option; scope = option;
} }
} else if (option === 'defaultScope' && _.isPlainObject(self.options.defaultScope)) {
scope = self.options.defaultScope;
} else { } else {
if (option === 'defaultScope' && _.isPlainObject(self.options.defaultScope)) { scopeName = option;
scope = self.options.defaultScope; scope = self.options.scopes[scopeName];
} else {
scopeName = option;
scope = self.options.scopes[scopeName];
if (_.isFunction(scope)) { if (_.isFunction(scope)) {
scope = scope(); scope = scope();
}
} }
} }
...@@ -2589,53 +2585,52 @@ class Model { ...@@ -2589,53 +2585,52 @@ class Model {
}).then(_instances => { }).then(_instances => {
instances = _instances; instances = _instances;
}); });
} else { }
// Create all in one query // Create all in one query
// Recreate records from instances to represent any changes made in hooks or validation // Recreate records from instances to represent any changes made in hooks or validation
records = instances.map(instance => { records = instances.map(instance => {
const values = instance.dataValues; const values = instance.dataValues;
// set createdAt/updatedAt attributes
if (createdAtAttr && !values[createdAtAttr]) {
values[createdAtAttr] = now;
!options.fields.includes(createdAtAttr) && options.fields.push(createdAtAttr);
}
if (updatedAtAttr && !values[updatedAtAttr]) {
values[updatedAtAttr] = now;
!options.fields.includes(updatedAtAttr) && options.fields.push(updatedAtAttr);
}
instance.dataValues = Utils.mapValueFieldNames(values, options.fields, this); // set createdAt/updatedAt attributes
if (createdAtAttr && !values[createdAtAttr]) {
values[createdAtAttr] = now;
!options.fields.includes(createdAtAttr) && options.fields.push(createdAtAttr);
}
if (updatedAtAttr && !values[updatedAtAttr]) {
values[updatedAtAttr] = now;
!options.fields.includes(updatedAtAttr) && options.fields.push(updatedAtAttr);
}
const out = Object.assign({}, instance.dataValues); instance.dataValues = Utils.mapValueFieldNames(values, options.fields, this);
for (const key of this._virtualAttributes) {
delete out[key];
}
return out;
});
// Map attributes to fields for serial identification const out = Object.assign({}, instance.dataValues);
const fieldMappedAttributes = {}; for (const key of this._virtualAttributes) {
for (const attr in this.tableAttributes) { delete out[key];
fieldMappedAttributes[this.rawAttributes[attr].field || attr] = this.rawAttributes[attr];
} }
return out;
});
// Map updateOnDuplicate attributes to fields // Map attributes to fields for serial identification
if (options.updateOnDuplicate) { const fieldMappedAttributes = {};
options.updateOnDuplicate = options.updateOnDuplicate.map(attr => this.rawAttributes[attr].field || attr); for (const attr in this.tableAttributes) {
} fieldMappedAttributes[this.rawAttributes[attr].field || attr] = this.rawAttributes[attr];
}
return this.QueryInterface.bulkInsert(this.getTableName(options), records, options, fieldMappedAttributes).then(results => { // Map updateOnDuplicate attributes to fields
if (Array.isArray(results)) { if (options.updateOnDuplicate) {
results.forEach((result, i) => { options.updateOnDuplicate = options.updateOnDuplicate.map(attr => this.rawAttributes[attr].field || attr);
if (instances[i] && !instances[i].get(this.primaryKeyAttribute)) {
instances[i].dataValues[this.primaryKeyField] = result[this.primaryKeyField];
}
});
}
return results;
});
} }
return this.QueryInterface.bulkInsert(this.getTableName(options), records, options, fieldMappedAttributes).then(results => {
if (Array.isArray(results)) {
results.forEach((result, i) => {
if (instances[i] && !instances[i].get(this.primaryKeyAttribute)) {
instances[i].dataValues[this.primaryKeyField] = result[this.primaryKeyField];
}
});
}
return results;
});
}).then(() => { }).then(() => {
// map fields back to attributes // map fields back to attributes
instances.forEach(instance => { instances.forEach(instance => {
...@@ -2756,9 +2751,8 @@ class Model { ...@@ -2756,9 +2751,8 @@ class Model {
attrValueHash[field] = Utils.now(this.sequelize.options.dialect); attrValueHash[field] = Utils.now(this.sequelize.options.dialect);
return this.QueryInterface.bulkUpdate(this.getTableName(options), attrValueHash, Object.assign(where, options.where), options, this.rawAttributes); return this.QueryInterface.bulkUpdate(this.getTableName(options), attrValueHash, Object.assign(where, options.where), options, this.rawAttributes);
} else {
return this.QueryInterface.bulkDelete(this.getTableName(options), options.where, options, this);
} }
return this.QueryInterface.bulkDelete(this.getTableName(options), options.where, options, this);
}).tap(() => { }).tap(() => {
// Run afterDestroy hook on each record individually // Run afterDestroy hook on each record individually
if (options.individualHooks) { if (options.individualHooks) {
...@@ -3847,11 +3841,10 @@ class Model { ...@@ -3847,11 +3841,10 @@ class Model {
return include.association.throughModel.create(values, includeOptions); return include.association.throughModel.create(values, includeOptions);
}); });
} else {
instance.set(include.association.foreignKey, this.get(include.association.sourceKey || this.constructor.primaryKeyAttribute, {raw: true}));
Object.assign(instance, include.association.scope);
return instance.save(includeOptions);
} }
instance.set(include.association.foreignKey, this.get(include.association.sourceKey || this.constructor.primaryKeyAttribute, {raw: true}));
Object.assign(instance, include.association.scope);
return instance.save(includeOptions);
}); });
}); });
}) })
......
...@@ -1186,9 +1186,8 @@ class QueryInterface { ...@@ -1186,9 +1186,8 @@ class QueryInterface {
options = options || {}; options = options || {};
if (sql) { if (sql) {
return this.sequelize.query(sql, options); return this.sequelize.query(sql, options);
} else {
return Promise.resolve();
} }
return Promise.resolve();
} }
dropTrigger(tableName, triggerName, options) { dropTrigger(tableName, triggerName, options) {
...@@ -1197,9 +1196,8 @@ class QueryInterface { ...@@ -1197,9 +1196,8 @@ class QueryInterface {
if (sql) { if (sql) {
return this.sequelize.query(sql, options); return this.sequelize.query(sql, options);
} else {
return Promise.resolve();
} }
return Promise.resolve();
} }
renameTrigger(tableName, oldTriggerName, newTriggerName, options) { renameTrigger(tableName, oldTriggerName, newTriggerName, options) {
...@@ -1208,9 +1206,8 @@ class QueryInterface { ...@@ -1208,9 +1206,8 @@ class QueryInterface {
if (sql) { if (sql) {
return this.sequelize.query(sql, options); return this.sequelize.query(sql, options);
} else {
return Promise.resolve();
} }
return Promise.resolve();
} }
/** /**
...@@ -1247,9 +1244,8 @@ class QueryInterface { ...@@ -1247,9 +1244,8 @@ class QueryInterface {
if (sql) { if (sql) {
return this.sequelize.query(sql, options); return this.sequelize.query(sql, options);
} else {
return Promise.resolve();
} }
return Promise.resolve();
} }
/** /**
...@@ -1276,9 +1272,8 @@ class QueryInterface { ...@@ -1276,9 +1272,8 @@ class QueryInterface {
if (sql) { if (sql) {
return this.sequelize.query(sql, options); return this.sequelize.query(sql, options);
} else {
return Promise.resolve();
} }
return Promise.resolve();
} }
/** /**
...@@ -1307,9 +1302,8 @@ class QueryInterface { ...@@ -1307,9 +1302,8 @@ class QueryInterface {
if (sql) { if (sql) {
return this.sequelize.query(sql, options); return this.sequelize.query(sql, options);
} else {
return Promise.resolve();
} }
return Promise.resolve();
} }
// Helper methods useful for querying // Helper methods useful for querying
......
...@@ -764,9 +764,8 @@ class Sequelize { ...@@ -764,9 +764,8 @@ class Sequelize {
if (options && options.cascade) { if (options && options.cascade) {
return Promise.each(models, truncateModel); return Promise.each(models, truncateModel);
} else {
return Promise.map(models, truncateModel);
} }
return Promise.map(models, truncateModel);
} }
/** /**
......
...@@ -117,9 +117,8 @@ function formatNamedParameters(sql, values, timeZone, dialect) { ...@@ -117,9 +117,8 @@ function formatNamedParameters(sql, values, timeZone, dialect) {
if (values[key] !== undefined) { if (values[key] !== undefined) {
return escape(values[key], timeZone, dialect, true); return escape(values[key], timeZone, dialect, true);
} else {
throw new Error(`Named parameter "${value}" has no value in the given object.`);
} }
throw new Error(`Named parameter "${value}" has no value in the given object.`);
}); });
} }
exports.formatNamedParameters = formatNamedParameters; exports.formatNamedParameters = formatNamedParameters;
...@@ -92,12 +92,11 @@ validator.isDate = function(dateString) { ...@@ -92,12 +92,11 @@ validator.isDate = function(dateString) {
if (isNaN(parsed)) { if (isNaN(parsed)) {
// fail if we can't parse it // fail if we can't parse it
return false; return false;
} else {
// otherwise convert to ISO 8601 as moment prefers
// http://momentjs.com/docs/#/parsing/string/
const date = new Date(parsed);
return moment(date.toISOString()).isValid();
} }
// otherwise convert to ISO 8601 as moment prefers
// http://momentjs.com/docs/#/parsing/string/
const date = new Date(parsed);
return moment(date.toISOString()).isValid();
}; };
exports.validator = validator; exports.validator = validator;
...@@ -21,6 +21,9 @@ ...@@ -21,6 +21,9 @@
"engines": { "engines": {
"node": ">=6.0.0" "node": ">=6.0.0"
}, },
"files": [
"lib"
],
"license": "MIT", "license": "MIT",
"dependencies": { "dependencies": {
"bluebird": "^3.5.0", "bluebird": "^3.5.0",
......
...@@ -1686,7 +1686,7 @@ describe(Support.getTestDialectTeaser('BelongsToMany'), () => { ...@@ -1686,7 +1686,7 @@ describe(Support.getTestDialectTeaser('BelongsToMany'), () => {
describe('add', () => { describe('add', () => {
it('should insert data provided on the object into the join table', function() { it('should insert data provided on the object into the join table', function() {
const ctx = { const ctx = {
UserProjects: this.UserProjects, UserProjects: this.UserProjects
}; };
return Promise.all([ return Promise.all([
this.User.create(), this.User.create(),
...@@ -1706,7 +1706,7 @@ describe(Support.getTestDialectTeaser('BelongsToMany'), () => { ...@@ -1706,7 +1706,7 @@ describe(Support.getTestDialectTeaser('BelongsToMany'), () => {
it('should insert data provided as a second argument into the join table', function() { it('should insert data provided as a second argument into the join table', function() {
const ctx = { const ctx = {
UserProjects: this.UserProjects, UserProjects: this.UserProjects
}; };
return Promise.all([ return Promise.all([
this.User.create(), this.User.create(),
...@@ -1814,7 +1814,7 @@ describe(Support.getTestDialectTeaser('BelongsToMany'), () => { ...@@ -1814,7 +1814,7 @@ describe(Support.getTestDialectTeaser('BelongsToMany'), () => {
expect(foo.bars[0].name).to.equal('bar...'); expect(foo.bars[0].name).to.equal('bar...');
expect(foo.bars[0].foobar).to.not.equal(null); expect(foo.bars[0].foobar).to.not.equal(null);
expect(foo.bars[0].foobar.baz).to.equal('baz...'); expect(foo.bars[0].foobar.baz).to.equal('baz...');
return Foo.findOne({ include: Bar }); return Foo.findOne({ include: Bar });
}).then(foo => { }).then(foo => {
expect(foo.name).to.equal('foo...'); expect(foo.name).to.equal('foo...');
......
...@@ -20,9 +20,8 @@ describe(Support.getTestDialectTeaser('Configuration'), () => { ...@@ -20,9 +20,8 @@ describe(Support.getTestDialectTeaser('Configuration'), () => {
if (dialect === 'sqlite') { if (dialect === 'sqlite') {
// SQLite doesn't have a breakdown of error codes, so we are unable to discern between the different types of errors. // SQLite doesn't have a breakdown of error codes, so we are unable to discern between the different types of errors.
return expect(seq.query('select 1 as hello')).to.eventually.be.rejectedWith(Sequelize.ConnectionError, 'SQLITE_CANTOPEN: unable to open database file'); return expect(seq.query('select 1 as hello')).to.eventually.be.rejectedWith(Sequelize.ConnectionError, 'SQLITE_CANTOPEN: unable to open database file');
} else {
return expect(seq.query('select 1 as hello')).to.eventually.be.rejectedWith([Sequelize.HostNotReachableError, Sequelize.InvalidConnectionError]);
} }
return expect(seq.query('select 1 as hello')).to.eventually.be.rejectedWith([Sequelize.HostNotReachableError, Sequelize.InvalidConnectionError]);
}); });
it('when we don\'t have the correct login information', () => { it('when we don\'t have the correct login information', () => {
...@@ -37,9 +36,8 @@ describe(Support.getTestDialectTeaser('Configuration'), () => { ...@@ -37,9 +36,8 @@ describe(Support.getTestDialectTeaser('Configuration'), () => {
if (dialect === 'sqlite') { if (dialect === 'sqlite') {
// SQLite doesn't require authentication and `select 1 as hello` is a valid query, so this should be fulfilled not rejected for it. // SQLite doesn't require authentication and `select 1 as hello` is a valid query, so this should be fulfilled not rejected for it.
return expect(seq.query('select 1 as hello')).to.eventually.be.fulfilled; return expect(seq.query('select 1 as hello')).to.eventually.be.fulfilled;
} else {
return expect(seq.query('select 1 as hello')).to.eventually.be.rejectedWith(Sequelize.ConnectionRefusedError, 'connect ECONNREFUSED');
} }
return expect(seq.query('select 1 as hello')).to.eventually.be.rejectedWith(Sequelize.ConnectionRefusedError, 'connect ECONNREFUSED');
}); });
it('when we don\'t have a valid dialect.', () => { it('when we don\'t have a valid dialect.', () => {
...@@ -57,14 +55,7 @@ describe(Support.getTestDialectTeaser('Configuration'), () => { ...@@ -57,14 +55,7 @@ describe(Support.getTestDialectTeaser('Configuration'), () => {
const createTableBar = 'CREATE TABLE bar (baz TEXT);'; const createTableBar = 'CREATE TABLE bar (baz TEXT);';
const testAccess = Sequelize.Promise.method(() => { const testAccess = Sequelize.Promise.method(() => {
if (fs.access) { return Sequelize.Promise.promisify(fs.access)(p, fs.R_OK | fs.W_OK);
return Sequelize.Promise.promisify(fs.access)(p, fs.R_OK | fs.W_OK);
} else { // Node v0.10 and older don't have fs.access
return Sequelize.Promise.promisify(fs.open)(p, 'r+')
.then(fd => {
return Sequelize.Promise.promisify(fs.close)(fd);
});
}
}); });
return Sequelize.Promise.promisify(fs.unlink)(p) return Sequelize.Promise.promisify(fs.unlink)(p)
......
...@@ -256,10 +256,9 @@ describe(Support.getTestDialectTeaser('DataTypes'), () => { ...@@ -256,10 +256,9 @@ describe(Support.getTestDialectTeaser('DataTypes'), () => {
// there is no dialect.supports.UUID yet // there is no dialect.supports.UUID yet
if (['postgres', 'sqlite'].includes(dialect)) { if (['postgres', 'sqlite'].includes(dialect)) {
return testSuccess(Type, uuid.v4()); return testSuccess(Type, uuid.v4());
} else {
// No native uuid type
testFailure(Type);
} }
// No native uuid type
testFailure(Type);
}); });
it('calls parse and stringify for CIDR', () => { it('calls parse and stringify for CIDR', () => {
...@@ -267,9 +266,8 @@ describe(Support.getTestDialectTeaser('DataTypes'), () => { ...@@ -267,9 +266,8 @@ describe(Support.getTestDialectTeaser('DataTypes'), () => {
if (['postgres'].includes(dialect)) { if (['postgres'].includes(dialect)) {
return testSuccess(Type, '10.1.2.3/32'); return testSuccess(Type, '10.1.2.3/32');
} else {
testFailure(Type);
} }
testFailure(Type);
}); });
it('calls parse and stringify for INET', () => { it('calls parse and stringify for INET', () => {
...@@ -277,9 +275,8 @@ describe(Support.getTestDialectTeaser('DataTypes'), () => { ...@@ -277,9 +275,8 @@ describe(Support.getTestDialectTeaser('DataTypes'), () => {
if (['postgres'].includes(dialect)) { if (['postgres'].includes(dialect)) {
return testSuccess(Type, '127.0.0.1'); return testSuccess(Type, '127.0.0.1');
} else {
testFailure(Type);
} }
testFailure(Type);
}); });
it('calls parse and stringify for CITEXT', () => { it('calls parse and stringify for CITEXT', () => {
...@@ -292,9 +289,8 @@ describe(Support.getTestDialectTeaser('DataTypes'), () => { ...@@ -292,9 +289,8 @@ describe(Support.getTestDialectTeaser('DataTypes'), () => {
if (dialect === 'postgres') { if (dialect === 'postgres') {
return testSuccess(Type, 'foobar'); return testSuccess(Type, 'foobar');
} else {
testFailure(Type);
} }
testFailure(Type);
}); });
it('calls parse and stringify for MACADDR', () => { it('calls parse and stringify for MACADDR', () => {
...@@ -302,9 +298,9 @@ describe(Support.getTestDialectTeaser('DataTypes'), () => { ...@@ -302,9 +298,9 @@ describe(Support.getTestDialectTeaser('DataTypes'), () => {
if (['postgres'].includes(dialect)) { if (['postgres'].includes(dialect)) {
return testSuccess(Type, '01:23:45:67:89:ab'); return testSuccess(Type, '01:23:45:67:89:ab');
} else {
testFailure(Type);
} }
testFailure(Type);
}); });
it('calls parse and stringify for ENUM', () => { it('calls parse and stringify for ENUM', () => {
...@@ -312,9 +308,8 @@ describe(Support.getTestDialectTeaser('DataTypes'), () => { ...@@ -312,9 +308,8 @@ describe(Support.getTestDialectTeaser('DataTypes'), () => {
if (['postgres'].includes(dialect)) { if (['postgres'].includes(dialect)) {
return testSuccess(Type, 'hat'); return testSuccess(Type, 'hat');
} else {
testFailure(Type);
} }
testFailure(Type);
}); });
if (current.dialect.supports.GEOMETRY) { if (current.dialect.supports.GEOMETRY) {
......
...@@ -514,9 +514,8 @@ describe(Support.getTestDialectTeaser('Include'), () => { ...@@ -514,9 +514,8 @@ describe(Support.getTestDialectTeaser('Include'), () => {
return previousInstance[`set${_.upperFirst(model.name)}`](instance).then(() => { return previousInstance[`set${_.upperFirst(model.name)}`](instance).then(() => {
previousInstance = instance; previousInstance = instance;
}); });
} else {
previousInstance = b = instance;
} }
previousInstance = b = instance;
}); });
}); });
}); });
...@@ -613,9 +612,8 @@ describe(Support.getTestDialectTeaser('Include'), () => { ...@@ -613,9 +612,8 @@ describe(Support.getTestDialectTeaser('Include'), () => {
return previousInstance[`set${_.upperFirst(model.name)}`](instance).then(() => { return previousInstance[`set${_.upperFirst(model.name)}`](instance).then(() => {
previousInstance = instance; previousInstance = instance;
}); });
} else {
previousInstance = b = instance;
} }
previousInstance = b = instance;
}); });
}); });
}); });
......
...@@ -313,9 +313,8 @@ describe(Support.getTestDialectTeaser('Include'), () => { ...@@ -313,9 +313,8 @@ describe(Support.getTestDialectTeaser('Include'), () => {
return previousInstance[`set${_.upperFirst(model.name)}`](instance).then(() => { return previousInstance[`set${_.upperFirst(model.name)}`](instance).then(() => {
previousInstance = instance; previousInstance = instance;
}); });
} else {
previousInstance = b = instance;
} }
previousInstance = b = instance;
}); });
}); });
}); });
......
...@@ -2319,9 +2319,8 @@ describe(Support.getTestDialectTeaser('Model'), () => { ...@@ -2319,9 +2319,8 @@ describe(Support.getTestDialectTeaser('Model'), () => {
return run.call(this); return run.call(this);
}); });
}); });
} else {
return run.call(this);
} }
return run.call(this);
}); });
it('should be able to create and update records under any valid schematic', function() { it('should be able to create and update records under any valid schematic', function() {
......
...@@ -893,7 +893,8 @@ describe(Support.getTestDialectTeaser('Model'), () => { ...@@ -893,7 +893,8 @@ describe(Support.getTestDialectTeaser('Model'), () => {
}); });
}); });
}); });
} else if (dialect === 'sqlite') { }
if (dialect === 'sqlite') {
// The definition here is a bit hacky. sqlite expects () around the expression for default values, so we call a function without a name // The definition here is a bit hacky. sqlite expects () around the expression for default values, so we call a function without a name
// to enclose the date function in (). http://www.sqlite.org/syntaxdiagrams.html#column-constraint // to enclose the date function in (). http://www.sqlite.org/syntaxdiagrams.html#column-constraint
userWithDefaults = this.sequelize.define('userWithDefaults', { userWithDefaults = this.sequelize.define('userWithDefaults', {
...@@ -918,10 +919,9 @@ describe(Support.getTestDialectTeaser('Model'), () => { ...@@ -918,10 +919,9 @@ describe(Support.getTestDialectTeaser('Model'), () => {
}); });
}); });
}); });
} else {
// functions as default values are not supported in mysql, see http://stackoverflow.com/a/270338/800016
return void 0;
} }
// functions as default values are not supported in mysql, see http://stackoverflow.com/a/270338/800016
return void 0;
}); });
if (dialect === 'postgres') { if (dialect === 'postgres') {
...@@ -983,7 +983,7 @@ describe(Support.getTestDialectTeaser('Model'), () => { ...@@ -983,7 +983,7 @@ describe(Support.getTestDialectTeaser('Model'), () => {
}); });
if (dialect === 'postgres' || dialect === 'sqlite') { if (dialect === 'postgres' || dialect === 'sqlite') {
it("doesn't allow case-insensitive duplicated records using CITEXT", function () { it("doesn't allow case-insensitive duplicated records using CITEXT", function() {
const User = this.sequelize.define('UserWithUniqueCITEXT', { const User = this.sequelize.define('UserWithUniqueCITEXT', {
username: {type: Sequelize.CITEXT, unique: true} username: {type: Sequelize.CITEXT, unique: true}
}); });
...@@ -999,7 +999,7 @@ describe(Support.getTestDialectTeaser('Model'), () => { ...@@ -999,7 +999,7 @@ describe(Support.getTestDialectTeaser('Model'), () => {
} }
if (current.dialect.supports.index.functionBased) { if (current.dialect.supports.index.functionBased) {
it("doesn't allow duplicated records with unique function based indexes", function () { it("doesn't allow duplicated records with unique function based indexes", function() {
const User = this.sequelize.define('UserWithUniqueUsernameFunctionIndex', { const User = this.sequelize.define('UserWithUniqueUsernameFunctionIndex', {
username: Sequelize.STRING, username: Sequelize.STRING,
email: {type: Sequelize.STRING, unique: true} email: {type: Sequelize.STRING, unique: true}
......
...@@ -776,7 +776,8 @@ describe(Support.getTestDialectTeaser('Model'), () => { ...@@ -776,7 +776,8 @@ describe(Support.getTestDialectTeaser('Model'), () => {
employment: 'Nuclear Safety Inspector' employment: 'Nuclear Safety Inspector'
}); });
}); });
} else if (current.options.dialect === 'postgres') { }
if (current.options.dialect === 'postgres') {
return expect(this.Event.findAll({ return expect(this.Event.findAll({
where: { where: {
data: { data: {
......
...@@ -520,10 +520,9 @@ describe(Support.getTestDialectTeaser('QueryInterface'), () => { ...@@ -520,10 +520,9 @@ describe(Support.getTestDialectTeaser('QueryInterface'), () => {
if (dialect === 'mysql') { if (dialect === 'mysql') {
expect(constraints).to.include('PRIMARY'); expect(constraints).to.include('PRIMARY');
return this.queryInterface.removeConstraint('users', 'PRIMARY'); return this.queryInterface.removeConstraint('users', 'PRIMARY');
} else {
expect(constraints).to.include('users_username_pk');
return this.queryInterface.removeConstraint('users', 'users_username_pk');
} }
expect(constraints).to.include('users_username_pk');
return this.queryInterface.removeConstraint('users', 'users_username_pk');
}) })
.then(() => this.queryInterface.showConstraint('users')) .then(() => this.queryInterface.showConstraint('users'))
.then(constraints => { .then(constraints => {
......
...@@ -600,18 +600,16 @@ if (current.dialect.supports.transactions) { ...@@ -600,18 +600,16 @@ if (current.dialect.supports.transactions) {
lock: t1.LOCK.UPDATE, lock: t1.LOCK.UPDATE,
transaction: t1 transaction: t1
})).to.be.rejectedWith('FOR UPDATE cannot be applied to the nullable side of an outer join'); })).to.be.rejectedWith('FOR UPDATE cannot be applied to the nullable side of an outer join');
} else {
return User.findOne({
where: {
username: 'John'
},
include: [Task],
lock: t1.LOCK.UPDATE,
transaction: t1
});
} }
return User.findOne({
where: {
username: 'John'
},
include: [Task],
lock: t1.LOCK.UPDATE,
transaction: t1
});
}); });
}); });
}); });
......
...@@ -78,12 +78,11 @@ const Support = { ...@@ -78,12 +78,11 @@ const Support = {
return _sequelize.sync({ force: true }).return (_sequelize); return _sequelize.sync({ force: true }).return (_sequelize);
} }
}); });
}
if (callback) {
callback(sequelize);
} else { } else {
if (callback) { return Sequelize.Promise.resolve(sequelize);
callback(sequelize);
} else {
return Sequelize.Promise.resolve(sequelize);
}
} }
}, },
......
...@@ -220,9 +220,8 @@ module.exports = function(Sequelize) { ...@@ -220,9 +220,8 @@ module.exports = function(Sequelize) {
if (logger) { if (logger) {
if ((sequelize.options.benchmark || options.benchmark) && logger === console.log) { if ((sequelize.options.benchmark || options.benchmark) && logger === console.log) {
return logger.call(this, `${arguments[0]} Elapsed time: ${arguments[1]}ms`); return logger.call(this, `${arguments[0]} Elapsed time: ${arguments[1]}ms`);
} else {
return logger.apply(this, arguments);
} }
return logger.apply(this, arguments);
} }
}; };
......
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!