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

Commit 25071392 by Simon Schick Committed by Sushant

refactor(*): cleanup code (#10091)

1 parent 3af05373
......@@ -747,7 +747,7 @@ Comment.prototype.getItem = function(options) {
return this[
'get' +
this.get('commentable')
.substr(0, 1)
[0]
.toUpperCase() +
this.get('commentable').substr(1)
](options);
......
......@@ -209,7 +209,7 @@ NUMBER.prototype.toSql = function toSql() {
};
NUMBER.prototype.validate = function(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;
......@@ -246,7 +246,7 @@ inherits(INTEGER, NUMBER);
INTEGER.prototype.key = INTEGER.key = 'INTEGER';
INTEGER.prototype.validate = function validate(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;
......@@ -406,24 +406,29 @@ DECIMAL.prototype.validate = function validate(value) {
return true;
};
for (const floating of [FLOAT, DOUBLE, REAL]) {
floating.prototype.escape = false;
floating.prototype._value = function _value(value) {
const protoExtensions = {
escape: false,
_value(value) {
if (isNaN(value)) {
return 'NaN';
} else if (!isFinite(value)) {
}
if (!isFinite(value)) {
const sign = value < 0 ? '-' : '';
return `${sign}Infinity`;
}
return value;
};
floating.prototype._stringify = function _stringify(value) {
},
_stringify(value) {
return `'${this._value(value)}'`;
};
floating.prototype._bindParam = function _bindParam(value, options) {
},
_bindParam(value, options) {
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';
* @namespace DataTypes.ENUM
*
*/
function ENUM(value) {
function ENUM(...args) {
const value = args[0];
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]);
}, [])
};
......
......@@ -101,4 +101,4 @@ const Deferrable = module.exports = { // eslint-disable-line
NOT: classToInvokable(NOT),
SET_DEFERRED: classToInvokable(SET_DEFERRED),
SET_IMMEDIATE: classToInvokable(SET_IMMEDIATE)
};
\ No newline at end of file
};
......@@ -67,18 +67,18 @@ class ConnectionManager {
try {
if (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;
} else {
return require(moduleName);
}
return require(moduleName);
} catch (err) {
if (err.code === 'MODULE_NOT_FOUND') {
if (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;
......
......@@ -498,35 +498,35 @@ class QueryGenerator {
const fieldsSql = options.fields.map(field => {
if (typeof field === 'string') {
return this.quoteIdentifier(field);
} else if (field instanceof Utils.SequelizeMethod) {
}
if (field instanceof Utils.SequelizeMethod) {
return this.handleSequelizeMethod(field);
} else {
let result = '';
if (field.attribute) {
field.name = field.attribute;
}
}
let result = '';
if (!field.name) {
throw new Error(`The following index field has no name: ${util.inspect(field)}`);
}
if (field.attribute) {
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 += ` COLLATE ${this.quoteIdentifier(field.collate)}`;
}
result += this.quoteIdentifier(field.name);
if (this._dialect.supports.index.length && field.length) {
result += `(${field.length})`;
}
if (this._dialect.supports.index.collate && field.collate) {
result += ` COLLATE ${this.quoteIdentifier(field.collate)}`;
}
if (field.order) {
result += ` ${field.order}`;
}
if (this._dialect.supports.index.length && field.length) {
result += `(${field.length})`;
}
return result;
if (field.order) {
result += ` ${field.order}`;
}
return result;
});
if (!options.name) {
......@@ -840,16 +840,18 @@ class QueryGenerator {
}, this);
return sql;
} else if (collection._modelAttribute) {
}
if (collection._modelAttribute) {
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);
} else if (_.isPlainObject(collection) && collection.raw) {
}
if (_.isPlainObject(collection) && collection.raw) {
// simple objects with raw is no longer supported
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 {
attrAs = attr[1];
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
} else if (attr instanceof Utils.Cast || attr instanceof Utils.Fn) {
}
if (attr instanceof Utils.Cast || attr instanceof Utils.Fn) {
throw new Error(
'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'
......@@ -1950,9 +1954,10 @@ class QueryGenerator {
if (value && value instanceof Utils.SequelizeMethod) {
value = this.getWhereConditions(value, tableName, factory, options, prepend);
result = value === 'NULL' ? `${key} IS NULL` : [key, value].join(` ${smth.comparator} `);
} else if (_.isPlainObject(value)) {
result = this.whereItemQuery(smth.attribute, value, {
return value === 'NULL' ? `${key} IS NULL` : [key, value].join(` ${smth.comparator} `);
}
if (_.isPlainObject(value)) {
return this.whereItemQuery(smth.attribute, value, {
model: factory
});
} else {
......@@ -1962,11 +1967,13 @@ class QueryGenerator {
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;
} else if (smth instanceof Utils.Cast) {
}
if (smth instanceof Utils.Literal) {
return smth.val;
}
if (smth instanceof Utils.Cast) {
if (smth.val instanceof Utils.SequelizeMethod) {
result = this.handleSequelizeMethod(smth.val, tableName, factory, options, prepend);
} else if (_.isPlainObject(smth.val)) {
......@@ -1975,31 +1982,29 @@ class QueryGenerator {
result = this.escape(smth.val);
}
result = `CAST(${result} AS ${smth.type.toUpperCase()})`;
} else if (smth instanceof Utils.Fn) {
result = `${smth.fn}(${smth.args.map(arg => {
return `CAST(${result} AS ${smth.type.toUpperCase()})`;
}
if (smth instanceof Utils.Fn) {
return `${smth.fn}(${smth.args.map(arg => {
if (arg instanceof Utils.SequelizeMethod) {
return this.handleSequelizeMethod(arg, tableName, factory, options, prepend);
} else if (_.isPlainObject(arg)) {
}
if (_.isPlainObject(arg)) {
return this.whereItemsQuery(arg);
} else {
return this.escape(arg);
}
return this.escape(arg);
}).join(', ') })`;
} else if (smth instanceof Utils.Col) {
if (Array.isArray(smth.col)) {
if (!factory) {
throw new Error('Cannot call Sequelize.col() with array outside of order / group clause');
}
} else if (smth.col.startsWith('*')) {
}
if (smth instanceof Utils.Col) {
if (Array.isArray(smth.col) && !factory) {
throw new Error('Cannot call Sequelize.col() with array outside of order / group clause');
}
if (smth.col.startsWith('*')) {
return '*';
}
return this.quote(smth.col, factory);
} else {
result = smth.toString(this, factory);
}
return result;
return smth.toString(this, factory);
}
whereQuery(where, options) {
......@@ -2027,7 +2032,7 @@ class QueryGenerator {
const items = [];
binding = binding || 'AND';
if (binding.substr(0, 1) !== ' ') binding = ` ${binding} `;
if (binding[0] !== ' ') binding = ` ${binding} `;
if (_.isPlainObject(where)) {
Utils.getComplexKeys(where).forEach(prop => {
......@@ -2330,7 +2335,7 @@ class QueryGenerator {
if (prop === Op.not) {
if (Array.isArray(value)) {
prop = Op.notIn;
} else if (![null, true, false].includes(value)) {
} else if (value !== null && value !== true && value !== false) {
prop = Op.ne;
}
}
......@@ -2410,7 +2415,8 @@ class QueryGenerator {
if (value === null && comparator === this.OperatorMap[Op.eq]) {
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);
}
......@@ -2422,7 +2428,6 @@ class QueryGenerator {
@private
*/
getWhereConditions(smth, tableName, factory, options, prepend) {
let result = null;
const where = {};
if (Array.isArray(tableName)) {
......@@ -2439,14 +2444,16 @@ class QueryGenerator {
}
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);
} else if (_.isPlainObject(smth)) {
return this.handleSequelizeMethod(smth, tableName, factory, options, prepend);
}
if (_.isPlainObject(smth)) {
return this.whereItemsQuery(smth, {
model: factory,
prefix: prepend && tableName,
type: options.type
});
} else if (typeof smth === 'number') {
}
if (typeof smth === 'number') {
let primaryKeys = factory ? Object.keys(factory.primaryKeys) : [];
if (primaryKeys.length > 0) {
......@@ -2462,29 +2469,32 @@ class QueryGenerator {
model: factory,
prefix: prepend && tableName
});
} else if (typeof smth === 'string') {
}
if (typeof smth === 'string') {
return this.whereItemsQuery(smth, {
model: factory,
prefix: prepend && tableName
});
} else if (Buffer.isBuffer(smth)) {
result = this.escape(smth);
} else if (Array.isArray(smth)) {
}
if (Buffer.isBuffer(smth)) {
return this.escape(smth);
}
if (Array.isArray(smth)) {
if (smth.length === 0 || smth.length > 0 && smth[0].length === 0) return '1=1';
if (Utils.canTreatArrayAsAnd(smth)) {
const _smth = { [Op.and]: smth };
result = this.getWhereConditions(_smth, tableName, factory, options, prepend);
} else {
throw new Error('Support for literal replacements in the `where` object has been removed.');
return this.getWhereConditions(_smth, tableName, factory, options, prepend);
}
} 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, {
model: factory,
prefix: prepend && tableName
});
}
return result ? result : '1=1';
return '1=1';
}
// A recursive parser for nested where conditions
......@@ -2492,10 +2502,9 @@ class QueryGenerator {
path = path || [];
return _.reduce(conditions, (result, value, key) => {
if (_.isObject(value)) {
result = result.concat(this.parseConditionObject(value, path.concat(key))); // Recursively parse objects
} else {
result.push({ path: path.concat(key), value });
return result.concat(this.parseConditionObject(value, path.concat(key))); // Recursively parse objects
}
result.push({ path: path.concat(key), value });
return result;
}, []);
}
......
......@@ -106,17 +106,20 @@ class ConnectionManager extends AbstractConnectionManager {
case 'ESOCKET':
if (error.message.includes('connect EHOSTUNREACH')) {
throw new sequelizeErrors.HostNotReachableError(error);
} else if (error.message.includes('connect ENETUNREACH')) {
}
if (error.message.includes('connect ENETUNREACH')) {
throw new sequelizeErrors.HostNotReachableError(error);
} else if (error.message.includes('connect EADDRNOTAVAIL')) {
}
if (error.message.includes('connect EADDRNOTAVAIL')) {
throw new sequelizeErrors.HostNotReachableError(error);
} else if (error.message.includes('getaddrinfo ENOTFOUND')) {
}
if (error.message.includes('getaddrinfo ENOTFOUND')) {
throw new sequelizeErrors.HostNotFoundError(error);
} else if (error.message.includes('connect ECONNREFUSED')) {
}
if (error.message.includes('connect ECONNREFUSED')) {
throw new sequelizeErrors.ConnectionRefusedError(error);
} else {
throw new sequelizeErrors.ConnectionError(error);
}
throw new sequelizeErrors.ConnectionError(error);
case 'ER_ACCESS_DENIED_ERROR':
case 'ELOGIN':
throw new sequelizeErrors.AccessDeniedError(error);
......
......@@ -62,81 +62,83 @@ class Query extends AbstractQuery {
return new Promise((resolve, reject) => {
// TRANSACTION SUPPORT
if (_.startsWith(this.sql, 'BEGIN TRANSACTION')) {
connection.beginTransaction(err => {
if (this.sql.startsWith('BEGIN TRANSACTION')) {
return connection.beginTransaction(err => {
if (err) {
reject(this.formatError(err));
} else {
resolve(this.formatResults());
return;
}
resolve(this.formatResults());
}, 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) {
reject(this.formatError(err));
} else {
resolve(this.formatResults());
return;
}
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) {
reject(this.formatError(err));
} else {
resolve(this.formatResults());
}
resolve(this.formatResults());
}, this.options.transaction.name);
} else if (_.startsWith(this.sql, 'SAVE TRANSACTION')) {
connection.saveTransaction(err => {
return;
}
if (this.sql.startsWith('SAVE TRANSACTION')) {
return connection.saveTransaction(err => {
if (err) {
reject(this.formatError(err));
} else {
resolve(this.formatResults());
return;
}
resolve(this.formatResults());
}, this.options.transaction.name);
} else {
const results = [];
const request = new connection.lib.Request(this.sql, (err, rowCount) => {
}
const results = [];
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) {
this.sequelize.log(`Executed (${this.connection.uuid || 'default'}): ${this.sql}`, Date.now() - queryBegin, this.options);
}
if (benchmark) {
this.sequelize.log(`Executed (${this.connection.uuid || 'default'}): ${this.sql}`, Date.now() - queryBegin, this.options);
}
if (err) {
err.sql = sql;
reject(this.formatError(err));
} else {
resolve(this.formatResults(results, rowCount));
}
if (err) {
err.sql = sql;
reject(this.formatError(err));
} else {
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) {
_.forOwn(parameters, (value, key) => {
const paramType = this.getSQLTypeFromJsType(value, connection.lib.TYPES);
request.addParameter(key, paramType.type, value, paramType.typeOptions);
});
}
request.on('row', columns => {
const row = {};
for (const column of columns) {
const typeid = column.metadata.type.id;
const parse = parserStore.get(typeid);
let value = column.value;
request.on('row', columns => {
const row = {};
for (const column of columns) {
const typeid = column.metadata.type.id;
const parse = parserStore.get(typeid);
let value = column.value;
if (value !== null & !!parse) {
value = parse(value);
}
row[column.metadata.colName] = value;
if (value !== null & !!parse) {
value = parse(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 {
}
if (this.isShowTablesQuery()) {
result = this.handleShowTablesQuery(data);
} else if (this.isDescribeQuery()) {
return this.handleShowTablesQuery(data);
}
if (this.isDescribeQuery()) {
result = {};
for (const _result of data) {
if (_result.Default) {
......@@ -220,29 +223,40 @@ class Query extends AbstractQuery {
}
}
} else if (this.isShowIndexesQuery()) {
result = this.handleShowIndexesQuery(data);
} else if (this.isSelectQuery()) {
result = this.handleSelectQuery(data);
} else if (this.isUpsertQuery()) {
result = data[0];
} else if (this.isCallQuery()) {
result = data[0];
} else if (this.isBulkUpdateQuery()) {
result = data.length;
} else if (this.isBulkDeleteQuery()) {
result = data[0] && data[0].AFFECTEDROWS;
} else if (this.isVersionQuery()) {
result = data[0].version;
} else if (this.isForeignKeysQuery()) {
result = data;
} else if (this.isInsertQuery() || this.isUpdateQuery()) {
result = [result, rowCount];
} else if (this.isShowConstraintsQuery()) {
result = this.handleShowConstraintsQuery(data);
} else if (this.isRawQuery()) {
}
if (this.isSelectQuery()) {
return this.handleSelectQuery(data);
}
if (this.isShowIndexesQuery()) {
return this.handleShowIndexesQuery(data);
}
if (this.isUpsertQuery()) {
return data[0];
}
if (this.isCallQuery()) {
return data[0];
}
if (this.isBulkUpdateQuery()) {
return data.length;
}
if (this.isBulkDeleteQuery()) {
return data[0] && data[0].AFFECTEDROWS;
}
if (this.isVersionQuery()) {
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
result = [data, data];
return [data, data];
}
return result;
......@@ -307,9 +321,7 @@ class Query extends AbstractQuery {
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 INSERT 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 '(.*)'./);
err.message.match(/The (?:INSERT|MERGE|UPDATE) statement conflicted with the FOREIGN KEY constraint "(.*)". The conflict occurred in database "(.*)", table "(.*)", column '(.*)'./);
if (match && match.length > 0) {
return new sequelizeErrors.ForeignKeyConstraintError({
fields: null,
......
......@@ -2,24 +2,24 @@
const Promise = require('../../promise');
function ResourceLock(resource) {
this.resource = resource;
this.previous = Promise.resolve(resource);
}
ResourceLock.prototype.unwrap = function() {
return this.resource;
};
class ResourceLock {
constructor(resource) {
this.resource = resource;
this.previous = Promise.resolve(resource);
}
ResourceLock.prototype.lock = function() {
const lock = this.previous;
let resolve;
unwrap() {
return this.resource;
}
this.previous = new Promise(r => {
resolve = r;
});
return lock.disposer(resolve);
};
lock() {
const lock = this.previous;
let resolve;
this.previous = new Promise(r => {
resolve = r;
});
return lock.disposer(resolve);
}
}
module.exports = ResourceLock;
......@@ -133,10 +133,12 @@ class Query extends AbstractQuery {
}
if (this.isSelectQuery()) {
result = this.handleSelectQuery(data);
} else if (this.isShowTablesQuery()) {
result = this.handleShowTablesQuery(data);
} else if (this.isDescribeQuery()) {
return this.handleSelectQuery(data);
}
if (this.isShowTablesQuery()) {
return this.handleShowTablesQuery(data);
}
if (this.isDescribeQuery()) {
result = {};
for (const _result of data) {
......@@ -150,24 +152,32 @@ class Query extends AbstractQuery {
comment: _result.Comment ? _result.Comment : null
};
}
} else if (this.isShowIndexesQuery()) {
result = this.handleShowIndexesQuery(data);
} else if (this.isCallQuery()) {
result = data[0];
} else if (this.isBulkUpdateQuery() || this.isBulkDeleteQuery() || this.isUpsertQuery()) {
result = data.affectedRows;
} else if (this.isVersionQuery()) {
result = data[0].version;
} else if (this.isForeignKeysQuery()) {
result = data;
} else if (this.isInsertQuery() || this.isUpdateQuery()) {
result = [result, data.affectedRows];
} else if (this.isShowConstraintsQuery()) {
result = data;
} else if (this.isRawQuery()) {
return result;
}
if (this.isShowIndexesQuery()) {
return this.handleShowIndexesQuery(data);
}
if (this.isCallQuery()) {
return data[0];
}
if (this.isBulkUpdateQuery() || this.isBulkDeleteQuery() || this.isUpsertQuery()) {
return data.affectedRows;
}
if (this.isVersionQuery()) {
return data[0].version;
}
if (this.isForeignKeysQuery()) {
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
result = [data, data];
return [data, data];
}
return result;
......
......@@ -48,9 +48,10 @@ module.exports = BaseTypes => {
DATEONLY.parse = function parse(value) {
if (value === 'infinity') {
value = Infinity;
} else if (value === '-infinity') {
value = -Infinity;
return Infinity;
}
if (value === '-infinity') {
return -Infinity;
}
return value;
......@@ -59,7 +60,8 @@ module.exports = BaseTypes => {
DATEONLY.prototype._stringify = function _stringify(value, options) {
if (value === Infinity) {
return 'Infinity';
} else if (value === -Infinity) {
}
if (value === -Infinity) {
return '-Infinity';
}
......@@ -69,9 +71,10 @@ module.exports = BaseTypes => {
DATEONLY.prototype._sanitize = function _sanitize(value, options) {
if ((!options || options && !options.raw) && value !== Infinity && value !== -Infinity) {
if (_.isString(value)) {
if (_.toLower(value) === 'infinity') {
if (value.toLowerCase() === 'infinity') {
return Infinity;
} else if (_.toLower(value) === '-infinity') {
}
if (value.toLowerCase() === '-infinity') {
return -Infinity;
}
}
......@@ -173,11 +176,12 @@ module.exports = BaseTypes => {
if (_.isString(value)) {
// 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.
value = value === 1 ? true : value === 0 ? false : value;
return value === 1 ? true : value === 0 ? false : value;
}
}
......@@ -208,7 +212,8 @@ module.exports = BaseTypes => {
DATE.prototype._stringify = function _stringify(value, options) {
if (value === Infinity) {
return 'Infinity';
} else if (value === -Infinity) {
}
if (value === -Infinity) {
return '-Infinity';
}
......@@ -218,9 +223,10 @@ module.exports = BaseTypes => {
DATE.prototype._sanitize = function _sanitize(value, options) {
if ((!options || options && !options.raw) && !(value instanceof Date) && !!value && value !== Infinity && value !== -Infinity) {
if (_.isString(value)) {
if (_.toLower(value) === 'infinity') {
if (value.toLowerCase() === 'infinity') {
return Infinity;
} else if (_.toLower(value) === '-infinity') {
}
if (value.toLowerCase() === '-infinity') {
return -Infinity;
}
}
......
......@@ -219,7 +219,8 @@ class PostgresQueryGenerator extends AbstractQueryGenerator {
);
return conditions.join(' AND ');
} else if (smth.path) {
}
if (smth.path) {
let str;
// Allow specifying conditions using the postgres json syntax
......
......@@ -113,7 +113,8 @@ class Query extends AbstractQuery {
name: row.relname,
tableName: row.relname.split('_')[0]
}));
} else if (isTableNameQuery) {
}
if (isTableNameQuery) {
return rows.map(row => _.values(row));
}
......@@ -123,10 +124,9 @@ class Query extends AbstractQuery {
code: '23505',
detail: rows[0].sequelize_caught_exception
});
} else {
for (const row of rows) {
delete row.sequelize_caught_exception;
}
}
for (const row of rows) {
delete row.sequelize_caught_exception;
}
}
......@@ -163,7 +163,8 @@ class Query extends AbstractQuery {
delete row.columns;
}
return rows;
} else if (this.isForeignKeysQuery()) {
}
if (this.isForeignKeysQuery()) {
const result = [];
for (const row of rows) {
let defParts;
......@@ -182,7 +183,8 @@ class Query extends AbstractQuery {
result.push(row);
}
return result;
} else if (this.isSelectQuery()) {
}
if (this.isSelectQuery()) {
let result = rows;
// Postgres will treat tables as case-insensitive, so fix the case
// of the returned values to match attributes
......@@ -203,7 +205,8 @@ class Query extends AbstractQuery {
});
}
return this.handleSelectQuery(result);
} else if (QueryTypes.DESCRIBE === this.options.type) {
}
if (QueryTypes.DESCRIBE === this.options.type) {
const result = {};
for (const row of rows) {
......@@ -237,20 +240,26 @@ class Query extends AbstractQuery {
}
return result;
} else if (this.isVersionQuery()) {
}
if (this.isVersionQuery()) {
return rows[0].server_version;
} else if (this.isShowOrDescribeQuery()) {
}
if (this.isShowOrDescribeQuery()) {
return rows;
} else if (QueryTypes.BULKUPDATE === this.options.type) {
}
if (QueryTypes.BULKUPDATE === this.options.type) {
if (!this.options.returning) {
return parseInt(rowCount, 10);
}
return this.handleSelectQuery(rows);
} else if (QueryTypes.BULKDELETE === this.options.type) {
}
if (QueryTypes.BULKDELETE === this.options.type) {
return parseInt(rowCount, 10);
} else if (this.isUpsertQuery()) {
}
if (this.isUpsertQuery()) {
return rows[0];
} else if (this.isInsertQuery() || this.isUpdateQuery()) {
}
if (this.isInsertQuery() || this.isUpdateQuery()) {
if (this.instance && this.instance.dataValues) {
for (const key in rows[0]) {
if (rows[0].hasOwnProperty(key)) {
......@@ -267,11 +276,11 @@ class Query extends AbstractQuery {
this.instance || rows && (this.options.plain && rows[0] || rows) || undefined,
rowCount
];
} else if (this.isRawQuery()) {
}
if (this.isRawQuery()) {
return [rows, queryResult];
} else {
return rows;
}
return rows;
});
}
......
......@@ -5,23 +5,25 @@ const _ = require('lodash');
function stringifyRangeBound(bound) {
if (bound === null) {
return '' ;
} else if (bound === Infinity || bound === -Infinity) {
}
if (bound === Infinity || bound === -Infinity) {
return bound.toString().toLowerCase();
} else {
return JSON.stringify(bound);
}
return JSON.stringify(bound);
}
function parseRangeBound(bound, parseType) {
if (!bound) {
return null;
} else if (bound === 'infinity') {
}
if (bound === 'infinity') {
return Infinity;
} else if (bound === '-infinity') {
}
if (bound === '-infinity') {
return -Infinity;
} else {
return parseType(bound);
}
return parseType(bound);
}
function stringify(data) {
......
......@@ -249,9 +249,11 @@ module.exports = BaseTypes => {
if (_.isString(value)) {
if (value === 'NaN') {
return NaN;
} else if (value === 'Infinity') {
}
if (value === 'Infinity') {
return Infinity;
} else if (value === '-Infinity') {
}
if (value === '-Infinity') {
return -Infinity;
}
}
......
......@@ -139,7 +139,8 @@ class SQLiteQueryGenerator extends MySqlQueryGenerator {
_toJSONValue(value) {
if (value instanceof Date) {
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;
......@@ -155,7 +156,8 @@ class SQLiteQueryGenerator extends MySqlQueryGenerator {
);
return conditions.join(' AND ');
} else if (smth.path) {
}
if (smth.path) {
let str;
// Allow specifying conditions using the sqlite json functions
......
......@@ -182,7 +182,8 @@ const Hooks = {
this.options.hooks[type] = this.options.hooks[type].filter(hook => {
if (isReference && typeof hook === 'function') {
return hook !== name; // check if same method
} else if (!isReference && typeof hook === 'object') {
}
if (!isReference && typeof hook === 'object') {
return hook.name !== name;
}
return true;
......
......@@ -190,7 +190,7 @@ class InstanceValidator {
const validators = [];
_.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
if (typeof test === 'object' && test !== null && test.msg) {
test = {
......
......@@ -97,9 +97,8 @@ class QueryInterface {
if (!this.QueryGenerator._dialect.supports.schemas) {
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 {
return this.sequelize.query('PRAGMA foreign_keys = OFF', options)
.then(() => dropAllTables(tableNames))
.then(() => this.sequelize.query('PRAGMA foreign_keys = ON', options));
} else {
return dropAllTables(tableNames);
}
return dropAllTables(tableNames);
});
} else {
return this.getForeignKeysForTables(tableNames, options).then(foreignKeys => {
const promises = [];
tableNames.forEach(tableName => {
let normalizedTableName = tableName;
if (_.isObject(tableName)) {
normalizedTableName = `${tableName.schema}.${tableName.tableName}`;
}
}
return this.getForeignKeysForTables(tableNames, options).then(foreignKeys => {
const promises = [];
foreignKeys[normalizedTableName].forEach(foreignKey => {
const sql = this.QueryGenerator.dropForeignKeyQuery(tableName, foreignKey);
promises.push(this.sequelize.query(sql, options));
});
});
tableNames.forEach(tableName => {
let normalizedTableName = tableName;
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 {
// it will not throw an error like built-ins do (e.g. DESCRIBE on MySql).
if (_.isEmpty(data)) {
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 {
if (this.sequelize.options.dialect === 'sqlite') {
// sqlite needs some special treatment as it cannot change a column
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 {
if (this.sequelize.options.dialect === 'sqlite') {
// sqlite needs some special treatment as it cannot rename a column
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 {
if (this.sequelize.dialect.name === 'sqlite') {
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) {
......@@ -1163,26 +1156,27 @@ class QueryInterface {
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 (!_.isNull(result)) {
result = parseFloat(result);
}
} else if (dataType instanceof DataTypes.INTEGER || dataType instanceof DataTypes.BIGINT) {
result = parseInt(result, 10);
} else if (dataType instanceof DataTypes.DATE) {
if (!_.isNull(result) && !_.isDate(result)) {
result = new Date(result);
}
} else if (dataType instanceof DataTypes.STRING) {
// Nothing to do, result is already a string.
if (dataType instanceof DataTypes.DECIMAL || dataType instanceof DataTypes.FLOAT) {
if (!_.isNull(result)) {
return parseFloat(result);
}
}
if (dataType instanceof DataTypes.INTEGER || dataType instanceof DataTypes.BIGINT) {
return parseInt(result, 10);
}
if (dataType instanceof DataTypes.DATE) {
if (!_.isNull(result) && !_.isDate(result)) {
return new Date(result);
}
}
return result;
});
}
......
......@@ -819,11 +819,11 @@ class Sequelize {
* @returns {Sequelize.fn}
*/
random() {
if (['postgres', 'sqlite'].includes(this.getDialect())) {
const dia = this.getDialect();
if (dia === 'postgres' || dia === 'sqlite') {
return this.fn('RANDOM');
} else {
return this.fn('RAND');
}
return this.fn('RAND');
}
/**
......@@ -1117,7 +1117,8 @@ class Sequelize {
if (type instanceof DataTypes.ARRAY) {
if (!type.type) {
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);
}
}
......
......@@ -2,7 +2,7 @@
/**
* An enum of table hints to be used in mssql for querying with table hints
*
*
* @property NOLOCK
* @property READUNCOMMITTED
* @property UPDLOCK
......
......@@ -8,7 +8,6 @@ const uuidv4 = require('uuid/v4');
const Promise = require('./promise');
const operators = require('./operators');
const operatorsArray = _.values(operators);
const primitives = ['string', 'number', 'boolean'];
let inflection = require('inflection');
......@@ -42,7 +41,8 @@ function underscoredIf(str, condition) {
exports.underscoredIf = underscoredIf;
function isPrimitive(val) {
return primitives.includes(typeof val);
const type = typeof val;
return type === 'string' || type === 'number' || type === 'boolean';
}
exports.isPrimitive = isPrimitive;
......@@ -65,7 +65,7 @@ function merge() {
for (const obj of arguments) {
_.forOwn(obj, (value, key) => {
if (typeof value !== 'undefined') {
if (value !== undefined) {
if (!result[key]) {
result[key] = value;
} else if (_.isPlainObject(value) && _.isPlainObject(result[key])) {
......@@ -146,7 +146,7 @@ exports.cloneDeep = cloneDeep;
function mapFinderOptions(options, Model) {
if (options.attributes && Array.isArray(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);
......@@ -231,18 +231,12 @@ function mapValueFieldNames(dataValues, fields, Model) {
exports.mapValueFieldNames = mapValueFieldNames;
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;
function canTreatArrayAsAnd(arr) {
return arr.reduce((treatAsAnd, arg) => {
if (treatAsAnd) {
return treatAsAnd;
} else {
return _.isPlainObject(arg);
}
}, false);
return arr.some(arg => _.isPlainObject(arg));
}
exports.canTreatArrayAsAnd = canTreatArrayAsAnd;
......@@ -256,20 +250,22 @@ function toDefaultValue(value, dialect) {
const tmp = value();
if (tmp instanceof DataTypes.ABSTRACT) {
return tmp.toSql();
} else {
return tmp;
}
} else if (value instanceof DataTypes.UUIDV1) {
return tmp;
}
if (value instanceof DataTypes.UUIDV1) {
return uuidv1();
} else if (value instanceof DataTypes.UUIDV4) {
}
if (value instanceof DataTypes.UUIDV4) {
return uuidv4();
} else if (value instanceof DataTypes.NOW) {
}
if (value instanceof DataTypes.NOW) {
return now(dialect);
} else if (_.isPlainObject(value) || Array.isArray(value)) {
}
if (_.isPlainObject(value) || Array.isArray(value)) {
return _.clone(value);
} else {
return value;
}
return value;
}
exports.toDefaultValue = toDefaultValue;
......@@ -308,7 +304,7 @@ function removeNullValuesFromHash(hash, omitNull, options) {
const _hash = {};
_.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;
}
});
......@@ -342,11 +338,11 @@ function sliceArgs(args, begin) {
exports.sliceArgs = sliceArgs;
function now(dialect) {
const now = new Date();
const d = new Date();
if (!['mysql', 'postgres', 'sqlite', 'mssql'].includes(dialect)) {
now.setMilliseconds(0);
d.setMilliseconds(0);
}
return now;
return d;
}
exports.now = now;
......@@ -643,5 +639,3 @@ function nameIndex(index, tableName) {
return index;
}
exports.nameIndex = nameIndex;
......@@ -53,7 +53,7 @@ const extensions = {
return this.notRegex(str, pattern, modifiers);
},
contains(str, elem) {
return str.includes(elem) && !!elem;
return !!elem && str.includes(elem);
},
notContains(str, elem) {
return !this.contains(str, elem);
......
......@@ -705,7 +705,7 @@ describe(Support.getTestDialectTeaser('DataTypes'), () => {
force: true
}).then(() => {
return ByteModel.create({
byteToBool: new Buffer([true])
byteToBool: Buffer.from([true])
});
}).then(byte => {
expect(byte.byteToBool).to.be.ok;
......
......@@ -2511,7 +2511,7 @@ describe(Support.getTestDialectTeaser('Model'), () => {
describe('buffers', () => {
it('should be able to take a buffer as parameter to a BLOB field', function() {
return this.BlobUser.create({
data: new Buffer('Sequelize')
data: Buffer.from('Sequelize')
}).then(user => {
expect(user).to.be.ok;
});
......@@ -2519,7 +2519,7 @@ describe(Support.getTestDialectTeaser('Model'), () => {
it('should return a buffer when fetching a blob', function() {
return this.BlobUser.create({
data: new Buffer('Sequelize')
data: Buffer.from('Sequelize')
}).then(user => {
return this.BlobUser.findByPk(user.id).then(user => {
expect(user.data).to.be.an.instanceOf(Buffer);
......
......@@ -704,7 +704,7 @@ describe(Support.getTestDialectTeaser('Model'), () => {
});
});
it('sholud validate', function() {
it('should validate', function() {
return this.User
.sync({ force: true })
.then(() => this.User.bulkCreate([
......
......@@ -62,7 +62,7 @@ describe(Support.getTestDialectTeaser('Model'), () => {
describe('special where conditions/smartWhere object', () => {
beforeEach(function() {
this.buf = new Buffer(16);
this.buf = Buffer.alloc(16);
this.buf.fill('\x01');
return this.User.bulkCreate([
{username: 'boo', intVal: 5, theDate: '2013-01-01 12:00'},
......@@ -261,7 +261,7 @@ describe(Support.getTestDialectTeaser('Model'), () => {
});
const buf1 = this.buf;
const buf2 = new Buffer(16);
const buf2 = Buffer.alloc(16);
buf2.fill('\x02');
User.belongsTo(Binary, { foreignKey: 'binary' });
......
......@@ -220,7 +220,7 @@ describe(Support.getTestDialectTeaser('Model'), () => {
});
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') {
expect(created).to.be.undefined;
} else {
......@@ -228,7 +228,7 @@ describe(Support.getTestDialectTeaser('Model'), () => {
}
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 => {
if (dialect === 'sqlite') {
expect(created).to.be.undefined;
......
......@@ -449,7 +449,7 @@ describe(Support.getTestDialectTeaser('Sequelize'), () => {
date = new Date(),
string = 't\'e"st',
boolean = true,
buffer = new Buffer('t\'e"st');
buffer = Buffer.from('t\'e"st');
date.setMilliseconds(0);
return this.sequelize.query({
......@@ -465,7 +465,7 @@ describe(Support.getTestDialectTeaser('Sequelize'), () => {
res.date = res.date && new Date(res.date);
res.boolean = res.boolean && true;
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({
number,
......
......@@ -11,7 +11,7 @@ const chai = require('chai'),
describe('connection manager', () => {
describe('_connect', () => {
beforeEach(function() {
this.sinon = sinon.sandbox.create();
this.sinon = sinon.createSandbox();
this.connection = {};
this.dialect = {
......
......@@ -17,7 +17,7 @@ if (dialect === 'mssql') {
describe('[MSSQL Specific] Query', () => {
describe('beginTransaction', () => {
beforeEach(() => {
sandbox = sinon.sandbox.create();
sandbox = sinon.createSandbox();
const options = {
transaction: { name: 'transactionName' },
isolationLevel: 'REPEATABLE_READ',
......
......@@ -413,7 +413,7 @@ if (dialect === 'mysql') {
context: QueryGenerator
}, {
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';",
context: QueryGenerator
}, {
......@@ -497,10 +497,10 @@ if (dialect === 'mysql') {
bind: ['foo', 1]
}
}, {
arguments: ['myTable', {data: new Buffer('Sequelize') }],
arguments: ['myTable', {data: Buffer.from('Sequelize') }],
expectation: {
query: 'INSERT INTO `myTable` (`data`) VALUES ($1);',
bind: [new Buffer('Sequelize')]
bind: [Buffer.from('Sequelize')]
}
}, {
arguments: ['myTable', {name: 'foo', foo: 1, nullValue: null}],
......
......@@ -475,7 +475,7 @@ if (dialect.startsWith('postgres')) {
expectation: "SELECT * FROM \"mySchema\".\"myTable\" WHERE \"mySchema\".\"myTable\".\"name\" = 'foo'';DROP TABLE mySchema.myTable;';"
}, {
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';",
context: QueryGenerator
}, {
......@@ -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()]
}
}, {
arguments: ['myTable', {data: new Buffer('Sequelize') }],
arguments: ['myTable', {data: Buffer.from('Sequelize') }],
expectation: {
query: 'INSERT INTO "myTable" ("data") VALUES ($1);',
bind: [new Buffer('Sequelize')]
bind: [Buffer.from('Sequelize')]
}
}, {
arguments: ['myTable', {name: 'foo', numbers: [1, 2, 3]}],
......
......@@ -343,7 +343,7 @@ if (dialect === 'sqlite') {
context: QueryGenerator
}, {
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';",
context: QueryGenerator
}, {
......@@ -383,10 +383,10 @@ if (dialect === 'sqlite') {
bind: ["'bar'"]
}
}, {
arguments: ['myTable', {data: new Buffer('Sequelize') }],
arguments: ['myTable', {data: Buffer.from('Sequelize') }],
expectation: {
query: 'INSERT INTO `myTable` (`data`) VALUES ($1);',
bind: [new Buffer('Sequelize')]
bind: [Buffer.from('Sequelize')]
}
}, {
arguments: ['myTable', { name: 'bar', value: null }],
......
......@@ -13,7 +13,7 @@ describe(Support.getTestDialectTeaser('Model'), () => {
const Model = current.define('Model', {});
beforeEach(function() {
this.sinon = sinon.sandbox.create();
this.sinon = sinon.createSandbox();
});
afterEach(function() {
......
......@@ -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');
});
});
......@@ -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');
});
});
......
......@@ -43,7 +43,7 @@ describe(Support.getTestDialectTeaser('Model'), () => {
});
beforeEach(function() {
this.sinon = sinon.sandbox.create();
this.sinon = sinon.createSandbox();
this.query = this.sinon.stub(current, 'query').returns(Promise.resolve());
this.stub = this.sinon.stub(current.getQueryInterface(), 'upsert').returns(Promise.resolve([true, undefined]));
......
......@@ -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
describe(Support.getTestDialectTeaser('SQL'), () => {
describe('DataTypes', () => {
const testsql = function(description, dataType, expectation) {
it(description, () => {
......@@ -1300,7 +1301,7 @@ describe(Support.getTestDialectTeaser('SQL'), () => {
const type = DataTypes.BLOB();
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'), () => {
});
describe('Buffer', () => {
testsql('field', new Buffer('Sequelize'), {
testsql('field', Buffer.from('Sequelize'), {
postgres: '"field" = E\'\\\\x53657175656c697a65\'',
sqlite: "`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!