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

Commit c1ac5433 by Simon Schick Committed by Sushant

refactor: reduce code complexity (#10120)

1 parent b896ba4d
......@@ -25,17 +25,17 @@
"keyword-spacing": "error",
"no-console": "off",
"no-extra-parens": "warn",
"no-extra-parens": "error",
"valid-jsdoc": "off",
"new-cap": [
"warn",
"error",
{
"properties": false
}
],
"no-extra-boolean-cast": "warn",
"no-extra-boolean-cast": "error",
"strict": [
"warn",
"error",
"global"
],
"no-var": "error",
......@@ -45,7 +45,7 @@
"always"
],
"space-before-function-paren": [
"warn",
"error",
"never"
],
"space-before-blocks": "error",
......@@ -55,7 +55,7 @@
"as-needed"
],
"comma-style": [
"warn",
"error",
"last"
],
"no-bitwise": "off",
......@@ -84,7 +84,7 @@
"no-irregular-whitespace": "error",
"max-depth": [
"error",
8
6
],
"quotes": [
"error",
......@@ -96,11 +96,13 @@
"linebreak-style": "error",
"no-loop-func": "warn",
"object-shorthand": "error",
"one-var-declaration-per-line": "warn",
"comma-dangle": "warn",
"one-var-declaration-per-line": "error",
"comma-dangle": "error",
"no-shadow": "warn",
"camelcase": "warn",
"prefer-template": "error"
"prefer-template": "error",
"no-else-return": ["error", { "allowElseIf": false }],
"no-lonely-if": "error"
},
"parserOptions": {
"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 {
where[Op.or] = instances.map(instance => {
if (instance instanceof association.target) {
return instance.where();
} else {
const where = {};
where[association.target.primaryKeyAttribute] = instance;
return where;
}
return {
[association.target.primaryKeyAttribute]: instance
};
});
options.where = {
......
......@@ -153,10 +153,9 @@ class BelongsTo extends Association {
} else {
if (this.targetKeyIsPrimary && !options.where) {
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 ?
......
......@@ -290,11 +290,10 @@ class HasMany extends Association {
where[Op.or] = targetInstances.map(instance => {
if (instance instanceof this.target) {
return instance.where();
} else {
const _where = {};
_where[this.target.primaryKeyAttribute] = instance;
return _where;
}
return {
[this.target.primaryKeyAttribute]: instance
};
});
options.where = {
......
......@@ -86,9 +86,8 @@ const Mixin = {
verifyAssociationAlias(association, alias) {
if (alias) {
return association.as === alias;
} else {
return !association.isAliased;
}
return !association.isAliased;
}
};
......
......@@ -548,15 +548,11 @@ DATE.prototype._isChanged = function _isChanged(value, originalValue) {
DATE.prototype._applyTimezone = function _applyTimezone(date, options) {
if (options.timezone) {
if (momentTz.tz.zone(options.timezone)) {
date = momentTz(date).tz(options.timezone);
} else {
date = moment(date).utcOffset(options.timezone);
return momentTz(date).tz(options.timezone);
}
} else {
date = momentTz(date);
return date = moment(date).utcOffset(options.timezone);
}
return date;
return momentTz(date);
};
DATE.prototype._stringify = function _stringify(date, options) {
......
......@@ -170,9 +170,8 @@ class ConnectionManager {
useMaster = _.isUndefined(useMaster) ? false : useMaster;
if (queryType === 'SELECT' && !useMaster) {
return this.pool.read.acquire();
} else {
return this.pool.write.acquire();
}
return this.pool.write.acquire();
},
destroy: connection => {
this.pool[connection.queryType].destroy(connection);
......
......@@ -716,7 +716,8 @@ class QueryGenerator {
// just quote as identifiers if string
if (typeof collection === 'string') {
return this.quoteIdentifiers(collection);
} else if (Array.isArray(collection)) {
}
if (Array.isArray(collection)) {
// iterate through the collection and mutate objects into associations
collection.forEach((item, index) => {
const previous = collection[index - 1];
......@@ -888,9 +889,8 @@ class QueryGenerator {
quoteAttribute(attribute, model) {
if (model && attribute in model.rawAttributes) {
return this.quoteIdentifier(attribute);
} else {
return this.quoteIdentifiers(attribute);
}
return this.quoteIdentifiers(attribute);
}
/**
......@@ -944,20 +944,19 @@ class QueryGenerator {
if (value !== null && value !== undefined) {
if (value instanceof Utils.SequelizeMethod) {
return this.handleSequelizeMethod(value);
} else {
if (field && field.type) {
this.validate(value, field, options);
}
if (field && field.type) {
this.validate(value, field, options);
if (field.type.stringify) {
// 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);
if (field.type.stringify) {
// 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);
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) {
// The data-type already did the required escaping
return value;
}
if (field.type.escape === false) {
// The data-type already did the required escaping
return value;
}
}
}
......@@ -983,13 +982,12 @@ class QueryGenerator {
if (value !== null && value !== undefined) {
if (value instanceof Utils.SequelizeMethod) {
throw new Error('Cannot pass SequelizeMethod as a bind parameter - use escape instead');
} else {
if (field && field.type) {
this.validate(value, field, options);
}
if (field && field.type) {
this.validate(value, field, options);
if (field.type.bindParam) {
return field.type.bindParam(value, { escape: _.identity, field, timezone: this.options.timezone, operation: options.operation, bindParam });
}
if (field.type.bindParam) {
return field.type.bindParam(value, { escape: _.identity, field, timezone: this.options.timezone, operation: options.operation, bindParam });
}
}
}
......@@ -1968,15 +1966,14 @@ class QueryGenerator {
return this.whereItemQuery(smth.attribute, value, {
model: factory
});
}
if (typeof value === 'boolean') {
value = this.booleanValue(value);
} else {
if (typeof value === 'boolean') {
value = this.booleanValue(value);
} else {
value = this.escape(value);
}
return value === 'NULL' ? `${key} IS NULL` : [key, value].join(` ${smth.comparator} `);
value = this.escape(value);
}
return value === 'NULL' ? `${key} IS NULL` : [key, value].join(` ${smth.comparator} `);
}
if (smth instanceof Utils.Literal) {
return smth.val;
......@@ -2145,9 +2142,8 @@ class QueryGenerator {
if (isPlainObject) {
if (this.OperatorMap[valueKeys[0]]) {
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) {
......
......@@ -63,10 +63,8 @@ function quoteIdentifier(dialect, identifier, options) {
// 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.
return rawIdentifier;
} else {
return Utils.addTicks(rawIdentifier, '"');
}
return Utils.addTicks(rawIdentifier, '"');
case 'mssql':
return `[${identifier.replace(/[\[\]']+/g, '')}]`;
......
......@@ -49,16 +49,14 @@ class AbstractQuery {
return undefined;
};
}
} else {
if (options.skipValueReplace) {
const origReplacementFunc = replacementFunc;
replacementFunc = (match, key, values, timeZone, dialect, options) => {
if (origReplacementFunc(match, key, values, timeZone, dialect, options) !== undefined) {
return match;
}
return undefined;
};
}
} else if (options.skipValueReplace) {
const origReplacementFunc = replacementFunc;
replacementFunc = (match, key, values, timeZone, dialect, options) => {
if (origReplacementFunc(match, key, values, timeZone, dialect, options) !== undefined) {
return match;
}
return undefined;
};
}
const timeZone = null;
......@@ -75,10 +73,8 @@ class AbstractQuery {
key = key - 1;
replVal = replacementFunc(match, key, values, timeZone, dialect, options);
}
} else {
if (!key.match(/^\d*$/)) {
replVal = replacementFunc(match, key, values, timeZone, dialect, options);
}
} else if (!key.match(/^\d*$/)) {
replVal = replacementFunc(match, key, values, timeZone, dialect, options);
}
if (replVal === undefined) {
throw new Error(`Named bind parameter "${match}" has no value in the given object.`);
......@@ -562,21 +558,19 @@ class AbstractQuery {
} else {
topExists = true;
}
} else {
if (!resultMap[itemHash]) {
$parent = resultMap[parentHash];
$lastKeyPrefix = lastKeyPrefix(prevKey);
} else if (!resultMap[itemHash]) {
$parent = resultMap[parentHash];
$lastKeyPrefix = lastKeyPrefix(prevKey);
if (includeMap[prevKey].association.isSingleAssociation) {
if ($parent) {
$parent[$lastKeyPrefix] = resultMap[itemHash] = values;
}
} else {
if (!$parent[$lastKeyPrefix]) {
$parent[$lastKeyPrefix] = [];
}
$parent[$lastKeyPrefix].push(resultMap[itemHash] = values);
if (includeMap[prevKey].association.isSingleAssociation) {
if ($parent) {
$parent[$lastKeyPrefix] = resultMap[itemHash] = values;
}
} else {
if (!$parent[$lastKeyPrefix]) {
$parent[$lastKeyPrefix] = [];
}
$parent[$lastKeyPrefix].push(resultMap[itemHash] = values);
}
}
......@@ -651,21 +645,19 @@ class AbstractQuery {
} else {
topExists = true;
}
} else {
if (!resultMap[itemHash]) {
$parent = resultMap[parentHash];
$lastKeyPrefix = lastKeyPrefix(prevKey);
} else if (!resultMap[itemHash]) {
$parent = resultMap[parentHash];
$lastKeyPrefix = lastKeyPrefix(prevKey);
if (includeMap[prevKey].association.isSingleAssociation) {
if ($parent) {
$parent[$lastKeyPrefix] = resultMap[itemHash] = values;
}
} else {
if (!$parent[$lastKeyPrefix]) {
$parent[$lastKeyPrefix] = [];
}
$parent[$lastKeyPrefix].push(resultMap[itemHash] = values);
if (includeMap[prevKey].association.isSingleAssociation) {
if ($parent) {
$parent[$lastKeyPrefix] = resultMap[itemHash] = values;
}
} else {
if (!$parent[$lastKeyPrefix]) {
$parent[$lastKeyPrefix] = [];
}
$parent[$lastKeyPrefix].push(resultMap[itemHash] = values);
}
}
if (!topExists) {
......
......@@ -80,18 +80,16 @@ module.exports = BaseTypes => {
STRING.prototype.toSql = function toSql() {
if (!this._binary) {
return `NVARCHAR(${this._length})`;
} else {
return `BINARY(${this._length})`;
}
return `BINARY(${this._length})`;
};
STRING.prototype.escape = false;
STRING.prototype._stringify = function _stringify(value, options) {
if (this._binary) {
return BLOB.prototype._stringify(value);
} else {
return options.escape(value);
}
return options.escape(value);
};
STRING.prototype._bindParam = function _bindParam(value, options) {
return options.bindParam(this._binary ? Buffer.from(value) : value);
......
......@@ -551,9 +551,8 @@ class MSSQLQueryGenerator extends AbstractQueryGenerator {
return this.escape(value);
}).join(', ') }))`;
return template;
} else {
template = attribute.type.toString();
}
template = attribute.type.toString();
if (attribute.allowNull === false) {
template += ' NOT NULL';
......@@ -825,9 +824,8 @@ class MSSQLQueryGenerator extends AbstractQueryGenerator {
` AS ${tmpTable} WHERE row_num > ${offset})` +
` AS ${tmpTable}`;
return fragment;
} else {
mainFragment = `SELECT ${topFragment}${attributes.join(', ')} FROM ${tables}`;
}
mainFragment = `SELECT ${topFragment}${attributes.join(', ')} FROM ${tables}`;
}
if (mainTableAs) {
......
......@@ -195,7 +195,8 @@ class MySQLQueryGenerator extends AbstractQueryGenerator {
);
return conditions.join(' and ');
} else if (smth.path) {
}
if (smth.path) {
let str;
// Allow specifying conditions using the sqlite json functions
......
......@@ -198,9 +198,8 @@ class Query extends AbstractQuery {
const targetAttr = attrsMap[key];
if (typeof targetAttr === 'string' && targetAttr !== key) {
return targetAttr;
} else {
return key;
}
return key;
});
});
}
......
......@@ -88,9 +88,8 @@ module.exports = BaseTypes => {
STRING.prototype.toSql = function toSql() {
if (this._binary) {
return `VARCHAR BINARY(${this._length})`;
} else {
return BaseTypes.STRING.prototype.toSql.call(this);
}
return BaseTypes.STRING.prototype.toSql.call(this);
};
function TEXT(length) {
......@@ -126,9 +125,8 @@ module.exports = BaseTypes => {
CHAR.prototype.toSql = function toSql() {
if (this._binary) {
return `CHAR BINARY(${this._length})`;
} else {
return BaseTypes.CHAR.prototype.toSql.call(this);
}
return BaseTypes.CHAR.prototype.toSql.call(this);
};
function NUMBER(options) {
......
......@@ -122,13 +122,12 @@ function removeConstraint(tableName, constraintName, options) {
createTableSql += ';';
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 => {
const sql = this.QueryGenerator._alterConstraintQuery(tableName, fields, createTableSql);
......
......@@ -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
tableNames = _.filter(tableNames, tableName => !(tableName in columnTypes) && tableName !== 'sqlite_master');
tableNames = tableNames.filter(tableName => !(tableName in columnTypes) && tableName !== 'sqlite_master');
if (!tableNames.length) {
return executeSql();
......
......@@ -327,7 +327,7 @@ class ValidationErrorItem {
if (ValidationErrorItem.Origins[ type ]) {
this.origin = type;
} else {
const lowercaseType = (`${type}`).toLowerCase().trim();
const lowercaseType = `${type}`.toLowerCase().trim();
const realType = ValidationErrorItem.TypeStringMap[ lowercaseType ];
if (realType && ValidationErrorItem.Origins[ realType ]) {
......
......@@ -256,11 +256,10 @@ class InstanceValidator {
}
return validatorFunction()
.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 {
if (options) {
if (typeof options === 'string') {
clone._schemaDelimiter = options;
} else {
if (options.schemaDelimiter) {
clone._schemaDelimiter = options.schemaDelimiter;
}
} else if (options.schemaDelimiter) {
clone._schemaDelimiter = options.schemaDelimiter;
}
}
......@@ -1554,16 +1552,14 @@ class Model {
} else {
scope = option;
}
} else if (option === 'defaultScope' && _.isPlainObject(self.options.defaultScope)) {
scope = self.options.defaultScope;
} else {
if (option === 'defaultScope' && _.isPlainObject(self.options.defaultScope)) {
scope = self.options.defaultScope;
} else {
scopeName = option;
scope = self.options.scopes[scopeName];
scopeName = option;
scope = self.options.scopes[scopeName];
if (_.isFunction(scope)) {
scope = scope();
}
if (_.isFunction(scope)) {
scope = scope();
}
}
......@@ -2589,53 +2585,52 @@ class Model {
}).then(_instances => {
instances = _instances;
});
} else {
// Create all in one query
// Recreate records from instances to represent any changes made in hooks or validation
records = instances.map(instance => {
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);
}
}
// Create all in one query
// Recreate records from instances to represent any changes made in hooks or validation
records = instances.map(instance => {
const values = instance.dataValues;
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);
for (const key of this._virtualAttributes) {
delete out[key];
}
return out;
});
instance.dataValues = Utils.mapValueFieldNames(values, options.fields, this);
// Map attributes to fields for serial identification
const fieldMappedAttributes = {};
for (const attr in this.tableAttributes) {
fieldMappedAttributes[this.rawAttributes[attr].field || attr] = this.rawAttributes[attr];
const out = Object.assign({}, instance.dataValues);
for (const key of this._virtualAttributes) {
delete out[key];
}
return out;
});
// Map updateOnDuplicate attributes to fields
if (options.updateOnDuplicate) {
options.updateOnDuplicate = options.updateOnDuplicate.map(attr => this.rawAttributes[attr].field || attr);
}
// Map attributes to fields for serial identification
const fieldMappedAttributes = {};
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 => {
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;
});
// Map updateOnDuplicate attributes to fields
if (options.updateOnDuplicate) {
options.updateOnDuplicate = options.updateOnDuplicate.map(attr => this.rawAttributes[attr].field || attr);
}
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(() => {
// map fields back to attributes
instances.forEach(instance => {
......@@ -2756,9 +2751,8 @@ class Model {
attrValueHash[field] = Utils.now(this.sequelize.options.dialect);
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(() => {
// Run afterDestroy hook on each record individually
if (options.individualHooks) {
......@@ -3847,11 +3841,10 @@ class Model {
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 {
options = options || {};
if (sql) {
return this.sequelize.query(sql, options);
} else {
return Promise.resolve();
}
return Promise.resolve();
}
dropTrigger(tableName, triggerName, options) {
......@@ -1197,9 +1196,8 @@ class QueryInterface {
if (sql) {
return this.sequelize.query(sql, options);
} else {
return Promise.resolve();
}
return Promise.resolve();
}
renameTrigger(tableName, oldTriggerName, newTriggerName, options) {
......@@ -1208,9 +1206,8 @@ class QueryInterface {
if (sql) {
return this.sequelize.query(sql, options);
} else {
return Promise.resolve();
}
return Promise.resolve();
}
/**
......@@ -1247,9 +1244,8 @@ class QueryInterface {
if (sql) {
return this.sequelize.query(sql, options);
} else {
return Promise.resolve();
}
return Promise.resolve();
}
/**
......@@ -1276,9 +1272,8 @@ class QueryInterface {
if (sql) {
return this.sequelize.query(sql, options);
} else {
return Promise.resolve();
}
return Promise.resolve();
}
/**
......@@ -1307,9 +1302,8 @@ class QueryInterface {
if (sql) {
return this.sequelize.query(sql, options);
} else {
return Promise.resolve();
}
return Promise.resolve();
}
// Helper methods useful for querying
......
......@@ -764,9 +764,8 @@ class Sequelize {
if (options && options.cascade) {
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) {
if (values[key] !== undefined) {
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;
......@@ -92,12 +92,11 @@ validator.isDate = function(dateString) {
if (isNaN(parsed)) {
// fail if we can't parse it
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;
......@@ -21,6 +21,9 @@
"engines": {
"node": ">=6.0.0"
},
"files": [
"lib"
],
"license": "MIT",
"dependencies": {
"bluebird": "^3.5.0",
......
......@@ -1686,7 +1686,7 @@ describe(Support.getTestDialectTeaser('BelongsToMany'), () => {
describe('add', () => {
it('should insert data provided on the object into the join table', function() {
const ctx = {
UserProjects: this.UserProjects,
UserProjects: this.UserProjects
};
return Promise.all([
this.User.create(),
......@@ -1706,7 +1706,7 @@ describe(Support.getTestDialectTeaser('BelongsToMany'), () => {
it('should insert data provided as a second argument into the join table', function() {
const ctx = {
UserProjects: this.UserProjects,
UserProjects: this.UserProjects
};
return Promise.all([
this.User.create(),
......@@ -1814,7 +1814,7 @@ describe(Support.getTestDialectTeaser('BelongsToMany'), () => {
expect(foo.bars[0].name).to.equal('bar...');
expect(foo.bars[0].foobar).to.not.equal(null);
expect(foo.bars[0].foobar.baz).to.equal('baz...');
return Foo.findOne({ include: Bar });
}).then(foo => {
expect(foo.name).to.equal('foo...');
......
......@@ -20,9 +20,8 @@ describe(Support.getTestDialectTeaser('Configuration'), () => {
if (dialect === 'sqlite') {
// 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');
} 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', () => {
......@@ -37,9 +36,8 @@ describe(Support.getTestDialectTeaser('Configuration'), () => {
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.
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.', () => {
......@@ -57,14 +55,7 @@ describe(Support.getTestDialectTeaser('Configuration'), () => {
const createTableBar = 'CREATE TABLE bar (baz TEXT);';
const testAccess = Sequelize.Promise.method(() => {
if (fs.access) {
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.access)(p, fs.R_OK | fs.W_OK);
});
return Sequelize.Promise.promisify(fs.unlink)(p)
......
......@@ -256,10 +256,9 @@ describe(Support.getTestDialectTeaser('DataTypes'), () => {
// there is no dialect.supports.UUID yet
if (['postgres', 'sqlite'].includes(dialect)) {
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', () => {
......@@ -267,9 +266,8 @@ describe(Support.getTestDialectTeaser('DataTypes'), () => {
if (['postgres'].includes(dialect)) {
return testSuccess(Type, '10.1.2.3/32');
} else {
testFailure(Type);
}
testFailure(Type);
});
it('calls parse and stringify for INET', () => {
......@@ -277,9 +275,8 @@ describe(Support.getTestDialectTeaser('DataTypes'), () => {
if (['postgres'].includes(dialect)) {
return testSuccess(Type, '127.0.0.1');
} else {
testFailure(Type);
}
testFailure(Type);
});
it('calls parse and stringify for CITEXT', () => {
......@@ -292,9 +289,8 @@ describe(Support.getTestDialectTeaser('DataTypes'), () => {
if (dialect === 'postgres') {
return testSuccess(Type, 'foobar');
} else {
testFailure(Type);
}
testFailure(Type);
});
it('calls parse and stringify for MACADDR', () => {
......@@ -302,9 +298,9 @@ describe(Support.getTestDialectTeaser('DataTypes'), () => {
if (['postgres'].includes(dialect)) {
return testSuccess(Type, '01:23:45:67:89:ab');
} else {
testFailure(Type);
}
testFailure(Type);
});
it('calls parse and stringify for ENUM', () => {
......@@ -312,9 +308,8 @@ describe(Support.getTestDialectTeaser('DataTypes'), () => {
if (['postgres'].includes(dialect)) {
return testSuccess(Type, 'hat');
} else {
testFailure(Type);
}
testFailure(Type);
});
if (current.dialect.supports.GEOMETRY) {
......
......@@ -514,9 +514,8 @@ describe(Support.getTestDialectTeaser('Include'), () => {
return previousInstance[`set${_.upperFirst(model.name)}`](instance).then(() => {
previousInstance = instance;
});
} else {
previousInstance = b = instance;
}
previousInstance = b = instance;
});
});
});
......@@ -613,9 +612,8 @@ describe(Support.getTestDialectTeaser('Include'), () => {
return previousInstance[`set${_.upperFirst(model.name)}`](instance).then(() => {
previousInstance = instance;
});
} else {
previousInstance = b = instance;
}
previousInstance = b = instance;
});
});
});
......
......@@ -313,9 +313,8 @@ describe(Support.getTestDialectTeaser('Include'), () => {
return previousInstance[`set${_.upperFirst(model.name)}`](instance).then(() => {
previousInstance = instance;
});
} else {
previousInstance = b = instance;
}
previousInstance = b = instance;
});
});
});
......
......@@ -2319,9 +2319,8 @@ describe(Support.getTestDialectTeaser('Model'), () => {
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() {
......
......@@ -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
// to enclose the date function in (). http://www.sqlite.org/syntaxdiagrams.html#column-constraint
userWithDefaults = this.sequelize.define('userWithDefaults', {
......@@ -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') {
......@@ -983,7 +983,7 @@ describe(Support.getTestDialectTeaser('Model'), () => {
});
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', {
username: {type: Sequelize.CITEXT, unique: true}
});
......@@ -999,7 +999,7 @@ describe(Support.getTestDialectTeaser('Model'), () => {
}
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', {
username: Sequelize.STRING,
email: {type: Sequelize.STRING, unique: true}
......
......@@ -776,7 +776,8 @@ describe(Support.getTestDialectTeaser('Model'), () => {
employment: 'Nuclear Safety Inspector'
});
});
} else if (current.options.dialect === 'postgres') {
}
if (current.options.dialect === 'postgres') {
return expect(this.Event.findAll({
where: {
data: {
......
......@@ -520,10 +520,9 @@ describe(Support.getTestDialectTeaser('QueryInterface'), () => {
if (dialect === 'mysql') {
expect(constraints).to.include('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(constraints => {
......
......@@ -600,18 +600,16 @@ if (current.dialect.supports.transactions) {
lock: t1.LOCK.UPDATE,
transaction: t1
})).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 = {
return _sequelize.sync({ force: true }).return (_sequelize);
}
});
}
if (callback) {
callback(sequelize);
} else {
if (callback) {
callback(sequelize);
} else {
return Sequelize.Promise.resolve(sequelize);
}
return Sequelize.Promise.resolve(sequelize);
}
},
......
......@@ -220,9 +220,8 @@ module.exports = function(Sequelize) {
if (logger) {
if ((sequelize.options.benchmark || options.benchmark) && logger === console.log) {
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!