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

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