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

Commit bb874f5e by Sushant Committed by GitHub

refactor: logging & utils (#9665)

1 parent b00148e0
......@@ -3,7 +3,6 @@
const Utils = require('./../utils');
const Helpers = require('./helpers');
const _ = require('lodash');
const Transaction = require('../transaction');
const Association = require('./base');
const Op = require('../operators');
......@@ -221,16 +220,11 @@ class BelongsTo extends Association {
*
* @return {Promise}
*/
create(sourceInstance, values, fieldsOrOptions) {
const options = {};
create(sourceInstance, values, options) {
values = values || {};
options = options || {};
options.logging = (fieldsOrOptions || {}).logging;
if ((fieldsOrOptions || {}).transaction instanceof Transaction) {
options.transaction = fieldsOrOptions.transaction;
}
return this.target.create(values, fieldsOrOptions)
return this.target.create(values, options)
.then(newAssociatedObject =>
sourceInstance[this.accessors.set](newAssociatedObject, options)
);
......
'use strict';
const Association = require('./base');
Association.BelongsTo = require('./belongs-to');
Association.HasOne = require('./has-one');
Association.HasMany = require('./has-many');
......
......@@ -9,7 +9,7 @@ const warnings = {};
const Validator = require('./utils/validator-extras').validator;
const momentTz = require('moment-timezone');
const moment = require('moment');
const Utils = require('./utils');
const logger = require('./utils/logger');
function ABSTRACT() {}
......@@ -24,7 +24,7 @@ ABSTRACT.prototype.toSql = function toSql() {
ABSTRACT.warn = function warn(link, text) {
if (!warnings[text]) {
warnings[text] = true;
Utils.warn(`${text}, '\n>> Check:', ${link}`);
logger.warn(`${text}, '\n>> Check:', ${link}`);
}
};
ABSTRACT.prototype.stringify = function stringify(value, options) {
......@@ -701,14 +701,6 @@ ARRAY.is = function is(obj, 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) {
const options = _.isPlainObject(type) ? type : {type, srid};
......@@ -796,6 +788,14 @@ MACADDR.prototype.validate = function validate(value) {
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 DataType of helpers[helper]) {
if (!DataType[helper]) {
......
'use strict';
const Pooling = require('generic-pool');
const Promise = require('../../promise');
const _ = require('lodash');
const Utils = require('../../utils');
const debug = Utils.getLogger().debugContext('pool');
const semver = require('semver');
const Promise = require('../../promise');
const logger = require('../../utils/logger');
const debug = logger.getLogger().debugContext('pool');
const defaultPoolingConfig = {
max: 5,
......
......@@ -7,6 +7,7 @@ const uuidv4 = require('uuid/v4');
const semver = require('semver');
const Utils = require('../../utils');
const logger = require('../../utils/logger');
const SqlString = require('../../sql-string');
const DataTypes = require('../../data-types');
const Model = require('../../model');
......@@ -1422,7 +1423,7 @@ class QueryGenerator {
} else if (attr[0].indexOf('(') === -1 && attr[0].indexOf(')') === -1) {
attr[0] = this.quoteIdentifier(attr[0]);
} 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 ');
} else {
......
'use strict';
const _ = require('lodash');
const Utils = require('../../utils');
const logger = require('../../utils/logger');
const SqlString = require('../../sql-string');
const Dot = require('dottie');
const QueryTypes = require('../../query-types');
......@@ -110,7 +110,7 @@ class AbstractQuery {
*/
checkLoggingOption() {
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;
}
}
......
......@@ -3,12 +3,12 @@
const AbstractConnectionManager = require('../abstract/connection-manager');
const ResourceLock = require('./resource-lock');
const Promise = require('../../promise');
const Utils = require('../../utils');
const debug = Utils.getLogger().debugContext('connection:mssql');
const debugTedious = Utils.getLogger().debugContext('connection:mssql:tedious');
const logger = require('../../utils/logger');
const sequelizeErrors = require('../../errors');
const DataTypes = require('../../data-types').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 {
constructor(dialect, sequelize) {
......
'use strict';
const Utils = require('../../utils');
const debug = Utils.getLogger().debugContext('sql:mssql');
const logger = require('../../utils/logger');
const Promise = require('../../promise');
const AbstractQuery = require('../abstract/query');
const sequelizeErrors = require('../../errors');
const parserStore = require('../parserStore')('mssql');
const _ = require('lodash');
const TYPES = require('tedious').TYPES;
const debug = logger.getLogger().debugContext('sql:mssql');
class Query extends AbstractQuery {
constructor(connection, sequelize, options) {
......@@ -29,7 +28,7 @@ class Query extends AbstractQuery {
return 'id';
}
getSQLTypeFromJsType(value) {
getSQLTypeFromJsType(value, TYPES) {
const paramType = {type: TYPES.VarChar, typeOptions: {} };
paramType.type = TYPES.NVarChar;
if (typeof value === 'number') {
......@@ -70,7 +69,7 @@ class Query extends AbstractQuery {
} else {
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')) {
connection.commitTransaction(err => {
if (err) {
......@@ -115,7 +114,7 @@ class Query extends AbstractQuery {
if (parameters) {
_.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);
});
}
......
......@@ -3,9 +3,10 @@
const AbstractConnectionManager = require('../abstract/connection-manager');
const SequelizeErrors = require('../../errors');
const Utils = require('../../utils');
const logger = require('../../utils/logger');
const DataTypes = require('../../data-types').mysql;
const momentTz = require('moment-timezone');
const debug = Utils.getLogger().debugContext('connection:mysql');
const debug = logger.getLogger().debugContext('connection:mysql');
const parserStore = require('../parserStore')('mysql');
/**
......
'use strict';
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 uuidv4 = require('uuid/v4');
const sequelizeErrors = require('../../errors');
......
......@@ -2,8 +2,8 @@
const _ = require('lodash');
const AbstractConnectionManager = require('../abstract/connection-manager');
const Utils = require('../../utils');
const debug = Utils.getLogger().debugContext('connection:pg');
const logger = require('../../utils/logger');
const debug = logger.getLogger().debugContext('connection:pg');
const Promise = require('../../promise');
const sequelizeErrors = require('../../errors');
const semver = require('semver');
......
'use strict';
const Utils = require('../../utils');
const debug = Utils.getLogger().debugContext('sql:pg');
const logger = require('../../utils/logger');
const debug = logger.getLogger().debugContext('sql:pg');
const AbstractQuery = require('../abstract/query');
const QueryTypes = require('../../query-types');
const Promise = require('../../promise');
......
......@@ -2,8 +2,8 @@
const AbstractConnectionManager = require('../abstract/connection-manager');
const Promise = require('../../promise');
const Utils = require('../../utils');
const debug = Utils.getLogger().debugContext('connection:sqlite');
const logger = require('../../utils/logger');
const debug = logger.getLogger().debugContext('connection:sqlite');
const dataTypes = require('../../data-types').sqlite;
const sequelizeErrors = require('../../errors');
const parserStore = require('../parserStore')('sqlite');
......
......@@ -2,7 +2,8 @@
const _ = require('lodash');
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 AbstractQuery = require('../abstract/query');
const QueryTypes = require('../../query-types');
......
......@@ -2,8 +2,9 @@
const _ = require('lodash');
const Utils = require('./utils');
const logger = require('./utils/logger');
const Promise = require('./promise');
const debug = Utils.getLogger().debugContext('hooks');
const debug = logger.getLogger().debugContext('hooks');
const hookTypes = {
beforeValidate: {params: 2},
......@@ -182,7 +183,7 @@ const Hooks = {
return this;
}
Utils.debug(`removing hook ${hookType}`);
debug(`removing hook ${hookType}`);
// check for proxies, add them too
hookType = getProxiedHooks(hookType);
......
......@@ -5,6 +5,7 @@ const Dottie = require('dottie');
const _ = require('lodash');
const Utils = require('./utils');
const logger = require('./utils/logger');
const BelongsTo = require('./associations/belongs-to');
const BelongsToMany = require('./associations/belongs-to-many');
const InstanceValidator = require('./instance-validator');
......@@ -1768,7 +1769,7 @@ class Model {
const unrecognizedOptions = _.difference(Object.keys(options), validQueryKeywords);
const unexpectedModelAttributes = _.intersection(unrecognizedOptions, validColumnNames);
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 {
const unknownDefaults = defaults.filter(name => !this.rawAttributes[name]);
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');
const _ = require('lodash');
const Utils = require('./utils');
const logger = require('./utils/logger');
const Model = require('./model');
const DataTypes = require('./data-types');
const Deferrable = require('./deferrable');
......@@ -189,7 +190,7 @@ class Sequelize {
}
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;
}
......@@ -235,10 +236,10 @@ class Sequelize {
this.dialect.QueryGenerator.typeValidation = options.typeValidation;
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);
} 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);
......@@ -1062,7 +1063,7 @@ class Sequelize {
if (options.logging) {
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;
}
......
......@@ -3,8 +3,6 @@
const DataTypes = require('./data-types');
const SqlString = require('./sql-string');
const _ = require('lodash');
const parameterValidator = require('./utils/parameter-validator');
const Logger = require('./utils/logger');
const uuidv1 = require('uuid/v1');
const uuidv4 = require('uuid/v4');
const Promise = require('./promise');
......@@ -13,13 +11,8 @@ const operatorsArray = _.values(operators);
const primitives = ['string', 'number', 'boolean'];
let inflection = require('inflection');
const logger = new Logger();
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) {
inflection = _inflection;
......@@ -503,28 +496,6 @@ class Where extends SequelizeMethod {
}
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
/**
......
......@@ -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', () => {
let sandbox;
beforeEach(() => {
sandbox = sinon.sandbox.create();
sandbox = sinon.createSandbox();
});
afterEach(() => {
......
......@@ -11,7 +11,7 @@ describe(Support.getTestDialectTeaser('Pooling'), function() {
if (dialect === 'sqlite') return;
beforeEach(() => {
this.sinon = sinon.sandbox.create();
this.sinon = sinon.createSandbox();
});
afterEach(() => {
......
......@@ -14,7 +14,7 @@ describe(Support.getTestDialectTeaser('Replication'), function() {
let readSpy, writeSpy;
beforeEach(() => {
sandbox = sinon.sandbox.create();
sandbox = sinon.createSandbox();
this.sequelize = Support.getSequelizeInstance(null, null, null, {
replication: {
......
......@@ -11,7 +11,7 @@ const chai = require('chai'),
config = require(__dirname + '/../config/config'),
moment = require('moment'),
Transaction = require(__dirname + '/../../lib/transaction'),
Utils = require(__dirname + '/../../lib/utils'),
logger = require(__dirname + '/../../lib/utils/logger'),
sinon = require('sinon'),
semver = require('semver'),
current = Support.sequelize;
......@@ -30,7 +30,7 @@ const qq = function(str) {
describe(Support.getTestDialectTeaser('Sequelize'), () => {
describe('constructor', () => {
afterEach(() => {
Utils.deprecate.restore && Utils.deprecate.restore();
logger.deprecate.restore && logger.deprecate.restore();
});
if (dialect !== 'sqlite') {
......
......@@ -12,7 +12,7 @@ if (current.dialect.supports.transactions) {
describe(Support.getTestDialectTeaser('Sequelize#transaction'), () => {
beforeEach(function() {
this.sinon = sinon.sandbox.create();
this.sinon = sinon.createSandbox();
});
afterEach(function() {
......
......@@ -14,7 +14,7 @@ if (current.dialect.supports.transactions) {
describe(Support.getTestDialectTeaser('Transaction'), () => {
beforeEach(function() {
this.sinon = sinon.sandbox.create();
this.sinon = sinon.createSandbox();
});
afterEach(function() {
......
......@@ -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') {
describe('json', () => {
beforeEach(function() {
......
......@@ -6,13 +6,13 @@ const Support = require(__dirname + '/../support');
const current = Support.sequelize;
const sinon = require('sinon');
const DataTypes = require(__dirname + '/../../../lib/data-types');
const Utils = require('../../../lib/utils.js');
const logger = require('../../../lib/utils/logger');
const sequelizeErrors = require('../../../lib/errors');
describe(Support.getTestDialectTeaser('Model'), () => {
describe('warnOnInvalidOptions', () => {
beforeEach(() => {
this.loggerSpy = sinon.spy(Utils, 'warn');
this.loggerSpy = sinon.spy(logger, 'warn');
});
afterEach(() => {
......
......@@ -5,8 +5,7 @@ const expect = chai.expect;
const Support = require(__dirname + '/support');
const DataTypes = require(__dirname + '/../../lib/data-types');
const Utils = require(__dirname + '/../../lib/utils');
const tedious = require('tedious');
const tediousIsolationLevel = tedious.ISOLATION_LEVEL;
const logger = require(__dirname + '/../../lib/utils/logger').getLogger();
const Op = Support.sequelize.Op;
suite(Support.getTestDialectTeaser('Utils'), () => {
......@@ -271,8 +270,6 @@ suite(Support.getTestDialectTeaser('Utils'), () => {
});
suite('Logger', () => {
const logger = Utils.getLogger();
test('deprecate', () => {
expect(logger.deprecate).to.be.a('function');
logger.deprecate('test deprecation');
......@@ -296,33 +293,4 @@ suite(Support.getTestDialectTeaser('Utils'), () => {
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!