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

Commit 62e068a6 by Sushant Committed by GitHub

refactor: remove old code and clean up (#9399)

1 parent f164535f
'use strict';
const AssociationError = require('./../errors').AssociationError;
const { AssociationError } = require('./../errors');
/**
* Creating associations in sequelize is done by calling one of the belongsTo / hasOne / hasMany / belongsToMany functions on a model (the source), and providing another model as the first argument to the function (the target).
......
......@@ -200,8 +200,8 @@ class BelongsToMany extends Association {
this.associationAccessor = this.as;
// Get singular and plural names, trying to uppercase the first letter, unless the model forbids it
const plural = Utils.uppercaseFirst(this.options.name.plural);
const singular = Utils.uppercaseFirst(this.options.name.singular);
const plural = _.upperFirst(this.options.name.plural);
const singular = _.upperFirst(this.options.name.singular);
this.accessors = {
get: 'get' + plural,
......
......@@ -69,7 +69,7 @@ class BelongsTo extends Association {
this.options.useHooks = options.useHooks;
// Get singular name, trying to uppercase the first letter, unless the model forbids it
const singular = Utils.uppercaseFirst(this.options.name.singular);
const singular = _.upperFirst(this.options.name.singular);
this.accessors = {
get: 'get' + singular,
......
......@@ -92,8 +92,8 @@ class HasMany extends Association {
// Get singular and plural names
// try to uppercase the first letter, unless the model forbids it
const plural = Utils.uppercaseFirst(this.options.name.plural);
const singular = Utils.uppercaseFirst(this.options.name.singular);
const plural = _.upperFirst(this.options.name.plural);
const singular = _.upperFirst(this.options.name.singular);
this.associationAccessor = this.as;
this.accessors = {
......
......@@ -68,7 +68,7 @@ class HasOne extends Association {
}
// Get singular name, trying to uppercase the first letter, unless the model forbids it
const singular = Utils.uppercaseFirst(this.options.name.singular);
const singular = _.upperFirst(this.options.name.singular);
this.accessors = {
get: 'get' + singular,
......
'use strict';
const Utils = require('./../utils');
const _ = require('lodash');
const HasOne = require('./has-one');
const HasMany = require('./has-many');
......@@ -82,7 +81,7 @@ const Mixin = {
function singleLinked(Type) {
return function(target, options = {}) { // testhint options:none
if (!isModel(target, this.sequelize)) {
throw new Error(`${this.name}.${Utils.lowercaseFirst(Type.name)} called with something that's not a subclass of Sequelize.Model`);
throw new Error(`${this.name}.${_.lowerFirst(Type.name)} called with something that's not a subclass of Sequelize.Model`);
}
const source = this;
......
'use strict';
const util = require('util');
const { classToInvokable } = require('./utils');
class ABSTRACT {
static toString() {
const instance = new this();
return instance.toString.apply(instance, arguments);
}
toString() {
return this.toSql.apply(this, arguments);
}
toSql() {
throw new Error('toSql implementation missing');
}
}
class INITIALLY_DEFERRED extends ABSTRACT {
toSql() {
return 'DEFERRABLE INITIALLY DEFERRED';
}
}
class INITIALLY_IMMEDIATE extends ABSTRACT {
toSql() {
return 'DEFERRABLE INITIALLY IMMEDIATE';
}
}
class NOT extends ABSTRACT {
toSql() {
return 'NOT DEFERRABLE';
}
}
class SET_DEFERRED extends ABSTRACT {
constructor(constraints) {
super();
this.constraints = constraints;
}
toSql(queryGenerator) {
return queryGenerator.setDeferredQuery(this.constraints);
}
}
class SET_IMMEDIATE extends ABSTRACT {
constructor(constraints) {
super();
this.constraints = constraints;
}
toSql(queryGenerator) {
return queryGenerator.setImmediateQuery(this.constraints);
}
}
/**
* A collection of properties related to deferrable constraints. It can be used to
......@@ -40,84 +94,11 @@ const util = require('util');
* @property SET_DEFERRED
* @property SET_IMMEDIATE
*/
const Deferrable = module.exports = {
INITIALLY_DEFERRED,
INITIALLY_IMMEDIATE,
NOT,
SET_DEFERRED,
SET_IMMEDIATE
};
function ABSTRACT() {}
ABSTRACT.prototype.toString = function() {
return this.toSql.apply(this, arguments);
};
function INITIALLY_DEFERRED() {
if (!(this instanceof INITIALLY_DEFERRED)) {
return new INITIALLY_DEFERRED();
}
}
util.inherits(INITIALLY_DEFERRED, ABSTRACT);
INITIALLY_DEFERRED.prototype.toSql = function() {
return 'DEFERRABLE INITIALLY DEFERRED';
};
function INITIALLY_IMMEDIATE() {
if (!(this instanceof INITIALLY_IMMEDIATE)) {
return new INITIALLY_IMMEDIATE();
}
}
util.inherits(INITIALLY_IMMEDIATE, ABSTRACT);
INITIALLY_IMMEDIATE.prototype.toSql = function() {
return 'DEFERRABLE INITIALLY IMMEDIATE';
};
function NOT() {
if (!(this instanceof NOT)) {
return new NOT();
}
}
util.inherits(NOT, ABSTRACT);
NOT.prototype.toSql = function() {
return 'NOT DEFERRABLE';
};
function SET_DEFERRED(constraints) {
if (!(this instanceof SET_DEFERRED)) {
return new SET_DEFERRED(constraints);
}
this.constraints = constraints;
}
util.inherits(SET_DEFERRED, ABSTRACT);
SET_DEFERRED.prototype.toSql = function(queryGenerator) {
return queryGenerator.setDeferredQuery(this.constraints);
};
function SET_IMMEDIATE(constraints) {
if (!(this instanceof SET_IMMEDIATE)) {
return new SET_IMMEDIATE(constraints);
}
this.constraints = constraints;
}
util.inherits(SET_IMMEDIATE, ABSTRACT);
SET_IMMEDIATE.prototype.toSql = function(queryGenerator) {
return queryGenerator.setImmediateQuery(this.constraints);
};
Object.keys(Deferrable).forEach(key => {
const DeferrableType = Deferrable[key];
DeferrableType.toString = function() {
const instance = new DeferrableType();
return instance.toString.apply(instance, arguments);
};
});
const Deferrable = module.exports = { // eslint-disable-line
INITIALLY_DEFERRED: classToInvokable(INITIALLY_DEFERRED),
INITIALLY_IMMEDIATE: classToInvokable(INITIALLY_IMMEDIATE),
NOT: classToInvokable(NOT),
SET_DEFERRED: classToInvokable(SET_DEFERRED),
SET_IMMEDIATE: classToInvokable(SET_IMMEDIATE)
};
\ No newline at end of file
......@@ -4,6 +4,8 @@ const url = require('url');
const Path = require('path');
const retry = require('retry-as-promised');
const clsBluebird = require('cls-bluebird');
const _ = require('lodash');
const Utils = require('./utils');
const Model = require('./model');
const DataTypes = require('./data-types');
......@@ -18,7 +20,6 @@ const Promise = require('./promise');
const Hooks = require('./hooks');
const Association = require('./associations/index');
const Validator = require('./utils/validator-extras').validator;
const _ = require('lodash');
const Op = require('./operators');
/**
......@@ -31,7 +32,6 @@ const Op = require('./operators');
* In addition to sequelize, the connection library for the dialect you want to use should also be installed in your project. You don't need to import it however, as sequelize will take care of that.
*/
class Sequelize {
/**
* Instantiate sequelize with name of database, username and password
*
......@@ -777,7 +777,13 @@ class Sequelize {
* @return {Promise}
*/
authenticate(options) {
return this.query('SELECT 1+1 AS result', _.assign({ raw: true, plain: true }, options)).return();
options = _.assign({
raw: true,
plain: true,
type: QueryTypes.SELECT
}, options);
return this.query('SELECT 1+1 AS result', options).return();
}
databaseVersion(options) {
......@@ -790,8 +796,7 @@ class Sequelize {
* @return {Sequelize.fn}
*/
random() {
const dialect = this.getDialect();
if (_.includes(['postgres', 'sqlite'], dialect)) {
if (['postgres', 'sqlite'].includes(this.getDialect())) {
return this.fn('RANDOM');
} else {
return this.fn('RAND');
......@@ -1099,6 +1104,7 @@ class Sequelize {
}
return type;
}
normalizeAttribute(attribute) {
if (!_.isPlainObject(attribute)) {
attribute = { type: attribute };
......@@ -1236,10 +1242,10 @@ Hooks.applyTo(Sequelize.prototype);
/**
* Expose various errors available
*/
Sequelize.prototype.Error = Sequelize.Error = sequelizeErrors.BaseError;
for (const error of Object.keys(sequelizeErrors)) {
if (sequelizeErrors[error] === sequelizeErrors.BaseError) {
Sequelize.prototype.Error = Sequelize.Error = sequelizeErrors.BaseError;
} else {
if (sequelizeErrors[error] !== sequelizeErrors.BaseError) {
Sequelize.prototype[error] = Sequelize[error] = sequelizeErrors[error];
}
}
......
......@@ -89,16 +89,6 @@ function merge() {
}
exports.merge = merge;
function lowercaseFirst(s) {
return s[0].toLowerCase() + s.slice(1);
}
exports.lowercaseFirst = lowercaseFirst;
function uppercaseFirst(s) {
return s[0].toUpperCase() + s.slice(1);
}
exports.uppercaseFirst = uppercaseFirst;
function spliceStr(str, index, count, add) {
return str.slice(0, index) + add + str.slice(index + count);
}
......@@ -114,6 +104,16 @@ function underscore(str) {
}
exports.underscore = underscore;
function singularize(str) {
return inflection.singularize(str);
}
exports.singularize = singularize;
function pluralize(str) {
return inflection.pluralize(str);
}
exports.pluralize = pluralize;
function format(arr, dialect) {
const timeZone = null;
// Make a clone of the array beacuse format modifies the passed args
......@@ -248,23 +248,6 @@ function isColString(value) {
}
exports.isColString = isColString;
function argsArePrimaryKeys(args, primaryKeys) {
let result = args.length === Object.keys(primaryKeys).length;
if (result) {
_.each(args, arg => {
if (result) {
if (['number', 'string'].indexOf(typeof arg) !== -1) {
result = true;
} else {
result = arg instanceof Date || Buffer.isBuffer(arg);
}
}
});
}
return result;
}
exports.argsArePrimaryKeys = argsArePrimaryKeys;
function canTreatArrayAsAnd(arr) {
return arr.reduce((treatAsAnd, arg) => {
if (treatAsAnd) {
......@@ -281,24 +264,6 @@ function combineTableNames(tableName1, tableName2) {
}
exports.combineTableNames = combineTableNames;
function singularize(str) {
return inflection.singularize(str);
}
exports.singularize = singularize;
function pluralize(str) {
return inflection.pluralize(str);
}
exports.pluralize = pluralize;
function removeCommentsFromFunctionString(s) {
s = s.replace(/\s*(\/\/.*)/g, '');
s = s.replace(/(\/\*[\n\r\s\S]*?\*\/)/mg, '');
return s;
}
exports.removeCommentsFromFunctionString = removeCommentsFromFunctionString;
function toDefaultValue(value, dialect) {
if (typeof value === 'function') {
const tmp = value();
......@@ -681,3 +646,12 @@ function defaults(object) {
}
exports.defaults = defaults;
function classToInvokable(Class) {
return new Proxy(Class, {
apply(Target, thisArg, args) {
return new Target(...args);
}
});
}
exports.classToInvokable = classToInvokable;
......@@ -5,7 +5,8 @@ const chai = require('chai'),
Support = require(__dirname + '/../support'),
Sequelize = require(__dirname + '/../../../index'),
Promise = Sequelize.Promise,
DataTypes = require(__dirname + '/../../../lib/data-types');
DataTypes = require(__dirname + '/../../../lib/data-types'),
_ = require('lodash');
describe(Support.getTestDialectTeaser('Include'), () => {
describe('find', () => {
......@@ -309,7 +310,7 @@ describe(Support.getTestDialectTeaser('Include'), () => {
promise = promise.then(() => {
return model.create(values).then(instance => {
if (previousInstance) {
return previousInstance['set'+ Sequelize.Utils.uppercaseFirst(model.name)](instance).then(() => {
return previousInstance['set'+ _.upperFirst(model.name)](instance).then(() => {
previousInstance = instance;
});
} else {
......
......@@ -6,7 +6,8 @@ const chai = require('chai'),
expect = chai.expect,
Support = require(__dirname + '/../support'),
DataTypes = require(__dirname + '/../../../lib/data-types'),
Promise = Sequelize.Promise;
Promise = Sequelize.Promise,
_ = require('lodash');
const sortById = function(a, b) {
return a.id < b.id ? -1 : 1;
......@@ -510,7 +511,7 @@ describe(Support.getTestDialectTeaser('Include'), () => {
promise = promise.then(() => {
return model.create({}).then(instance => {
if (previousInstance) {
return previousInstance['set'+ Sequelize.Utils.uppercaseFirst(model.name)](instance).then(() => {
return previousInstance['set'+ _.upperFirst(model.name)](instance).then(() => {
previousInstance = instance;
});
} else {
......@@ -609,7 +610,7 @@ describe(Support.getTestDialectTeaser('Include'), () => {
promise = promise.then(() => {
return model.create(values).then(instance => {
if (previousInstance) {
return previousInstance['set'+ Sequelize.Utils.uppercaseFirst(model.name)](instance).then(() => {
return previousInstance['set'+ _.upperFirst(model.name)](instance).then(() => {
previousInstance = instance;
});
} else {
......
......@@ -7,7 +7,8 @@ const chai = require('chai'),
Support = require(__dirname + '/../support'),
DataTypes = require(__dirname + '/../../../lib/data-types'),
Promise = Sequelize.Promise,
dialect = Support.getTestDialect();
dialect = Support.getTestDialect(),
_ = require('lodash');
const sortById = function(a, b) {
return a.id < b.id ? -1 : 1;
......@@ -382,7 +383,7 @@ describe(Support.getTestDialectTeaser('Includes with schemas'), () => {
return Promise.each(singles, model => {
return model.create({}).then(instance => {
if (previousInstance) {
return previousInstance['set'+ Sequelize.Utils.uppercaseFirst(model.name)](instance).then(() => {
return previousInstance['set'+ _.upperFirst(model.name)](instance).then(() => {
previousInstance = instance;
});
}
......
......@@ -9,65 +9,6 @@ const chai = require('chai'),
Op = Sequelize.Op;
describe(Support.getTestDialectTeaser('Utils'), () => {
describe('removeCommentsFromFunctionString', () => {
it('removes line comments at the start of a line', () => {
const functionWithLineComments = function() {
// noot noot
};
const string = functionWithLineComments.toString(),
result = Utils.removeCommentsFromFunctionString(string);
expect(result).not.to.match(/.*noot.*/);
});
it('removes lines comments in the middle of a line', () => {
const functionWithLineComments = function() {
console.log(1); // noot noot
};
const string = functionWithLineComments.toString(),
result = Utils.removeCommentsFromFunctionString(string);
expect(result).not.to.match(/.*noot.*/);
});
it('removes range comments', () => {
const s = function() {
console.log(1); /*
noot noot
*/
console.log(2); /*
foo
*/
}.toString();
const result = Utils.removeCommentsFromFunctionString(s);
expect(result).not.to.match(/.*noot.*/);
expect(result).not.to.match(/.*foo.*/);
expect(result).to.match(/.*console.log\(2\).*/);
});
});
describe('argsArePrimaryKeys', () => {
it('doesn\'t detect primary keys if primareyKeys and values have different lengths', () => {
expect(Utils.argsArePrimaryKeys([1, 2, 3], [1])).to.be.false;
});
it('doesn\'t detect primary keys if primary keys are hashes or arrays', () => {
expect(Utils.argsArePrimaryKeys([[]], [1])).to.be.false;
});
it('detects primary keys if length is correct and data types are matching', () => {
expect(Utils.argsArePrimaryKeys([1, 2, 3], ['INTEGER', 'INTEGER', 'INTEGER'])).to.be.true;
});
it('detects primary keys if primary keys are dates and lengths are matching', () => {
expect(Utils.argsArePrimaryKeys([new Date()], ['foo'])).to.be.true;
});
});
describe('underscore', () => {
describe('underscoredIf', () => {
it('is defined', () => {
......
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!