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

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
......
......@@ -77,6 +77,162 @@ class Query extends AbstractQuery {
return ret;
}
_handleQueryResponse(metaData, columnTypes, benchmark, queryBegin, err, results) {
debug(`executed(${this.database.uuid || 'default'}) : ${this.sql}`);
if (benchmark) {
this.sequelize.log(`Executed (${this.database.uuid || 'default'}): ${this.sql}`, Date.now() - queryBegin, this.options);
}
if (err) {
err.sql = this.sql;
throw this.formatError(err);
}
let result = this.instance;
// add the inserted row id to the instance
if (this.isInsertQuery(results, metaData)) {
this.handleInsertQuery(results, metaData);
if (!this.instance) {
// handle bulkCreate AI primary key
if (
metaData.constructor.name === 'Statement'
&& this.model
&& this.model.autoIncrementAttribute
&& this.model.autoIncrementAttribute === this.model.primaryKeyAttribute
&& this.model.rawAttributes[this.model.primaryKeyAttribute]
) {
const startId = metaData[this.getInsertIdField()] - metaData.changes + 1;
result = [];
for (let i = startId; i < startId + metaData.changes; i++) {
result.push({ [this.model.rawAttributes[this.model.primaryKeyAttribute].field]: i });
}
} else {
result = metaData[this.getInsertIdField()];
}
}
}
if (this.isShowTablesQuery()) {
return results.map(row => row.name);
}
if (this.isShowConstraintsQuery()) {
result = results;
if (results && results[0] && results[0].sql) {
result = this.parseConstraintsFromSql(results[0].sql);
}
return result;
}
if (this.isSelectQuery()) {
if (this.options.raw) {
return this.handleSelectQuery(results);
}
// This is a map of prefix strings to models, e.g. user.projects -> Project model
const prefixes = this._collectModels(this.options.include);
results = results.map(result => {
return _.mapValues(result, (value, name) => {
let model;
if (name.includes('.')) {
const lastind = name.lastIndexOf('.');
model = prefixes[name.substr(0, lastind)];
name = name.substr(lastind + 1);
} else {
model = this.options.model;
}
const tableName = model.getTableName().toString().replace(/`/g, '');
const tableTypes = columnTypes[tableName] || {};
if (tableTypes && !(name in tableTypes)) {
// The column is aliased
_.forOwn(model.rawAttributes, (attribute, key) => {
if (name === key && attribute.field) {
name = attribute.field;
return false;
}
});
}
return tableTypes.hasOwnProperty(name)
? this.applyParsers(tableTypes[name], value)
: value;
});
});
return this.handleSelectQuery(results);
}
if (this.isShowOrDescribeQuery()) {
return results;
}
if (this.sql.includes('PRAGMA INDEX_LIST')) {
return this.handleShowIndexesQuery(results);
}
if (this.sql.includes('PRAGMA INDEX_INFO')) {
return results;
}
if (this.sql.includes('PRAGMA TABLE_INFO')) {
// this is the sqlite way of getting the metadata of a table
result = {};
let defaultValue;
for (const _result of results) {
if (_result.dflt_value === null) {
// Column schema omits any "DEFAULT ..."
defaultValue = undefined;
} else if (_result.dflt_value === 'NULL') {
// Column schema is a "DEFAULT NULL"
defaultValue = null;
} else {
defaultValue = _result.dflt_value;
}
result[_result.name] = {
type: _result.type,
allowNull: _result.notnull === 0,
defaultValue,
primaryKey: _result.pk !== 0
};
if (result[_result.name].type === 'TINYINT(1)') {
result[_result.name].defaultValue = { '0': false, '1': true }[result[_result.name].defaultValue];
}
if (typeof result[_result.name].defaultValue === 'string') {
result[_result.name].defaultValue = result[_result.name].defaultValue.replace(/'/g, '');
}
}
return result;
}
if (this.sql.includes('PRAGMA foreign_keys;')) {
return results[0];
}
if (this.sql.includes('PRAGMA foreign_keys')) {
return results;
}
if (this.sql.includes('PRAGMA foreign_key_list')) {
return results;
}
if ([QueryTypes.BULKUPDATE, QueryTypes.BULKDELETE].includes(this.options.type)) {
return metaData.changes;
}
if (this.options.type === QueryTypes.UPSERT) {
return undefined;
}
if (this.options.type === QueryTypes.VERSION) {
return results[0].version;
}
if (this.options.type === QueryTypes.RAW) {
return [results, metaData];
}
if (this.isUpdateQuery() || this.isInsertQuery()) {
return [result, metaData.changes];
}
return result;
}
run(sql, parameters) {
this.sql = sql;
const method = this.getDatabaseMethod();
......@@ -104,162 +260,28 @@ class Query extends AbstractQuery {
const executeSql = () => {
if (this.sql.startsWith('-- ')) {
return resolve();
} else {
resolve(new Promise((resolve, reject) => {
const query = this;
// cannot use arrow function here because the function is bound to the statement
function afterExecute(err, results) {
debug(`executed(${query.database.uuid || 'default'}) : ${query.sql}`);
if (benchmark) {
query.sequelize.log(`Executed (${query.database.uuid || 'default'}): ${query.sql}`, Date.now() - queryBegin, query.options);
}
if (err) {
err.sql = query.sql;
reject(query.formatError(err));
} else {
const metaData = this;
let result = query.instance;
// add the inserted row id to the instance
if (query.isInsertQuery(results, metaData)) {
query.handleInsertQuery(results, metaData);
if (!query.instance) {
// handle bulkCreate AI primary key
if (
metaData.constructor.name === 'Statement'
&& query.model
&& query.model.autoIncrementAttribute
&& query.model.autoIncrementAttribute === query.model.primaryKeyAttribute
&& query.model.rawAttributes[query.model.primaryKeyAttribute]
) {
const startId = metaData[query.getInsertIdField()] - metaData.changes + 1;
result = [];
for (let i = startId; i < startId + metaData.changes; i++) {
result.push({ [query.model.rawAttributes[query.model.primaryKeyAttribute].field]: i });
}
} else {
result = metaData[query.getInsertIdField()];
}
}
}
if (query.isShowTablesQuery()) {
result = results.map(row => row.name);
} else if (query.isShowConstraintsQuery()) {
result = results;
if (results && results[0] && results[0].sql) {
result = query.parseConstraintsFromSql(results[0].sql);
}
} else if (query.isSelectQuery()) {
if (!query.options.raw) {
// This is a map of prefix strings to models, e.g. user.projects -> Project model
const prefixes = query._collectModels(query.options.include);
results = results.map(result => {
return _.mapValues(result, (value, name) => {
let model;
if (name.includes('.')) {
const lastind = name.lastIndexOf('.');
model = prefixes[name.substr(0, lastind)];
name = name.substr(lastind + 1);
} else {
model = query.options.model;
}
const tableName = model.getTableName().toString().replace(/`/g, '');
const tableTypes = columnTypes[tableName] || {};
if (tableTypes && !(name in tableTypes)) {
// The column is aliased
_.forOwn(model.rawAttributes, (attribute, key) => {
if (name === key && attribute.field) {
name = attribute.field;
return false;
}
});
}
return tableTypes.hasOwnProperty(name)
? query.applyParsers(tableTypes[name], value)
: value;
});
});
}
result = query.handleSelectQuery(results);
} else if (query.isShowOrDescribeQuery()) {
result = results;
} else if (query.sql.includes('PRAGMA INDEX_LIST')) {
result = query.handleShowIndexesQuery(results);
} else if (query.sql.includes('PRAGMA INDEX_INFO')) {
result = results;
} else if (query.sql.includes('PRAGMA TABLE_INFO')) {
// this is the sqlite way of getting the metadata of a table
result = {};
let defaultValue;
for (const _result of results) {
if (_result.dflt_value === null) {
// Column schema omits any "DEFAULT ..."
defaultValue = undefined;
} else if (_result.dflt_value === 'NULL') {
// Column schema is a "DEFAULT NULL"
defaultValue = null;
} else {
defaultValue = _result.dflt_value;
}
result[_result.name] = {
type: _result.type,
allowNull: _result.notnull === 0,
defaultValue,
primaryKey: _result.pk !== 0
};
if (result[_result.name].type === 'TINYINT(1)') {
result[_result.name].defaultValue = { '0': false, '1': true }[result[_result.name].defaultValue];
}
if (typeof result[_result.name].defaultValue === 'string') {
result[_result.name].defaultValue = result[_result.name].defaultValue.replace(/'/g, '');
}
}
} else if (query.sql.includes('PRAGMA foreign_keys;')) {
result = results[0];
} else if (query.sql.includes('PRAGMA foreign_keys')) {
result = results;
} else if (query.sql.includes('PRAGMA foreign_key_list')) {
result = results;
} else if ([QueryTypes.BULKUPDATE, QueryTypes.BULKDELETE].includes(query.options.type)) {
result = metaData.changes;
} else if (query.options.type === QueryTypes.UPSERT) {
result = undefined;
} else if (query.options.type === QueryTypes.VERSION) {
result = results[0].version;
} else if (query.options.type === QueryTypes.RAW) {
result = [results, metaData];
} else if (query.isUpdateQuery() || query.isInsertQuery()) {
result = [result, metaData.changes];
}
resolve(result);
}
}
resolve(new Promise((resolve, reject) => {
const query = this;
// cannot use arrow function here because the function is bound to the statement
function afterExecute(executionError, results) {
try {
resolve(query._handleQueryResponse(this, columnTypes, benchmark, queryBegin, executionError, results));
return;
} catch (error) {
reject(error);
}
}
if (method === 'exec') {
// exec does not support bind parameter
this.database[method](this.sql, afterExecute);
} else {
if (!parameters) parameters = [];
this.database[method](this.sql, parameters, afterExecute);
}
}));
return null;
}
if (method === 'exec') {
// exec does not support bind parameter
this.database[method](this.sql, afterExecute);
} else {
if (!parameters) parameters = [];
this.database[method](this.sql, parameters, afterExecute);
}
}));
return null;
};
if (this.getDatabaseMethod() === 'all') {
......@@ -275,26 +297,24 @@ class Query extends AbstractQuery {
if (!tableNames.length) {
return executeSql();
} else {
return Promise.map(tableNames, tableName =>
new Promise(resolve => {
tableName = tableName.replace(/`/g, '');
columnTypes[tableName] = {};
this.database.all(`PRAGMA table_info(\`${tableName}\`)`, (err, results) => {
if (!err) {
for (const result of results) {
columnTypes[tableName][result.name] = result.type;
}
}
resolve();
});
})
).then(executeSql);
}
} else {
return executeSql();
return Promise.map(tableNames, tableName =>
new Promise(resolve => {
tableName = tableName.replace(/`/g, '');
columnTypes[tableName] = {};
this.database.all(`PRAGMA table_info(\`${tableName}\`)`, (err, results) => {
if (!err) {
for (const result of results) {
columnTypes[tableName][result.name] = result.type;
}
}
resolve();
});
})
).then(executeSql);
}
return executeSql();
});
});
}
......@@ -446,11 +466,11 @@ class Query extends AbstractQuery {
getDatabaseMethod() {
if (this.isUpsertQuery()) {
return 'exec'; // Needed to run multiple queries in one
} else if (this.isInsertQuery() || this.isUpdateQuery() || this.isBulkUpdateQuery() || this.sql.toLowerCase().includes('CREATE TEMPORARY TABLE'.toLowerCase()) || this.options.type === QueryTypes.BULKDELETE) {
}
if (this.isInsertQuery() || this.isUpdateQuery() || this.isBulkUpdateQuery() || this.sql.toLowerCase().includes('CREATE TEMPORARY TABLE'.toLowerCase()) || this.options.type === QueryTypes.BULKDELETE) {
return 'run';
} else {
return 'all';
}
return 'all';
}
}
......
......@@ -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 = {
......
......@@ -338,10 +338,12 @@ class Model {
model = include.target;
}
include = { model, association: include, as: include.as };
} else if (include.prototype && include.prototype instanceof Model) {
include = { model: include };
} else if (_.isPlainObject(include)) {
return { model, association: include, as: include.as };
}
if (include.prototype && include.prototype instanceof Model) {
return { model: include };
}
if (_.isPlainObject(include)) {
if (include.association) {
include.association = this._transformStringAssociation(include.association, self);
......@@ -363,11 +365,9 @@ class Model {
}
this._conformOptions(include, model);
} else {
throw new Error('Include unexpected. Element has to be either a Model, an Association or an object.');
return include;
}
return include;
throw new Error('Include unexpected. Element has to be either a Model, an Association or an object.');
}
static _expandIncludeAllElement(includes, include) {
......@@ -694,24 +694,24 @@ class Model {
let association = null;
if (associations.length === 0) {
throw new sequelizeErrors.EagerLoadingError(`${targetModel.name} is not associated to ${this.name}!`);
} else if (associations.length === 1) {
}
if (associations.length === 1) {
association = this.getAssociationForAlias(targetModel, targetAlias);
if (!association) {
if (targetAlias) {
const existingAliases = this.getAssociations(targetModel).map(association => association.as);
throw new sequelizeErrors.EagerLoadingError(`${targetModel.name} is associated to ${this.name} using an alias. ` +
`You've included an alias (${targetAlias}), but it does not match the alias(es) defined in your association (${existingAliases.join(', ')}).`);
} else {
throw new sequelizeErrors.EagerLoadingError(`${targetModel.name} is associated to ${this.name} using an alias. ` +
'You must use the \'as\' keyword to specify the alias within your include statement.');
}
if (association) {
return association;
}
} else {
association = this.getAssociationForAlias(targetModel, targetAlias);
if (!association) {
throw new sequelizeErrors.EagerLoadingError(`${targetModel.name} is associated to ${this.name} multiple times. ` +
'To identify the correct association, you must use the \'as\' keyword to specify the alias of the association you want to include.');
if (targetAlias) {
const existingAliases = this.getAssociations(targetModel).map(association => association.as);
throw new sequelizeErrors.EagerLoadingError(`${targetModel.name} is associated to ${this.name} using an alias. ` +
`You've included an alias (${targetAlias}), but it does not match the alias(es) defined in your association (${existingAliases.join(', ')}).`);
}
throw new sequelizeErrors.EagerLoadingError(`${targetModel.name} is associated to ${this.name} using an alias. ` +
'You must use the \'as\' keyword to specify the alias within your include statement.');
}
association = this.getAssociationForAlias(targetModel, targetAlias);
if (!association) {
throw new sequelizeErrors.EagerLoadingError(`${targetModel.name} is associated to ${this.name} multiple times. ` +
'To identify the correct association, you must use the \'as\' keyword to specify the alias of the association you want to include.');
}
return association;
}
......@@ -777,7 +777,8 @@ class Model {
static _mergeFunction(objValue, srcValue, key) {
if (Array.isArray(objValue) && Array.isArray(srcValue)) {
return _.union(objValue, srcValue);
} else if (key === 'where') {
}
if (key === 'where') {
if (srcValue instanceof Utils.SequelizeMethod) {
srcValue = { [Op.and]: srcValue };
}
......@@ -1040,7 +1041,7 @@ class Model {
this.prototype._customGetters = {};
this.prototype._customSetters = {};
_.each(['get', 'set'], type => {
['get', 'set'].forEach(type => {
const opt = `${type}terMethods`;
const funcs = _.clone(_.isObject(this.options[opt]) ? this.options[opt] : {});
const _custom = type === 'get' ? this.prototype._customGetters : this.prototype._customSetters;
......@@ -1289,56 +1290,57 @@ class Model {
})
.then(() => this.QueryInterface.createTable(this.getTableName(options), attributes, options, this))
.then(() => {
if (options.alter) {
return Promise.all([
this.QueryInterface.describeTable(this.getTableName(options)),
this.QueryInterface.getForeignKeyReferencesForTable(this.getTableName(options))
])
.then(tableInfos => {
const columns = tableInfos[0];
// Use for alter foreign keys
const foreignKeyReferences = tableInfos[1];
const changes = []; // array of promises to run
const removedConstraints = {};
_.each(attributes, (columnDesc, columnName) => {
if (!columns[columnName]) {
changes.push(() => this.QueryInterface.addColumn(this.getTableName(options), attributes[columnName].field || columnName, attributes[columnName]));
}
});
_.each(columns, (columnDesc, columnName) => {
const currentAttribute = rawAttributes[columnName];
if (!currentAttribute) {
changes.push(() => this.QueryInterface.removeColumn(this.getTableName(options), columnName, options));
} else if (!currentAttribute.primaryKey) {
// Check foreign keys. If it's a foreign key, it should remove constraint first.
const references = currentAttribute.references;
if (currentAttribute.references) {
const database = this.sequelize.config.database;
const schema = this.sequelize.config.schema;
// Find existed foreign keys
_.each(foreignKeyReferences, foreignKeyReference => {
const constraintName = foreignKeyReference.constraintName;
if (!!constraintName
&& foreignKeyReference.tableCatalog === database
&& (schema ? foreignKeyReference.tableSchema === schema : true)
&& foreignKeyReference.referencedTableName === references.model
&& foreignKeyReference.referencedColumnName === references.key
&& (schema ? foreignKeyReference.referencedTableSchema === schema : true)
&& !removedConstraints[constraintName]) {
// Remove constraint on foreign keys.
changes.push(() => this.QueryInterface.removeConstraint(this.getTableName(options), constraintName, options));
removedConstraints[constraintName] = true;
}
});
}
changes.push(() => this.QueryInterface.changeColumn(this.getTableName(options), columnName, currentAttribute));
if (!options.alter) {
return;
}
return Promise.all([
this.QueryInterface.describeTable(this.getTableName(options)),
this.QueryInterface.getForeignKeyReferencesForTable(this.getTableName(options))
])
.then(tableInfos => {
const columns = tableInfos[0];
// Use for alter foreign keys
const foreignKeyReferences = tableInfos[1];
const changes = []; // array of promises to run
const removedConstraints = {};
_.each(attributes, (columnDesc, columnName) => {
if (!columns[columnName]) {
changes.push(() => this.QueryInterface.addColumn(this.getTableName(options), attributes[columnName].field || columnName, attributes[columnName]));
}
});
_.each(columns, (columnDesc, columnName) => {
const currentAttribute = rawAttributes[columnName];
if (!currentAttribute) {
changes.push(() => this.QueryInterface.removeColumn(this.getTableName(options), columnName, options));
} else if (!currentAttribute.primaryKey) {
// Check foreign keys. If it's a foreign key, it should remove constraint first.
const references = currentAttribute.references;
if (currentAttribute.references) {
const database = this.sequelize.config.database;
const schema = this.sequelize.config.schema;
// Find existed foreign keys
_.each(foreignKeyReferences, foreignKeyReference => {
const constraintName = foreignKeyReference.constraintName;
if (!!constraintName
&& foreignKeyReference.tableCatalog === database
&& (schema ? foreignKeyReference.tableSchema === schema : true)
&& foreignKeyReference.referencedTableName === references.model
&& foreignKeyReference.referencedColumnName === references.key
&& (schema ? foreignKeyReference.referencedTableSchema === schema : true)
&& !removedConstraints[constraintName]) {
// Remove constraint on foreign keys.
changes.push(() => this.QueryInterface.removeConstraint(this.getTableName(options), constraintName, options));
removedConstraints[constraintName] = true;
}
});
}
});
return changes.reduce((p, fn) => p.then(fn), Promise.resolve());
changes.push(() => this.QueryInterface.changeColumn(this.getTableName(options), columnName, currentAttribute));
}
});
}
return changes.reduce((p, fn) => p.then(fn), Promise.resolve());
});
})
.then(() => this.QueryInterface.showIndex(this.getTableName(options), options))
.then(indexes => {
......@@ -1760,11 +1762,11 @@ class Model {
if (_.isEmpty(results) && options.rejectOnEmpty) {
if (typeof options.rejectOnEmpty === 'function') {
throw new options.rejectOnEmpty();
} else if (typeof options.rejectOnEmpty === 'object') {
}
if (typeof options.rejectOnEmpty === 'object') {
throw options.rejectOnEmpty;
} else {
throw new sequelizeErrors.EmptyResultError();
}
throw new sequelizeErrors.EmptyResultError();
}
return Model._findSeparate(results, originalOptions);
......@@ -2605,7 +2607,11 @@ class Model {
instance.dataValues = Utils.mapValueFieldNames(values, options.fields, this);
return _.omit(instance.dataValues, this._virtualAttributes);
const out = Object.assign({}, instance.dataValues);
for (const key of this._virtualAttributes) {
delete out[key];
}
return out;
});
// Map attributes to fields for serial identification
......@@ -2987,20 +2993,19 @@ class Model {
options.fields = _.union(options.fields, keys);
}
return;
} else {
// Hooks change values in a different way for each record
// Do not run original query but save each record individually
return Promise.map(instances, instance => {
const individualOptions = _.clone(options);
delete individualOptions.individualHooks;
individualOptions.hooks = false;
individualOptions.validate = false;
return instance.save(individualOptions);
}).tap(_instances => {
instances = _instances;
});
}
// Hooks change values in a different way for each record
// Do not run original query but save each record individually
return Promise.map(instances, instance => {
const individualOptions = _.clone(options);
delete individualOptions.individualHooks;
individualOptions.hooks = false;
individualOptions.validate = false;
return instance.save(individualOptions);
}).tap(_instances => {
instances = _instances;
});
});
});
}
......@@ -3300,11 +3305,11 @@ class Model {
if (options.plain && this._options.include && this._options.includeNames.includes(key)) {
if (Array.isArray(this.dataValues[key])) {
return this.dataValues[key].map(instance => instance.get(options));
} else if (this.dataValues[key] instanceof Model) {
}
if (this.dataValues[key] instanceof Model) {
return this.dataValues[key].get(options);
} else {
return this.dataValues[key];
}
return this.dataValues[key];
}
return this.dataValues[key];
......@@ -3387,7 +3392,7 @@ class Model {
}
// If raw, and we're not dealing with includes or special attributes, just set it straight on the dataValues object
if (options.raw && !(this._options && this._options.include) && !(options && options.attributes) && !this.constructor._hasBooleanAttributes && !this.constructor._hasDateAttributes) {
if (options.raw && !(this._options && this._options.include) && !(options && options.attributes) && !this.constructor._hasDateAttributes && !this.constructor._hasBooleanAttributes) {
if (Object.keys(this.dataValues).length) {
this.dataValues = Object.assign(this.dataValues, values);
} else {
......@@ -3407,10 +3412,11 @@ class Model {
keys = keys.concat(this._options.includeNames);
}
for (let i = 0, length = keys.length; i < length; i++) {
if (values[keys[i]] !== undefined) {
this.set(keys[i], values[keys[i]], options);
for (const k of keys) {
if (values[k] === undefined) {
continue;
}
this.set(k, values[k], options);
}
} else {
for (const key in values) {
......@@ -3423,80 +3429,79 @@ class Model {
this._previousDataValues = _.clone(this.dataValues);
}
}
return this;
}
if (!options)
options = {};
if (!options.raw) {
originalValue = this.dataValues[key];
}
// If not raw, and there's a custom setter
if (!options.raw && this._customSetters[key]) {
this._customSetters[key].call(this, value, key);
// custom setter should have changed value, get that changed value
// TODO: v5 make setters return new value instead of changing internal store
const newValue = this.dataValues[key];
if (!Utils.isPrimitive(newValue) && newValue !== null || newValue !== originalValue) {
this._previousDataValues[key] = originalValue;
this.changed(key, true);
}
} else {
if (!options)
options = {};
// Check if we have included models, and if this key matches the include model names/aliases
if (this._options && this._options.include && this._options.includeNames.includes(key)) {
// Pass it on to the include handler
this._setInclude(key, value, options);
return this;
}
// Bunch of stuff we won't do when it's raw
if (!options.raw) {
originalValue = this.dataValues[key];
}
// If not raw, and there's a custom setter
if (!options.raw && this._customSetters[key]) {
this._customSetters[key].call(this, value, key);
// custom setter should have changed value, get that changed value
// TODO: v5 make setters return new value instead of changing internal store
const newValue = this.dataValues[key];
if (!Utils.isPrimitive(newValue) && newValue !== null || newValue !== originalValue) {
this._previousDataValues[key] = originalValue;
this.changed(key, true);
}
} else {
// Check if we have included models, and if this key matches the include model names/aliases
if (this._options && this._options.include && this._options.includeNames.includes(key)) {
// Pass it on to the include handler
this._setInclude(key, value, options);
return this;
} else {
// Bunch of stuff we won't do when it's raw
if (!options.raw) {
// If attribute is not in model definition, return
if (!this._isAttribute(key)) {
if (key.includes('.') && this.constructor._isJsonAttribute(key.split('.')[0])) {
const previousNestedValue = Dottie.get(this.dataValues, key);
if (!_.isEqual(previousNestedValue, value)) {
Dottie.set(this.dataValues, key, value);
this.changed(key.split('.')[0], true);
}
}
return this;
}
// If attempting to set primary key and primary key is already defined, return
if (this.constructor._hasPrimaryKeys && originalValue && this.constructor._isPrimaryKey(key)) {
return this;
}
// If attempting to set read only attributes, return
if (!this.isNewRecord && this.constructor._hasReadOnlyAttributes && this.constructor._isReadOnlyAttribute(key)) {
return this;
// If attribute is not in model definition, return
if (!this._isAttribute(key)) {
if (key.includes('.') && this.constructor._isJsonAttribute(key.split('.')[0])) {
const previousNestedValue = Dottie.get(this.dataValues, key);
if (!_.isEqual(previousNestedValue, value)) {
Dottie.set(this.dataValues, key, value);
this.changed(key.split('.')[0], true);
}
}
return this;
}
// If there's a data type sanitizer
if (!(value instanceof Utils.SequelizeMethod) && this.constructor._dataTypeSanitizers.hasOwnProperty(key)) {
value = this.constructor._dataTypeSanitizers[key].call(this, value, options);
}
// Set when the value has changed and not raw
if (
!options.raw &&
(
// True when sequelize method
value instanceof Utils.SequelizeMethod ||
// Check for data type type comparators
!(value instanceof Utils.SequelizeMethod) && this.constructor._dataTypeChanges[key] && this.constructor._dataTypeChanges[key].call(this, value, originalValue, options) ||
// Check default
!this.constructor._dataTypeChanges[key] && (!Utils.isPrimitive(value) && value !== null || value !== originalValue)
)
) {
this._previousDataValues[key] = originalValue;
this.changed(key, true);
}
// If attempting to set primary key and primary key is already defined, return
if (this.constructor._hasPrimaryKeys && originalValue && this.constructor._isPrimaryKey(key)) {
return this;
}
// set data value
this.dataValues[key] = value;
// If attempting to set read only attributes, return
if (!this.isNewRecord && this.constructor._hasReadOnlyAttributes && this.constructor._isReadOnlyAttribute(key)) {
return this;
}
}
// If there's a data type sanitizer
if (!(value instanceof Utils.SequelizeMethod) && this.constructor._dataTypeSanitizers.hasOwnProperty(key)) {
value = this.constructor._dataTypeSanitizers[key].call(this, value, options);
}
// Set when the value has changed and not raw
if (
!options.raw &&
(
// True when sequelize method
value instanceof Utils.SequelizeMethod ||
// Check for data type type comparators
!(value instanceof Utils.SequelizeMethod) && this.constructor._dataTypeChanges[key] && this.constructor._dataTypeChanges[key].call(this, value, originalValue, options) ||
// Check default
!this.constructor._dataTypeChanges[key] && (!Utils.isPrimitive(value) && value !== null || value !== originalValue)
)
) {
this._previousDataValues[key] = originalValue;
this.changed(key, true);
}
// set data value
this.dataValues[key] = value;
}
return this;
}
......@@ -4006,9 +4011,8 @@ class Model {
}
return results;
});
} else {
return this.constructor.QueryInterface.delete(this, this.constructor.getTableName(options), where, Object.assign({ type: QueryTypes.DELETE, limit: null }, options));
}
return this.constructor.QueryInterface.delete(this, this.constructor.getTableName(options), where, Object.assign({ type: QueryTypes.DELETE, limit: null }, options));
}).tap(() => {
// Run after hook
if (options.hooks) {
......
......@@ -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!