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

Commit e68096f3 by Felix Becker Committed by Jan Aagaard Meier

Fix all auto-fixable ESLint issues (#6436)

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