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

Commit e68096f3 by Felix Becker Committed by Jan Aagaard Meier

Fix all auto-fixable ESLint issues (#6436)

1 parent fb2d28c2
......@@ -3,7 +3,7 @@
var Association = function() {};
// Normalize input - may be array or single obj, instance or primary key - convert it to an array of built objects
Association.prototype.toInstanceArray = function (objs) {
Association.prototype.toInstanceArray = function(objs) {
if (!Array.isArray(objs)) {
objs = [objs];
}
......
......@@ -2,7 +2,7 @@
const Utils = require('./../utils');
function checkNamingCollision (association) {
function checkNamingCollision(association) {
if (association.source.rawAttributes.hasOwnProperty(association.as)) {
throw new Error(
'Naming collision between attribute \'' + association.as +
......@@ -13,7 +13,7 @@ function checkNamingCollision (association) {
}
exports.checkNamingCollision = checkNamingCollision;
function addForeignKeyConstraints (newAttribute, source, target, options, key) {
function addForeignKeyConstraints(newAttribute, source, target, options, key) {
// FK constraints are opt-in: users must either set `foreignKeyConstraints`
// on the association, or request an `onDelete` or `onUpdate` behaviour
......
......@@ -154,14 +154,14 @@ inherits(TEXT, ABSTRACT);
TEXT.prototype.key = TEXT.key = 'TEXT';
TEXT.prototype.toSql = function toSql() {
switch (this._length.toLowerCase()) {
case 'tiny':
return 'TINYTEXT';
case 'medium':
return 'MEDIUMTEXT';
case 'long':
return 'LONGTEXT';
default:
return this.key;
case 'tiny':
return 'TINYTEXT';
case 'medium':
return 'MEDIUMTEXT';
case 'long':
return 'LONGTEXT';
default:
return this.key;
}
};
TEXT.prototype.validate = function validate(value) {
......@@ -347,7 +347,7 @@ DECIMAL.prototype.key = DECIMAL.key = 'DECIMAL';
DECIMAL.prototype.toSql = function toSql() {
if (this._precision || this._scale) {
return 'DECIMAL(' + [this._precision, this._scale].filter(_.identity).join(',') + ')';
return 'DECIMAL(' + [this._precision, this._scale].filter(_.identity).join(',') + ')';
}
return 'DECIMAL';
......@@ -548,14 +548,14 @@ inherits(BLOB, ABSTRACT);
BLOB.prototype.key = BLOB.key = 'BLOB';
BLOB.prototype.toSql = function toSql() {
switch (this._length.toLowerCase()) {
case 'tiny':
return 'TINYBLOB';
case 'medium':
return 'MEDIUMBLOB';
case 'long':
return 'LONGBLOB';
default:
return this.key;
case 'tiny':
return 'TINYBLOB';
case 'medium':
return 'MEDIUMBLOB';
case 'long':
return 'LONGBLOB';
default:
return this.key;
}
};
BLOB.prototype.validate = function validate(value) {
......
......@@ -37,16 +37,16 @@ var util = require('util');
* @return {object}
*/
var Deferrable = module.exports = {
INITIALLY_DEFERRED: INITIALLY_DEFERRED,
INITIALLY_IMMEDIATE: INITIALLY_IMMEDIATE,
NOT: NOT,
SET_DEFERRED: SET_DEFERRED,
SET_IMMEDIATE: SET_IMMEDIATE
INITIALLY_DEFERRED,
INITIALLY_IMMEDIATE,
NOT,
SET_DEFERRED,
SET_IMMEDIATE
};
function ABSTRACT () {}
function ABSTRACT() {}
ABSTRACT.prototype.toString = function () {
ABSTRACT.prototype.toString = function() {
return this.toSql.apply(this, arguments);
};
......@@ -56,14 +56,14 @@ ABSTRACT.prototype.toString = function () {
*
* @property INITIALLY_DEFERRED
*/
function INITIALLY_DEFERRED () {
function INITIALLY_DEFERRED() {
if (!(this instanceof INITIALLY_DEFERRED)) {
return new INITIALLY_DEFERRED();
}
}
util.inherits(INITIALLY_DEFERRED, ABSTRACT);
INITIALLY_DEFERRED.prototype.toSql = function () {
INITIALLY_DEFERRED.prototype.toSql = function() {
return 'DEFERRABLE INITIALLY DEFERRED';
};
......@@ -73,14 +73,14 @@ INITIALLY_DEFERRED.prototype.toSql = function () {
*
* @property INITIALLY_IMMEDIATE
*/
function INITIALLY_IMMEDIATE () {
function INITIALLY_IMMEDIATE() {
if (!(this instanceof INITIALLY_IMMEDIATE)) {
return new INITIALLY_IMMEDIATE();
}
}
util.inherits(INITIALLY_IMMEDIATE, ABSTRACT);
INITIALLY_IMMEDIATE.prototype.toSql = function () {
INITIALLY_IMMEDIATE.prototype.toSql = function() {
return 'DEFERRABLE INITIALLY IMMEDIATE';
};
......@@ -92,14 +92,14 @@ INITIALLY_IMMEDIATE.prototype.toSql = function () {
*
* @property NOT
*/
function NOT () {
function NOT() {
if (!(this instanceof NOT)) {
return new NOT();
}
}
util.inherits(NOT, ABSTRACT);
NOT.prototype.toSql = function () {
NOT.prototype.toSql = function() {
return 'NOT DEFERRABLE';
};
......@@ -111,7 +111,7 @@ NOT.prototype.toSql = function () {
* @param {Array} constraints An array of constraint names. Will defer all constraints by default.
* @property SET_DEFERRED
*/
function SET_DEFERRED (constraints) {
function SET_DEFERRED(constraints) {
if (!(this instanceof SET_DEFERRED)) {
return new SET_DEFERRED(constraints);
}
......@@ -120,7 +120,7 @@ function SET_DEFERRED (constraints) {
}
util.inherits(SET_DEFERRED, ABSTRACT);
SET_DEFERRED.prototype.toSql = function (queryGenerator) {
SET_DEFERRED.prototype.toSql = function(queryGenerator) {
return queryGenerator.setDeferredQuery(this.constraints);
};
......@@ -132,7 +132,7 @@ SET_DEFERRED.prototype.toSql = function (queryGenerator) {
* @param {Array} constraints An array of constraint names. Will defer all constraints by default.
* @property SET_IMMEDIATE
*/
function SET_IMMEDIATE (constraints) {
function SET_IMMEDIATE(constraints) {
if (!(this instanceof SET_IMMEDIATE)) {
return new SET_IMMEDIATE(constraints);
}
......@@ -141,14 +141,14 @@ function SET_IMMEDIATE (constraints) {
}
util.inherits(SET_IMMEDIATE, ABSTRACT);
SET_IMMEDIATE.prototype.toSql = function (queryGenerator) {
SET_IMMEDIATE.prototype.toSql = function(queryGenerator) {
return queryGenerator.setImmediateQuery(this.constraints);
};
Object.keys(Deferrable).forEach(function (key) {
Object.keys(Deferrable).forEach(function(key) {
var DeferrableType = Deferrable[key];
DeferrableType.toString = function () {
DeferrableType.toString = function() {
var instance = new DeferrableType();
return instance.toString.apply(instance, arguments);
};
......
......@@ -53,7 +53,7 @@ class ConnectionManager {
onProcessExit() {
if (this.pool) {
this.pool.drain(() => {
debug(`connection drain due to process exit`);
debug('connection drain due to process exit');
this.pool.destroyAllNow();
});
}
......@@ -83,7 +83,7 @@ class ConnectionManager {
});
},
destroy: (connection) => {
debug(`connection destroy`);
debug('connection destroy');
this._disconnect(connection);
return null;
},
......@@ -127,11 +127,11 @@ class ConnectionManager {
}
},
destroy: (connection) => {
debug(`connection destroy`);
debug('connection destroy');
return this.pool[connection.queryType].destroy(connection);
},
destroyAllNow: () => {
debug(`all connection destroy`);
debug('all connection destroy');
this.pool.read.destroyAllNow();
this.pool.write.destroyAllNow();
},
......@@ -215,7 +215,7 @@ class ConnectionManager {
return promise.then(() => new Promise((resolve, reject) => {
this.pool.acquire((err, connection) => {
if (err) return reject(err);
debug(`connection acquired`);
debug('connection acquired');
resolve(connection);
}, options.priority, options.type, options.useMaster);
}));
......@@ -224,7 +224,7 @@ class ConnectionManager {
releaseConnection(connection) {
return new Promise((resolve, reject) => {
this.pool.release(connection);
debug(`connection released`);
debug('connection released');
resolve();
});
}
......
......@@ -50,7 +50,7 @@ AbstractDialect.prototype.supports = {
parser: false,
concurrently: false,
type: false,
using: true,
using: true
},
joinTableDependent: true,
groupedLimit: true,
......
......@@ -199,7 +199,7 @@ const QueryGenerator = {
}
if (this._dialect.supports.returnValues && options.returning) {
if (!!this._dialect.supports.returnValues.returning) {
if (this._dialect.supports.returnValues.returning) {
valueQuery += ' RETURNING *';
emptyQuery += ' RETURNING *';
} else if (!!this._dialect.supports.returnValues.output) {
......@@ -270,7 +270,7 @@ const QueryGenerator = {
// SERIALS' can't be NULL in postgresql, use DEFAULT where supported
if (modelAttributeMap && modelAttributeMap[key] && modelAttributeMap[key].autoIncrement === true && !value) {
if (!this._dialect.supports.autoIncrement.defaultValue) {
fields.splice(-1,1);
fields.splice(-1, 1);
} else if (this._dialect.supports.DEFAULT) {
values.push('DEFAULT');
} else {
......@@ -300,7 +300,7 @@ const QueryGenerator = {
query = [
'SET IDENTITY_INSERT', this.quoteTable(table), 'ON;',
query,
'SET IDENTITY_INSERT', this.quoteTable(table), 'OFF;',
'SET IDENTITY_INSERT', this.quoteTable(table), 'OFF;'
].join(' ');
}
......
......@@ -72,7 +72,7 @@ class ConnectionManager extends AbstractConnectionManager {
connection.on('connect', err => {
if (!err) {
debug(`connection acquired`);
debug('connection acquired');
resolve(connectionLock);
return;
}
......@@ -137,7 +137,7 @@ class ConnectionManager extends AbstractConnectionManager {
return new Promise(resolve => {
connection.on('end', resolve);
connection.close();
debug(`connection closed`);
debug('connection closed');
});
}
......
......@@ -14,7 +14,7 @@ var MssqlDialect = function(sequelize) {
this.QueryGenerator = _.extend({}, QueryGenerator, {
options: sequelize.options,
_dialect: this,
sequelize: sequelize
sequelize
});
};
......@@ -44,7 +44,7 @@ MssqlDialect.prototype.supports = _.merge(_.cloneDeep(Abstract.prototype.support
length: false,
parser: false,
type: true,
using: false,
using: false
},
NUMERIC: true,
tmpTableTrigger: true
......
......@@ -18,13 +18,13 @@
@param {Object} options
@param {Boolean|Function} [options.logging] A function that logs the sql queries, or false for explicitly not logging these queries
*/
var removeColumn = function (tableName, attributeName, options) {
var removeColumn = function(tableName, attributeName, options) {
var self = this;
options = options || {};
var findConstraintSql = self.QueryGenerator.getDefaultConstraintQuery(tableName, attributeName);
return self.sequelize.query(findConstraintSql, { raw: true, logging: options.logging})
.spread(function (results) {
.spread(function(results) {
if (!results.length) {
// No default constraint found -- we can cleanly remove the column
return;
......@@ -32,24 +32,24 @@ var removeColumn = function (tableName, attributeName, options) {
var dropConstraintSql = self.QueryGenerator.dropConstraintQuery(tableName, results[0].name);
return self.sequelize.query(dropConstraintSql, { raw: true, logging: options.logging});
})
.then(function () {
.then(function() {
var findForeignKeySql = self.QueryGenerator.getForeignKeyQuery(tableName, attributeName);
return self.sequelize.query(findForeignKeySql , { raw: true, logging: options.logging});
return self.sequelize.query(findForeignKeySql, { raw: true, logging: options.logging});
})
.spread(function (results) {
.spread(function(results) {
if (!results.length) {
// No foreign key constraints found, so we can remove the column
return;
}
var dropForeignKeySql = self.QueryGenerator.dropForeignKeyQuery(tableName, results[0].constraint_name);
return self.sequelize.query(dropForeignKeySql , { raw: true, logging: options.logging});
return self.sequelize.query(dropForeignKeySql, { raw: true, logging: options.logging});
})
.then(function () {
.then(function() {
var removeSql = self.QueryGenerator.removeColumnQuery(tableName, attributeName);
return self.sequelize.query(removeSql, { raw: true, logging: options.logging});
});
};
module.exports = {
removeColumn: removeColumn
removeColumn
};
......@@ -44,68 +44,68 @@ class Query extends AbstractQuery {
return new Promise((resolve, reject) => {
// TRANSACTION SUPPORT
if (_.includes(this.sql, 'BEGIN TRANSACTION')) {
connection.beginTransaction(err => {
if (!!err) {
reject(this.formatError(err));
} else {
resolve(this.formatResults());
}
} /* name, isolation_level */);
} else if (_.includes(this.sql, 'COMMIT TRANSACTION')) {
connection.commitTransaction(err => {
if (!!err) {
reject(this.formatError(err));
} else {
resolve(this.formatResults());
}
});
} else if (_.includes(this.sql, 'ROLLBACK TRANSACTION')) {
connection.rollbackTransaction(err => {
if (!!err) {
reject(this.formatError(err));
} else {
resolve(this.formatResults());
}
});
} else {
if (_.includes(this.sql, 'BEGIN TRANSACTION')) {
connection.beginTransaction(err => {
if (!!err) {
reject(this.formatError(err));
} else {
resolve(this.formatResults());
}
} /* name, isolation_level */);
} else if (_.includes(this.sql, 'COMMIT TRANSACTION')) {
connection.commitTransaction(err => {
if (!!err) {
reject(this.formatError(err));
} else {
resolve(this.formatResults());
}
});
} else if (_.includes(this.sql, 'ROLLBACK TRANSACTION')) {
connection.rollbackTransaction(err => {
if (!!err) {
reject(this.formatError(err));
} else {
resolve(this.formatResults());
}
});
} else {
// QUERY SUPPORT
const results = [];
const results = [];
const request = new connection.lib.Request(this.sql, err => {
const request = new connection.lib.Request(this.sql, err => {
debug(`executed(${connection.uuid || 'default'}) : ${this.sql}`);
debug(`executed(${connection.uuid || 'default'}) : ${this.sql}`);
if (benchmark) {
this.sequelize.log('Executed (' + (connection.uuid || 'default') + '): ' + this.sql, (Date.now() - queryBegin), this.options);
}
if (benchmark) {
this.sequelize.log('Executed (' + (connection.uuid || 'default') + '): ' + this.sql, (Date.now() - queryBegin), this.options);
}
if (err) {
err.sql = sql;
reject(this.formatError(err));
} else {
resolve(this.formatResults(results));
}
});
request.on('row', columns => {
const row = {};
for (const column of columns) {
const typeid = column.metadata.type.id;
const parse = parserStore.get(typeid);
let value = column.value;
if (value !== null & !!parse) {
value = parse(value);
}
row[column.metadata.colName] = value;
if (err) {
err.sql = sql;
reject(this.formatError(err));
} else {
resolve(this.formatResults(results));
}
});
request.on('row', columns => {
const row = {};
for (const column of columns) {
const typeid = column.metadata.type.id;
const parse = parserStore.get(typeid);
let value = column.value;
if (value !== null & !!parse) {
value = parse(value);
}
row[column.metadata.colName] = value;
}
results.push(row);
});
results.push(row);
});
connection.execSql(request);
}
connection.execSql(request);
}
});
}
......@@ -154,7 +154,7 @@ class Query extends AbstractQuery {
result = {};
for (const _result of data) {
if (_result.Default) {
_result.Default = _result.Default.replace("('",'').replace("')",'').replace(/'/g,''); /* jshint ignore: line */
_result.Default = _result.Default.replace("('", '').replace("')", '').replace(/'/g, ''); /* jshint ignore: line */
}
result[_result.Name] = {
......@@ -267,7 +267,7 @@ class Query extends AbstractQuery {
Utils._.forEach(item.index_keys.split(','), column => {
let columnName = column.trim();
if (columnName.indexOf('(-)') !== -1) {
columnName = columnName.replace('(-)','');
columnName = columnName.replace('(-)', '');
}
acc[item.index_name].fields.push({
......
......@@ -7,15 +7,15 @@ function ResourceLock(resource) {
this.previous = Promise.resolve(resource);
}
ResourceLock.prototype.unwrap = function () {
ResourceLock.prototype.unwrap = function() {
return this.resource;
};
ResourceLock.prototype.lock = function () {
ResourceLock.prototype.lock = function() {
var lock = this.previous;
var resolve;
this.previous = new Promise(function (r) {
this.previous = new Promise(function(r) {
resolve = r;
});
......
......@@ -67,44 +67,44 @@ class ConnectionManager extends AbstractConnectionManager {
* @return Promise<Connection>
*/
connect(config) {
const connectionConfig = {
host: config.host,
port: config.port,
user: config.username,
password: config.password,
database: config.database,
timezone: this.sequelize.options.timezone,
typeCast: ConnectionManager._typecast.bind(this),
bigNumberStrings: false,
supportBigNumbers: true
};
if (config.dialectOptions) {
for (const key of Object.keys(config.dialectOptions)) {
connectionConfig[key] = config.dialectOptions[key];
}
const connectionConfig = {
host: config.host,
port: config.port,
user: config.username,
password: config.password,
database: config.database,
timezone: this.sequelize.options.timezone,
typeCast: ConnectionManager._typecast.bind(this),
bigNumberStrings: false,
supportBigNumbers: true
};
if (config.dialectOptions) {
for (const key of Object.keys(config.dialectOptions)) {
connectionConfig[key] = config.dialectOptions[key];
}
}
return new Utils.Promise((resolve, reject) => {
const connection = this.lib.createConnection(connectionConfig);
return new Utils.Promise((resolve, reject) => {
const connection = this.lib.createConnection(connectionConfig);
/*jshint latedef:false*/
const errorHandler = (e) => {
const errorHandler = (e) => {
// clean up connect event if there is error
connection.removeListener('connect', connectHandler);
reject(e);
};
connection.removeListener('connect', connectHandler);
reject(e);
};
const connectHandler = () => {
const connectHandler = () => {
// clean up error event if connected
connection.removeListener('error', errorHandler);
resolve(connection);
};
connection.removeListener('error', errorHandler);
resolve(connection);
};
/*jshint latedef:true*/
connection.once('error', errorHandler);
connection.once('connect', connectHandler);
})
connection.once('error', errorHandler);
connection.once('connect', connectHandler);
})
.then((connection) => {
if (config.pool.handleDisconnects) {
......@@ -123,7 +123,7 @@ class ConnectionManager extends AbstractConnectionManager {
});
}
debug(`connection acquired`);
debug('connection acquired');
return connection;
})
.then((connection) => {
......@@ -164,7 +164,7 @@ class ConnectionManager extends AbstractConnectionManager {
// Dont disconnect connections with CLOSED state
if (connection._closing) {
debug(`connection tried to disconnect but was already at CLOSED state`);
debug('connection tried to disconnect but was already at CLOSED state');
return Utils.Promise.resolve();
}
......@@ -173,7 +173,7 @@ class ConnectionManager extends AbstractConnectionManager {
if (err) {
reject(new SequelizeErrors.ConnectionError(err));
} else {
debug(`connection disconnected`);
debug('connection disconnected');
resolve();
}
});
......
......@@ -31,8 +31,8 @@ module.exports = BaseTypes => {
}
inherits(BLOB, BaseTypes.BLOB);
BLOB.parse = function (value, options, next) {
let data = next();
BLOB.parse = function(value, options, next) {
const data = next();
if (Buffer.isBuffer(data) && data.length === 0) {
return null;
......@@ -51,11 +51,11 @@ module.exports = BaseTypes => {
let definition = BaseTypes.DECIMAL.prototype.toSql.apply(this);
if (this._unsigned) {
definition += ' UNSIGNED';
definition += ' UNSIGNED';
}
if (this._zerofill) {
definition += ' ZEROFILL';
definition += ' ZEROFILL';
}
return definition;
......
......@@ -14,7 +14,7 @@ var MysqlDialect = function(sequelize) {
this.QueryGenerator = _.extend({}, QueryGenerator, {
options: sequelize.options,
_dialect: this,
sequelize: sequelize
sequelize
});
};
......@@ -29,7 +29,7 @@ MysqlDialect.prototype.supports = _.merge(_.cloneDeep(Abstract.prototype.support
length: true,
parser: true,
type: true,
using: 1,
using: 1
},
ignoreDuplicates: ' IGNORE',
updateOnDuplicate: true,
......
......@@ -119,7 +119,7 @@ const QueryGenerator = {
if (definition.match(/REFERENCES/)) {
const fkName = this.quoteIdentifier(tableName + '_' + attributeName + '_foreign_idx');
const attrName = this.quoteIdentifier(attributeName);
definition = definition.replace(/.+?(?=REFERENCES)/,'');
definition = definition.replace(/.+?(?=REFERENCES)/, '');
constraintString.push(`${fkName} FOREIGN KEY (${attrName}) ${definition}`);
} else {
attrString.push('`' + attributeName + '` `' + attributeName + '` ' + definition);
......
......@@ -227,7 +227,7 @@ class Query extends AbstractQuery {
name: item.Key_name,
tableName: item.Table,
unique: (item.Non_unique !== 1),
type: item.Index_type,
type: item.Index_type
}));
}
}
......
......@@ -64,20 +64,20 @@ class ConnectionManager extends AbstractConnectionManager {
Utils._.merge(connectionConfig,
Utils._.pick(config.dialectOptions, [
// see [http://www.postgresql.org/docs/9.3/static/runtime-config-logging.html#GUC-APPLICATION-NAME]
'application_name',
'application_name',
// choose the SSL mode with the PGSSLMODE environment variable
// object format: [https://github.com/brianc/node-postgres/blob/master/lib/connection.js#L79]
// see also [http://www.postgresql.org/docs/9.3/static/libpq-ssl.html]
'ssl',
'ssl',
// In addition to the values accepted by the corresponding server,
// you can use "auto" to determine the right encoding from the
// current locale in the client (LC_CTYPE environment variable on Unix systems)
'client_encoding',
'client_encoding',
// !! DONT SET THIS TO TRUE !!
// (unless you know what you're doing)
// see [http://www.postgresql.org/message-id/flat/bc9549a50706040852u27633f41ib1e6b09f8339d845@mail.gmail.com#bc9549a50706040852u27633f41ib1e6b09f8339d845@mail.gmail.com]
'binary'
]));
'binary'
]));
}
return new Promise((resolve, reject) => {
......@@ -88,21 +88,21 @@ class ConnectionManager extends AbstractConnectionManager {
if (err) {
if (err.code) {
switch (err.code) {
case 'ECONNREFUSED':
reject(new sequelizeErrors.ConnectionRefusedError(err));
break;
case 'ENOTFOUND':
reject(new sequelizeErrors.HostNotFoundError(err));
break;
case 'EHOSTUNREACH':
reject(new sequelizeErrors.HostNotReachableError(err));
break;
case 'EINVAL':
reject(new sequelizeErrors.InvalidConnectionError(err));
break;
default:
reject(new sequelizeErrors.ConnectionError(err));
break;
case 'ECONNREFUSED':
reject(new sequelizeErrors.ConnectionRefusedError(err));
break;
case 'ENOTFOUND':
reject(new sequelizeErrors.HostNotFoundError(err));
break;
case 'EHOSTUNREACH':
reject(new sequelizeErrors.HostNotReachableError(err));
break;
case 'EINVAL':
reject(new sequelizeErrors.InvalidConnectionError(err));
break;
default:
reject(new sequelizeErrors.ConnectionError(err));
break;
}
} else {
reject(new sequelizeErrors.ConnectionError(err));
......@@ -110,13 +110,13 @@ class ConnectionManager extends AbstractConnectionManager {
return;
}
responded = true;
debug(`connection acquired`);
debug('connection acquired');
resolve(connection);
});
// If we didn't ever hear from the client.connect() callback the connection timeout, node-postgres does not treat this as an error since no active query was ever emitted
connection.on('end', () => {
debug(`connection timeout`);
debug('connection timeout');
if (!responded) {
reject(new sequelizeErrors.ConnectionTimedOutError(new Error('Connection timed out')));
}
......
......@@ -265,7 +265,7 @@ module.exports = BaseTypes => {
BLOB.prototype._hexify = function _hexify(hex) {
// bytea hex format http://www.postgresql.org/docs/current/static/datatype-binary.html
return "E'\\\\x" + hex + "'";
return "E'\\\\x" + hex + "'";
};
BaseTypes.BLOB.types.postgres = {
......@@ -397,7 +397,7 @@ module.exports = BaseTypes => {
3912: 1082, // date
3913: 1082,
3926: 20, // int8
3927: 20,
3927: 20
};
const range = require('./range');
......
......@@ -2,14 +2,14 @@
const hstore = require('pg-hstore')({sanitize : true});
function stringify (data) {
if (data === null) return null;
return hstore.stringify(data);
function stringify(data) {
if (data === null) return null;
return hstore.stringify(data);
}
exports.stringify = stringify;
function parse (value) {
if (value === null) return null;
return hstore.parse(value);
function parse(value) {
if (value === null) return null;
return hstore.parse(value);
}
exports.parse = parse;
......@@ -180,7 +180,7 @@ const QueryGenerator = {
},
changeColumnQuery(tableName, attributes) {
let query = 'ALTER TABLE <%= tableName %> ALTER COLUMN <%= query %>;';
const query = 'ALTER TABLE <%= tableName %> ALTER COLUMN <%= query %>;';
const sql = [];
for (const attributeName in attributes) {
......@@ -231,7 +231,7 @@ const QueryGenerator = {
}
if (definition.match(/REFERENCES/)) {
definition = definition.replace(/.+?(?=REFERENCES)/,'');
definition = definition.replace(/.+?(?=REFERENCES)/, '');
attrSql += Utils._.template(query.replace('ALTER COLUMN', ''))({
tableName: this.quoteTable(tableName),
query: 'ADD CONSTRAINT ' + this.quoteIdentifier(attributeName + '_foreign_idx') + ' FOREIGN KEY (' + this.quoteIdentifier(attributeName) + ') ' + definition
......
......@@ -194,7 +194,7 @@ class Query extends AbstractQuery {
m[k.toLowerCase()] = k;
return m;
}, {});
rows = _.map(rows,(row)=> {
rows = _.map(rows, (row)=> {
return _.mapKeys(row, (value, key)=> {
const targetAttr = attrsMap[key];
if (typeof targetAttr === 'string' && targetAttr !== key) {
......
......@@ -2,7 +2,7 @@
const _ = require('lodash');
function stringifyRangeBound (bound) {
function stringifyRangeBound(bound) {
if (bound === null) {
return '' ;
} else if (bound === Infinity || bound === -Infinity) {
......@@ -12,7 +12,7 @@ function stringifyRangeBound (bound) {
}
}
function parseRangeBound (bound, parseType) {
function parseRangeBound(bound, parseType) {
if (!bound) {
return null;
} else if (bound === 'infinity') {
......@@ -24,7 +24,7 @@ function parseRangeBound (bound, parseType) {
}
}
function stringify (data) {
function stringify(data) {
if (data === null) return null;
if (!_.isArray(data)) throw new Error('range must be an array');
......@@ -53,7 +53,7 @@ function stringify (data) {
}
exports.stringify = stringify;
function parse (value, parser) {
function parse(value, parser) {
if (value === null) return null;
if (value === 'empty') {
const empty = [];
......
......@@ -357,7 +357,7 @@ class Query extends AbstractQuery {
item.fields[column.seqno] = {
attribute: column.name,
length: undefined,
order: undefined,
order: undefined
};
}
......
......@@ -227,7 +227,7 @@ const Hooks = {
*/
hasHook(hookType) {
return this.options.hooks[hookType] && !!this.options.hooks[hookType].length;
},
}
};
Hooks.hasHooks = Hooks.hasHook;
......
......@@ -1146,11 +1146,11 @@ class Model {
}
}
if (!!scope) {
if (scope) {
_.assignWith(self._scope, scope, (objectValue, sourceValue, key) => {
if (key === 'where') {
return Array.isArray(sourceValue) ? sourceValue : _.assign(objectValue || {}, sourceValue);
} else if ( (['attributes','include'].indexOf(key) >= 0) && Array.isArray(objectValue) && Array.isArray(sourceValue)) {
} else if (['attributes', 'include'].indexOf(key) >= 0 && Array.isArray(objectValue) && Array.isArray(sourceValue)) {
return objectValue.concat(sourceValue);
}
......@@ -1287,7 +1287,7 @@ class Model {
// forgot to pass options.where ?
if (!options.where) {
let commonKeys = _.intersection(_.keys(options), _.keys(this.rawAttributes));
const commonKeys = _.intersection(_.keys(options), _.keys(this.rawAttributes));
// jshint -W030
commonKeys.length && Utils.warn(`Model attributes (${commonKeys.join(',')}) found in finder method options but options.where object is empty. Did you forget to use options.where?`);
}
......@@ -1944,10 +1944,10 @@ class Model {
options.fields = Object.keys(values);
}
const createdAtAttr = this._timestampAttributes.createdAt
, updatedAtAttr = this._timestampAttributes.updatedAt
, hadPrimary = this.primaryKeyField in values || this.primaryKeyAttribute in values
, instance = this.build(values);
const createdAtAttr = this._timestampAttributes.createdAt;
const updatedAtAttr = this._timestampAttributes.updatedAt;
const hadPrimary = this.primaryKeyField in values || this.primaryKeyAttribute in values;
const instance = this.build(values);
return instance.validate(options).then(() => {
// Map field names
......@@ -1975,9 +1975,9 @@ class Model {
if (options.hooks) {
return this.runHooks('beforeUpsert', values, options);
}
}).then(() => (
this.QueryInterface.upsert(this.getTableName(options), insertValues, updateValues, instance.where(), this, options)
)).tap(result => {
}).then(() => {
return this.QueryInterface.upsert(this.getTableName(options), insertValues, updateValues, instance.where(), this, options);
}).tap(result => {
if (options.hooks) {
return this.runHooks('afterUpsert', result, options);
}
......@@ -2057,8 +2057,8 @@ class Model {
}).then(() => {
// Validate
if (options.validate) {
const errors = new Promise.AggregateError()
, validateOptions = _.clone(options);
const errors = new Promise.AggregateError();
const validateOptions = _.clone(options);
validateOptions.hooks = options.individualHooks;
return Promise.map(instances, instance =>
......@@ -2075,7 +2075,7 @@ class Model {
}).then(() => {
/* jshint -W030 */
for (const instance of instances) {
let values = instance.dataValues;
const values = instance.dataValues;
// set createdAt/updatedAt attributes
if (createdAtAttr && !values[createdAtAttr]) {
......@@ -2230,10 +2230,10 @@ class Model {
}).then(() => {
// Run delete query (or update if paranoid)
if (this._timestampAttributes.deletedAt && !options.force) {
const attrValueHash = {}
, deletedAtAttribute = this.rawAttributes[this._timestampAttributes.deletedAt]
, field = this.rawAttributes[this._timestampAttributes.deletedAt].field
, where = {};
const attrValueHash = {};
const deletedAtAttribute = this.rawAttributes[this._timestampAttributes.deletedAt];
const field = this.rawAttributes[this._timestampAttributes.deletedAt].field;
const where = {};
where[field] = deletedAtAttribute.hasOwnProperty('defaultValue') ? deletedAtAttribute.defaultValue : null;
......@@ -2669,7 +2669,7 @@ class Model {
if (this.constructor._hasDefaultValues) {
defaults = _.mapValues(this.constructor._defaultValues, valueFn => {
const value = valueFn();
return (value && value._isSequelizeMethod) ? value : _.cloneDeep(value);
return value && value._isSequelizeMethod ? value : _.cloneDeep(value);
});
}
......@@ -2961,11 +2961,11 @@ class Model {
if (_.isString(value)) {
// Only take action on valid boolean strings.
value = (value === 'true') ? true : (value === 'false') ? false : value;
value = value === 'true' ? true : value === 'false' ? false : value;
} else if (_.isNumber(value)) {
// Only take action on valid boolean integers.
value = (value === 1) ? true : (value === 0) ? false : value;
value = value === 1 ? true : value === 0 ? false : value;
}
}
......
......@@ -7,7 +7,7 @@ const shimmer = require('shimmer');
// fnArgs: The arguments index that should be CLS enabled (typically all callbacks). Offset from last if negative
function shimCLS(object, functionName, fnArgs){
shimmer.wrap(object, functionName, fn => {
return function () {
return function() {
if (Promise.Sequelize && Promise.Sequelize.cls) {
const ns = Promise.Sequelize.cls;
for(let x = 0; x < fnArgs.length; x++) {
......
......@@ -13,5 +13,5 @@ module.exports = {
SHOWINDEXES: 'SHOWINDEXES',
DESCRIBE: 'DESCRIBE',
RAW: 'RAW',
FOREIGNKEYS: 'FOREIGNKEYS',
FOREIGNKEYS: 'FOREIGNKEYS'
};
......@@ -118,7 +118,7 @@ class Sequelize {
// new Sequelize({ ... options })
options = database;
config = _.pick(options, 'host', 'port', 'database', 'username', 'password');
} else if ((arguments.length === 1 && typeof database === 'string') || (arguments.length === 2 && typeof username === 'object')) {
} else if (arguments.length === 1 && typeof database === 'string' || arguments.length === 2 && typeof username === 'object') {
// new Sequelize(URI, { ... options })
config = {};
......@@ -140,9 +140,9 @@ class Sequelize {
if (urlParts.auth) {
const authParts = urlParts.auth.split(':');
config.username = authParts[0];
if (authParts.length > 1)
config.password = authParts.slice(1).join(':');
}
......@@ -198,7 +198,7 @@ class Sequelize {
this.options.hooks = this.replaceHookAliases(this.options.hooks);
if ((['', null, false].indexOf(config.password) > -1) || (typeof config.password === 'undefined')) {
if (['', null, false].indexOf(config.password) > -1 || typeof config.password === 'undefined') {
config.password = null;
}
......@@ -451,7 +451,7 @@ class Sequelize {
*/
isDefined(modelName) {
const models = this.modelManager.models;
return (models.filter(model => model.name === modelName).length !== 0);
return models.filter(model => model.name === modelName).length !== 0;
}
/**
......@@ -474,7 +474,7 @@ class Sequelize {
}
if (!this.importCache[path]) {
let defineCall = (arguments.length > 1 ? arguments[1] : require(path));
let defineCall = arguments.length > 1 ? arguments[1] : require(path);
if (typeof defineCall === 'object' && defineCall.__esModule) {
// Babel/ES6 module compatability
defineCall = defineCall['default'];
......@@ -593,7 +593,7 @@ class Sequelize {
options = _.defaults(options, {
logging: this.options.hasOwnProperty('logging') ? this.options.logging : console.log,
searchPath: this.options.hasOwnProperty('searchPath') ? this.options.searchPath : 'DEFAULT',
searchPath: this.options.hasOwnProperty('searchPath') ? this.options.searchPath : 'DEFAULT'
});
if (options.transaction === undefined && Sequelize.cls) {
......@@ -1057,11 +1057,11 @@ class Sequelize {
autoCallback = ns.bind(autoCallback);
}
const result = autoCallback(transaction);
if (!result || !result.then) throw new Error('You need to return a promise chain/thenable to the sequelize.transaction() callback');
const returnValue = autoCallback(transaction);
if (!returnValue || !returnValue.then) throw new Error('You need to return a promise chain/thenable to the sequelize.transaction() callback');
return result.then(result => transaction.commit()).then(() => {
resolve(result);
return returnValue.then(result => transaction.commit()).then(() => {
resolve(returnValue);
});
}).catch(err => {
// If the transaction has already finished (commit, rollback, etc), reject with the original error
......
......@@ -18,21 +18,21 @@ function escape(val, timeZone, dialect, format) {
return 'NULL';
}
switch (typeof val) {
case 'boolean':
case 'boolean':
// SQLite doesn't have true/false support. MySQL aliases true/false to 1/0
// for us. Postgres actually has a boolean type with true/false literals,
// but sequelize doesn't use it yet.
if (dialect === 'sqlite' || dialect === 'mssql') {
return +!!val;
}
return '' + !!val;
case 'number':
return val + '';
case 'string':
if (dialect === 'sqlite' || dialect === 'mssql') {
return +!!val;
}
return '' + !!val;
case 'number':
return val + '';
case 'string':
// In mssql, prepend N to all quoted vals which are originally a string (for
// unicode compatibility)
prependN = dialect === 'mssql';
break;
prependN = dialect === 'mssql';
break;
}
if (val instanceof Date) {
......
......@@ -125,7 +125,7 @@ class Transaction {
.startTransaction(this, this.options);
}
setDeferrable () {
setDeferrable() {
if (this.options.deferrable) {
return this
.sequelize
......@@ -154,7 +154,7 @@ class Transaction {
return res;
}
_clearCls () {
_clearCls() {
const cls = this.sequelize.constructor.cls;
if (cls) {
......
......@@ -10,7 +10,7 @@ const Promise = require('./promise');
const primitives = ['string', 'number', 'boolean'];
let inflection = require('inflection');
let logger = new Logger();
const logger = new Logger();
exports.Promise = Promise;
exports._ = _;
......
......@@ -3,7 +3,7 @@
const _ = require('lodash');
const util = require('util');
function validateDeprecation (value, expectation, options) {
function validateDeprecation(value, expectation, options) {
if (!options.deprecated) {
return;
}
......@@ -19,7 +19,7 @@ function validateDeprecation (value, expectation, options) {
return valid;
}
function validate (value, expectation) {
function validate(value, expectation) {
// the second part of this check is a workaround to deal with an issue that occurs in node-webkit when
// using object literals. https://github.com/sequelize/sequelize/issues/2685
if (value instanceof expectation || Object.prototype.toString.call(value) === Object.prototype.toString.call(expectation.call())) {
......@@ -29,7 +29,7 @@ function validate (value, expectation) {
throw new Error(`The parameter (value: ${value}) is no ${expectation.name}`);
}
function check (value, expectation, options) {
function check(value, expectation, options) {
options = _.extend({
deprecated: false,
index: null,
......
......@@ -59,7 +59,7 @@ const extensions = {
},
is(str, pattern, modifiers) {
return this.regex(str, pattern, modifiers);
},
}
};
exports.extensions = extensions;
......@@ -67,7 +67,7 @@ function extendModelValidations(modelInstance) {
const extensions = {
isImmutable(str, param, field) {
return (modelInstance.isNewRecord || modelInstance.dataValues[field] === modelInstance._previousDataValues[field]);
},
}
};
_.forEach(extensions, (extend, key) => {
......
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!