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

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,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!