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

Commit 25071392 by Simon Schick Committed by Sushant

refactor(*): cleanup code (#10091)

1 parent 3af05373
...@@ -747,7 +747,7 @@ Comment.prototype.getItem = function(options) { ...@@ -747,7 +747,7 @@ Comment.prototype.getItem = function(options) {
return this[ return this[
'get' + 'get' +
this.get('commentable') this.get('commentable')
.substr(0, 1) [0]
.toUpperCase() + .toUpperCase() +
this.get('commentable').substr(1) this.get('commentable').substr(1)
](options); ](options);
......
...@@ -209,7 +209,7 @@ NUMBER.prototype.toSql = function toSql() { ...@@ -209,7 +209,7 @@ NUMBER.prototype.toSql = function toSql() {
}; };
NUMBER.prototype.validate = function(value) { NUMBER.prototype.validate = function(value) {
if (!Validator.isFloat(String(value))) { if (!Validator.isFloat(String(value))) {
throw new sequelizeErrors.ValidationError(util.format(`%j is not a valid ${_.toLower(this.key)}`, value)); throw new sequelizeErrors.ValidationError(util.format(`%j is not a valid ${this.key.toLowerCase()}`, value));
} }
return true; return true;
...@@ -246,7 +246,7 @@ inherits(INTEGER, NUMBER); ...@@ -246,7 +246,7 @@ inherits(INTEGER, NUMBER);
INTEGER.prototype.key = INTEGER.key = 'INTEGER'; INTEGER.prototype.key = INTEGER.key = 'INTEGER';
INTEGER.prototype.validate = function validate(value) { INTEGER.prototype.validate = function validate(value) {
if (!Validator.isInt(String(value))) { if (!Validator.isInt(String(value))) {
throw new sequelizeErrors.ValidationError(util.format(`%j is not a valid ${_.toLower(this.key)}`, value)); throw new sequelizeErrors.ValidationError(util.format(`%j is not a valid ${this.key.toLowerCase()}`, value));
} }
return true; return true;
...@@ -406,24 +406,29 @@ DECIMAL.prototype.validate = function validate(value) { ...@@ -406,24 +406,29 @@ DECIMAL.prototype.validate = function validate(value) {
return true; return true;
}; };
for (const floating of [FLOAT, DOUBLE, REAL]) { const protoExtensions = {
floating.prototype.escape = false; escape: false,
floating.prototype._value = function _value(value) { _value(value) {
if (isNaN(value)) { if (isNaN(value)) {
return 'NaN'; return 'NaN';
} else if (!isFinite(value)) { }
if (!isFinite(value)) {
const sign = value < 0 ? '-' : ''; const sign = value < 0 ? '-' : '';
return `${sign}Infinity`; return `${sign}Infinity`;
} }
return value; return value;
}; },
floating.prototype._stringify = function _stringify(value) { _stringify(value) {
return `'${this._value(value)}'`; return `'${this._value(value)}'`;
}; },
floating.prototype._bindParam = function _bindParam(value, options) { _bindParam(value, options) {
return options.bindParam(this._value(value)); return options.bindParam(this._value(value));
}; }
};
for (const floating of [FLOAT, DOUBLE, REAL]) {
Object.assign(floating.prototype, protoExtensions);
} }
/** /**
...@@ -896,9 +901,10 @@ VIRTUAL.prototype.key = VIRTUAL.key = 'VIRTUAL'; ...@@ -896,9 +901,10 @@ VIRTUAL.prototype.key = VIRTUAL.key = 'VIRTUAL';
* @namespace DataTypes.ENUM * @namespace DataTypes.ENUM
* *
*/ */
function ENUM(value) { function ENUM(...args) {
const value = args[0];
const options = typeof value === 'object' && !Array.isArray(value) && value || { const options = typeof value === 'object' && !Array.isArray(value) && value || {
values: Array.prototype.slice.call(arguments).reduce((result, element) => { values: args.reduce((result, element) => {
return result.concat(Array.isArray(element) ? element : [element]); return result.concat(Array.isArray(element) ? element : [element]);
}, []) }, [])
}; };
......
...@@ -101,4 +101,4 @@ const Deferrable = module.exports = { // eslint-disable-line ...@@ -101,4 +101,4 @@ const Deferrable = module.exports = { // eslint-disable-line
NOT: classToInvokable(NOT), NOT: classToInvokable(NOT),
SET_DEFERRED: classToInvokable(SET_DEFERRED), SET_DEFERRED: classToInvokable(SET_DEFERRED),
SET_IMMEDIATE: classToInvokable(SET_IMMEDIATE) SET_IMMEDIATE: classToInvokable(SET_IMMEDIATE)
}; };
\ No newline at end of file
...@@ -67,18 +67,18 @@ class ConnectionManager { ...@@ -67,18 +67,18 @@ class ConnectionManager {
try { try {
if (this.sequelize.config.dialectModulePath) { if (this.sequelize.config.dialectModulePath) {
return require(this.sequelize.config.dialectModulePath); return require(this.sequelize.config.dialectModulePath);
} else if (this.sequelize.config.dialectModule) { }
if (this.sequelize.config.dialectModule) {
return this.sequelize.config.dialectModule; return this.sequelize.config.dialectModule;
} else {
return require(moduleName);
} }
return require(moduleName);
} catch (err) { } catch (err) {
if (err.code === 'MODULE_NOT_FOUND') { if (err.code === 'MODULE_NOT_FOUND') {
if (this.sequelize.config.dialectModulePath) { if (this.sequelize.config.dialectModulePath) {
throw new Error(`Unable to find dialect at ${this.sequelize.config.dialectModulePath}`); throw new Error(`Unable to find dialect at ${this.sequelize.config.dialectModulePath}`);
} else {
throw new Error(`Please install ${moduleName} package manually`);
} }
throw new Error(`Please install ${moduleName} package manually`);
} }
throw err; throw err;
......
...@@ -498,35 +498,35 @@ class QueryGenerator { ...@@ -498,35 +498,35 @@ class QueryGenerator {
const fieldsSql = options.fields.map(field => { const fieldsSql = options.fields.map(field => {
if (typeof field === 'string') { if (typeof field === 'string') {
return this.quoteIdentifier(field); return this.quoteIdentifier(field);
} else if (field instanceof Utils.SequelizeMethod) { }
if (field instanceof Utils.SequelizeMethod) {
return this.handleSequelizeMethod(field); return this.handleSequelizeMethod(field);
} else { }
let result = ''; let result = '';
if (field.attribute) {
field.name = field.attribute;
}
if (!field.name) { if (field.attribute) {
throw new Error(`The following index field has no name: ${util.inspect(field)}`); field.name = field.attribute;
} }
result += this.quoteIdentifier(field.name); if (!field.name) {
throw new Error(`The following index field has no name: ${util.inspect(field)}`);
}
if (this._dialect.supports.index.collate && field.collate) { result += this.quoteIdentifier(field.name);
result += ` COLLATE ${this.quoteIdentifier(field.collate)}`;
}
if (this._dialect.supports.index.length && field.length) { if (this._dialect.supports.index.collate && field.collate) {
result += `(${field.length})`; result += ` COLLATE ${this.quoteIdentifier(field.collate)}`;
} }
if (field.order) { if (this._dialect.supports.index.length && field.length) {
result += ` ${field.order}`; result += `(${field.length})`;
} }
return result; if (field.order) {
result += ` ${field.order}`;
} }
return result;
}); });
if (!options.name) { if (!options.name) {
...@@ -840,16 +840,18 @@ class QueryGenerator { ...@@ -840,16 +840,18 @@ class QueryGenerator {
}, this); }, this);
return sql; return sql;
} else if (collection._modelAttribute) { }
if (collection._modelAttribute) {
return `${this.quoteTable(collection.Model.name)}.${this.quoteIdentifier(collection.fieldName)}`; return `${this.quoteTable(collection.Model.name)}.${this.quoteIdentifier(collection.fieldName)}`;
} else if (collection instanceof Utils.SequelizeMethod) { }
if (collection instanceof Utils.SequelizeMethod) {
return this.handleSequelizeMethod(collection); return this.handleSequelizeMethod(collection);
} else if (_.isPlainObject(collection) && collection.raw) { }
if (_.isPlainObject(collection) && collection.raw) {
// simple objects with raw is no longer supported // simple objects with raw is no longer supported
throw new Error('The `{raw: "..."}` syntax is no longer supported. Use `sequelize.literal` instead.'); throw new Error('The `{raw: "..."}` syntax is no longer supported. Use `sequelize.literal` instead.');
} else {
throw new Error(`Unknown structure passed to order / group: ${util.inspect(collection)}`);
} }
throw new Error(`Unknown structure passed to order / group: ${util.inspect(collection)}`);
} }
/** /**
...@@ -1442,9 +1444,11 @@ class QueryGenerator { ...@@ -1442,9 +1444,11 @@ class QueryGenerator {
attrAs = attr[1]; attrAs = attr[1];
attr = attr[0]; attr = attr[0];
} else if (attr instanceof Utils.Literal) { }
if (attr instanceof Utils.Literal) {
return attr.val; // We trust the user to rename the field correctly return attr.val; // We trust the user to rename the field correctly
} else if (attr instanceof Utils.Cast || attr instanceof Utils.Fn) { }
if (attr instanceof Utils.Cast || attr instanceof Utils.Fn) {
throw new Error( throw new Error(
'Tried to select attributes using Sequelize.cast or Sequelize.fn without specifying an alias for the result, during eager loading. ' + 'Tried to select attributes using Sequelize.cast or Sequelize.fn without specifying an alias for the result, during eager loading. ' +
'This means the attribute will not be added to the returned instance' 'This means the attribute will not be added to the returned instance'
...@@ -1950,9 +1954,10 @@ class QueryGenerator { ...@@ -1950,9 +1954,10 @@ class QueryGenerator {
if (value && value instanceof Utils.SequelizeMethod) { if (value && value instanceof Utils.SequelizeMethod) {
value = this.getWhereConditions(value, tableName, factory, options, prepend); value = this.getWhereConditions(value, tableName, factory, options, prepend);
result = value === 'NULL' ? `${key} IS NULL` : [key, value].join(` ${smth.comparator} `); return value === 'NULL' ? `${key} IS NULL` : [key, value].join(` ${smth.comparator} `);
} else if (_.isPlainObject(value)) { }
result = this.whereItemQuery(smth.attribute, value, { if (_.isPlainObject(value)) {
return this.whereItemQuery(smth.attribute, value, {
model: factory model: factory
}); });
} else { } else {
...@@ -1962,11 +1967,13 @@ class QueryGenerator { ...@@ -1962,11 +1967,13 @@ class QueryGenerator {
value = this.escape(value); value = this.escape(value);
} }
result = value === 'NULL' ? `${key} IS NULL` : [key, value].join(` ${smth.comparator} `); return value === 'NULL' ? `${key} IS NULL` : [key, value].join(` ${smth.comparator} `);
} }
} else if (smth instanceof Utils.Literal) { }
result = smth.val; if (smth instanceof Utils.Literal) {
} else if (smth instanceof Utils.Cast) { return smth.val;
}
if (smth instanceof Utils.Cast) {
if (smth.val instanceof Utils.SequelizeMethod) { if (smth.val instanceof Utils.SequelizeMethod) {
result = this.handleSequelizeMethod(smth.val, tableName, factory, options, prepend); result = this.handleSequelizeMethod(smth.val, tableName, factory, options, prepend);
} else if (_.isPlainObject(smth.val)) { } else if (_.isPlainObject(smth.val)) {
...@@ -1975,31 +1982,29 @@ class QueryGenerator { ...@@ -1975,31 +1982,29 @@ class QueryGenerator {
result = this.escape(smth.val); result = this.escape(smth.val);
} }
result = `CAST(${result} AS ${smth.type.toUpperCase()})`; return `CAST(${result} AS ${smth.type.toUpperCase()})`;
} else if (smth instanceof Utils.Fn) { }
result = `${smth.fn}(${smth.args.map(arg => { if (smth instanceof Utils.Fn) {
return `${smth.fn}(${smth.args.map(arg => {
if (arg instanceof Utils.SequelizeMethod) { if (arg instanceof Utils.SequelizeMethod) {
return this.handleSequelizeMethod(arg, tableName, factory, options, prepend); return this.handleSequelizeMethod(arg, tableName, factory, options, prepend);
} else if (_.isPlainObject(arg)) { }
if (_.isPlainObject(arg)) {
return this.whereItemsQuery(arg); return this.whereItemsQuery(arg);
} else {
return this.escape(arg);
} }
return this.escape(arg);
}).join(', ') })`; }).join(', ') })`;
} else if (smth instanceof Utils.Col) { }
if (Array.isArray(smth.col)) { if (smth instanceof Utils.Col) {
if (!factory) { if (Array.isArray(smth.col) && !factory) {
throw new Error('Cannot call Sequelize.col() with array outside of order / group clause'); throw new Error('Cannot call Sequelize.col() with array outside of order / group clause');
} }
} else if (smth.col.startsWith('*')) { if (smth.col.startsWith('*')) {
return '*'; return '*';
} }
return this.quote(smth.col, factory); return this.quote(smth.col, factory);
} else {
result = smth.toString(this, factory);
} }
return smth.toString(this, factory);
return result;
} }
whereQuery(where, options) { whereQuery(where, options) {
...@@ -2027,7 +2032,7 @@ class QueryGenerator { ...@@ -2027,7 +2032,7 @@ class QueryGenerator {
const items = []; const items = [];
binding = binding || 'AND'; binding = binding || 'AND';
if (binding.substr(0, 1) !== ' ') binding = ` ${binding} `; if (binding[0] !== ' ') binding = ` ${binding} `;
if (_.isPlainObject(where)) { if (_.isPlainObject(where)) {
Utils.getComplexKeys(where).forEach(prop => { Utils.getComplexKeys(where).forEach(prop => {
...@@ -2330,7 +2335,7 @@ class QueryGenerator { ...@@ -2330,7 +2335,7 @@ class QueryGenerator {
if (prop === Op.not) { if (prop === Op.not) {
if (Array.isArray(value)) { if (Array.isArray(value)) {
prop = Op.notIn; prop = Op.notIn;
} else if (![null, true, false].includes(value)) { } else if (value !== null && value !== true && value !== false) {
prop = Op.ne; prop = Op.ne;
} }
} }
...@@ -2410,7 +2415,8 @@ class QueryGenerator { ...@@ -2410,7 +2415,8 @@ class QueryGenerator {
if (value === null && comparator === this.OperatorMap[Op.eq]) { if (value === null && comparator === this.OperatorMap[Op.eq]) {
return this._joinKeyValue(key, this.escape(value, field, escapeOptions), this.OperatorMap[Op.is], options.prefix); return this._joinKeyValue(key, this.escape(value, field, escapeOptions), this.OperatorMap[Op.is], options.prefix);
} else if (value === null && comparator === this.OperatorMap[Op.ne]) { }
if (value === null && comparator === this.OperatorMap[Op.ne]) {
return this._joinKeyValue(key, this.escape(value, field, escapeOptions), this.OperatorMap[Op.not], options.prefix); return this._joinKeyValue(key, this.escape(value, field, escapeOptions), this.OperatorMap[Op.not], options.prefix);
} }
...@@ -2422,7 +2428,6 @@ class QueryGenerator { ...@@ -2422,7 +2428,6 @@ class QueryGenerator {
@private @private
*/ */
getWhereConditions(smth, tableName, factory, options, prepend) { getWhereConditions(smth, tableName, factory, options, prepend) {
let result = null;
const where = {}; const where = {};
if (Array.isArray(tableName)) { if (Array.isArray(tableName)) {
...@@ -2439,14 +2444,16 @@ class QueryGenerator { ...@@ -2439,14 +2444,16 @@ class QueryGenerator {
} }
if (smth && smth instanceof Utils.SequelizeMethod) { // Checking a property is cheaper than a lot of instanceof calls if (smth && smth instanceof Utils.SequelizeMethod) { // Checking a property is cheaper than a lot of instanceof calls
result = this.handleSequelizeMethod(smth, tableName, factory, options, prepend); return this.handleSequelizeMethod(smth, tableName, factory, options, prepend);
} else if (_.isPlainObject(smth)) { }
if (_.isPlainObject(smth)) {
return this.whereItemsQuery(smth, { return this.whereItemsQuery(smth, {
model: factory, model: factory,
prefix: prepend && tableName, prefix: prepend && tableName,
type: options.type type: options.type
}); });
} else if (typeof smth === 'number') { }
if (typeof smth === 'number') {
let primaryKeys = factory ? Object.keys(factory.primaryKeys) : []; let primaryKeys = factory ? Object.keys(factory.primaryKeys) : [];
if (primaryKeys.length > 0) { if (primaryKeys.length > 0) {
...@@ -2462,29 +2469,32 @@ class QueryGenerator { ...@@ -2462,29 +2469,32 @@ class QueryGenerator {
model: factory, model: factory,
prefix: prepend && tableName prefix: prepend && tableName
}); });
} else if (typeof smth === 'string') { }
if (typeof smth === 'string') {
return this.whereItemsQuery(smth, { return this.whereItemsQuery(smth, {
model: factory, model: factory,
prefix: prepend && tableName prefix: prepend && tableName
}); });
} else if (Buffer.isBuffer(smth)) { }
result = this.escape(smth); if (Buffer.isBuffer(smth)) {
} else if (Array.isArray(smth)) { return this.escape(smth);
}
if (Array.isArray(smth)) {
if (smth.length === 0 || smth.length > 0 && smth[0].length === 0) return '1=1'; if (smth.length === 0 || smth.length > 0 && smth[0].length === 0) return '1=1';
if (Utils.canTreatArrayAsAnd(smth)) { if (Utils.canTreatArrayAsAnd(smth)) {
const _smth = { [Op.and]: smth }; const _smth = { [Op.and]: smth };
result = this.getWhereConditions(_smth, tableName, factory, options, prepend); return this.getWhereConditions(_smth, tableName, factory, options, prepend);
} else {
throw new Error('Support for literal replacements in the `where` object has been removed.');
} }
} else if (smth === null) { throw new Error('Support for literal replacements in the `where` object has been removed.');
}
if (smth === null) {
return this.whereItemsQuery(smth, { return this.whereItemsQuery(smth, {
model: factory, model: factory,
prefix: prepend && tableName prefix: prepend && tableName
}); });
} }
return result ? result : '1=1'; return '1=1';
} }
// A recursive parser for nested where conditions // A recursive parser for nested where conditions
...@@ -2492,10 +2502,9 @@ class QueryGenerator { ...@@ -2492,10 +2502,9 @@ class QueryGenerator {
path = path || []; path = path || [];
return _.reduce(conditions, (result, value, key) => { return _.reduce(conditions, (result, value, key) => {
if (_.isObject(value)) { if (_.isObject(value)) {
result = result.concat(this.parseConditionObject(value, path.concat(key))); // Recursively parse objects return result.concat(this.parseConditionObject(value, path.concat(key))); // Recursively parse objects
} else {
result.push({ path: path.concat(key), value });
} }
result.push({ path: path.concat(key), value });
return result; return result;
}, []); }, []);
} }
......
...@@ -106,17 +106,20 @@ class ConnectionManager extends AbstractConnectionManager { ...@@ -106,17 +106,20 @@ class ConnectionManager extends AbstractConnectionManager {
case 'ESOCKET': case 'ESOCKET':
if (error.message.includes('connect EHOSTUNREACH')) { if (error.message.includes('connect EHOSTUNREACH')) {
throw new sequelizeErrors.HostNotReachableError(error); throw new sequelizeErrors.HostNotReachableError(error);
} else if (error.message.includes('connect ENETUNREACH')) { }
if (error.message.includes('connect ENETUNREACH')) {
throw new sequelizeErrors.HostNotReachableError(error); throw new sequelizeErrors.HostNotReachableError(error);
} else if (error.message.includes('connect EADDRNOTAVAIL')) { }
if (error.message.includes('connect EADDRNOTAVAIL')) {
throw new sequelizeErrors.HostNotReachableError(error); throw new sequelizeErrors.HostNotReachableError(error);
} else if (error.message.includes('getaddrinfo ENOTFOUND')) { }
if (error.message.includes('getaddrinfo ENOTFOUND')) {
throw new sequelizeErrors.HostNotFoundError(error); throw new sequelizeErrors.HostNotFoundError(error);
} else if (error.message.includes('connect ECONNREFUSED')) { }
if (error.message.includes('connect ECONNREFUSED')) {
throw new sequelizeErrors.ConnectionRefusedError(error); throw new sequelizeErrors.ConnectionRefusedError(error);
} else {
throw new sequelizeErrors.ConnectionError(error);
} }
throw new sequelizeErrors.ConnectionError(error);
case 'ER_ACCESS_DENIED_ERROR': case 'ER_ACCESS_DENIED_ERROR':
case 'ELOGIN': case 'ELOGIN':
throw new sequelizeErrors.AccessDeniedError(error); throw new sequelizeErrors.AccessDeniedError(error);
......
...@@ -62,81 +62,83 @@ class Query extends AbstractQuery { ...@@ -62,81 +62,83 @@ class Query extends AbstractQuery {
return new Promise((resolve, reject) => { return new Promise((resolve, reject) => {
// TRANSACTION SUPPORT // TRANSACTION SUPPORT
if (_.startsWith(this.sql, 'BEGIN TRANSACTION')) { if (this.sql.startsWith('BEGIN TRANSACTION')) {
connection.beginTransaction(err => { return connection.beginTransaction(err => {
if (err) { if (err) {
reject(this.formatError(err)); reject(this.formatError(err));
} else { return;
resolve(this.formatResults());
} }
resolve(this.formatResults());
}, this.options.transaction.name, connection.lib.ISOLATION_LEVEL[this.options.isolationLevel]); }, this.options.transaction.name, connection.lib.ISOLATION_LEVEL[this.options.isolationLevel]);
} else if (_.startsWith(this.sql, 'COMMIT TRANSACTION')) { }
connection.commitTransaction(err => { if (this.sql.startsWith('COMMIT TRANSACTION')) {
return connection.commitTransaction(err => {
if (err) { if (err) {
reject(this.formatError(err)); reject(this.formatError(err));
} else { return;
resolve(this.formatResults());
} }
resolve(this.formatResults());
}); });
} else if (_.startsWith(this.sql, 'ROLLBACK TRANSACTION')) { }
connection.rollbackTransaction(err => { if (this.sql.startsWith('ROLLBACK TRANSACTION')) {
return connection.rollbackTransaction(err => {
if (err) { if (err) {
reject(this.formatError(err)); reject(this.formatError(err));
} else {
resolve(this.formatResults());
} }
resolve(this.formatResults());
}, this.options.transaction.name); }, this.options.transaction.name);
} else if (_.startsWith(this.sql, 'SAVE TRANSACTION')) { return;
connection.saveTransaction(err => { }
if (this.sql.startsWith('SAVE TRANSACTION')) {
return connection.saveTransaction(err => {
if (err) { if (err) {
reject(this.formatError(err)); reject(this.formatError(err));
} else { return;
resolve(this.formatResults());
} }
resolve(this.formatResults());
}, this.options.transaction.name); }, this.options.transaction.name);
} else { }
const results = []; const results = [];
const request = new connection.lib.Request(this.sql, (err, rowCount) => { const request = new connection.lib.Request(this.sql, (err, rowCount) => {
debug(`executed(${this.connection.uuid || 'default'}) : ${this.sql}`); debug(`executed(${this.connection.uuid || 'default'}) : ${this.sql}`);
if (benchmark) { if (benchmark) {
this.sequelize.log(`Executed (${this.connection.uuid || 'default'}): ${this.sql}`, Date.now() - queryBegin, this.options); this.sequelize.log(`Executed (${this.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, rowCount)); resolve(this.formatResults(results, rowCount));
} }
});
if (parameters) {
_.forOwn(parameters, (value, key) => {
const paramType = this.getSQLTypeFromJsType(value, connection.lib.TYPES);
request.addParameter(key, paramType.type, value, paramType.typeOptions);
}); });
}
if (parameters) { request.on('row', columns => {
_.forOwn(parameters, (value, key) => { const row = {};
const paramType = this.getSQLTypeFromJsType(value, connection.lib.TYPES); for (const column of columns) {
request.addParameter(key, paramType.type, value, paramType.typeOptions); const typeid = column.metadata.type.id;
}); const parse = parserStore.get(typeid);
} let value = column.value;
request.on('row', columns => { if (value !== null & !!parse) {
const row = {}; value = parse(value);
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;
} }
row[column.metadata.colName] = value;
}
results.push(row); results.push(row);
}); });
connection.execSql(request); connection.execSql(request);
}
}); });
} }
...@@ -195,8 +197,9 @@ class Query extends AbstractQuery { ...@@ -195,8 +197,9 @@ class Query extends AbstractQuery {
} }
if (this.isShowTablesQuery()) { if (this.isShowTablesQuery()) {
result = this.handleShowTablesQuery(data); return this.handleShowTablesQuery(data);
} else if (this.isDescribeQuery()) { }
if (this.isDescribeQuery()) {
result = {}; result = {};
for (const _result of data) { for (const _result of data) {
if (_result.Default) { if (_result.Default) {
...@@ -220,29 +223,40 @@ class Query extends AbstractQuery { ...@@ -220,29 +223,40 @@ class Query extends AbstractQuery {
} }
} }
} else if (this.isShowIndexesQuery()) { }
result = this.handleShowIndexesQuery(data); if (this.isSelectQuery()) {
} else if (this.isSelectQuery()) { return this.handleSelectQuery(data);
result = this.handleSelectQuery(data); }
} else if (this.isUpsertQuery()) { if (this.isShowIndexesQuery()) {
result = data[0]; return this.handleShowIndexesQuery(data);
} else if (this.isCallQuery()) { }
result = data[0]; if (this.isUpsertQuery()) {
} else if (this.isBulkUpdateQuery()) { return data[0];
result = data.length; }
} else if (this.isBulkDeleteQuery()) { if (this.isCallQuery()) {
result = data[0] && data[0].AFFECTEDROWS; return data[0];
} else if (this.isVersionQuery()) { }
result = data[0].version; if (this.isBulkUpdateQuery()) {
} else if (this.isForeignKeysQuery()) { return data.length;
result = data; }
} else if (this.isInsertQuery() || this.isUpdateQuery()) { if (this.isBulkDeleteQuery()) {
result = [result, rowCount]; return data[0] && data[0].AFFECTEDROWS;
} else if (this.isShowConstraintsQuery()) { }
result = this.handleShowConstraintsQuery(data); if (this.isVersionQuery()) {
} else if (this.isRawQuery()) { return data[0].version;
}
if (this.isForeignKeysQuery()) {
return data;
}
if (this.isInsertQuery() || this.isUpdateQuery()) {
return [result, rowCount];
}
if (this.isShowConstraintsQuery()) {
return this.handleShowConstraintsQuery(data);
}
if (this.isRawQuery()) {
// MSSQL returns row data and metadata (affected rows etc) in a single object - let's standarize it, sorta // MSSQL returns row data and metadata (affected rows etc) in a single object - let's standarize it, sorta
result = [data, data]; return [data, data];
} }
return result; return result;
...@@ -307,9 +321,7 @@ class Query extends AbstractQuery { ...@@ -307,9 +321,7 @@ class Query extends AbstractQuery {
match = err.message.match(/Failed on step '(.*)'.Could not create constraint. See previous errors./) || match = err.message.match(/Failed on step '(.*)'.Could not create constraint. See previous errors./) ||
err.message.match(/The DELETE statement conflicted with the REFERENCE constraint "(.*)". The conflict occurred in database "(.*)", table "(.*)", column '(.*)'./) || err.message.match(/The DELETE statement conflicted with the REFERENCE constraint "(.*)". The conflict occurred in database "(.*)", table "(.*)", column '(.*)'./) ||
err.message.match(/The INSERT statement conflicted with the FOREIGN KEY constraint "(.*)". The conflict occurred in database "(.*)", table "(.*)", column '(.*)'./) || err.message.match(/The (?:INSERT|MERGE|UPDATE) statement conflicted with the FOREIGN KEY constraint "(.*)". The conflict occurred in database "(.*)", table "(.*)", column '(.*)'./);
err.message.match(/The MERGE statement conflicted with the FOREIGN KEY constraint "(.*)". The conflict occurred in database "(.*)", table "(.*)", column '(.*)'./) ||
err.message.match(/The UPDATE statement conflicted with the FOREIGN KEY constraint "(.*)". The conflict occurred in database "(.*)", table "(.*)", column '(.*)'./);
if (match && match.length > 0) { if (match && match.length > 0) {
return new sequelizeErrors.ForeignKeyConstraintError({ return new sequelizeErrors.ForeignKeyConstraintError({
fields: null, fields: null,
......
...@@ -2,24 +2,24 @@ ...@@ -2,24 +2,24 @@
const Promise = require('../../promise'); const Promise = require('../../promise');
function ResourceLock(resource) { class ResourceLock {
this.resource = resource; constructor(resource) {
this.previous = Promise.resolve(resource); this.resource = resource;
} this.previous = Promise.resolve(resource);
}
ResourceLock.prototype.unwrap = function() {
return this.resource;
};
ResourceLock.prototype.lock = function() { unwrap() {
const lock = this.previous; return this.resource;
let resolve; }
this.previous = new Promise(r => { lock() {
resolve = r; const lock = this.previous;
}); let resolve;
this.previous = new Promise(r => {
return lock.disposer(resolve); resolve = r;
}; });
return lock.disposer(resolve);
}
}
module.exports = ResourceLock; module.exports = ResourceLock;
...@@ -133,10 +133,12 @@ class Query extends AbstractQuery { ...@@ -133,10 +133,12 @@ class Query extends AbstractQuery {
} }
if (this.isSelectQuery()) { if (this.isSelectQuery()) {
result = this.handleSelectQuery(data); return this.handleSelectQuery(data);
} else if (this.isShowTablesQuery()) { }
result = this.handleShowTablesQuery(data); if (this.isShowTablesQuery()) {
} else if (this.isDescribeQuery()) { return this.handleShowTablesQuery(data);
}
if (this.isDescribeQuery()) {
result = {}; result = {};
for (const _result of data) { for (const _result of data) {
...@@ -150,24 +152,32 @@ class Query extends AbstractQuery { ...@@ -150,24 +152,32 @@ class Query extends AbstractQuery {
comment: _result.Comment ? _result.Comment : null comment: _result.Comment ? _result.Comment : null
}; };
} }
} else if (this.isShowIndexesQuery()) { return result;
result = this.handleShowIndexesQuery(data); }
if (this.isShowIndexesQuery()) {
} else if (this.isCallQuery()) { return this.handleShowIndexesQuery(data);
result = data[0]; }
} else if (this.isBulkUpdateQuery() || this.isBulkDeleteQuery() || this.isUpsertQuery()) { if (this.isCallQuery()) {
result = data.affectedRows; return data[0];
} else if (this.isVersionQuery()) { }
result = data[0].version; if (this.isBulkUpdateQuery() || this.isBulkDeleteQuery() || this.isUpsertQuery()) {
} else if (this.isForeignKeysQuery()) { return data.affectedRows;
result = data; }
} else if (this.isInsertQuery() || this.isUpdateQuery()) { if (this.isVersionQuery()) {
result = [result, data.affectedRows]; return data[0].version;
} else if (this.isShowConstraintsQuery()) { }
result = data; if (this.isForeignKeysQuery()) {
} else if (this.isRawQuery()) { return data;
}
if (this.isInsertQuery() || this.isUpdateQuery()) {
return [result, data.affectedRows];
}
if (this.isShowConstraintsQuery()) {
return data;
}
if (this.isRawQuery()) {
// MySQL returns row data and metadata (affected rows etc) in a single object - let's standarize it, sorta // MySQL returns row data and metadata (affected rows etc) in a single object - let's standarize it, sorta
result = [data, data]; return [data, data];
} }
return result; return result;
......
...@@ -48,9 +48,10 @@ module.exports = BaseTypes => { ...@@ -48,9 +48,10 @@ module.exports = BaseTypes => {
DATEONLY.parse = function parse(value) { DATEONLY.parse = function parse(value) {
if (value === 'infinity') { if (value === 'infinity') {
value = Infinity; return Infinity;
} else if (value === '-infinity') { }
value = -Infinity; if (value === '-infinity') {
return -Infinity;
} }
return value; return value;
...@@ -59,7 +60,8 @@ module.exports = BaseTypes => { ...@@ -59,7 +60,8 @@ module.exports = BaseTypes => {
DATEONLY.prototype._stringify = function _stringify(value, options) { DATEONLY.prototype._stringify = function _stringify(value, options) {
if (value === Infinity) { if (value === Infinity) {
return 'Infinity'; return 'Infinity';
} else if (value === -Infinity) { }
if (value === -Infinity) {
return '-Infinity'; return '-Infinity';
} }
...@@ -69,9 +71,10 @@ module.exports = BaseTypes => { ...@@ -69,9 +71,10 @@ module.exports = BaseTypes => {
DATEONLY.prototype._sanitize = function _sanitize(value, options) { DATEONLY.prototype._sanitize = function _sanitize(value, options) {
if ((!options || options && !options.raw) && value !== Infinity && value !== -Infinity) { if ((!options || options && !options.raw) && value !== Infinity && value !== -Infinity) {
if (_.isString(value)) { if (_.isString(value)) {
if (_.toLower(value) === 'infinity') { if (value.toLowerCase() === 'infinity') {
return Infinity; return Infinity;
} else if (_.toLower(value) === '-infinity') { }
if (value.toLowerCase() === '-infinity') {
return -Infinity; return -Infinity;
} }
} }
...@@ -173,11 +176,12 @@ module.exports = BaseTypes => { ...@@ -173,11 +176,12 @@ module.exports = BaseTypes => {
if (_.isString(value)) { if (_.isString(value)) {
// Only take action on valid boolean strings. // Only take action on valid boolean strings.
value = value === 'true' || value === 't' ? true : value === 'false' || value === 'f' ? false : value; return value === 'true' || value === 't' ? true : value === 'false' || value === 'f' ? false : value;
} else if (_.isNumber(value)) { }
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; return value === 1 ? true : value === 0 ? false : value;
} }
} }
...@@ -208,7 +212,8 @@ module.exports = BaseTypes => { ...@@ -208,7 +212,8 @@ module.exports = BaseTypes => {
DATE.prototype._stringify = function _stringify(value, options) { DATE.prototype._stringify = function _stringify(value, options) {
if (value === Infinity) { if (value === Infinity) {
return 'Infinity'; return 'Infinity';
} else if (value === -Infinity) { }
if (value === -Infinity) {
return '-Infinity'; return '-Infinity';
} }
...@@ -218,9 +223,10 @@ module.exports = BaseTypes => { ...@@ -218,9 +223,10 @@ module.exports = BaseTypes => {
DATE.prototype._sanitize = function _sanitize(value, options) { DATE.prototype._sanitize = function _sanitize(value, options) {
if ((!options || options && !options.raw) && !(value instanceof Date) && !!value && value !== Infinity && value !== -Infinity) { if ((!options || options && !options.raw) && !(value instanceof Date) && !!value && value !== Infinity && value !== -Infinity) {
if (_.isString(value)) { if (_.isString(value)) {
if (_.toLower(value) === 'infinity') { if (value.toLowerCase() === 'infinity') {
return Infinity; return Infinity;
} else if (_.toLower(value) === '-infinity') { }
if (value.toLowerCase() === '-infinity') {
return -Infinity; return -Infinity;
} }
} }
......
...@@ -219,7 +219,8 @@ class PostgresQueryGenerator extends AbstractQueryGenerator { ...@@ -219,7 +219,8 @@ class PostgresQueryGenerator extends AbstractQueryGenerator {
); );
return conditions.join(' AND '); return conditions.join(' AND ');
} else if (smth.path) { }
if (smth.path) {
let str; let str;
// Allow specifying conditions using the postgres json syntax // Allow specifying conditions using the postgres json syntax
......
...@@ -113,7 +113,8 @@ class Query extends AbstractQuery { ...@@ -113,7 +113,8 @@ class Query extends AbstractQuery {
name: row.relname, name: row.relname,
tableName: row.relname.split('_')[0] tableName: row.relname.split('_')[0]
})); }));
} else if (isTableNameQuery) { }
if (isTableNameQuery) {
return rows.map(row => _.values(row)); return rows.map(row => _.values(row));
} }
...@@ -123,10 +124,9 @@ class Query extends AbstractQuery { ...@@ -123,10 +124,9 @@ class Query extends AbstractQuery {
code: '23505', code: '23505',
detail: rows[0].sequelize_caught_exception detail: rows[0].sequelize_caught_exception
}); });
} else { }
for (const row of rows) { for (const row of rows) {
delete row.sequelize_caught_exception; delete row.sequelize_caught_exception;
}
} }
} }
...@@ -163,7 +163,8 @@ class Query extends AbstractQuery { ...@@ -163,7 +163,8 @@ class Query extends AbstractQuery {
delete row.columns; delete row.columns;
} }
return rows; return rows;
} else if (this.isForeignKeysQuery()) { }
if (this.isForeignKeysQuery()) {
const result = []; const result = [];
for (const row of rows) { for (const row of rows) {
let defParts; let defParts;
...@@ -182,7 +183,8 @@ class Query extends AbstractQuery { ...@@ -182,7 +183,8 @@ class Query extends AbstractQuery {
result.push(row); result.push(row);
} }
return result; return result;
} else if (this.isSelectQuery()) { }
if (this.isSelectQuery()) {
let result = rows; let result = rows;
// Postgres will treat tables as case-insensitive, so fix the case // Postgres will treat tables as case-insensitive, so fix the case
// of the returned values to match attributes // of the returned values to match attributes
...@@ -203,7 +205,8 @@ class Query extends AbstractQuery { ...@@ -203,7 +205,8 @@ class Query extends AbstractQuery {
}); });
} }
return this.handleSelectQuery(result); return this.handleSelectQuery(result);
} else if (QueryTypes.DESCRIBE === this.options.type) { }
if (QueryTypes.DESCRIBE === this.options.type) {
const result = {}; const result = {};
for (const row of rows) { for (const row of rows) {
...@@ -237,20 +240,26 @@ class Query extends AbstractQuery { ...@@ -237,20 +240,26 @@ class Query extends AbstractQuery {
} }
return result; return result;
} else if (this.isVersionQuery()) { }
if (this.isVersionQuery()) {
return rows[0].server_version; return rows[0].server_version;
} else if (this.isShowOrDescribeQuery()) { }
if (this.isShowOrDescribeQuery()) {
return rows; return rows;
} else if (QueryTypes.BULKUPDATE === this.options.type) { }
if (QueryTypes.BULKUPDATE === this.options.type) {
if (!this.options.returning) { if (!this.options.returning) {
return parseInt(rowCount, 10); return parseInt(rowCount, 10);
} }
return this.handleSelectQuery(rows); return this.handleSelectQuery(rows);
} else if (QueryTypes.BULKDELETE === this.options.type) { }
if (QueryTypes.BULKDELETE === this.options.type) {
return parseInt(rowCount, 10); return parseInt(rowCount, 10);
} else if (this.isUpsertQuery()) { }
if (this.isUpsertQuery()) {
return rows[0]; return rows[0];
} else if (this.isInsertQuery() || this.isUpdateQuery()) { }
if (this.isInsertQuery() || this.isUpdateQuery()) {
if (this.instance && this.instance.dataValues) { if (this.instance && this.instance.dataValues) {
for (const key in rows[0]) { for (const key in rows[0]) {
if (rows[0].hasOwnProperty(key)) { if (rows[0].hasOwnProperty(key)) {
...@@ -267,11 +276,11 @@ class Query extends AbstractQuery { ...@@ -267,11 +276,11 @@ class Query extends AbstractQuery {
this.instance || rows && (this.options.plain && rows[0] || rows) || undefined, this.instance || rows && (this.options.plain && rows[0] || rows) || undefined,
rowCount rowCount
]; ];
} else if (this.isRawQuery()) { }
if (this.isRawQuery()) {
return [rows, queryResult]; return [rows, queryResult];
} else {
return rows;
} }
return rows;
}); });
} }
......
...@@ -5,23 +5,25 @@ const _ = require('lodash'); ...@@ -5,23 +5,25 @@ const _ = require('lodash');
function stringifyRangeBound(bound) { function stringifyRangeBound(bound) {
if (bound === null) { if (bound === null) {
return '' ; return '' ;
} else if (bound === Infinity || bound === -Infinity) { }
if (bound === Infinity || bound === -Infinity) {
return bound.toString().toLowerCase(); return bound.toString().toLowerCase();
} else {
return JSON.stringify(bound);
} }
return JSON.stringify(bound);
} }
function parseRangeBound(bound, parseType) { function parseRangeBound(bound, parseType) {
if (!bound) { if (!bound) {
return null; return null;
} else if (bound === 'infinity') { }
if (bound === 'infinity') {
return Infinity; return Infinity;
} else if (bound === '-infinity') { }
if (bound === '-infinity') {
return -Infinity; return -Infinity;
} else {
return parseType(bound);
} }
return parseType(bound);
} }
function stringify(data) { function stringify(data) {
......
...@@ -249,9 +249,11 @@ module.exports = BaseTypes => { ...@@ -249,9 +249,11 @@ module.exports = BaseTypes => {
if (_.isString(value)) { if (_.isString(value)) {
if (value === 'NaN') { if (value === 'NaN') {
return NaN; return NaN;
} else if (value === 'Infinity') { }
if (value === 'Infinity') {
return Infinity; return Infinity;
} else if (value === '-Infinity') { }
if (value === '-Infinity') {
return -Infinity; return -Infinity;
} }
} }
......
...@@ -139,7 +139,8 @@ class SQLiteQueryGenerator extends MySqlQueryGenerator { ...@@ -139,7 +139,8 @@ class SQLiteQueryGenerator extends MySqlQueryGenerator {
_toJSONValue(value) { _toJSONValue(value) {
if (value instanceof Date) { if (value instanceof Date) {
return value.toISOString(); return value.toISOString();
} else if (Array.isArray(value) && value[0] instanceof Date) { }
if (Array.isArray(value) && value[0] instanceof Date) {
return value.map(val => val.toISOString()); return value.map(val => val.toISOString());
} }
return value; return value;
...@@ -155,7 +156,8 @@ class SQLiteQueryGenerator extends MySqlQueryGenerator { ...@@ -155,7 +156,8 @@ class SQLiteQueryGenerator extends MySqlQueryGenerator {
); );
return conditions.join(' AND '); return conditions.join(' AND ');
} else if (smth.path) { }
if (smth.path) {
let str; let str;
// Allow specifying conditions using the sqlite json functions // Allow specifying conditions using the sqlite json functions
......
...@@ -182,7 +182,8 @@ const Hooks = { ...@@ -182,7 +182,8 @@ const Hooks = {
this.options.hooks[type] = this.options.hooks[type].filter(hook => { this.options.hooks[type] = this.options.hooks[type].filter(hook => {
if (isReference && typeof hook === 'function') { if (isReference && typeof hook === 'function') {
return hook !== name; // check if same method return hook !== name; // check if same method
} else if (!isReference && typeof hook === 'object') { }
if (!isReference && typeof hook === 'object') {
return hook.name !== name; return hook.name !== name;
} }
return true; return true;
......
...@@ -190,7 +190,7 @@ class InstanceValidator { ...@@ -190,7 +190,7 @@ class InstanceValidator {
const validators = []; const validators = [];
_.forIn(this.modelInstance.validators[field], (test, validatorType) => { _.forIn(this.modelInstance.validators[field], (test, validatorType) => {
if (['isUrl', 'isURL', 'isEmail'].includes(validatorType)) { if (validatorType === 'isUrl' || validatorType === 'isURL' || validatorType === 'isEmail') {
// Preserve backwards compat. Validator.js now expects the second param to isURL and isEmail to be an object // Preserve backwards compat. Validator.js now expects the second param to isURL and isEmail to be an object
if (typeof test === 'object' && test !== null && test.msg) { if (typeof test === 'object' && test !== null && test.msg) {
test = { test = {
......
...@@ -97,9 +97,8 @@ class QueryInterface { ...@@ -97,9 +97,8 @@ class QueryInterface {
if (!this.QueryGenerator._dialect.supports.schemas) { if (!this.QueryGenerator._dialect.supports.schemas) {
return this.sequelize.drop(options); return this.sequelize.drop(options);
} else {
return this.showAllSchemas(options).map(schemaName => this.dropSchema(schemaName, options));
} }
return this.showAllSchemas(options).map(schemaName => this.dropSchema(schemaName, options));
} }
/** /**
...@@ -308,29 +307,27 @@ class QueryInterface { ...@@ -308,29 +307,27 @@ class QueryInterface {
return this.sequelize.query('PRAGMA foreign_keys = OFF', options) return this.sequelize.query('PRAGMA foreign_keys = OFF', options)
.then(() => dropAllTables(tableNames)) .then(() => dropAllTables(tableNames))
.then(() => this.sequelize.query('PRAGMA foreign_keys = ON', options)); .then(() => this.sequelize.query('PRAGMA foreign_keys = ON', options));
} else {
return dropAllTables(tableNames);
} }
return dropAllTables(tableNames);
}); });
} else { }
return this.getForeignKeysForTables(tableNames, options).then(foreignKeys => { return this.getForeignKeysForTables(tableNames, options).then(foreignKeys => {
const promises = []; const promises = [];
tableNames.forEach(tableName => {
let normalizedTableName = tableName;
if (_.isObject(tableName)) {
normalizedTableName = `${tableName.schema}.${tableName.tableName}`;
}
foreignKeys[normalizedTableName].forEach(foreignKey => { tableNames.forEach(tableName => {
const sql = this.QueryGenerator.dropForeignKeyQuery(tableName, foreignKey); let normalizedTableName = tableName;
promises.push(this.sequelize.query(sql, options)); if (_.isObject(tableName)) {
}); normalizedTableName = `${tableName.schema}.${tableName.tableName}`;
}); }
return Promise.all(promises).then(() => dropAllTables(tableNames)); foreignKeys[normalizedTableName].forEach(foreignKey => {
const sql = this.QueryGenerator.dropForeignKeyQuery(tableName, foreignKey);
promises.push(this.sequelize.query(sql, options));
});
}); });
}
return Promise.all(promises).then(() => dropAllTables(tableNames));
});
}); });
} }
...@@ -479,9 +476,8 @@ class QueryInterface { ...@@ -479,9 +476,8 @@ class QueryInterface {
// it will not throw an error like built-ins do (e.g. DESCRIBE on MySql). // it will not throw an error like built-ins do (e.g. DESCRIBE on MySql).
if (_.isEmpty(data)) { if (_.isEmpty(data)) {
return Promise.reject(`No description found for "${tableName}" table. Check the table name and schema; remember, they _are_ case sensitive.`); return Promise.reject(`No description found for "${tableName}" table. Check the table name and schema; remember, they _are_ case sensitive.`);
} else {
return Promise.resolve(data);
} }
return data;
}); });
} }
...@@ -562,12 +558,11 @@ class QueryInterface { ...@@ -562,12 +558,11 @@ class QueryInterface {
if (this.sequelize.options.dialect === 'sqlite') { if (this.sequelize.options.dialect === 'sqlite') {
// sqlite needs some special treatment as it cannot change a column // sqlite needs some special treatment as it cannot change a column
return SQLiteQueryInterface.changeColumn.call(this, tableName, attributes, options); return SQLiteQueryInterface.changeColumn.call(this, tableName, attributes, options);
} else {
const query = this.QueryGenerator.attributesToSQL(attributes);
const sql = this.QueryGenerator.changeColumnQuery(tableName, query);
return this.sequelize.query(sql, options);
} }
const query = this.QueryGenerator.attributesToSQL(attributes);
const sql = this.QueryGenerator.changeColumnQuery(tableName, query);
return this.sequelize.query(sql, options);
} }
/** /**
...@@ -606,14 +601,13 @@ class QueryInterface { ...@@ -606,14 +601,13 @@ class QueryInterface {
if (this.sequelize.options.dialect === 'sqlite') { if (this.sequelize.options.dialect === 'sqlite') {
// sqlite needs some special treatment as it cannot rename a column // sqlite needs some special treatment as it cannot rename a column
return SQLiteQueryInterface.renameColumn.call(this, tableName, attrNameBefore, attrNameAfter, options); return SQLiteQueryInterface.renameColumn.call(this, tableName, attrNameBefore, attrNameAfter, options);
} else {
const sql = this.QueryGenerator.renameColumnQuery(
tableName,
attrNameBefore,
this.QueryGenerator.attributesToSQL(_options)
);
return this.sequelize.query(sql, options);
} }
const sql = this.QueryGenerator.renameColumnQuery(
tableName,
attrNameBefore,
this.QueryGenerator.attributesToSQL(_options)
);
return this.sequelize.query(sql, options);
}); });
} }
...@@ -833,10 +827,9 @@ class QueryInterface { ...@@ -833,10 +827,9 @@ class QueryInterface {
if (this.sequelize.dialect.name === 'sqlite') { if (this.sequelize.dialect.name === 'sqlite') {
return SQLiteQueryInterface.addConstraint.call(this, tableName, options, rawTablename); return SQLiteQueryInterface.addConstraint.call(this, tableName, options, rawTablename);
} else {
const sql = this.QueryGenerator.addConstraintQuery(tableName, options, rawTablename);
return this.sequelize.query(sql, options);
} }
const sql = this.QueryGenerator.addConstraintQuery(tableName, options, rawTablename);
return this.sequelize.query(sql, options);
} }
showConstraint(tableName, constraintName, options) { showConstraint(tableName, constraintName, options) {
...@@ -1163,26 +1156,27 @@ class QueryInterface { ...@@ -1163,26 +1156,27 @@ class QueryInterface {
return data; return data;
} }
let result = data ? data[attributeSelector] : null; const result = data ? data[attributeSelector] : null;
if (!options || !options.dataType) {
return result;
}
if (options && options.dataType) { const dataType = options.dataType;
const dataType = options.dataType;
if (dataType instanceof DataTypes.DECIMAL || dataType instanceof DataTypes.FLOAT) { if (dataType instanceof DataTypes.DECIMAL || dataType instanceof DataTypes.FLOAT) {
if (!_.isNull(result)) { if (!_.isNull(result)) {
result = parseFloat(result); return parseFloat(result);
} }
} else if (dataType instanceof DataTypes.INTEGER || dataType instanceof DataTypes.BIGINT) { }
result = parseInt(result, 10); if (dataType instanceof DataTypes.INTEGER || dataType instanceof DataTypes.BIGINT) {
} else if (dataType instanceof DataTypes.DATE) { return parseInt(result, 10);
if (!_.isNull(result) && !_.isDate(result)) { }
result = new Date(result); if (dataType instanceof DataTypes.DATE) {
} if (!_.isNull(result) && !_.isDate(result)) {
} else if (dataType instanceof DataTypes.STRING) { return new Date(result);
// Nothing to do, result is already a string.
} }
} }
return result; return result;
}); });
} }
......
...@@ -819,11 +819,11 @@ class Sequelize { ...@@ -819,11 +819,11 @@ class Sequelize {
* @returns {Sequelize.fn} * @returns {Sequelize.fn}
*/ */
random() { random() {
if (['postgres', 'sqlite'].includes(this.getDialect())) { const dia = this.getDialect();
if (dia === 'postgres' || dia === 'sqlite') {
return this.fn('RANDOM'); return this.fn('RANDOM');
} else {
return this.fn('RAND');
} }
return this.fn('RAND');
} }
/** /**
...@@ -1117,7 +1117,8 @@ class Sequelize { ...@@ -1117,7 +1117,8 @@ class Sequelize {
if (type instanceof DataTypes.ARRAY) { if (type instanceof DataTypes.ARRAY) {
if (!type.type) { if (!type.type) {
throw new Error('ARRAY is missing type definition for its values.'); throw new Error('ARRAY is missing type definition for its values.');
} else if (dialectTypes[type.type.key]) { }
if (dialectTypes[type.type.key]) {
type.type = dialectTypes[type.type.key].extend(type.type); type.type = dialectTypes[type.type.key].extend(type.type);
} }
} }
......
...@@ -2,7 +2,7 @@ ...@@ -2,7 +2,7 @@
/** /**
* An enum of table hints to be used in mssql for querying with table hints * An enum of table hints to be used in mssql for querying with table hints
* *
* @property NOLOCK * @property NOLOCK
* @property READUNCOMMITTED * @property READUNCOMMITTED
* @property UPDLOCK * @property UPDLOCK
......
...@@ -8,7 +8,6 @@ const uuidv4 = require('uuid/v4'); ...@@ -8,7 +8,6 @@ const uuidv4 = require('uuid/v4');
const Promise = require('./promise'); const Promise = require('./promise');
const operators = require('./operators'); const operators = require('./operators');
const operatorsArray = _.values(operators); const operatorsArray = _.values(operators);
const primitives = ['string', 'number', 'boolean'];
let inflection = require('inflection'); let inflection = require('inflection');
...@@ -42,7 +41,8 @@ function underscoredIf(str, condition) { ...@@ -42,7 +41,8 @@ function underscoredIf(str, condition) {
exports.underscoredIf = underscoredIf; exports.underscoredIf = underscoredIf;
function isPrimitive(val) { function isPrimitive(val) {
return primitives.includes(typeof val); const type = typeof val;
return type === 'string' || type === 'number' || type === 'boolean';
} }
exports.isPrimitive = isPrimitive; exports.isPrimitive = isPrimitive;
...@@ -65,7 +65,7 @@ function merge() { ...@@ -65,7 +65,7 @@ function merge() {
for (const obj of arguments) { for (const obj of arguments) {
_.forOwn(obj, (value, key) => { _.forOwn(obj, (value, key) => {
if (typeof value !== 'undefined') { if (value !== undefined) {
if (!result[key]) { if (!result[key]) {
result[key] = value; result[key] = value;
} else if (_.isPlainObject(value) && _.isPlainObject(result[key])) { } else if (_.isPlainObject(value) && _.isPlainObject(result[key])) {
...@@ -146,7 +146,7 @@ exports.cloneDeep = cloneDeep; ...@@ -146,7 +146,7 @@ exports.cloneDeep = cloneDeep;
function mapFinderOptions(options, Model) { function mapFinderOptions(options, Model) {
if (options.attributes && Array.isArray(options.attributes)) { if (options.attributes && Array.isArray(options.attributes)) {
options.attributes = Model._injectDependentVirtualAttributes(options.attributes); options.attributes = Model._injectDependentVirtualAttributes(options.attributes);
options.attributes = _.without(options.attributes, ...Model._virtualAttributes); options.attributes = options.attributes.filter(v => !Model._isVirtualAttribute(v));
} }
mapOptionFieldNames(options, Model); mapOptionFieldNames(options, Model);
...@@ -231,18 +231,12 @@ function mapValueFieldNames(dataValues, fields, Model) { ...@@ -231,18 +231,12 @@ function mapValueFieldNames(dataValues, fields, Model) {
exports.mapValueFieldNames = mapValueFieldNames; exports.mapValueFieldNames = mapValueFieldNames;
function isColString(value) { function isColString(value) {
return typeof value === 'string' && value.substr(0, 1) === '$' && value.substr(value.length - 1, 1) === '$'; return typeof value === 'string' && value[0] === '$' && value[value.length - 1] === '$';
} }
exports.isColString = isColString; exports.isColString = isColString;
function canTreatArrayAsAnd(arr) { function canTreatArrayAsAnd(arr) {
return arr.reduce((treatAsAnd, arg) => { return arr.some(arg => _.isPlainObject(arg));
if (treatAsAnd) {
return treatAsAnd;
} else {
return _.isPlainObject(arg);
}
}, false);
} }
exports.canTreatArrayAsAnd = canTreatArrayAsAnd; exports.canTreatArrayAsAnd = canTreatArrayAsAnd;
...@@ -256,20 +250,22 @@ function toDefaultValue(value, dialect) { ...@@ -256,20 +250,22 @@ function toDefaultValue(value, dialect) {
const tmp = value(); const tmp = value();
if (tmp instanceof DataTypes.ABSTRACT) { if (tmp instanceof DataTypes.ABSTRACT) {
return tmp.toSql(); return tmp.toSql();
} else {
return tmp;
} }
} else if (value instanceof DataTypes.UUIDV1) { return tmp;
}
if (value instanceof DataTypes.UUIDV1) {
return uuidv1(); return uuidv1();
} else if (value instanceof DataTypes.UUIDV4) { }
if (value instanceof DataTypes.UUIDV4) {
return uuidv4(); return uuidv4();
} else if (value instanceof DataTypes.NOW) { }
if (value instanceof DataTypes.NOW) {
return now(dialect); return now(dialect);
} else if (_.isPlainObject(value) || Array.isArray(value)) { }
if (_.isPlainObject(value) || Array.isArray(value)) {
return _.clone(value); return _.clone(value);
} else {
return value;
} }
return value;
} }
exports.toDefaultValue = toDefaultValue; exports.toDefaultValue = toDefaultValue;
...@@ -308,7 +304,7 @@ function removeNullValuesFromHash(hash, omitNull, options) { ...@@ -308,7 +304,7 @@ function removeNullValuesFromHash(hash, omitNull, options) {
const _hash = {}; const _hash = {};
_.forIn(hash, (val, key) => { _.forIn(hash, (val, key) => {
if (options.allowNull.includes(key) || key.match(/Id$/) || val !== null && val !== undefined) { if (options.allowNull.includes(key) || key.endsWith('Id') || val !== null && val !== undefined) {
_hash[key] = val; _hash[key] = val;
} }
}); });
...@@ -342,11 +338,11 @@ function sliceArgs(args, begin) { ...@@ -342,11 +338,11 @@ function sliceArgs(args, begin) {
exports.sliceArgs = sliceArgs; exports.sliceArgs = sliceArgs;
function now(dialect) { function now(dialect) {
const now = new Date(); const d = new Date();
if (!['mysql', 'postgres', 'sqlite', 'mssql'].includes(dialect)) { if (!['mysql', 'postgres', 'sqlite', 'mssql'].includes(dialect)) {
now.setMilliseconds(0); d.setMilliseconds(0);
} }
return now; return d;
} }
exports.now = now; exports.now = now;
...@@ -643,5 +639,3 @@ function nameIndex(index, tableName) { ...@@ -643,5 +639,3 @@ function nameIndex(index, tableName) {
return index; return index;
} }
exports.nameIndex = nameIndex; exports.nameIndex = nameIndex;
...@@ -53,7 +53,7 @@ const extensions = { ...@@ -53,7 +53,7 @@ const extensions = {
return this.notRegex(str, pattern, modifiers); return this.notRegex(str, pattern, modifiers);
}, },
contains(str, elem) { contains(str, elem) {
return str.includes(elem) && !!elem; return !!elem && str.includes(elem);
}, },
notContains(str, elem) { notContains(str, elem) {
return !this.contains(str, elem); return !this.contains(str, elem);
......
...@@ -705,7 +705,7 @@ describe(Support.getTestDialectTeaser('DataTypes'), () => { ...@@ -705,7 +705,7 @@ describe(Support.getTestDialectTeaser('DataTypes'), () => {
force: true force: true
}).then(() => { }).then(() => {
return ByteModel.create({ return ByteModel.create({
byteToBool: new Buffer([true]) byteToBool: Buffer.from([true])
}); });
}).then(byte => { }).then(byte => {
expect(byte.byteToBool).to.be.ok; expect(byte.byteToBool).to.be.ok;
......
...@@ -2511,7 +2511,7 @@ describe(Support.getTestDialectTeaser('Model'), () => { ...@@ -2511,7 +2511,7 @@ describe(Support.getTestDialectTeaser('Model'), () => {
describe('buffers', () => { describe('buffers', () => {
it('should be able to take a buffer as parameter to a BLOB field', function() { it('should be able to take a buffer as parameter to a BLOB field', function() {
return this.BlobUser.create({ return this.BlobUser.create({
data: new Buffer('Sequelize') data: Buffer.from('Sequelize')
}).then(user => { }).then(user => {
expect(user).to.be.ok; expect(user).to.be.ok;
}); });
...@@ -2519,7 +2519,7 @@ describe(Support.getTestDialectTeaser('Model'), () => { ...@@ -2519,7 +2519,7 @@ describe(Support.getTestDialectTeaser('Model'), () => {
it('should return a buffer when fetching a blob', function() { it('should return a buffer when fetching a blob', function() {
return this.BlobUser.create({ return this.BlobUser.create({
data: new Buffer('Sequelize') data: Buffer.from('Sequelize')
}).then(user => { }).then(user => {
return this.BlobUser.findByPk(user.id).then(user => { return this.BlobUser.findByPk(user.id).then(user => {
expect(user.data).to.be.an.instanceOf(Buffer); expect(user.data).to.be.an.instanceOf(Buffer);
......
...@@ -704,7 +704,7 @@ describe(Support.getTestDialectTeaser('Model'), () => { ...@@ -704,7 +704,7 @@ describe(Support.getTestDialectTeaser('Model'), () => {
}); });
}); });
it('sholud validate', function() { it('should validate', function() {
return this.User return this.User
.sync({ force: true }) .sync({ force: true })
.then(() => this.User.bulkCreate([ .then(() => this.User.bulkCreate([
......
...@@ -62,7 +62,7 @@ describe(Support.getTestDialectTeaser('Model'), () => { ...@@ -62,7 +62,7 @@ describe(Support.getTestDialectTeaser('Model'), () => {
describe('special where conditions/smartWhere object', () => { describe('special where conditions/smartWhere object', () => {
beforeEach(function() { beforeEach(function() {
this.buf = new Buffer(16); this.buf = Buffer.alloc(16);
this.buf.fill('\x01'); this.buf.fill('\x01');
return this.User.bulkCreate([ return this.User.bulkCreate([
{username: 'boo', intVal: 5, theDate: '2013-01-01 12:00'}, {username: 'boo', intVal: 5, theDate: '2013-01-01 12:00'},
...@@ -261,7 +261,7 @@ describe(Support.getTestDialectTeaser('Model'), () => { ...@@ -261,7 +261,7 @@ describe(Support.getTestDialectTeaser('Model'), () => {
}); });
const buf1 = this.buf; const buf1 = this.buf;
const buf2 = new Buffer(16); const buf2 = Buffer.alloc(16);
buf2.fill('\x02'); buf2.fill('\x02');
User.belongsTo(Binary, { foreignKey: 'binary' }); User.belongsTo(Binary, { foreignKey: 'binary' });
......
...@@ -220,7 +220,7 @@ describe(Support.getTestDialectTeaser('Model'), () => { ...@@ -220,7 +220,7 @@ describe(Support.getTestDialectTeaser('Model'), () => {
}); });
it('works with BLOBs', function() { it('works with BLOBs', function() {
return this.User.upsert({ id: 42, username: 'john', blob: new Buffer('kaj') }).then(created => { return this.User.upsert({ id: 42, username: 'john', blob: Buffer.from('kaj') }).then(created => {
if (dialect === 'sqlite') { if (dialect === 'sqlite') {
expect(created).to.be.undefined; expect(created).to.be.undefined;
} else { } else {
...@@ -228,7 +228,7 @@ describe(Support.getTestDialectTeaser('Model'), () => { ...@@ -228,7 +228,7 @@ describe(Support.getTestDialectTeaser('Model'), () => {
} }
this.clock.tick(1000); this.clock.tick(1000);
return this.User.upsert({ id: 42, username: 'doe', blob: new Buffer('andrea') }); return this.User.upsert({ id: 42, username: 'doe', blob: Buffer.from('andrea') });
}).then(created => { }).then(created => {
if (dialect === 'sqlite') { if (dialect === 'sqlite') {
expect(created).to.be.undefined; expect(created).to.be.undefined;
......
...@@ -449,7 +449,7 @@ describe(Support.getTestDialectTeaser('Sequelize'), () => { ...@@ -449,7 +449,7 @@ describe(Support.getTestDialectTeaser('Sequelize'), () => {
date = new Date(), date = new Date(),
string = 't\'e"st', string = 't\'e"st',
boolean = true, boolean = true,
buffer = new Buffer('t\'e"st'); buffer = Buffer.from('t\'e"st');
date.setMilliseconds(0); date.setMilliseconds(0);
return this.sequelize.query({ return this.sequelize.query({
...@@ -465,7 +465,7 @@ describe(Support.getTestDialectTeaser('Sequelize'), () => { ...@@ -465,7 +465,7 @@ describe(Support.getTestDialectTeaser('Sequelize'), () => {
res.date = res.date && new Date(res.date); res.date = res.date && new Date(res.date);
res.boolean = res.boolean && true; res.boolean = res.boolean && true;
if (typeof res.buffer === 'string' && res.buffer.startsWith('\\x')) { if (typeof res.buffer === 'string' && res.buffer.startsWith('\\x')) {
res.buffer = new Buffer(res.buffer.substring(2), 'hex'); res.buffer = Buffer.from(res.buffer.substring(2), 'hex');
} }
expect(res).to.deep.equal({ expect(res).to.deep.equal({
number, number,
......
...@@ -11,7 +11,7 @@ const chai = require('chai'), ...@@ -11,7 +11,7 @@ const chai = require('chai'),
describe('connection manager', () => { describe('connection manager', () => {
describe('_connect', () => { describe('_connect', () => {
beforeEach(function() { beforeEach(function() {
this.sinon = sinon.sandbox.create(); this.sinon = sinon.createSandbox();
this.connection = {}; this.connection = {};
this.dialect = { this.dialect = {
......
...@@ -17,7 +17,7 @@ if (dialect === 'mssql') { ...@@ -17,7 +17,7 @@ if (dialect === 'mssql') {
describe('[MSSQL Specific] Query', () => { describe('[MSSQL Specific] Query', () => {
describe('beginTransaction', () => { describe('beginTransaction', () => {
beforeEach(() => { beforeEach(() => {
sandbox = sinon.sandbox.create(); sandbox = sinon.createSandbox();
const options = { const options = {
transaction: { name: 'transactionName' }, transaction: { name: 'transactionName' },
isolationLevel: 'REPEATABLE_READ', isolationLevel: 'REPEATABLE_READ',
......
...@@ -413,7 +413,7 @@ if (dialect === 'mysql') { ...@@ -413,7 +413,7 @@ if (dialect === 'mysql') {
context: QueryGenerator context: QueryGenerator
}, { }, {
title: 'buffer as where argument', title: 'buffer as where argument',
arguments: ['myTable', {where: { field: new Buffer('Sequelize')}}], arguments: ['myTable', {where: { field: Buffer.from('Sequelize')}}],
expectation: "SELECT * FROM `myTable` WHERE `myTable`.`field` = X'53657175656c697a65';", expectation: "SELECT * FROM `myTable` WHERE `myTable`.`field` = X'53657175656c697a65';",
context: QueryGenerator context: QueryGenerator
}, { }, {
...@@ -497,10 +497,10 @@ if (dialect === 'mysql') { ...@@ -497,10 +497,10 @@ if (dialect === 'mysql') {
bind: ['foo', 1] bind: ['foo', 1]
} }
}, { }, {
arguments: ['myTable', {data: new Buffer('Sequelize') }], arguments: ['myTable', {data: Buffer.from('Sequelize') }],
expectation: { expectation: {
query: 'INSERT INTO `myTable` (`data`) VALUES ($1);', query: 'INSERT INTO `myTable` (`data`) VALUES ($1);',
bind: [new Buffer('Sequelize')] bind: [Buffer.from('Sequelize')]
} }
}, { }, {
arguments: ['myTable', {name: 'foo', foo: 1, nullValue: null}], arguments: ['myTable', {name: 'foo', foo: 1, nullValue: null}],
......
...@@ -475,7 +475,7 @@ if (dialect.startsWith('postgres')) { ...@@ -475,7 +475,7 @@ if (dialect.startsWith('postgres')) {
expectation: "SELECT * FROM \"mySchema\".\"myTable\" WHERE \"mySchema\".\"myTable\".\"name\" = 'foo'';DROP TABLE mySchema.myTable;';" expectation: "SELECT * FROM \"mySchema\".\"myTable\" WHERE \"mySchema\".\"myTable\".\"name\" = 'foo'';DROP TABLE mySchema.myTable;';"
}, { }, {
title: 'buffer as where argument', title: 'buffer as where argument',
arguments: ['myTable', {where: { field: new Buffer('Sequelize')}}], arguments: ['myTable', {where: { field: Buffer.from('Sequelize')}}],
expectation: "SELECT * FROM \"myTable\" WHERE \"myTable\".\"field\" = E'\\\\x53657175656c697a65';", expectation: "SELECT * FROM \"myTable\" WHERE \"myTable\".\"field\" = E'\\\\x53657175656c697a65';",
context: QueryGenerator context: QueryGenerator
}, { }, {
...@@ -638,10 +638,10 @@ if (dialect.startsWith('postgres')) { ...@@ -638,10 +638,10 @@ if (dialect.startsWith('postgres')) {
bind: ['foo', moment('2011-03-27 10:01:55 +0000', 'YYYY-MM-DD HH:mm:ss Z').toDate()] bind: ['foo', moment('2011-03-27 10:01:55 +0000', 'YYYY-MM-DD HH:mm:ss Z').toDate()]
} }
}, { }, {
arguments: ['myTable', {data: new Buffer('Sequelize') }], arguments: ['myTable', {data: Buffer.from('Sequelize') }],
expectation: { expectation: {
query: 'INSERT INTO "myTable" ("data") VALUES ($1);', query: 'INSERT INTO "myTable" ("data") VALUES ($1);',
bind: [new Buffer('Sequelize')] bind: [Buffer.from('Sequelize')]
} }
}, { }, {
arguments: ['myTable', {name: 'foo', numbers: [1, 2, 3]}], arguments: ['myTable', {name: 'foo', numbers: [1, 2, 3]}],
......
...@@ -343,7 +343,7 @@ if (dialect === 'sqlite') { ...@@ -343,7 +343,7 @@ if (dialect === 'sqlite') {
context: QueryGenerator context: QueryGenerator
}, { }, {
title: 'buffer as where argument', title: 'buffer as where argument',
arguments: ['myTable', {where: { field: new Buffer('Sequelize')}}], arguments: ['myTable', {where: { field: Buffer.from('Sequelize')}}],
expectation: "SELECT * FROM `myTable` WHERE `myTable`.`field` = X'53657175656c697a65';", expectation: "SELECT * FROM `myTable` WHERE `myTable`.`field` = X'53657175656c697a65';",
context: QueryGenerator context: QueryGenerator
}, { }, {
...@@ -383,10 +383,10 @@ if (dialect === 'sqlite') { ...@@ -383,10 +383,10 @@ if (dialect === 'sqlite') {
bind: ["'bar'"] bind: ["'bar'"]
} }
}, { }, {
arguments: ['myTable', {data: new Buffer('Sequelize') }], arguments: ['myTable', {data: Buffer.from('Sequelize') }],
expectation: { expectation: {
query: 'INSERT INTO `myTable` (`data`) VALUES ($1);', query: 'INSERT INTO `myTable` (`data`) VALUES ($1);',
bind: [new Buffer('Sequelize')] bind: [Buffer.from('Sequelize')]
} }
}, { }, {
arguments: ['myTable', { name: 'bar', value: null }], arguments: ['myTable', { name: 'bar', value: null }],
......
...@@ -13,7 +13,7 @@ describe(Support.getTestDialectTeaser('Model'), () => { ...@@ -13,7 +13,7 @@ describe(Support.getTestDialectTeaser('Model'), () => {
const Model = current.define('Model', {}); const Model = current.define('Model', {});
beforeEach(function() { beforeEach(function() {
this.sinon = sinon.sandbox.create(); this.sinon = sinon.createSandbox();
}); });
afterEach(function() { afterEach(function() {
......
...@@ -55,7 +55,7 @@ describe(Support.getTestDialectTeaser('Model'), () => { ...@@ -55,7 +55,7 @@ describe(Support.getTestDialectTeaser('Model'), () => {
} }
}); });
return Model.findOne({ where: { id: new Buffer('foo') }}).then(() => { return Model.findOne({ where: { id: Buffer.from('foo') }}).then(() => {
expect(this.stub.getCall(0).args[0]).to.be.an('object').not.to.have.property('limit'); expect(this.stub.getCall(0).args[0]).to.be.an('object').not.to.have.property('limit');
}); });
}); });
...@@ -91,7 +91,7 @@ describe(Support.getTestDialectTeaser('Model'), () => { ...@@ -91,7 +91,7 @@ describe(Support.getTestDialectTeaser('Model'), () => {
} }
}); });
return Model.findOne({ where: { unique: new Buffer('foo') }}).then(() => { return Model.findOne({ where: { unique: Buffer.from('foo') }}).then(() => {
expect(this.stub.getCall(0).args[0]).to.be.an('object').not.to.have.property('limit'); expect(this.stub.getCall(0).args[0]).to.be.an('object').not.to.have.property('limit');
}); });
}); });
......
...@@ -43,7 +43,7 @@ describe(Support.getTestDialectTeaser('Model'), () => { ...@@ -43,7 +43,7 @@ describe(Support.getTestDialectTeaser('Model'), () => {
}); });
beforeEach(function() { beforeEach(function() {
this.sinon = sinon.sandbox.create(); this.sinon = sinon.createSandbox();
this.query = this.sinon.stub(current, 'query').returns(Promise.resolve()); this.query = this.sinon.stub(current, 'query').returns(Promise.resolve());
this.stub = this.sinon.stub(current.getQueryInterface(), 'upsert').returns(Promise.resolve([true, undefined])); this.stub = this.sinon.stub(current.getQueryInterface(), 'upsert').returns(Promise.resolve([true, undefined]));
......
...@@ -14,6 +14,7 @@ const Support = require('../support'), ...@@ -14,6 +14,7 @@ const Support = require('../support'),
// Notice: [] will be replaced by dialect specific tick/quote character when there is not dialect specific expectation but only a default expectation // Notice: [] will be replaced by dialect specific tick/quote character when there is not dialect specific expectation but only a default expectation
describe(Support.getTestDialectTeaser('SQL'), () => { describe(Support.getTestDialectTeaser('SQL'), () => {
describe('DataTypes', () => { describe('DataTypes', () => {
const testsql = function(description, dataType, expectation) { const testsql = function(description, dataType, expectation) {
it(description, () => { it(description, () => {
...@@ -1300,7 +1301,7 @@ describe(Support.getTestDialectTeaser('SQL'), () => { ...@@ -1300,7 +1301,7 @@ describe(Support.getTestDialectTeaser('SQL'), () => {
const type = DataTypes.BLOB(); const type = DataTypes.BLOB();
expect(type.validate('foobar')).to.equal(true); expect(type.validate('foobar')).to.equal(true);
expect(type.validate(new Buffer('foobar'))).to.equal(true); expect(type.validate(Buffer.from('foobar'))).to.equal(true);
}); });
}); });
}); });
......
...@@ -146,7 +146,7 @@ describe(Support.getTestDialectTeaser('SQL'), () => { ...@@ -146,7 +146,7 @@ describe(Support.getTestDialectTeaser('SQL'), () => {
}); });
describe('Buffer', () => { describe('Buffer', () => {
testsql('field', new Buffer('Sequelize'), { testsql('field', Buffer.from('Sequelize'), {
postgres: '"field" = E\'\\\\x53657175656c697a65\'', postgres: '"field" = E\'\\\\x53657175656c697a65\'',
sqlite: "`field` = X'53657175656c697a65'", sqlite: "`field` = X'53657175656c697a65'",
mysql: "`field` = X'53657175656c697a65'", mysql: "`field` = X'53657175656c697a65'",
......
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!