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

Commit 3fedaa43 by Michael Kaufman Committed by Sushant

refactor(lodash): use lodash directly (#8368)

1 parent 0d232c5c
......@@ -82,7 +82,7 @@ class BelongsToMany extends Association {
if (this.as) {
this.isAliased = true;
if (Utils._.isPlainObject(this.as)) {
if (_.isPlainObject(this.as)) {
this.options.name = this.as;
this.as = this.as.plural;
} else {
......
'use strict';
const Utils = require('./../utils');
const _ = require('lodash');
function checkNamingCollision(association) {
if (association.source.rawAttributes.hasOwnProperty(association.as)) {
......@@ -20,7 +20,7 @@ function addForeignKeyConstraints(newAttribute, source, target, options, key) {
if (options.foreignKeyConstraint || options.onDelete || options.onUpdate) {
// Find primary keys: composite keys not supported with this approach
const primaryKeys = Utils._.chain(source.rawAttributes).keys()
const primaryKeys = _.chain(source.rawAttributes).keys()
.filter(key => source.rawAttributes[key].primaryKey)
.map(key => source.rawAttributes[key].field || key).value();
......
......@@ -15,6 +15,7 @@ const uuid = require('uuid');
const semver = require('semver');
const QueryGenerator = {
_templateSettings: require('lodash').runInContext().templateSettings,
options: {},
extractTableDetails(tableName, options) {
......@@ -132,7 +133,7 @@ const QueryGenerator = {
columns: tmpColumns
};
tmpTable = _.template(tmpTable)(replacement).trim();
tmpTable = _.template(tmpTable, this._templateSettings)(replacement).trim();
outputFragment = ' OUTPUT ' + outputColumns + ' into @tmp';
const selectFromTmp = ';select * from @tmp';
......@@ -207,7 +208,7 @@ const QueryGenerator = {
].join(' ');
}
return _.template(query)(replacements);
return _.template(query, this._templateSettings)(replacements);
},
/*
......@@ -263,7 +264,7 @@ const QueryGenerator = {
returning: this._dialect.supports.returnValues && options.returning ? ' RETURNING *' : ''
};
return _.template(query)(replacements);
return _.template(query, this._templateSettings)(replacements);
},
/*
......@@ -324,7 +325,7 @@ const QueryGenerator = {
columns : tmpColumns
};
tmpTable = _.template(tmpTable)(replacement).trim();
tmpTable = _.template(tmpTable, this._templateSettings)(replacement).trim();
outputFragment = ' OUTPUT ' + outputColumns + ' into @tmp';
selectFromTmp = ';select * from @tmp';
......@@ -370,7 +371,7 @@ const QueryGenerator = {
return '';
}
return _.template(query)(replacements).trim();
return _.template(query, this._templateSettings)(replacements).trim();
},
/*
......@@ -419,7 +420,7 @@ const QueryGenerator = {
where: this.whereQuery(where)
};
return _.template(query)(replacements);
return _.template(query, this._templateSettings)(replacements);
},
nameIndexes(indexes, rawTablename) {
......
'use strict';
const _ = require('lodash');
const Utils = require('../../utils');
const SqlString = require('../../sql-string');
const Dot = require('dottie');
......@@ -213,7 +214,7 @@ class AbstractQuery {
}
handleShowTablesQuery(results) {
return Utils._.flatten(results.map(resultSet => Utils._.values(resultSet)));
return _.flatten(results.map(resultSet => _.values(resultSet)));
}
isShowIndexesQuery() {
......@@ -253,7 +254,7 @@ class AbstractQuery {
// Map raw fields to names if a mapping is provided
if (this.options.fieldMap) {
const fieldMap = this.options.fieldMap;
results = Utils._.map(results, result => Utils._.reduce(fieldMap, (result, name, field) => {
results = _.map(results, result => _.reduce(fieldMap, (result, name, field) => {
if (result[field] !== undefined) {
result[name] = result[field];
delete result[field];
......@@ -470,10 +471,10 @@ class AbstractQuery {
return lastKeyPrefixMemo[key];
};
const getUniqueKeyAttributes = model => {
let uniqueKeyAttributes = Utils._.chain(model.uniqueKeys);
let uniqueKeyAttributes = _.chain(model.uniqueKeys);
uniqueKeyAttributes = uniqueKeyAttributes
.result(uniqueKeyAttributes.findKey() + '.fields')
.map(field => Utils._.findKey(model.attributes, chr => chr.field === field))
.map(field => _.findKey(model.attributes, chr => chr.field === field))
.value();
return uniqueKeyAttributes;
......@@ -505,7 +506,7 @@ class AbstractQuery {
topHash += row[includeOptions.model.primaryKeyAttributes[$i]];
}
}
else if (!Utils._.isEmpty(includeOptions.model.uniqueKeys)) {
else if (!_.isEmpty(includeOptions.model.uniqueKeys)) {
uniqueKeyAttributes = getUniqueKeyAttributes(includeOptions.model);
for ($i = 0; $i < uniqueKeyAttributes.length; $i++) {
topHash += row[uniqueKeyAttributes[$i]];
......@@ -557,7 +558,7 @@ class AbstractQuery {
itemHash += row[prefix+'.'+primaryKeyAttributes[$i]];
}
}
else if (!Utils._.isEmpty(includeMap[prefix].model.uniqueKeys)) {
else if (!_.isEmpty(includeMap[prefix].model.uniqueKeys)) {
uniqueKeyAttributes = getUniqueKeyAttributes(includeMap[prefix].model);
for ($i = 0; $i < uniqueKeyAttributes.length; $i++) {
itemHash += row[prefix+'.'+uniqueKeyAttributes[$i]];
......@@ -646,7 +647,7 @@ class AbstractQuery {
itemHash += row[prefix+'.'+primaryKeyAttributes[$i]];
}
}
else if (!Utils._.isEmpty(includeMap[prefix].model.uniqueKeys)) {
else if (!_.isEmpty(includeMap[prefix].model.uniqueKeys)) {
uniqueKeyAttributes = getUniqueKeyAttributes(includeMap[prefix].model);
for ($i = 0; $i < uniqueKeyAttributes.length; $i++) {
itemHash += row[prefix+'.'+uniqueKeyAttributes[$i]];
......
'use strict';
const Utils = require('../../utils'),
DataTypes = require('../../data-types'),
AbstractQueryGenerator = require('../abstract/query-generator'),
randomBytes = require('crypto').randomBytes,
semver = require('semver');
const _ = require('lodash');
const Utils = require('../../utils');
const DataTypes = require('../../data-types');
const AbstractQueryGenerator = require('../abstract/query-generator');
const randomBytes = require('crypto').randomBytes;
const semver = require('semver');
/* istanbul ignore next */
const throwMethodUndefined = function(methodName) {
......@@ -59,10 +60,10 @@ const QueryGenerator = {
const dataType = attributes[attr];
let match;
if (Utils._.includes(dataType, 'PRIMARY KEY')) {
if (_.includes(dataType, 'PRIMARY KEY')) {
primaryKeys.push(attr);
if (Utils._.includes(dataType, 'REFERENCES')) {
if (_.includes(dataType, 'REFERENCES')) {
// MSSQL doesn't support inline REFERENCES declarations: move to the end
match = dataType.match(/^(.+) (REFERENCES.*)$/);
attrStr.push(this.quoteIdentifier(attr) + ' ' + match[1].replace(/PRIMARY KEY/, ''));
......@@ -70,7 +71,7 @@ const QueryGenerator = {
} else {
attrStr.push(this.quoteIdentifier(attr) + ' ' + dataType.replace(/PRIMARY KEY/, ''));
}
} else if (Utils._.includes(dataType, 'REFERENCES')) {
} else if (_.includes(dataType, 'REFERENCES')) {
// MSSQL doesn't support inline REFERENCES declarations: move to the end
match = dataType.match(/^(.+) (REFERENCES.*)$/);
attrStr.push(this.quoteIdentifier(attr) + ' ' + match[1]);
......@@ -88,11 +89,11 @@ const QueryGenerator = {
pkString = primaryKeys.map(pk => { return this.quoteIdentifier(pk); }).join(', ');
if (options.uniqueKeys) {
Utils._.each(options.uniqueKeys, (columns, indexName) => {
if (!Utils._.isString(indexName)) {
_.each(options.uniqueKeys, (columns, indexName) => {
if (!_.isString(indexName)) {
indexName = 'uniq_' + tableName + '_' + columns.fields.join('_');
}
values.attributes += ', CONSTRAINT ' + self.quoteIdentifier(indexName) + ' UNIQUE (' + Utils._.map(columns.fields, self.quoteIdentifier).join(', ') + ')';
values.attributes += ', CONSTRAINT ' + self.quoteIdentifier(indexName) + ' UNIQUE (' + _.map(columns.fields, self.quoteIdentifier).join(', ') + ')';
});
}
......@@ -106,7 +107,7 @@ const QueryGenerator = {
}
}
return Utils._.template(query)(values).trim() + ';';
return _.template(query, this._templateSettings)(values).trim() + ';';
},
describeTableQuery(tableName, schema) {
......@@ -144,7 +145,7 @@ const QueryGenerator = {
renameTableQuery(before, after) {
const query = 'EXEC sp_rename <%= before %>, <%= after %>;';
return Utils._.template(query)({
return _.template(query, this._templateSettings)({
before: this.quoteTable(before),
after: this.quoteTable(after)
});
......@@ -160,7 +161,7 @@ const QueryGenerator = {
table: this.quoteTable(tableName)
};
return Utils._.template(query)(values).trim() + ';';
return _.template(query, this._templateSettings)(values).trim() + ';';
},
addColumnQuery(table, key, dataType) {
......@@ -169,14 +170,14 @@ const QueryGenerator = {
dataType.field = key;
const query = 'ALTER TABLE <%= table %> ADD <%= attribute %>;',
attribute = Utils._.template('<%= key %> <%= definition %>')({
attribute = _.template('<%= key %> <%= definition %>', this._templateSettings)({
key: this.quoteIdentifier(key),
definition: this.attributeToSQL(dataType, {
context: 'addColumn'
})
});
return Utils._.template(query)({
return _.template(query, this._templateSettings)({
table: this.quoteTable(table),
attribute
});
......@@ -184,7 +185,7 @@ const QueryGenerator = {
removeColumnQuery(tableName, attributeName) {
const query = 'ALTER TABLE <%= tableName %> DROP COLUMN <%= attributeName %>;';
return Utils._.template(query)({
return _.template(query, this._templateSettings)({
tableName: this.quoteTable(tableName),
attributeName: this.quoteIdentifier(attributeName)
});
......@@ -198,13 +199,13 @@ const QueryGenerator = {
for (const attributeName in attributes) {
const definition = attributes[attributeName];
if (definition.match(/REFERENCES/)) {
constraintString.push(Utils._.template('<%= fkName %> FOREIGN KEY (<%= attrName %>) <%= definition %>')({
constraintString.push(_.template('<%= fkName %> FOREIGN KEY (<%= attrName %>) <%= definition %>', this._templateSettings)({
fkName: this.quoteIdentifier(attributeName + '_foreign_idx'),
attrName: this.quoteIdentifier(attributeName),
definition: definition.replace(/.+?(?=REFERENCES)/, '')
}));
} else {
attrString.push(Utils._.template('<%= attrName %> <%= definition %>')({
attrString.push(_.template('<%= attrName %> <%= definition %>', this._templateSettings)({
attrName: this.quoteIdentifier(attributeName),
definition
}));
......@@ -220,7 +221,7 @@ const QueryGenerator = {
finalQuery += 'ADD CONSTRAINT ' + constraintString.join(', ');
}
return Utils._.template(query)({
return _.template(query, this._templateSettings)({
tableName: this.quoteTable(tableName),
query: finalQuery
});
......@@ -230,7 +231,7 @@ const QueryGenerator = {
const query = "EXEC sp_rename '<%= tableName %>.<%= before %>', '<%= after %>', 'COLUMN';",
newName = Object.keys(attributes)[0];
return Utils._.template(query)({
return _.template(query, this._templateSettings)({
tableName: this.quoteTable(tableName),
before: attrBefore,
after: newName
......@@ -253,7 +254,7 @@ const QueryGenerator = {
outputFragment = ' OUTPUT INSERTED.*';
}
Utils._.forEach(attrValueHashes, attrValueHash => {
_.forEach(attrValueHashes, attrValueHash => {
// special case for empty objects with primary keys
const fields = Object.keys(attrValueHash);
const firstAttr = attributes[fields[0]];
......@@ -263,7 +264,7 @@ const QueryGenerator = {
}
// normal case
Utils._.forOwn(attrValueHash, (value, key) => {
_.forOwn(attrValueHash, (value, key) => {
if (value !== null && attributes[key] && attributes[key].autoIncrement) {
needIdentityInsertWrapper = true;
}
......@@ -278,7 +279,7 @@ const QueryGenerator = {
});
if (allAttributes.length > 0) {
Utils._.forEach(attrValueHashes, attrValueHash => {
_.forEach(attrValueHashes, attrValueHash => {
tuples.push('(' +
allAttributes.map(key =>
this.escape(attrValueHash[key])).join(',') +
......@@ -299,7 +300,7 @@ const QueryGenerator = {
output: outputFragment
};
let generatedQuery = Utils._.template(allQueries.join(';'))(replacements);
let generatedQuery = _.template(allQueries.join(';'), this._templateSettings)(replacements);
if (needIdentityInsertWrapper) {
generatedQuery = [
'SET IDENTITY_INSERT', this.quoteTable(tableName), 'ON;',
......@@ -454,7 +455,7 @@ const QueryGenerator = {
const query = 'DELETE<%= limit %> FROM <%= table %><%= where %>; ' +
'SELECT @@ROWCOUNT AS AFFECTEDROWS;';
if (Utils._.isUndefined(options.limit)) {
if (_.isUndefined(options.limit)) {
options.limit = 1;
}
......@@ -472,12 +473,12 @@ const QueryGenerator = {
replacements.where = ' WHERE ' + replacements.where;
}
return Utils._.template(query)(replacements);
return _.template(query, this._templateSettings)(replacements);
},
showIndexesQuery(tableName) {
const sql = "EXEC sys.sp_helpindex @objname = N'<%= tableName %>';";
return Utils._.template(sql)({
return _.template(sql, this._templateSettings)({
tableName: this.quoteTable(tableName)
});
},
......@@ -499,11 +500,11 @@ const QueryGenerator = {
indexName: this.quoteIdentifiers(indexName)
};
return Utils._.template(sql)(values);
return _.template(sql, this._templateSettings)(values);
},
attributeToSQL(attribute) {
if (!Utils._.isPlainObject(attribute)) {
if (!_.isPlainObject(attribute)) {
attribute = {
type: attribute
};
......@@ -527,7 +528,7 @@ const QueryGenerator = {
// enums are a special case
template = attribute.type.toSql();
template += ' CHECK (' + this.quoteIdentifier(attribute.field) + ' IN(' + Utils._.map(attribute.values, value => {
template += ' CHECK (' + this.quoteIdentifier(attribute.field) + ' IN(' + _.map(attribute.values, value => {
return this.escape(value);
}).join(', ') + '))';
return template;
......@@ -700,7 +701,7 @@ const QueryGenerator = {
},
dropForeignKeyQuery(tableName, foreignKey) {
return Utils._.template('ALTER TABLE <%= table %> DROP <%= key %>')({
return _.template('ALTER TABLE <%= table %> DROP <%= key %>', this._templateSettings)({
table: this.quoteTable(tableName),
key: this.quoteIdentifier(foreignKey)
});
......@@ -711,7 +712,7 @@ const QueryGenerator = {
"WHERE PARENT_OBJECT_ID = OBJECT_ID('<%= table %>', 'U') " +
"AND PARENT_COLUMN_ID = (SELECT column_id FROM sys.columns WHERE NAME = ('<%= column %>') " +
"AND object_id = OBJECT_ID('<%= table %>', 'U'));";
return Utils._.template(sql)({
return _.template(sql, this._templateSettings)({
table: this.quoteTable(tableName),
column: attributeName
});
......@@ -719,7 +720,7 @@ const QueryGenerator = {
dropConstraintQuery(tableName, constraintName) {
const sql = 'ALTER TABLE <%= table %> DROP CONSTRAINT <%= constraint %>;';
return Utils._.template(sql)({
return _.template(sql, this._templateSettings)({
table: this.quoteTable(tableName),
constraint: this.quoteIdentifier(constraintName)
});
......
......@@ -16,7 +16,7 @@ class Query extends AbstractQuery {
this.instance = options.instance;
this.model = options.model;
this.sequelize = sequelize;
this.options = Utils._.extend({
this.options = _.extend({
logging: console.log,
plain: false,
raw: false
......@@ -283,14 +283,14 @@ class Query extends AbstractQuery {
if (match[4]) {
const values = match[4].split(',').map(part => part.trim());
if (uniqueKey) {
fields = Utils._.zipObject(uniqueKey.fields, values);
fields = _.zipObject(uniqueKey.fields, values);
} else {
fields[match[1]] = match[4];
}
}
const errors = [];
Utils._.forOwn(fields, (value, field) => {
_.forOwn(fields, (value, field) => {
errors.push(new sequelizeErrors.ValidationErrorItem(
this.getUniqueConstraintErrorMessage(field),
'unique violation', field, value
......@@ -344,7 +344,7 @@ class Query extends AbstractQuery {
item.fields = [];
}
Utils._.forEach(item.index_keys.split(','), column => {
_.forEach(item.index_keys.split(','), column => {
let columnName = column.trim();
if (columnName.indexOf('(-)') !== -1) {
columnName = columnName.replace('(-)', '');
......@@ -361,7 +361,7 @@ class Query extends AbstractQuery {
return acc;
}, {});
return Utils._.map(data, item => ({
return _.map(data, item => ({
primary: item.index_name.toLowerCase().indexOf('pk') === 0,
fields: item.fields,
name: item.index_name,
......
'use strict';
const _ = require('lodash');
const AbstractConnectionManager = require('../abstract/connection-manager');
const SequelizeErrors = require('../../errors');
const Utils = require('../../utils');
......@@ -175,7 +176,7 @@ class ConnectionManager extends AbstractConnectionManager {
}
}
Utils._.extend(ConnectionManager.prototype, AbstractConnectionManager.prototype);
_.extend(ConnectionManager.prototype, AbstractConnectionManager.prototype);
module.exports = ConnectionManager;
module.exports.ConnectionManager = ConnectionManager;
......
'use strict';
const _ = require('lodash');
const Utils = require('../../utils');
const AbstractQueryGenerator = require('../abstract/query-generator');
......@@ -25,7 +26,7 @@ const QueryGenerator = {
},
createTableQuery(tableName, attributes, options) {
options = Utils._.extend({
options = _.extend({
engine: 'InnoDB',
charset: null,
rowFormat: null
......@@ -41,10 +42,10 @@ const QueryGenerator = {
const dataType = attributes[attr];
let match;
if (Utils._.includes(dataType, 'PRIMARY KEY')) {
if (_.includes(dataType, 'PRIMARY KEY')) {
primaryKeys.push(attr);
if (Utils._.includes(dataType, 'REFERENCES')) {
if (_.includes(dataType, 'REFERENCES')) {
// MySQL doesn't support inline REFERENCES declarations: move to the end
match = dataType.match(/^(.+) (REFERENCES.*)$/);
attrStr.push(this.quoteIdentifier(attr) + ' ' + match[1].replace(/PRIMARY KEY/, ''));
......@@ -52,7 +53,7 @@ const QueryGenerator = {
} else {
attrStr.push(this.quoteIdentifier(attr) + ' ' + dataType.replace(/PRIMARY KEY/, ''));
}
} else if (Utils._.includes(dataType, 'REFERENCES')) {
} else if (_.includes(dataType, 'REFERENCES')) {
// MySQL doesn't support inline REFERENCES declarations: move to the end
match = dataType.match(/^(.+) (REFERENCES.*)$/);
attrStr.push(this.quoteIdentifier(attr) + ' ' + match[1]);
......@@ -66,7 +67,7 @@ const QueryGenerator = {
const values = {
table: this.quoteTable(tableName),
attributes: attrStr.join(', '),
comment: options.comment && Utils._.isString(options.comment) ? ' COMMENT ' + this.escape(options.comment) : '',
comment: options.comment && _.isString(options.comment) ? ' COMMENT ' + this.escape(options.comment) : '',
engine: options.engine,
charset: options.charset ? ' DEFAULT CHARSET=' + options.charset : '',
collation: options.collate ? ' COLLATE ' + options.collate : '',
......@@ -76,12 +77,12 @@ const QueryGenerator = {
const pkString = primaryKeys.map(pk => this.quoteIdentifier(pk)).join(', ');
if (options.uniqueKeys) {
Utils._.each(options.uniqueKeys, (columns, indexName) => {
_.each(options.uniqueKeys, (columns, indexName) => {
if (!columns.singleField) { // If it's a single field its handled in column def, not as an index
if (!Utils._.isString(indexName)) {
if (!_.isString(indexName)) {
indexName = 'uniq_' + tableName + '_' + columns.fields.join('_');
}
values.attributes += ', UNIQUE ' + this.quoteIdentifier(indexName) + ' (' + Utils._.map(columns.fields, this.quoteIdentifier).join(', ') + ')';
values.attributes += ', UNIQUE ' + this.quoteIdentifier(indexName) + ' (' + _.map(columns.fields, this.quoteIdentifier).join(', ') + ')';
}
});
}
......@@ -96,7 +97,7 @@ const QueryGenerator = {
}
}
return Utils._.template(query)(values).trim() + ';';
return _.template(query, this._templateSettings)(values).trim() + ';';
},
showTablesQuery() {
......@@ -179,7 +180,7 @@ const QueryGenerator = {
where = this.getWhereConditions(where);
let limit = '';
if (Utils._.isUndefined(options.limit)) {
if (_.isUndefined(options.limit)) {
options.limit = 1;
}
......@@ -228,7 +229,7 @@ const QueryGenerator = {
},
attributeToSQL(attribute, options) {
if (!Utils._.isPlainObject(attribute)) {
if (!_.isPlainObject(attribute)) {
attribute = {
type: attribute
};
......
......@@ -15,7 +15,7 @@ class Query extends AbstractQuery {
this.model = options.model;
this.sequelize = sequelize;
this.uuid = uuid.v4();
this.options = Utils._.extend({
this.options = _.extend({
logging: console.log,
plain: false,
raw: false,
......@@ -185,13 +185,13 @@ class Query extends AbstractQuery {
if (uniqueKey) {
if (uniqueKey.msg) message = uniqueKey.msg;
fields = Utils._.zipObject(uniqueKey.fields, values);
fields = _.zipObject(uniqueKey.fields, values);
} else {
fields[match[2]] = match[1];
}
const errors = [];
Utils._.forOwn(fields, (value, field) => {
_.forOwn(fields, (value, field) => {
errors.push(new sequelizeErrors.ValidationErrorItem(
this.getUniqueConstraintErrorMessage(field),
'unique violation', field, value
......@@ -241,7 +241,7 @@ class Query extends AbstractQuery {
return acc;
}, {});
return Utils._.map(data, item => ({
return _.map(data, item => ({
primary: item.Key_name === 'PRIMARY',
fields: item.fields,
name: item.Key_name,
......
'use strict';
const _ = require('lodash');
const AbstractConnectionManager = require('../abstract/connection-manager');
const Utils = require('../../utils');
const debug = Utils.getLogger().debugContext('connection:pg');
......@@ -54,13 +55,13 @@ class ConnectionManager extends AbstractConnectionManager {
connect(config) {
config.user = config.username;
const connectionConfig = Utils._.pick(config, [
const connectionConfig = _.pick(config, [
'user', 'password', 'host', 'database', 'port'
]);
if (config.dialectOptions) {
Utils._.merge(connectionConfig,
Utils._.pick(config.dialectOptions, [
_.merge(connectionConfig,
_.pick(config.dialectOptions, [
// see [http://www.postgresql.org/docs/9.3/static/runtime-config-logging.html#GUC-APPLICATION-NAME]
'application_name',
// choose the SSL mode with the PGSSLMODE environment variable
......@@ -187,7 +188,7 @@ class ConnectionManager extends AbstractConnectionManager {
}
}
Utils._.extend(ConnectionManager.prototype, AbstractConnectionManager.prototype);
_.extend(ConnectionManager.prototype, AbstractConnectionManager.prototype);
module.exports = ConnectionManager;
module.exports.ConnectionManager = ConnectionManager;
......
......@@ -34,15 +34,15 @@ const QueryGenerator = {
createTableQuery(tableName, attributes, options) {
options = Utils._.extend({
options = _.extend({
}, options || {});
//Postgres 9.0 does not support CREATE TABLE IF NOT EXISTS, 9.1 and above do
const databaseVersion = Utils._.get(this, 'sequelize.options.databaseVersion', 0);
const databaseVersion = _.get(this, 'sequelize.options.databaseVersion', 0);
const attrStr = [];
let comments = '';
if (options.comment && Utils._.isString(options.comment)) {
if (options.comment && _.isString(options.comment)) {
comments += '; COMMENT ON TABLE <%= table %> IS ' + this.escape(options.comment);
}
......@@ -61,11 +61,11 @@ const QueryGenerator = {
const values = {
table: this.quoteTable(tableName),
attributes: attrStr.join(', '),
comments: Utils._.template(comments)({ table: this.quoteTable(tableName) })
comments: _.template(comments, this._templateSettings)({ table: this.quoteTable(tableName) })
};
if (options.uniqueKeys) {
Utils._.each(options.uniqueKeys, columns => {
_.each(options.uniqueKeys, columns => {
if (!columns.singleField) { // If it's a single field its handled in column def, not as an index
values.attributes += ', UNIQUE (' + columns.fields.map(f => this.quoteIdentifiers(f)).join(', ') + ')';
}
......@@ -264,28 +264,28 @@ const QueryGenerator = {
let attrSql = '';
if (definition.indexOf('NOT NULL') > 0) {
attrSql += Utils._.template(query)({
attrSql += _.template(query, this._templateSettings)({
tableName: this.quoteTable(tableName),
query: this.quoteIdentifier(attributeName) + ' SET NOT NULL'
});
definition = definition.replace('NOT NULL', '').trim();
} else if (!definition.match(/REFERENCES/)) {
attrSql += Utils._.template(query)({
attrSql += _.template(query, this._templateSettings)({
tableName: this.quoteTable(tableName),
query: this.quoteIdentifier(attributeName) + ' DROP NOT NULL'
});
}
if (definition.indexOf('DEFAULT') > 0) {
attrSql += Utils._.template(query)({
attrSql += _.template(query, this._templateSettings)({
tableName: this.quoteTable(tableName),
query: this.quoteIdentifier(attributeName) + ' SET DEFAULT ' + definition.match(/DEFAULT ([^;]+)/)[1]
});
definition = definition.replace(/(DEFAULT[^;]+)/, '').trim();
} else if (!definition.match(/REFERENCES/)) {
attrSql += Utils._.template(query)({
attrSql += _.template(query, this._templateSettings)({
tableName: this.quoteTable(tableName),
query: this.quoteIdentifier(attributeName) + ' DROP DEFAULT'
});
......@@ -300,7 +300,7 @@ const QueryGenerator = {
if (definition.match(/UNIQUE;*$/)) {
definition = definition.replace(/UNIQUE;*$/, '');
attrSql += Utils._.template(query.replace('ALTER COLUMN', ''))({
attrSql += _.template(query.replace('ALTER COLUMN', ''), this._templateSettings)({
tableName: this.quoteTable(tableName),
query: 'ADD CONSTRAINT ' + this.quoteIdentifier(attributeName + '_unique_idx') + ' UNIQUE (' + this.quoteIdentifier(attributeName) + ')'
});
......@@ -308,12 +308,12 @@ const QueryGenerator = {
if (definition.match(/REFERENCES/)) {
definition = definition.replace(/.+?(?=REFERENCES)/, '');
attrSql += Utils._.template(query.replace('ALTER COLUMN', ''))({
attrSql += _.template(query.replace('ALTER COLUMN', ''), this._templateSettings)({
tableName: this.quoteTable(tableName),
query: 'ADD CONSTRAINT ' + this.quoteIdentifier(attributeName + '_foreign_idx') + ' FOREIGN KEY (' + this.quoteIdentifier(attributeName) + ') ' + definition
});
} else {
attrSql += Utils._.template(query)({
attrSql += _.template(query, this._templateSettings)({
tableName: this.quoteTable(tableName),
query: this.quoteIdentifier(attributeName) + ' TYPE ' + definition
});
......@@ -330,7 +330,7 @@ const QueryGenerator = {
const attrString = [];
for (const attributeName in attributes) {
attrString.push(Utils._.template('<%= before %> TO <%= after %>')({
attrString.push(_.template('<%= before %> TO <%= after %>', this._templateSettings)({
before: this.quoteIdentifier(attrBefore),
after: this.quoteIdentifier(attributeName)
}));
......@@ -391,7 +391,7 @@ const QueryGenerator = {
return query;
}
if (Utils._.isUndefined(options.limit)) {
if (_.isUndefined(options.limit)) {
options.limit = 1;
}
......@@ -420,13 +420,13 @@ const QueryGenerator = {
replacements.where = ' WHERE ' + replacements.where;
}
return Utils._.template(query)(replacements);
return _.template(query, this._templateSettings)(replacements);
},
showIndexesQuery(tableName) {
let schemaJoin = '';
let schemaWhere = '';
if (!Utils._.isString(tableName)) {
if (!_.isString(tableName)) {
schemaJoin = ', pg_namespace s';
schemaWhere = ` AND s.oid = t.relnamespace AND s.nspname = '${tableName.schema}'`;
tableName = tableName.tableName;
......@@ -483,7 +483,7 @@ const QueryGenerator = {
},
attributeToSQL(attribute) {
if (!Utils._.isPlainObject(attribute)) {
if (!_.isPlainObject(attribute)) {
attribute = {
type: attribute
};
......@@ -494,7 +494,7 @@ const QueryGenerator = {
if (attribute.type.values && !attribute.values) attribute.values = attribute.type.values;
if (Array.isArray(attribute.values) && attribute.values.length > 0) {
type = 'ENUM(' + Utils._.map(attribute.values, value => this.escape(value)).join(', ') + ')';
type = 'ENUM(' + _.map(attribute.values, value => this.escape(value)).join(', ') + ')';
} else {
throw new Error("Values for ENUM haven't been defined.");
}
......@@ -653,16 +653,16 @@ const QueryGenerator = {
},
expandFunctionParamList(params) {
if (Utils._.isUndefined(params) || !Utils._.isArray(params)) {
if (_.isUndefined(params) || !_.isArray(params)) {
throw new Error('expandFunctionParamList: function parameters array required, including an empty one for no arguments');
}
const paramList = [];
Utils._.each(params, curParam => {
_.each(params, curParam => {
const paramDef = [];
if (Utils._.has(curParam, 'type')) {
if (Utils._.has(curParam, 'direction')) { paramDef.push(curParam.direction); }
if (Utils._.has(curParam, 'name')) { paramDef.push(curParam.name); }
if (_.has(curParam, 'type')) {
if (_.has(curParam, 'direction')) { paramDef.push(curParam.direction); }
if (_.has(curParam, 'name')) { paramDef.push(curParam.name); }
paramDef.push(curParam.type);
} else {
throw new Error('function or trigger used with a parameter without any type');
......@@ -677,7 +677,7 @@ const QueryGenerator = {
},
expandOptions(options) {
return Utils._.isUndefined(options) || Utils._.isEmpty(options) ?
return _.isUndefined(options) || _.isEmpty(options) ?
'' : '\n\t' + options.join('\n\t');
},
......@@ -689,7 +689,7 @@ const QueryGenerator = {
'after_constraint': 'AFTER'
};
if (!Utils._.has(EVENT_DECODER, eventSpecifier)) {
if (!_.has(EVENT_DECODER, eventSpecifier)) {
throw new Error('Invalid trigger event specified: ' + eventSpecifier);
}
......@@ -701,11 +701,11 @@ const QueryGenerator = {
},
expandTriggerEventSpec(fireOnSpec) {
if (Utils._.isEmpty(fireOnSpec)) {
if (_.isEmpty(fireOnSpec)) {
throw new Error('no table change events specified to trigger on');
}
return Utils._.map(fireOnSpec, (fireValue, fireKey) => {
return _.map(fireOnSpec, (fireValue, fireKey) => {
const EVENT_MAP = {
'insert': 'INSERT',
'update': 'UPDATE',
......@@ -713,13 +713,13 @@ const QueryGenerator = {
'truncate': 'TRUNCATE'
};
if (!Utils._.has(EVENT_MAP, fireValue)) {
if (!_.has(EVENT_MAP, fireValue)) {
throw new Error('parseTriggerEventSpec: undefined trigger event ' + fireKey);
}
let eventSpec = EVENT_MAP[fireValue];
if (eventSpec === 'UPDATE') {
if (Utils._.isArray(fireValue) && fireValue.length > 0) {
if (_.isArray(fireValue) && fireValue.length > 0) {
eventSpec += ' OF ' + fireValue.join(', ');
}
}
......@@ -814,12 +814,12 @@ const QueryGenerator = {
},
dataTypeMapping(tableName, attr, dataType) {
if (Utils._.includes(dataType, 'PRIMARY KEY')) {
if (_.includes(dataType, 'PRIMARY KEY')) {
dataType = dataType.replace(/PRIMARY KEY/, '');
}
if (Utils._.includes(dataType, 'SERIAL')) {
if (Utils._.includes(dataType, 'BIGINT')) {
if (_.includes(dataType, 'SERIAL')) {
if (_.includes(dataType, 'BIGINT')) {
dataType = dataType.replace(/SERIAL/, 'BIGSERIAL');
dataType = dataType.replace(/BIGINT/, '');
} else {
......
......@@ -56,7 +56,7 @@ class Query extends AbstractQuery {
run(sql, parameters) {
this.sql = sql;
if (!Utils._.isEmpty(this.options.searchPath)) {
if (!_.isEmpty(this.options.searchPath)) {
this.sql = this.sequelize.getQueryInterface().QueryGenerator.setSearchPath(this.options.searchPath) + sql;
}
......
......@@ -28,21 +28,21 @@ const QueryGenerator = {
options = options || {};
const primaryKeys = [];
const needsMultiplePrimaryKeys = Utils._.values(attributes).filter(definition => _.includes(definition, 'PRIMARY KEY')).length > 1;
const needsMultiplePrimaryKeys = _.values(attributes).filter(definition => _.includes(definition, 'PRIMARY KEY')).length > 1;
const attrArray = [];
for (const attr in attributes) {
if (attributes.hasOwnProperty(attr)) {
let dataType = attributes[attr];
const containsAutoIncrement = Utils._.includes(dataType, 'AUTOINCREMENT');
const containsAutoIncrement = _.includes(dataType, 'AUTOINCREMENT');
if (containsAutoIncrement) {
dataType = dataType.replace(/BIGINT/, 'INTEGER');
}
let dataTypeString = dataType;
if (Utils._.includes(dataType, 'PRIMARY KEY')) {
if (Utils._.includes(dataType, 'INTEGER')) { // Only INTEGER is allowed for primary key, see https://github.com/sequelize/sequelize/issues/969 (no lenght, unsigned etc)
if (_.includes(dataType, 'PRIMARY KEY')) {
if (_.includes(dataType, 'INTEGER')) { // Only INTEGER is allowed for primary key, see https://github.com/sequelize/sequelize/issues/969 (no lenght, unsigned etc)
dataTypeString = containsAutoIncrement ? 'INTEGER PRIMARY KEY AUTOINCREMENT' : 'INTEGER PRIMARY KEY';
}
......@@ -60,7 +60,7 @@ const QueryGenerator = {
const pkString = primaryKeys.map(pk => this.quoteIdentifier(pk)).join(', ');
if (options.uniqueKeys) {
Utils._.each(options.uniqueKeys, columns => {
_.each(options.uniqueKeys, columns => {
if (!columns.singleField) { // If it's a single field its handled in column def, not as an index
attrStr += ', UNIQUE (' + columns.fields.map(field => this.quoteIdentifier(field)).join(', ') + ')';
}
......@@ -299,7 +299,7 @@ const QueryGenerator = {
const dataType = attributes[name];
const fieldName = dataType.field || name;
if (Utils._.isObject(dataType)) {
if (_.isObject(dataType)) {
let sql = dataType.type.toString();
if (dataType.hasOwnProperty('allowNull') && !dataType.allowNull) {
......
'use strict';
const Utils = require('../../utils');
const _ = require('lodash');
const Promise = require('../../promise');
const UnknownConstraintError = require('../../errors').UnknownConstraintError;
......@@ -37,7 +37,7 @@ function removeColumn(tableName, attributeName, options) {
const sql = this.QueryGenerator.removeColumnQuery(tableName, fields);
const subQueries = sql.split(';').filter(q => q !== '');
return Promise.each(subQueries, subQuery => this.sequelize.query(subQuery + ';', Utils._.assign({raw: true}, options)));
return Promise.each(subQueries, subQuery => this.sequelize.query(subQuery + ';', _.assign({raw: true}, options)));
});
}
exports.removeColumn = removeColumn;
......@@ -68,7 +68,7 @@ function changeColumn(tableName, attributes, options) {
const sql = this.QueryGenerator.removeColumnQuery(tableName, fields);
const subQueries = sql.split(';').filter(q => q !== '');
return Promise.each(subQueries, subQuery => this.sequelize.query(subQuery + ';', Utils._.assign({raw: true}, options)));
return Promise.each(subQueries, subQuery => this.sequelize.query(subQuery + ';', _.assign({raw: true}, options)));
});
}
exports.changeColumn = changeColumn;
......@@ -94,13 +94,13 @@ function renameColumn(tableName, attrNameBefore, attrNameAfter, options) {
options = options || {};
return this.describeTable(tableName, options).then(fields => {
fields[attrNameAfter] = Utils._.clone(fields[attrNameBefore]);
fields[attrNameAfter] = _.clone(fields[attrNameBefore]);
delete fields[attrNameBefore];
const sql = this.QueryGenerator.renameColumnQuery(tableName, attrNameBefore, attrNameAfter, fields);
const subQueries = sql.split(';').filter(q => q !== '');
return Promise.each(subQueries, subQuery => this.sequelize.query(subQuery + ';', Utils._.assign({raw: true}, options)));
return Promise.each(subQueries, subQuery => this.sequelize.query(subQuery + ';', _.assign({raw: true}, options)));
});
}
exports.renameColumn = renameColumn;
......@@ -138,7 +138,7 @@ function removeConstraint(tableName, constraintName, options) {
const sql = this.QueryGenerator._alterConstraintQuery(tableName, fields, createTableSql);
const subQueries = sql.split(';').filter(q => q !== '');
return Promise.each(subQueries, subQuery => this.sequelize.query(subQuery + ';', Utils._.assign({raw: true}, options)));
return Promise.each(subQueries, subQuery => this.sequelize.query(subQuery + ';', _.assign({raw: true}, options)));
});
}
exports.removeConstraint = removeConstraint;
......@@ -162,7 +162,7 @@ function addConstraint(tableName, options) {
const sql = this.QueryGenerator._alterConstraintQuery(tableName, fields, createTableSql);
const subQueries = sql.split(';').filter(q => q !== '');
return Promise.each(subQueries, subQuery => this.sequelize.query(subQuery + ';', Utils._.assign({raw: true}, options)));
return Promise.each(subQueries, subQuery => this.sequelize.query(subQuery + ';', _.assign({raw: true}, options)));
});
}
exports.addConstraint = addConstraint;
'use strict';
const _ = require('lodash');
const Utils = require('./utils');
const Promise = require('./promise');
const debug = Utils.getLogger().debugContext('hooks');
......@@ -67,7 +68,7 @@ const getProxiedHooks = hookType =>
const Hooks = {
replaceHookAliases(hooks) {
Utils._.each(hooks, (hooksArray, name) => {
_.each(hooks, (hooksArray, name) => {
// Does an alias for this hook name exist?
const realHookName = hookAliases[name];
if (realHookName) {
......@@ -148,7 +149,7 @@ const Hooks = {
// check for proxies, add them too
hookType = getProxiedHooks(hookType);
Utils._.each(hookType, type => {
_.each(hookType, type => {
this.options.hooks[type] = this.options.hooks[type] || [];
this.options.hooks[type].push(name ? {name, fn} : fn);
});
......@@ -209,7 +210,7 @@ Hooks.hasHooks = Hooks.hasHook;
function applyTo(target) {
Utils._.mixin(target, Hooks);
_.mixin(target, Hooks);
const allHooks = Object.keys(hookTypes).concat(Object.keys(hookAliases));
for (const hook of allHooks) {
......
......@@ -22,11 +22,11 @@ class InstanceValidator {
options = _.clone(options) || {};
if (options.fields && !options.skip) {
options.skip = Utils._.difference(Object.keys(modelInstance.constructor.rawAttributes), options.fields);
options.skip = _.difference(Object.keys(modelInstance.constructor.rawAttributes), options.fields);
}
// assign defined and default options
this.options = Utils._.defaults(options, {
this.options = _.defaults(options, {
skip: [],
hooks: true
});
......@@ -124,7 +124,7 @@ class InstanceValidator {
_builtinValidators() {
// promisify all attribute invocations
const validators = [];
Utils._.forIn(this.modelInstance.rawAttributes, (rawAttribute, field) => {
_.forIn(this.modelInstance.rawAttributes, (rawAttribute, field) => {
if (this.options.skip.indexOf(field) >= 0) {
return;
}
......@@ -152,7 +152,7 @@ class InstanceValidator {
*/
_customValidators() {
const validators = [];
Utils._.each(this.modelInstance._modelOptions.validate, (validator, validatorType) => {
_.each(this.modelInstance._modelOptions.validate, (validator, validatorType) => {
if (this.options.skip.indexOf(validatorType) >= 0) {
return;
}
......@@ -185,7 +185,7 @@ class InstanceValidator {
// Promisify each validator
const validators = [];
Utils._.forIn(this.modelInstance.validators[field], (test, validatorType) => {
_.forIn(this.modelInstance.validators[field], (test, validatorType) => {
if (['isUrl', 'isURL', 'isEmail'].indexOf(validatorType) !== -1) {
// Preserve backwards compat. Validator.js now expects the second param to isURL and isEmail to be an object
......
......@@ -81,7 +81,7 @@ class Model {
deletedAtObject[deletedAtAttribute.field || deletedAtCol] = deletedAtDefaultValue;
if (Utils._.isEmpty(options.where)) {
if (_.isEmpty(options.where)) {
options.where = deletedAtObject;
} else {
options.where = { $and: [deletedAtObject, options.where] };
......@@ -145,19 +145,19 @@ class Model {
};
}
const existingAttributes = Utils._.clone(this.rawAttributes);
const existingAttributes = _.clone(this.rawAttributes);
this.rawAttributes = {};
Utils._.each(head, (value, attr) => {
_.each(head, (value, attr) => {
this.rawAttributes[attr] = value;
});
Utils._.each(existingAttributes, (value, attr) => {
_.each(existingAttributes, (value, attr) => {
this.rawAttributes[attr] = value;
});
Utils._.each(tail, (value, attr) => {
if (Utils._.isUndefined(this.rawAttributes[attr])) {
_.each(tail, (value, attr) => {
if (_.isUndefined(this.rawAttributes[attr])) {
this.rawAttributes[attr] = value;
}
});
......@@ -319,7 +319,7 @@ class Model {
const used = [];
(function addAllIncludes(parent, includes) {
Utils._.forEach(parent.associations, association => {
_.forEach(parent.associations, association => {
if (all !== true && all.indexOf(association.associationType) === -1) {
return;
}
......@@ -334,7 +334,7 @@ class Model {
predicate.as = as;
}
if (Utils._.find(includes, predicate)) {
if (_.find(includes, predicate)) {
return;
}
......@@ -496,7 +496,7 @@ class Model {
if (!include.include) include.include = [];
const through = include.association.through;
include.through = Utils._.defaults(include.through || {}, {
include.through = _.defaults(include.through || {}, {
model: through.model,
as: through.model.name,
association: {
......@@ -610,7 +610,7 @@ class Model {
}
}
Utils._.forEach(includes, include => {
_.forEach(includes, include => {
this._expandIncludeAll.call(include.model, include);
});
}
......@@ -779,7 +779,7 @@ class Model {
// error check options
_.each(options.validate, (validator, validatorType) => {
if (_.includes(Utils._.keys(attributes), validatorType)) {
if (_.includes(_.keys(attributes), validatorType)) {
throw new Error('A model validator function must not have the same name as a field. Model: ' + this.name + ', field/validation name: ' + validatorType);
}
......@@ -823,12 +823,12 @@ class Model {
}
// Add head and tail default attributes (id, timestamps)
this._readOnlyAttributes = Utils._.values(this._timestampAttributes);
this._readOnlyAttributes = _.values(this._timestampAttributes);
if (this._versionAttribute) {
this._readOnlyAttributes.push(this._versionAttribute);
}
this._hasReadOnlyAttributes = this._readOnlyAttributes && this._readOnlyAttributes.length;
this._isReadOnlyAttribute = Utils._.memoize(key => this._hasReadOnlyAttributes && this._readOnlyAttributes.indexOf(key) !== -1);
this._isReadOnlyAttribute = _.memoize(key => this._hasReadOnlyAttributes && this._readOnlyAttributes.indexOf(key) !== -1);
this._addDefaultAttributes();
this.refreshAttributes();
......@@ -873,12 +873,12 @@ class Model {
this.prototype._customGetters = {};
this.prototype._customSetters = {};
Utils._.each(['get', 'set'], type => {
_.each(['get', 'set'], type => {
const opt = type + 'terMethods';
const funcs = Utils._.clone(Utils._.isObject(this.options[opt]) ? this.options[opt] : {});
const funcs = _.clone(_.isObject(this.options[opt]) ? this.options[opt] : {});
const _custom = type === 'get' ? this.prototype._customGetters : this.prototype._customSetters;
Utils._.each(funcs, (method, attribute) => {
_.each(funcs, (method, attribute) => {
_custom[attribute] = method;
if (type === 'get') {
......@@ -893,7 +893,7 @@ class Model {
}
});
Utils._.each(this.rawAttributes, (options, attribute) => {
_.each(this.rawAttributes, (options, attribute) => {
if (options.hasOwnProperty(type)) {
_custom[attribute] = options[type];
}
......@@ -910,7 +910,7 @@ class Model {
}
});
Utils._.each(funcs, (fct, name) => {
_.each(funcs, (fct, name) => {
if (!attributeManipulation[name]) {
attributeManipulation[name] = {
configurable: true
......@@ -969,7 +969,7 @@ class Model {
}
if (definition.hasOwnProperty('defaultValue')) {
this._defaultValues[name] = Utils._.partial(Utils.toDefaultValue, definition.defaultValue);
this._defaultValues[name] = _.partial(Utils.toDefaultValue, definition.defaultValue);
}
if (definition.hasOwnProperty('unique') && definition.unique !== false) {
......@@ -1006,7 +1006,7 @@ class Model {
}
});
// Create a map of field to attribute names
this.fieldAttributeMap = Utils._.reduce(this.fieldRawAttributesMap, (map, value, key) => {
this.fieldAttributeMap = _.reduce(this.fieldRawAttributesMap, (map, value, key) => {
if (key !== value.fieldName) {
map[key] = value.fieldName;
}
......@@ -1016,33 +1016,33 @@ class Model {
this.uniqueKeys = this.options.uniqueKeys;
this._hasBooleanAttributes = !!this._booleanAttributes.length;
this._isBooleanAttribute = Utils._.memoize(key => this._booleanAttributes.indexOf(key) !== -1);
this._isBooleanAttribute = _.memoize(key => this._booleanAttributes.indexOf(key) !== -1);
this._hasDateAttributes = !!this._dateAttributes.length;
this._isDateAttribute = Utils._.memoize(key => this._dateAttributes.indexOf(key) !== -1);
this._isDateAttribute = _.memoize(key => this._dateAttributes.indexOf(key) !== -1);
this._hasHstoreAttributes = !!this._hstoreAttributes.length;
this._isHstoreAttribute = Utils._.memoize(key => this._hstoreAttributes.indexOf(key) !== -1);
this._isHstoreAttribute = _.memoize(key => this._hstoreAttributes.indexOf(key) !== -1);
this._hasRangeAttributes = !!this._rangeAttributes.length;
this._isRangeAttribute = Utils._.memoize(key => this._rangeAttributes.indexOf(key) !== -1);
this._isRangeAttribute = _.memoize(key => this._rangeAttributes.indexOf(key) !== -1);
this._hasJsonAttributes = !!this._jsonAttributes.length;
this._isJsonAttribute = Utils._.memoize(key => this._jsonAttributes.indexOf(key) !== -1);
this._isJsonAttribute = _.memoize(key => this._jsonAttributes.indexOf(key) !== -1);
this._hasVirtualAttributes = !!this._virtualAttributes.length;
this._isVirtualAttribute = Utils._.memoize(key => this._virtualAttributes.indexOf(key) !== -1);
this._isVirtualAttribute = _.memoize(key => this._virtualAttributes.indexOf(key) !== -1);
this._hasGeometryAttributes = !!this._geometryAttributes.length;
this._isGeometryAttribute = Utils._.memoize(key => this._geometryAttributes.indexOf(key) !== -1);
this._isGeometryAttribute = _.memoize(key => this._geometryAttributes.indexOf(key) !== -1);
this._hasDefaultValues = !Utils._.isEmpty(this._defaultValues);
this._hasDefaultValues = !_.isEmpty(this._defaultValues);
// DEPRECATE: All code base is free from this.attributes now
// This should be removed in v5
this.attributes = this.rawAttributes;
this.tableAttributes = Utils._.omit(this.rawAttributes, this._virtualAttributes);
this.tableAttributes = _.omit(this.rawAttributes, this._virtualAttributes);
this.prototype._hasCustomGetters = Object.keys(this.prototype._customGetters).length;
this.prototype._hasCustomSetters = Object.keys(this.prototype._customSetters).length;
......@@ -1058,7 +1058,7 @@ class Model {
this.prototype.rawAttributes = this.rawAttributes;
this.prototype.attributes = Object.keys(this.prototype.rawAttributes);
this.prototype._isAttribute = Utils._.memoize(key => this.prototype.attributes.indexOf(key) !== -1);
this.prototype._isAttribute = _.memoize(key => this.prototype.attributes.indexOf(key) !== -1);
// Primary key convenience constiables
this.primaryKeyAttributes = Object.keys(this.primaryKeys);
......@@ -1068,7 +1068,7 @@ class Model {
}
this._hasPrimaryKeys = this.primaryKeyAttributes.length > 0;
this._isPrimaryKey = Utils._.memoize(key => this.primaryKeyAttributes.indexOf(key) !== -1);
this._isPrimaryKey = _.memoize(key => this.primaryKeyAttributes.indexOf(key) !== -1);
}
/**
......@@ -2002,9 +2002,9 @@ class Model {
return this.find(options).then(instance => {
if (instance === null) {
values = Utils._.clone(options.defaults) || {};
if (Utils._.isPlainObject(options.where)) {
values = Utils._.defaults(values, options.where);
values = _.clone(options.defaults) || {};
if (_.isPlainObject(options.where)) {
values = _.defaults(values, options.where);
}
instance = this.build(values);
......@@ -2063,8 +2063,8 @@ class Model {
return [instance, false];
}
values = Utils._.clone(options.defaults) || {};
if (Utils._.isPlainObject(options.where)) {
values = _.clone(options.defaults) || {};
if (_.isPlainObject(options.where)) {
values = _.defaults(values, options.where);
}
......@@ -2133,8 +2133,8 @@ class Model {
);
}
let values = Utils._.clone(options.defaults) || {};
if (Utils._.isPlainObject(options.where)) {
let values = _.clone(options.defaults) || {};
if (_.isPlainObject(options.where)) {
values = _.defaults(values, options.where);
}
......@@ -2174,7 +2174,7 @@ class Model {
* @return {Promise<created>} Returns a boolean indicating whether the row was created or updated.
*/
static upsert(values, options) {
options = Utils._.extend({
options = _.extend({
hooks: true
}, Utils.cloneDeep(options || {}));
......@@ -2255,7 +2255,7 @@ class Model {
return Promise.resolve([]);
}
options = Utils._.extend({
options = _.extend({
validate: false,
hooks: true,
individualHooks: false,
......@@ -2274,9 +2274,9 @@ class Model {
if (options.updateOnDuplicate) {
// By default, all attributes except 'createdAt' can be updated
let updatableFields = Utils._.pull(Object.keys(this.tableAttributes), 'createdAt');
if (Utils._.isArray(options.updateOnDuplicate) && !Utils._.isEmpty(options.updateOnDuplicate)) {
updatableFields = Utils._.intersection(updatableFields, options.updateOnDuplicate);
let updatableFields = _.pull(Object.keys(this.tableAttributes), 'createdAt');
if (_.isArray(options.updateOnDuplicate) && !_.isEmpty(options.updateOnDuplicate)) {
updatableFields = _.intersection(updatableFields, options.updateOnDuplicate);
}
options.updateOnDuplicate = updatableFields;
}
......@@ -2332,7 +2332,7 @@ class Model {
if (options.individualHooks) {
// Create each instance individually
return Promise.map(instances, instance => {
const individualOptions = Utils._.clone(options);
const individualOptions = _.clone(options);
delete individualOptions.fields;
delete individualOptions.individualHooks;
delete individualOptions.ignoreDuplicates;
......@@ -2347,7 +2347,7 @@ class Model {
// Create all in one query
// Recreate records from instances to represent any changes made in hooks or validation
records = instances.map(instance => {
return Utils._.omit(instance.dataValues, this._virtualAttributes);
return _.omit(instance.dataValues, this._virtualAttributes);
});
// Map attributes for serial identification
......@@ -2513,7 +2513,7 @@ class Model {
static restore(options) {
if (!this._timestampAttributes.deletedAt) throw new Error('Model is not paranoid');
options = Utils._.extend({
options = _.extend({
hooks: true,
individualHooks: false
}, options || {});
......@@ -2634,16 +2634,16 @@ class Model {
build.set(this._timestampAttributes.updatedAt, values[this._timestampAttributes.updatedAt], { raw: true });
if (options.sideEffects) {
values = Utils._.assign(values, Utils._.pick(build.get(), build.changed()));
options.fields = Utils._.union(options.fields, Object.keys(values));
values = _.assign(values, _.pick(build.get(), build.changed()));
options.fields = _.union(options.fields, Object.keys(values));
}
// We want to skip validations for all other fields
options.skip = Utils._.difference(Object.keys(this.rawAttributes), Object.keys(values));
options.skip = _.difference(Object.keys(this.rawAttributes), Object.keys(values));
return build.validate(options).then(attributes => {
options.skip = undefined;
if (attributes && attributes.dataValues) {
values = Utils._.pick(attributes.dataValues, Object.keys(values));
values = _.pick(attributes.dataValues, Object.keys(values));
}
});
}
......@@ -2676,9 +2676,9 @@ class Model {
return Promise.map(instances, instance => {
// Record updates in instances dataValues
Utils._.extend(instance.dataValues, values);
_.extend(instance.dataValues, values);
// Set the changed fields on the instance
Utils._.forIn(valuesUse, (newValue, attr) => {
_.forIn(valuesUse, (newValue, attr) => {
if (newValue !== instance._previousDataValues[attr]) {
instance.setDataValue(attr, newValue);
}
......@@ -2688,7 +2688,7 @@ class Model {
return this.runHooks('beforeUpdate', instance, options).then(() => {
if (!different) {
const thisChangedValues = {};
Utils._.forIn(instance.dataValues, (newValue, attr) => {
_.forIn(instance.dataValues, (newValue, attr) => {
if (newValue !== instance._previousDataValues[attr]) {
thisChangedValues[attr] = newValue;
}
......@@ -2697,7 +2697,7 @@ class Model {
if (!changedValues) {
changedValues = thisChangedValues;
} else {
different = !Utils._.isEqual(changedValues, thisChangedValues);
different = !_.isEqual(changedValues, thisChangedValues);
}
}
......@@ -2712,14 +2712,14 @@ class Model {
if (keys.length) {
// Hooks change values - record changes in valuesUse so they are executed
valuesUse = changedValues;
options.fields = Utils._.union(options.fields, keys);
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 = Utils._.clone(options);
const individualOptions = _.clone(options);
delete individualOptions.individualHooks;
individualOptions.hooks = false;
individualOptions.validate = false;
......@@ -2887,10 +2887,10 @@ class Model {
const where = _.extend({}, options.where);
let values = {};
if (Utils._.isString(fields)) {
if (_.isString(fields)) {
values[fields] = options.by;
} else if (Utils._.isArray(fields)) {
Utils._.each(fields, field => {
} else if (_.isArray(fields)) {
_.each(fields, field => {
values[field] = options.by;
});
} else { // Assume fields is key-value pairs
......@@ -3474,7 +3474,7 @@ class Model {
if (options.silent === true && !(this.isNewRecord && this.get(updatedAtAttr, {raw: true}))) {
// UpdateAtAttr might have been added as a result of Object.keys(Model.attributes). In that case we have to remove it again
Utils._.remove(options.fields, val => val === updatedAtAttr);
_.remove(options.fields, val => val === updatedAtAttr);
updatedAtAttr = false;
}
......@@ -3778,7 +3778,7 @@ class Model {
*/
destroy(options) {
options = Utils._.extend({
options = _.extend({
hooks: true,
force: false
}, options);
......@@ -3869,7 +3869,7 @@ class Model {
restore(options) {
if (!this.constructor._timestampAttributes.deletedAt) throw new Error('Model is not paranoid');
options = Utils._.extend({
options = _.extend({
hooks: true,
force: false
}, options);
......@@ -3979,7 +3979,7 @@ class Model {
return false;
}
return Utils._.every(this.constructor.primaryKeyAttributes, attribute => this.get(attribute, {raw: true}) === other.get(attribute, {raw: true}));
return _.every(this.constructor.primaryKeyAttributes, attribute => this.get(attribute, {raw: true}) === other.get(attribute, {raw: true}));
}
/**
......@@ -4003,7 +4003,7 @@ class Model {
* @return {object}
*/
toJSON() {
return Utils._.clone(
return _.clone(
this.get({
plain: true
})
......@@ -4112,7 +4112,7 @@ Model.findAndCountAll = Model.findAndCount;
Model.findOrInitialize = Model.findOrBuild;
Model.insertOrUpdate = Model.upsert;
Utils._.extend(Model, associationsMixin);
_.extend(Model, associationsMixin);
Hooks.applyTo(Model);
module.exports = Model;
......@@ -81,8 +81,8 @@ class QueryInterface {
const showSchemasSql = this.QueryGenerator.showSchemasQuery();
return this.sequelize.query(showSchemasSql, options).then(schemaNames => Utils._.flatten(
Utils._.map(schemaNames, value => value.schema_name ? value.schema_name : value)
return this.sequelize.query(showSchemasSql, options).then(schemaNames => _.flatten(
_.map(schemaNames, value => value.schema_name ? value.schema_name : value)
));
}
......@@ -161,8 +161,8 @@ class QueryInterface {
options = _.clone(options) || {};
attributes = Utils._.mapValues(attributes, attribute => {
if (!Utils._.isPlainObject(attribute)) {
attributes = _.mapValues(attributes, attribute => {
if (!_.isPlainObject(attribute)) {
attribute = { type: attribute, allowNull: true };
}
......@@ -340,7 +340,7 @@ class QueryInterface {
tableNames.forEach(tableName => {
let normalizedTableName = tableName;
if (Utils._.isObject(tableName)) {
if (_.isObject(tableName)) {
normalizedTableName = tableName.schema + '.' + tableName.tableName;
}
......@@ -424,7 +424,7 @@ class QueryInterface {
});
const showTablesSql = this.QueryGenerator.showTablesQuery();
return this.sequelize.query(showTablesSql, options).then(tableNames => Utils._.flatten(tableNames));
return this.sequelize.query(showTablesSql, options).then(tableNames => _.flatten(tableNames));
}
/**
......@@ -476,7 +476,7 @@ class QueryInterface {
// If no data is returned from the query, then the table name may be wrong.
// Query generators that use information_schema for retrieving table info will just return an empty result set,
// it will not throw an error like built-ins do (e.g. DESCRIBE on MySql).
if (Utils._.isEmpty(data)) {
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);
......@@ -544,7 +544,7 @@ class QueryInterface {
const attributes = {};
options = options || {};
if (Utils._.values(DataTypes).indexOf(dataTypeOrOptions) > -1) {
if (_.values(DataTypes).indexOf(dataTypeOrOptions) > -1) {
attributes[attributeName] = { type: dataTypeOrOptions, allowNull: true };
} else {
attributes[attributeName] = dataTypeOrOptions;
......@@ -675,11 +675,11 @@ class QueryInterface {
const result = {};
tableNames.forEach((tableName, i) => {
if (Utils._.isObject(tableName)) {
if (_.isObject(tableName)) {
tableName = tableName.schema + '.' + tableName.tableName;
}
result[tableName] = Utils._.compact(results[i]).map(r => r.constraint_name);
result[tableName] = _.compact(results[i]).map(r => r.constraint_name);
});
return result;
......@@ -848,20 +848,20 @@ class QueryInterface {
options = _.clone(options);
if (!Utils._.isEmpty(where)) {
if (!_.isEmpty(where)) {
wheres.push(where);
}
// Lets combine uniquekeys and indexes into one
indexes = Utils._.map(model.options.uniqueKeys, value => {
indexes = _.map(model.options.uniqueKeys, value => {
return value.fields;
});
Utils._.each(model.options.indexes, value => {
_.each(model.options.indexes, value => {
if (value.unique) {
// fields in the index may both the strings or objects with an attribute property - lets sanitize that
indexFields = Utils._.map(value.fields, field => {
if (Utils._.isPlainObject(field)) {
indexFields = _.map(value.fields, field => {
if (_.isPlainObject(field)) {
return field.attribute;
}
return field;
......@@ -871,7 +871,7 @@ class QueryInterface {
});
for (const index of indexes) {
if (Utils._.intersection(attributes, index).length === index.length) {
if (_.intersection(attributes, index).length === index.length) {
where = {};
for (const field of index) {
where[field] = valuesByField[field];
......@@ -941,8 +941,8 @@ class QueryInterface {
if (typeof identifier === 'object') identifier = Utils.cloneDeep(identifier);
const sql = this.QueryGenerator.updateQuery(tableName, values, identifier, options, attributes);
const table = Utils._.isObject(tableName) ? tableName : { tableName };
const model = Utils._.find(this.sequelize.modelManager.models, { tableName: table.tableName });
const table = _.isObject(tableName) ? tableName : { tableName };
const model = _.find(this.sequelize.modelManager.models, { tableName: table.tableName });
options.model = model;
return this.sequelize.query(sql, options);
......@@ -1073,7 +1073,7 @@ class QueryInterface {
} else if (dataType instanceof DataTypes.INTEGER || dataType instanceof DataTypes.BIGINT) {
result = parseInt(result, 10);
} else if (dataType instanceof DataTypes.DATE) {
if (!Utils._.isNull(result) && !Utils._.isDate(result)) {
if (!_.isNull(result) && !_.isDate(result)) {
result = new Date(result);
}
} else if (dataType instanceof DataTypes.STRING) {
......
......@@ -142,7 +142,7 @@ class Sequelize {
Sequelize.runHooks('beforeInit', config, options);
this.options = Utils._.extend({
this.options = _.extend({
dialect: null,
dialectModulePath: null,
host: 'localhost',
......@@ -528,7 +528,7 @@ class Sequelize {
return options.transaction ? options.transaction.connection : this.connectionManager.getConnection(options);
}).then(connection => {
const query = new this.dialect.Query(connection, this, options);
const retryOptions = Utils._.extend(this.options.retry, options.retry || {});
const retryOptions = _.extend(this.options.retry, options.retry || {});
return retry(() => query.run(sql, bindParameters), retryOptions)
.finally(() => {
......@@ -558,7 +558,7 @@ class Sequelize {
set(variables, options) {
// Prepare options
options = Utils._.extend({}, this.options.set, typeof options === 'object' && options || {});
options = _.extend({}, this.options.set, typeof options === 'object' && options || {});
if (this.options.dialect !== 'mysql') {
throw new Error('sequelize.set is only supported for mysql');
......@@ -575,7 +575,7 @@ class Sequelize {
// Generate SQL Query
const query =
'SET '+
Utils._.map(variables, (v, k) => '@'+k +' := '+ (typeof v === 'string' ? '"'+v+'"' : v)).join(', ');
_.map(variables, (v, k) => '@'+k +' := '+ (typeof v === 'string' ? '"'+v+'"' : v)).join(', ');
return this.query(query, options);
}
......@@ -663,7 +663,7 @@ class Sequelize {
options = _.clone(options) || {};
options.hooks = options.hooks === undefined ? true : !!options.hooks;
options = Utils._.defaults(options, this.options.sync, this.options);
options = _.defaults(options, this.options.sync, this.options);
if (options.match) {
if (!options.match.test(this.config.database)) {
......@@ -756,7 +756,7 @@ class Sequelize {
* @return {Promise}
*/
authenticate(options) {
return this.query('SELECT 1+1 AS result', Utils._.assign({ raw: true, plain: true }, options)).return();
return this.query('SELECT 1+1 AS result', _.assign({ raw: true, plain: true }, options)).return();
}
databaseVersion(options) {
......@@ -1026,9 +1026,9 @@ class Sequelize {
log() {
let options;
let args = Utils.sliceArgs(arguments);
const last = Utils._.last(args);
const last = _.last(args);
if (last && Utils._.isPlainObject(last) && last.hasOwnProperty('logging')) {
if (last && _.isPlainObject(last) && last.hasOwnProperty('logging')) {
options = last;
// remove options from set of logged arguments if options.logging is equal to console.log
......@@ -1080,7 +1080,7 @@ class Sequelize {
return type;
}
normalizeAttribute(attribute) {
if (!Utils._.isPlainObject(attribute)) {
if (!_.isPlainObject(attribute)) {
attribute = { type: attribute };
}
......
'use strict';
const _ = require('lodash');
const Utils = require('./utils');
/**
......@@ -26,7 +27,7 @@ class Transaction {
const transactionOptions = sequelize.dialect.supports.transactionOptions || {};
const generateTransactionId = this.sequelize.dialect.QueryGenerator.generateTransactionId;
this.options = Utils._.extend({
this.options = _.extend({
autocommit: transactionOptions.autocommit || null,
type: sequelize.options.transactionType,
isolationLevel: sequelize.options.isolationLevel,
......
......@@ -2,7 +2,7 @@
const DataTypes = require('./data-types');
const SqlString = require('./sql-string');
const _ = require('lodash').runInContext(); // Prevent anyone messing with template settings by creating a fresh copy
const _ = require('lodash');
const parameterValidator = require('./utils/parameter-validator');
const Logger = require('./utils/logger');
const uuid = require('uuid');
......@@ -13,7 +13,6 @@ let inflection = require('inflection');
const logger = new Logger();
exports.Promise = Promise;
exports._ = _;
exports.debug = logger.debug.bind(logger);
exports.deprecate = logger.deprecate.bind(logger);
exports.warn = logger.warn.bind(logger);
......@@ -55,7 +54,7 @@ exports.isPrimitive = isPrimitive;
function mergeDefaults(a, b) {
return _.mergeWith(a, b, objectValue => {
// If it's an object, let _ handle it this time, we will be called again for each property
if (!this._.isPlainObject(objectValue) && objectValue !== undefined) {
if (!_.isPlainObject(objectValue) && objectValue !== undefined) {
return objectValue;
}
});
......
......@@ -67,7 +67,7 @@ const Support = {
resolve();
}
}).then(() => {
const options = Sequelize.Utils._.extend({}, sequelize.options, { storage: p }),
const options = _.extend({}, sequelize.options, { storage: p }),
_sequelize = new Sequelize(sequelize.config.database, null, null, options);
if (callback) {
......
......@@ -4,6 +4,7 @@ const chai = require('chai');
const sinon = require('sinon');
const expect = chai.expect;
const stub = sinon.stub;
const _ = require('lodash');
const Support = require(__dirname + '/../support');
const DataTypes = require(__dirname + '/../../../lib/data-types');
const BelongsTo = require(__dirname + '/../../../lib/associations/belongs-to');
......@@ -72,7 +73,7 @@ describe(Support.getTestDialectTeaser('belongsToMany'), () => {
const User = current.define('User');
const Task = current.define('Task');
current.Utils._.each(methods, (alias, method) => {
_.each(methods, (alias, method) => {
User.prototype[method] = function() {
const realMethod = this.constructor.associations.task[alias];
expect(realMethod).to.be.a('function');
......@@ -84,7 +85,7 @@ describe(Support.getTestDialectTeaser('belongsToMany'), () => {
const user = User.build();
current.Utils._.each(methods, (alias, method) => {
_.each(methods, (alias, method) => {
expect(user[method]()).to.be.a('function');
});
});
......
......@@ -2,6 +2,7 @@
const chai = require('chai'),
expect = chai.expect,
_ = require('lodash'),
Support = require(__dirname + '/../support'),
current = Support.sequelize;
......@@ -15,7 +16,7 @@ describe(Support.getTestDialectTeaser('belongsTo'), () => {
const User = current.define('User');
const Task = current.define('Task');
current.Utils._.each(methods, (alias, method) => {
_.each(methods, (alias, method) => {
User.prototype[method] = function() {
const realMethod = this.constructor.associations.task[alias];
expect(realMethod).to.be.a('function');
......@@ -27,7 +28,7 @@ describe(Support.getTestDialectTeaser('belongsTo'), () => {
const user = User.build();
current.Utils._.each(methods, (alias, method) => {
_.each(methods, (alias, method) => {
expect(user[method]()).to.be.a('function');
});
});
......
......@@ -4,6 +4,7 @@ const chai = require('chai'),
sinon = require('sinon'),
expect = chai.expect,
stub = sinon.stub,
_ = require('lodash'),
Support = require(__dirname + '/../support'),
DataTypes = require(__dirname + '/../../../lib/data-types'),
HasMany = require(__dirname + '/../../../lib/associations/has-many'),
......@@ -98,7 +99,7 @@ describe(Support.getTestDialectTeaser('hasMany'), () => {
createTask: 'create'
};
current.Utils._.each(methods, (alias, method) => {
_.each(methods, (alias, method) => {
User.prototype[method] = function() {
const realMethod = this.constructor.associations.task[alias];
expect(realMethod).to.be.a('function');
......@@ -110,7 +111,7 @@ describe(Support.getTestDialectTeaser('hasMany'), () => {
const user = User.build();
current.Utils._.each(methods, (alias, method) => {
_.each(methods, (alias, method) => {
expect(user[method]()).to.be.a('function');
});
});
......
......@@ -2,6 +2,7 @@
const chai = require('chai'),
expect = chai.expect,
_ = require('lodash'),
Support = require(__dirname + '/../support'),
DataTypes = require(__dirname + '/../../../lib/data-types'),
current = Support.sequelize;
......@@ -27,7 +28,7 @@ describe(Support.getTestDialectTeaser('hasOne'), () => {
const User = current.define('User');
const Task = current.define('Task');
current.Utils._.each(methods, (alias, method) => {
_.each(methods, (alias, method) => {
User.prototype[method] = function() {
const realMethod = this.constructor.associations.task[alias];
expect(realMethod).to.be.a('function');
......@@ -39,7 +40,7 @@ describe(Support.getTestDialectTeaser('hasOne'), () => {
const user = User.build();
current.Utils._.each(methods, (alias, method) => {
_.each(methods, (alias, method) => {
expect(user[method]()).to.be.a('function');
});
});
......
......@@ -7,7 +7,6 @@ const Support = require(__dirname + '/../support'),
sql = current.dialect.QueryGenerator,
_ = require('lodash');
describe(Support.getTestDialectTeaser('SQL'), () => {
describe('createTable', () => {
const FooUser = current.define('user', {
......@@ -49,6 +48,31 @@ describe(Support.getTestDialectTeaser('SQL'), () => {
});
});
});
describe('Attempt to use different lodash template settings', () => {
before(() => {
// make handlebars
_.templateSettings.evaluate = /{{([\s\S]+?)}}/g;
_.templateSettings.interpolate = /{{=([\s\S]+?)}}/g;
_.templateSettings.escape = /{{-([\s\S]+?)}}/g;
});
after(() => {
// reset
const __ = require('lodash').runInContext();
_.templateSettings.evaluate = __.templateSettings.evaluate;
_.templateSettings.interpolate = __.templateSettings.interpolate;
_.templateSettings.escape = __.templateSettings.escape;
});
it('it should be a okay!', () => {
expectsql(sql.createTableQuery(FooUser.getTableName(), sql.attributesToSQL(FooUser.rawAttributes), {
comment: 'This is a test of the lodash template settings.'
}), {
postgres: 'CREATE TABLE IF NOT EXISTS "foo"."users" ("id" SERIAL , "mood" "foo"."enum_users_mood", PRIMARY KEY ("id")); COMMENT ON TABLE "foo"."users" IS \'This is a test of the lodash template settings.\';'
});
});
});
}
});
});
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!