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

Commit bb874f5e by Sushant Committed by GitHub

refactor: logging & utils (#9665)

1 parent b00148e0
...@@ -3,7 +3,6 @@ ...@@ -3,7 +3,6 @@
const Utils = require('./../utils'); const Utils = require('./../utils');
const Helpers = require('./helpers'); const Helpers = require('./helpers');
const _ = require('lodash'); const _ = require('lodash');
const Transaction = require('../transaction');
const Association = require('./base'); const Association = require('./base');
const Op = require('../operators'); const Op = require('../operators');
...@@ -221,16 +220,11 @@ class BelongsTo extends Association { ...@@ -221,16 +220,11 @@ class BelongsTo extends Association {
* *
* @return {Promise} * @return {Promise}
*/ */
create(sourceInstance, values, fieldsOrOptions) { create(sourceInstance, values, options) {
const options = {}; values = values || {};
options = options || {};
options.logging = (fieldsOrOptions || {}).logging; return this.target.create(values, options)
if ((fieldsOrOptions || {}).transaction instanceof Transaction) {
options.transaction = fieldsOrOptions.transaction;
}
return this.target.create(values, fieldsOrOptions)
.then(newAssociatedObject => .then(newAssociatedObject =>
sourceInstance[this.accessors.set](newAssociatedObject, options) sourceInstance[this.accessors.set](newAssociatedObject, options)
); );
......
'use strict'; 'use strict';
const Association = require('./base'); const Association = require('./base');
Association.BelongsTo = require('./belongs-to'); Association.BelongsTo = require('./belongs-to');
Association.HasOne = require('./has-one'); Association.HasOne = require('./has-one');
Association.HasMany = require('./has-many'); Association.HasMany = require('./has-many');
......
...@@ -9,7 +9,7 @@ const warnings = {}; ...@@ -9,7 +9,7 @@ const warnings = {};
const Validator = require('./utils/validator-extras').validator; const Validator = require('./utils/validator-extras').validator;
const momentTz = require('moment-timezone'); const momentTz = require('moment-timezone');
const moment = require('moment'); const moment = require('moment');
const Utils = require('./utils'); const logger = require('./utils/logger');
function ABSTRACT() {} function ABSTRACT() {}
...@@ -24,7 +24,7 @@ ABSTRACT.prototype.toSql = function toSql() { ...@@ -24,7 +24,7 @@ ABSTRACT.prototype.toSql = function toSql() {
ABSTRACT.warn = function warn(link, text) { ABSTRACT.warn = function warn(link, text) {
if (!warnings[text]) { if (!warnings[text]) {
warnings[text] = true; warnings[text] = true;
Utils.warn(`${text}, '\n>> Check:', ${link}`); logger.warn(`${text}, '\n>> Check:', ${link}`);
} }
}; };
ABSTRACT.prototype.stringify = function stringify(value, options) { ABSTRACT.prototype.stringify = function stringify(value, options) {
...@@ -701,14 +701,6 @@ ARRAY.is = function is(obj, type) { ...@@ -701,14 +701,6 @@ ARRAY.is = function is(obj, type) {
return obj instanceof ARRAY && obj.type instanceof type; return obj instanceof ARRAY && obj.type instanceof type;
}; };
const helpers = {
BINARY: [STRING, CHAR],
UNSIGNED: [NUMBER, TINYINT, SMALLINT, MEDIUMINT, INTEGER, BIGINT, FLOAT, DOUBLE, REAL, DECIMAL],
ZEROFILL: [NUMBER, TINYINT, SMALLINT, MEDIUMINT, INTEGER, BIGINT, FLOAT, DOUBLE, REAL, DECIMAL],
PRECISION: [DECIMAL],
SCALE: [DECIMAL]
};
function GEOMETRY(type, srid) { function GEOMETRY(type, srid) {
const options = _.isPlainObject(type) ? type : {type, srid}; const options = _.isPlainObject(type) ? type : {type, srid};
...@@ -796,6 +788,14 @@ MACADDR.prototype.validate = function validate(value) { ...@@ -796,6 +788,14 @@ MACADDR.prototype.validate = function validate(value) {
return true; return true;
}; };
const helpers = {
BINARY: [STRING, CHAR],
UNSIGNED: [NUMBER, TINYINT, SMALLINT, MEDIUMINT, INTEGER, BIGINT, FLOAT, DOUBLE, REAL, DECIMAL],
ZEROFILL: [NUMBER, TINYINT, SMALLINT, MEDIUMINT, INTEGER, BIGINT, FLOAT, DOUBLE, REAL, DECIMAL],
PRECISION: [DECIMAL],
SCALE: [DECIMAL]
};
for (const helper of Object.keys(helpers)) { for (const helper of Object.keys(helpers)) {
for (const DataType of helpers[helper]) { for (const DataType of helpers[helper]) {
if (!DataType[helper]) { if (!DataType[helper]) {
......
'use strict'; 'use strict';
const Pooling = require('generic-pool'); const Pooling = require('generic-pool');
const Promise = require('../../promise');
const _ = require('lodash'); const _ = require('lodash');
const Utils = require('../../utils');
const debug = Utils.getLogger().debugContext('pool');
const semver = require('semver'); const semver = require('semver');
const Promise = require('../../promise');
const logger = require('../../utils/logger');
const debug = logger.getLogger().debugContext('pool');
const defaultPoolingConfig = { const defaultPoolingConfig = {
max: 5, max: 5,
......
...@@ -7,6 +7,7 @@ const uuidv4 = require('uuid/v4'); ...@@ -7,6 +7,7 @@ const uuidv4 = require('uuid/v4');
const semver = require('semver'); const semver = require('semver');
const Utils = require('../../utils'); const Utils = require('../../utils');
const logger = require('../../utils/logger');
const SqlString = require('../../sql-string'); const SqlString = require('../../sql-string');
const DataTypes = require('../../data-types'); const DataTypes = require('../../data-types');
const Model = require('../../model'); const Model = require('../../model');
...@@ -1422,7 +1423,7 @@ class QueryGenerator { ...@@ -1422,7 +1423,7 @@ class QueryGenerator {
} else if (attr[0].indexOf('(') === -1 && attr[0].indexOf(')') === -1) { } else if (attr[0].indexOf('(') === -1 && attr[0].indexOf(')') === -1) {
attr[0] = this.quoteIdentifier(attr[0]); attr[0] = this.quoteIdentifier(attr[0]);
} else { } else {
Utils.deprecate('Use sequelize.fn / sequelize.literal to construct attributes'); logger.deprecate('Use sequelize.fn / sequelize.literal to construct attributes');
} }
attr = [attr[0], this.quoteIdentifier(attr[1])].join(' AS '); attr = [attr[0], this.quoteIdentifier(attr[1])].join(' AS ');
} else { } else {
......
'use strict'; 'use strict';
const _ = require('lodash'); const _ = require('lodash');
const Utils = require('../../utils'); const logger = require('../../utils/logger');
const SqlString = require('../../sql-string'); const SqlString = require('../../sql-string');
const Dot = require('dottie'); const Dot = require('dottie');
const QueryTypes = require('../../query-types'); const QueryTypes = require('../../query-types');
...@@ -110,7 +110,7 @@ class AbstractQuery { ...@@ -110,7 +110,7 @@ class AbstractQuery {
*/ */
checkLoggingOption() { checkLoggingOption() {
if (this.options.logging === true) { if (this.options.logging === true) {
Utils.deprecate('The logging-option should be either a function or false. Default: console.log'); logger.deprecate('The logging-option should be either a function or false. Default: console.log');
this.options.logging = console.log; this.options.logging = console.log;
} }
} }
...@@ -238,7 +238,7 @@ class AbstractQuery { ...@@ -238,7 +238,7 @@ class AbstractQuery {
return result; return result;
}, result)); }, result));
} }
// Raw queries // Raw queries
if (this.options.raw) { if (this.options.raw) {
result = results.map(result => { result = results.map(result => {
......
...@@ -3,12 +3,12 @@ ...@@ -3,12 +3,12 @@
const AbstractConnectionManager = require('../abstract/connection-manager'); const AbstractConnectionManager = require('../abstract/connection-manager');
const ResourceLock = require('./resource-lock'); const ResourceLock = require('./resource-lock');
const Promise = require('../../promise'); const Promise = require('../../promise');
const Utils = require('../../utils'); const logger = require('../../utils/logger');
const debug = Utils.getLogger().debugContext('connection:mssql');
const debugTedious = Utils.getLogger().debugContext('connection:mssql:tedious');
const sequelizeErrors = require('../../errors'); const sequelizeErrors = require('../../errors');
const DataTypes = require('../../data-types').mssql; const DataTypes = require('../../data-types').mssql;
const parserStore = require('../parserStore')('mssql'); const parserStore = require('../parserStore')('mssql');
const debug = logger.getLogger().debugContext('connection:mssql');
const debugTedious = logger.getLogger().debugContext('connection:mssql:tedious');
class ConnectionManager extends AbstractConnectionManager { class ConnectionManager extends AbstractConnectionManager {
constructor(dialect, sequelize) { constructor(dialect, sequelize) {
......
'use strict'; 'use strict';
const Utils = require('../../utils'); const logger = require('../../utils/logger');
const debug = Utils.getLogger().debugContext('sql:mssql');
const Promise = require('../../promise'); const Promise = require('../../promise');
const AbstractQuery = require('../abstract/query'); const AbstractQuery = require('../abstract/query');
const sequelizeErrors = require('../../errors'); const sequelizeErrors = require('../../errors');
const parserStore = require('../parserStore')('mssql'); const parserStore = require('../parserStore')('mssql');
const _ = require('lodash'); const _ = require('lodash');
const TYPES = require('tedious').TYPES; const debug = logger.getLogger().debugContext('sql:mssql');
class Query extends AbstractQuery { class Query extends AbstractQuery {
constructor(connection, sequelize, options) { constructor(connection, sequelize, options) {
...@@ -29,7 +28,7 @@ class Query extends AbstractQuery { ...@@ -29,7 +28,7 @@ class Query extends AbstractQuery {
return 'id'; return 'id';
} }
getSQLTypeFromJsType(value) { getSQLTypeFromJsType(value, TYPES) {
const paramType = {type: TYPES.VarChar, typeOptions: {} }; const paramType = {type: TYPES.VarChar, typeOptions: {} };
paramType.type = TYPES.NVarChar; paramType.type = TYPES.NVarChar;
if (typeof value === 'number') { if (typeof value === 'number') {
...@@ -70,7 +69,7 @@ class Query extends AbstractQuery { ...@@ -70,7 +69,7 @@ class Query extends AbstractQuery {
} else { } else {
resolve(this.formatResults()); resolve(this.formatResults());
} }
}, this.options.transaction.name, Utils.mapIsolationLevelStringToTedious(this.options.isolationLevel, connection.lib)); }, this.options.transaction.name, connection.lib.ISOLATION_LEVEL[this.options.isolationLevel]);
} else if (_.startsWith(this.sql, 'COMMIT TRANSACTION')) { } else if (_.startsWith(this.sql, 'COMMIT TRANSACTION')) {
connection.commitTransaction(err => { connection.commitTransaction(err => {
if (err) { if (err) {
...@@ -115,7 +114,7 @@ class Query extends AbstractQuery { ...@@ -115,7 +114,7 @@ class Query extends AbstractQuery {
if (parameters) { if (parameters) {
_.forOwn(parameters, (value, key) => { _.forOwn(parameters, (value, key) => {
const paramType = this.getSQLTypeFromJsType(value); const paramType = this.getSQLTypeFromJsType(value, connection.lib.TYPES);
request.addParameter(key, paramType.type, value, paramType.typeOptions); request.addParameter(key, paramType.type, value, paramType.typeOptions);
}); });
} }
...@@ -263,7 +262,7 @@ class Query extends AbstractQuery { ...@@ -263,7 +262,7 @@ class Query extends AbstractQuery {
formatError(err) { formatError(err) {
let match; let match;
match = err.message.match(/Violation of (?:UNIQUE|PRIMARY) KEY constraint '((.|\s)*)'. Cannot insert duplicate key in object '.*'.(:? The duplicate key value is \((.*)\).)?/); match = err.message.match(/Violation of (?:UNIQUE|PRIMARY) KEY constraint '((.|\s)*)'. Cannot insert duplicate key in object '.*'.(:? The duplicate key value is \((.*)\).)?/);
match = match || err.message.match(/Cannot insert duplicate key row in object .* with unique index '(.*)'/); match = match || err.message.match(/Cannot insert duplicate key row in object .* with unique index '(.*)'/);
if (match && match.length > 1) { if (match && match.length > 1) {
......
...@@ -3,9 +3,10 @@ ...@@ -3,9 +3,10 @@
const AbstractConnectionManager = require('../abstract/connection-manager'); const AbstractConnectionManager = require('../abstract/connection-manager');
const SequelizeErrors = require('../../errors'); const SequelizeErrors = require('../../errors');
const Utils = require('../../utils'); const Utils = require('../../utils');
const logger = require('../../utils/logger');
const DataTypes = require('../../data-types').mysql; const DataTypes = require('../../data-types').mysql;
const momentTz = require('moment-timezone'); const momentTz = require('moment-timezone');
const debug = Utils.getLogger().debugContext('connection:mysql'); const debug = logger.getLogger().debugContext('connection:mysql');
const parserStore = require('../parserStore')('mysql'); const parserStore = require('../parserStore')('mysql');
/** /**
......
'use strict'; 'use strict';
const Utils = require('../../utils'); const Utils = require('../../utils');
const debug = Utils.getLogger().debugContext('sql:mysql'); const logger = require('../../utils/logger');
const debug = logger.getLogger().debugContext('sql:mysql');
const AbstractQuery = require('../abstract/query'); const AbstractQuery = require('../abstract/query');
const uuidv4 = require('uuid/v4'); const uuidv4 = require('uuid/v4');
const sequelizeErrors = require('../../errors'); const sequelizeErrors = require('../../errors');
......
...@@ -2,8 +2,8 @@ ...@@ -2,8 +2,8 @@
const _ = require('lodash'); const _ = require('lodash');
const AbstractConnectionManager = require('../abstract/connection-manager'); const AbstractConnectionManager = require('../abstract/connection-manager');
const Utils = require('../../utils'); const logger = require('../../utils/logger');
const debug = Utils.getLogger().debugContext('connection:pg'); const debug = logger.getLogger().debugContext('connection:pg');
const Promise = require('../../promise'); const Promise = require('../../promise');
const sequelizeErrors = require('../../errors'); const sequelizeErrors = require('../../errors');
const semver = require('semver'); const semver = require('semver');
......
'use strict'; 'use strict';
const Utils = require('../../utils'); const logger = require('../../utils/logger');
const debug = Utils.getLogger().debugContext('sql:pg'); const debug = logger.getLogger().debugContext('sql:pg');
const AbstractQuery = require('../abstract/query'); const AbstractQuery = require('../abstract/query');
const QueryTypes = require('../../query-types'); const QueryTypes = require('../../query-types');
const Promise = require('../../promise'); const Promise = require('../../promise');
......
...@@ -2,8 +2,8 @@ ...@@ -2,8 +2,8 @@
const AbstractConnectionManager = require('../abstract/connection-manager'); const AbstractConnectionManager = require('../abstract/connection-manager');
const Promise = require('../../promise'); const Promise = require('../../promise');
const Utils = require('../../utils'); const logger = require('../../utils/logger');
const debug = Utils.getLogger().debugContext('connection:sqlite'); const debug = logger.getLogger().debugContext('connection:sqlite');
const dataTypes = require('../../data-types').sqlite; const dataTypes = require('../../data-types').sqlite;
const sequelizeErrors = require('../../errors'); const sequelizeErrors = require('../../errors');
const parserStore = require('../parserStore')('sqlite'); const parserStore = require('../parserStore')('sqlite');
......
...@@ -2,7 +2,8 @@ ...@@ -2,7 +2,8 @@
const _ = require('lodash'); const _ = require('lodash');
const Utils = require('../../utils'); const Utils = require('../../utils');
const debug = Utils.getLogger().debugContext('sql:sqlite'); const logger = require('../../utils/logger');
const debug = logger.getLogger().debugContext('sql:sqlite');
const Promise = require('../../promise'); const Promise = require('../../promise');
const AbstractQuery = require('../abstract/query'); const AbstractQuery = require('../abstract/query');
const QueryTypes = require('../../query-types'); const QueryTypes = require('../../query-types');
......
...@@ -2,8 +2,9 @@ ...@@ -2,8 +2,9 @@
const _ = require('lodash'); const _ = require('lodash');
const Utils = require('./utils'); const Utils = require('./utils');
const logger = require('./utils/logger');
const Promise = require('./promise'); const Promise = require('./promise');
const debug = Utils.getLogger().debugContext('hooks'); const debug = logger.getLogger().debugContext('hooks');
const hookTypes = { const hookTypes = {
beforeValidate: {params: 2}, beforeValidate: {params: 2},
...@@ -182,7 +183,7 @@ const Hooks = { ...@@ -182,7 +183,7 @@ const Hooks = {
return this; return this;
} }
Utils.debug(`removing hook ${hookType}`); debug(`removing hook ${hookType}`);
// check for proxies, add them too // check for proxies, add them too
hookType = getProxiedHooks(hookType); hookType = getProxiedHooks(hookType);
......
...@@ -5,6 +5,7 @@ const Dottie = require('dottie'); ...@@ -5,6 +5,7 @@ const Dottie = require('dottie');
const _ = require('lodash'); const _ = require('lodash');
const Utils = require('./utils'); const Utils = require('./utils');
const logger = require('./utils/logger');
const BelongsTo = require('./associations/belongs-to'); const BelongsTo = require('./associations/belongs-to');
const BelongsToMany = require('./associations/belongs-to-many'); const BelongsToMany = require('./associations/belongs-to-many');
const InstanceValidator = require('./instance-validator'); const InstanceValidator = require('./instance-validator');
...@@ -1768,7 +1769,7 @@ class Model { ...@@ -1768,7 +1769,7 @@ class Model {
const unrecognizedOptions = _.difference(Object.keys(options), validQueryKeywords); const unrecognizedOptions = _.difference(Object.keys(options), validQueryKeywords);
const unexpectedModelAttributes = _.intersection(unrecognizedOptions, validColumnNames); const unexpectedModelAttributes = _.intersection(unrecognizedOptions, validColumnNames);
if (!options.where && unexpectedModelAttributes.length > 0) { if (!options.where && unexpectedModelAttributes.length > 0) {
Utils.warn(`Model attributes (${unexpectedModelAttributes.join(', ')}) passed into finder method options of model ${this.name}, but the options.where object is empty. Did you forget to use options.where?`); logger.warn(`Model attributes (${unexpectedModelAttributes.join(', ')}) passed into finder method options of model ${this.name}, but the options.where object is empty. Did you forget to use options.where?`);
} }
} }
...@@ -2254,7 +2255,7 @@ class Model { ...@@ -2254,7 +2255,7 @@ class Model {
const unknownDefaults = defaults.filter(name => !this.rawAttributes[name]); const unknownDefaults = defaults.filter(name => !this.rawAttributes[name]);
if (unknownDefaults.length) { if (unknownDefaults.length) {
Utils.warn(`Unknown attributes (${unknownDefaults}) passed to defaults option of findOrCreate`); logger.warn(`Unknown attributes (${unknownDefaults}) passed to defaults option of findOrCreate`);
} }
} }
......
...@@ -7,6 +7,7 @@ const clsBluebird = require('cls-bluebird'); ...@@ -7,6 +7,7 @@ const clsBluebird = require('cls-bluebird');
const _ = require('lodash'); const _ = require('lodash');
const Utils = require('./utils'); const Utils = require('./utils');
const logger = require('./utils/logger');
const Model = require('./model'); const Model = require('./model');
const DataTypes = require('./data-types'); const DataTypes = require('./data-types');
const Deferrable = require('./deferrable'); const Deferrable = require('./deferrable');
...@@ -189,7 +190,7 @@ class Sequelize { ...@@ -189,7 +190,7 @@ class Sequelize {
} }
if (this.options.logging === true) { if (this.options.logging === true) {
Utils.deprecate('The logging-option should be either a function or false. Default: console.log'); logger.deprecate('The logging-option should be either a function or false. Default: console.log');
this.options.logging = console.log; this.options.logging = console.log;
} }
...@@ -235,10 +236,10 @@ class Sequelize { ...@@ -235,10 +236,10 @@ class Sequelize {
this.dialect.QueryGenerator.typeValidation = options.typeValidation; this.dialect.QueryGenerator.typeValidation = options.typeValidation;
if (_.isPlainObject(this.options.operatorsAliases)) { if (_.isPlainObject(this.options.operatorsAliases)) {
Utils.deprecate('String based operators are deprecated. Please use Symbol based operators for better security, read more at http://docs.sequelizejs.com/manual/tutorial/querying.html#operators'); logger.deprecate('String based operators are deprecated. Please use Symbol based operators for better security, read more at http://docs.sequelizejs.com/manual/tutorial/querying.html#operators');
this.dialect.QueryGenerator.setOperatorsAliases(this.options.operatorsAliases); this.dialect.QueryGenerator.setOperatorsAliases(this.options.operatorsAliases);
} else if (_.isBoolean(this.options.operatorsAliases)) { } else if (_.isBoolean(this.options.operatorsAliases)) {
Utils.warn('A boolean value was passed to options.operatorsAliases. This is a no-op with v5 and should be removed.'); logger.warn('A boolean value was passed to options.operatorsAliases. This is a no-op with v5 and should be removed.');
} }
this.queryInterface = new QueryInterface(this); this.queryInterface = new QueryInterface(this);
...@@ -1062,7 +1063,7 @@ class Sequelize { ...@@ -1062,7 +1063,7 @@ class Sequelize {
if (options.logging) { if (options.logging) {
if (options.logging === true) { if (options.logging === true) {
Utils.deprecate('The logging-option should be either a function or false. Default: console.log'); logger.deprecate('The logging-option should be either a function or false. Default: console.log');
options.logging = console.log; options.logging = console.log;
} }
......
...@@ -3,8 +3,6 @@ ...@@ -3,8 +3,6 @@
const DataTypes = require('./data-types'); const DataTypes = require('./data-types');
const SqlString = require('./sql-string'); const SqlString = require('./sql-string');
const _ = require('lodash'); const _ = require('lodash');
const parameterValidator = require('./utils/parameter-validator');
const Logger = require('./utils/logger');
const uuidv1 = require('uuid/v1'); const uuidv1 = require('uuid/v1');
const uuidv4 = require('uuid/v4'); const uuidv4 = require('uuid/v4');
const Promise = require('./promise'); const Promise = require('./promise');
...@@ -13,13 +11,8 @@ const operatorsArray = _.values(operators); ...@@ -13,13 +11,8 @@ const operatorsArray = _.values(operators);
const primitives = ['string', 'number', 'boolean']; const primitives = ['string', 'number', 'boolean'];
let inflection = require('inflection'); let inflection = require('inflection');
const logger = new Logger();
exports.Promise = Promise; exports.Promise = Promise;
exports.debug = logger.debug.bind(logger);
exports.deprecate = logger.deprecate.bind(logger);
exports.warn = logger.warn.bind(logger);
exports.getLogger = () => logger ;
function useInflection(_inflection) { function useInflection(_inflection) {
inflection = _inflection; inflection = _inflection;
...@@ -503,28 +496,6 @@ class Where extends SequelizeMethod { ...@@ -503,28 +496,6 @@ class Where extends SequelizeMethod {
} }
exports.Where = Where; exports.Where = Where;
exports.validateParameter = parameterValidator;
exports.mapIsolationLevelStringToTedious = (isolationLevel, tedious) => {
if (!tedious) {
throw new Error('An instance of tedious lib should be passed to this function');
}
const tediousIsolationLevel = tedious.ISOLATION_LEVEL;
switch (isolationLevel) {
case 'READ_UNCOMMITTED':
return tediousIsolationLevel.READ_UNCOMMITTED;
case 'READ_COMMITTED':
return tediousIsolationLevel.READ_COMMITTED;
case 'REPEATABLE_READ':
return tediousIsolationLevel.REPEATABLE_READ;
case 'SERIALIZABLE':
return tediousIsolationLevel.SERIALIZABLE;
case 'SNAPSHOT':
return tediousIsolationLevel.SNAPSHOT;
}
};
//Collection of helper methods to make it easier to work with symbol operators //Collection of helper methods to make it easier to work with symbol operators
/** /**
......
...@@ -44,4 +44,10 @@ class Logger { ...@@ -44,4 +44,10 @@ class Logger {
} }
} }
module.exports = Logger; exports.Logger = Logger;
const logger = new Logger();
exports.deprecate = logger.deprecate.bind(logger);
exports.warn = logger.warn.bind(logger);
exports.getLogger = () => logger ;
'use strict';
const _ = require('lodash');
const util = require('util');
const Utils = require('../utils');
function validateDeprecation(value, expectation, options) {
if (!options.deprecated) {
return;
}
const valid = value instanceof options.deprecated || Object.prototype.toString.call(value) === Object.prototype.toString.call(options.deprecated.call());
if (valid) {
const message = `${util.inspect(value)} should not be of type "${options.deprecated.name}"`;
Utils.deprecate(options.deprecationWarning || message);
}
return valid;
}
function validate(value, expectation) {
// the second part of this check is a workaround to deal with an issue that occurs in node-webkit when
// using object literals. https://github.com/sequelize/sequelize/issues/2685
if (value instanceof expectation || Object.prototype.toString.call(value) === Object.prototype.toString.call(expectation.call())) {
return true;
}
throw new Error(`The parameter (value: ${value}) is no ${expectation.name}`);
}
function check(value, expectation, options) {
options = _.extend({
deprecated: false,
index: null,
method: null,
optional: false
}, options || {});
if (!value && options.optional) {
return true;
}
if (value === undefined) {
throw new Error('No value has been passed.');
}
if (expectation === undefined) {
throw new Error('No expectation has been passed.');
}
return false
|| validateDeprecation(value, expectation, options)
|| validate(value, expectation, options);
}
module.exports = check;
module.exports.check = check;
module.exports.default = check;
...@@ -21,7 +21,7 @@ describe('Connection Manager', () => { ...@@ -21,7 +21,7 @@ describe('Connection Manager', () => {
let sandbox; let sandbox;
beforeEach(() => { beforeEach(() => {
sandbox = sinon.sandbox.create(); sandbox = sinon.createSandbox();
}); });
afterEach(() => { afterEach(() => {
......
...@@ -11,7 +11,7 @@ describe(Support.getTestDialectTeaser('Pooling'), function() { ...@@ -11,7 +11,7 @@ describe(Support.getTestDialectTeaser('Pooling'), function() {
if (dialect === 'sqlite') return; if (dialect === 'sqlite') return;
beforeEach(() => { beforeEach(() => {
this.sinon = sinon.sandbox.create(); this.sinon = sinon.createSandbox();
}); });
afterEach(() => { afterEach(() => {
...@@ -33,7 +33,7 @@ describe(Support.getTestDialectTeaser('Pooling'), function() { ...@@ -33,7 +33,7 @@ describe(Support.getTestDialectTeaser('Pooling'), function() {
return expect(this.testInstance.authenticate()) return expect(this.testInstance.authenticate())
.to.eventually.be.rejectedWith('ResourceRequest timed out'); .to.eventually.be.rejectedWith('ResourceRequest timed out');
}); });
it('should not result in unhandled promise rejection when unable to acquire connection', () => { it('should not result in unhandled promise rejection when unable to acquire connection', () => {
this.testInstance = new Sequelize('localhost', 'ffd', 'dfdf', { this.testInstance = new Sequelize('localhost', 'ffd', 'dfdf', {
dialect, dialect,
......
...@@ -14,7 +14,7 @@ describe(Support.getTestDialectTeaser('Replication'), function() { ...@@ -14,7 +14,7 @@ describe(Support.getTestDialectTeaser('Replication'), function() {
let readSpy, writeSpy; let readSpy, writeSpy;
beforeEach(() => { beforeEach(() => {
sandbox = sinon.sandbox.create(); sandbox = sinon.createSandbox();
this.sequelize = Support.getSequelizeInstance(null, null, null, { this.sequelize = Support.getSequelizeInstance(null, null, null, {
replication: { replication: {
......
...@@ -11,7 +11,7 @@ const chai = require('chai'), ...@@ -11,7 +11,7 @@ const chai = require('chai'),
config = require(__dirname + '/../config/config'), config = require(__dirname + '/../config/config'),
moment = require('moment'), moment = require('moment'),
Transaction = require(__dirname + '/../../lib/transaction'), Transaction = require(__dirname + '/../../lib/transaction'),
Utils = require(__dirname + '/../../lib/utils'), logger = require(__dirname + '/../../lib/utils/logger'),
sinon = require('sinon'), sinon = require('sinon'),
semver = require('semver'), semver = require('semver'),
current = Support.sequelize; current = Support.sequelize;
...@@ -30,7 +30,7 @@ const qq = function(str) { ...@@ -30,7 +30,7 @@ const qq = function(str) {
describe(Support.getTestDialectTeaser('Sequelize'), () => { describe(Support.getTestDialectTeaser('Sequelize'), () => {
describe('constructor', () => { describe('constructor', () => {
afterEach(() => { afterEach(() => {
Utils.deprecate.restore && Utils.deprecate.restore(); logger.deprecate.restore && logger.deprecate.restore();
}); });
if (dialect !== 'sqlite') { if (dialect !== 'sqlite') {
......
...@@ -12,7 +12,7 @@ if (current.dialect.supports.transactions) { ...@@ -12,7 +12,7 @@ if (current.dialect.supports.transactions) {
describe(Support.getTestDialectTeaser('Sequelize#transaction'), () => { describe(Support.getTestDialectTeaser('Sequelize#transaction'), () => {
beforeEach(function() { beforeEach(function() {
this.sinon = sinon.sandbox.create(); this.sinon = sinon.createSandbox();
}); });
afterEach(function() { afterEach(function() {
......
...@@ -14,7 +14,7 @@ if (current.dialect.supports.transactions) { ...@@ -14,7 +14,7 @@ if (current.dialect.supports.transactions) {
describe(Support.getTestDialectTeaser('Transaction'), () => { describe(Support.getTestDialectTeaser('Transaction'), () => {
beforeEach(function() { beforeEach(function() {
this.sinon = sinon.sandbox.create(); this.sinon = sinon.createSandbox();
}); });
afterEach(function() { afterEach(function() {
......
...@@ -88,42 +88,6 @@ describe(Support.getTestDialectTeaser('Utils'), () => { ...@@ -88,42 +88,6 @@ describe(Support.getTestDialectTeaser('Utils'), () => {
}); });
}); });
describe('validateParameter', () => {
describe('method signature', () => {
it('throws an error if the value is not defined', () => {
expect(() => {
Utils.validateParameter();
}).to.throw('No value has been passed.');
});
it('does not throw an error if the value is not defined and the parameter is optional', () => {
expect(() => {
Utils.validateParameter(undefined, Object, { optional: true });
}).to.not.throw();
});
it('throws an error if the expectation is not defined', () => {
expect(() => {
Utils.validateParameter(1);
}).to.throw('No expectation has been passed.');
});
});
describe('expectation', () => {
it('uses the instanceof method if the expectation is a class', () => {
expect(Utils.validateParameter(new Number(1), Number)).to.be.true;
});
});
describe('failing expectations', () => {
it('throws an error if the expectation does not match', () => {
expect(() => {
Utils.validateParameter(1, String);
}).to.throw(/The parameter.*is no.*/);
});
});
});
if (Support.getTestDialect() === 'postgres') { if (Support.getTestDialect() === 'postgres') {
describe('json', () => { describe('json', () => {
beforeEach(function() { beforeEach(function() {
......
...@@ -6,13 +6,13 @@ const Support = require(__dirname + '/../support'); ...@@ -6,13 +6,13 @@ const Support = require(__dirname + '/../support');
const current = Support.sequelize; const current = Support.sequelize;
const sinon = require('sinon'); const sinon = require('sinon');
const DataTypes = require(__dirname + '/../../../lib/data-types'); const DataTypes = require(__dirname + '/../../../lib/data-types');
const Utils = require('../../../lib/utils.js'); const logger = require('../../../lib/utils/logger');
const sequelizeErrors = require('../../../lib/errors'); const sequelizeErrors = require('../../../lib/errors');
describe(Support.getTestDialectTeaser('Model'), () => { describe(Support.getTestDialectTeaser('Model'), () => {
describe('warnOnInvalidOptions', () => { describe('warnOnInvalidOptions', () => {
beforeEach(() => { beforeEach(() => {
this.loggerSpy = sinon.spy(Utils, 'warn'); this.loggerSpy = sinon.spy(logger, 'warn');
}); });
afterEach(() => { afterEach(() => {
......
...@@ -5,8 +5,7 @@ const expect = chai.expect; ...@@ -5,8 +5,7 @@ const expect = chai.expect;
const Support = require(__dirname + '/support'); const Support = require(__dirname + '/support');
const DataTypes = require(__dirname + '/../../lib/data-types'); const DataTypes = require(__dirname + '/../../lib/data-types');
const Utils = require(__dirname + '/../../lib/utils'); const Utils = require(__dirname + '/../../lib/utils');
const tedious = require('tedious'); const logger = require(__dirname + '/../../lib/utils/logger').getLogger();
const tediousIsolationLevel = tedious.ISOLATION_LEVEL;
const Op = Support.sequelize.Op; const Op = Support.sequelize.Op;
suite(Support.getTestDialectTeaser('Utils'), () => { suite(Support.getTestDialectTeaser('Utils'), () => {
...@@ -271,8 +270,6 @@ suite(Support.getTestDialectTeaser('Utils'), () => { ...@@ -271,8 +270,6 @@ suite(Support.getTestDialectTeaser('Utils'), () => {
}); });
suite('Logger', () => { suite('Logger', () => {
const logger = Utils.getLogger();
test('deprecate', () => { test('deprecate', () => {
expect(logger.deprecate).to.be.a('function'); expect(logger.deprecate).to.be.a('function');
logger.deprecate('test deprecation'); logger.deprecate('test deprecation');
...@@ -296,33 +293,4 @@ suite(Support.getTestDialectTeaser('Utils'), () => { ...@@ -296,33 +293,4 @@ suite(Support.getTestDialectTeaser('Utils'), () => {
expect(testLogger.namespace).to.be.eql('sequelize:test'); expect(testLogger.namespace).to.be.eql('sequelize:test');
}); });
}); });
if (Support.getTestDialect() === 'mssql') {
suite('mapIsolationLevelStringToTedious', () => {
test('READ_UNCOMMITTED', () => {
expect(Utils.mapIsolationLevelStringToTedious('READ_UNCOMMITTED', tedious)).to.equal(tediousIsolationLevel.READ_UNCOMMITTED);
});
test('READ_COMMITTED', () => {
expect(Utils.mapIsolationLevelStringToTedious('READ_COMMITTED', tedious)).to.equal(tediousIsolationLevel.READ_COMMITTED);
});
test('REPEATABLE_READ', () => {
expect(Utils.mapIsolationLevelStringToTedious('REPEATABLE_READ', tedious)).to.equal(tediousIsolationLevel.REPEATABLE_READ);
});
test('SERIALIZABLE', () => {
expect(Utils.mapIsolationLevelStringToTedious('SERIALIZABLE', tedious)).to.equal(tediousIsolationLevel.SERIALIZABLE);
});
test('SNAPSHOT', () => {
expect(Utils.mapIsolationLevelStringToTedious('SNAPSHOT', tedious)).to.equal(tediousIsolationLevel.SNAPSHOT);
});
test('should throw error if tedious lib is not passed as a parameter', () => {
expect(Utils.mapIsolationLevelStringToTedious.bind(Utils, 'SNAPSHOT')).to.throw('An instance of tedious lib should be passed to this function');
});
});
}
}); });
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!