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

Commit 2fba6364 by Felix Becker Committed by Mick Hansen

ES6 Refactor: dialects / MySQL (#6047)

* Make Mysql ConnectionManager an ES6 class

* ES6 refactor of MySQL ConnectionManager

let, const, for of, arrow functions, Map, export default

* Make MySQL Query an ES6 class

* ES6 refactor of MySQL Query

let, const, for of, arrow functions, export default

* ES6 refactor of MySQL QueryInterface

* ES6 refactor of MySQL QueryGenerator
1 parent c032ec90
'use strict';
var AbstractConnectionManager = require('../abstract/connection-manager')
, ConnectionManager
, Utils = require('../../utils')
, Promise = require('../../promise')
, sequelizeErrors = require('../../errors')
, dataTypes = require('../../data-types').mysql
, parserMap = {};
ConnectionManager = function(dialect, sequelize) {
AbstractConnectionManager.call(this, dialect, sequelize);
this.sequelize = sequelize;
this.sequelize.config.port = this.sequelize.config.port || 3306;
try {
if (sequelize.config.dialectModulePath) {
this.lib = require(sequelize.config.dialectModulePath);
} else {
this.lib = require('mysql');
}
} catch (err) {
if (err.code === 'MODULE_NOT_FOUND') {
throw new Error('Please install mysql package manually');
const AbstractConnectionManager = require('../abstract/connection-manager');
const Utils = require('../../utils');
const Promise = require('../../promise');
const sequelizeErrors = require('../../errors');
const dataTypes = require('../../data-types').mysql;
const parserMap = new Map();
class ConnectionManager extends AbstractConnectionManager {
constructor(dialect, sequelize) {
super(dialect, sequelize);
this.sequelize = sequelize;
this.sequelize.config.port = this.sequelize.config.port || 3306;
try {
if (sequelize.config.dialectModulePath) {
this.lib = require(sequelize.config.dialectModulePath);
} else {
this.lib = require('mysql');
}
} catch (err) {
if (err.code === 'MODULE_NOT_FOUND') {
throw new Error('Please install mysql package manually');
}
throw err;
}
throw err;
}
this.refreshTypeParser(dataTypes);
};
this.refreshTypeParser(dataTypes);
}
Utils._.extend(ConnectionManager.prototype, AbstractConnectionManager.prototype);
// Expose this as a method so that the parsing may be updated when the user has added additional, custom types
$refreshTypeParser(dataType) {
for (const type of dataType.types.mysql) {
parserMap.set(type, dataType.parse);
}
}
// Expose this as a method so that the parsing may be updated when the user has added additional, custom types
ConnectionManager.prototype.$refreshTypeParser = function (dataType) {
dataType.types.mysql.forEach(function (type) {
parserMap[type] = dataType.parse;
});
};
$clearTypeParser() {
parserMap.clear();
}
ConnectionManager.prototype.$clearTypeParser = function () {
parserMap = {};
};
static $typecast(field, next) {
if (parserMap.has(field.type)) {
return parserMap.get(field.type)(field, this.sequelize.options);
}
ConnectionManager.$typecast = function (field, next) {
if (parserMap[field.type]) {
return parserMap[field.type](field, this.sequelize.options);
return next();
}
return next();
};
ConnectionManager.prototype.connect = function(config) {
var self = this;
return new Promise(function (resolve, reject) {
var connectionConfig = {
host: config.host,
port: config.port,
user: config.username,
password: config.password,
database: config.database,
timezone: self.sequelize.options.timezone,
typeCast: ConnectionManager.$typecast.bind(self),
bigNumberStrings: false,
supportBigNumbers: true
};
if (config.dialectOptions) {
Object.keys(config.dialectOptions).forEach(function(key) {
connectionConfig[key] = config.dialectOptions[key];
});
}
connect(config) {
return new Promise((resolve, reject) => {
const connectionConfig = {
host: config.host,
port: config.port,
user: config.username,
password: config.password,
database: config.database,
timezone: this.sequelize.options.timezone,
typeCast: ConnectionManager.$typecast.bind(this),
bigNumberStrings: false,
supportBigNumbers: true
};
if (config.dialectOptions) {
for (const key of Object.keys(config.dialectOptions)) {
connectionConfig[key] = config.dialectOptions[key];
}
}
var connection = self.lib.createConnection(connectionConfig);
connection.connect(function(err) {
if (err) {
if (err.code) {
switch (err.code) {
case 'ECONNREFUSED':
reject(new sequelizeErrors.ConnectionRefusedError(err));
break;
case 'ER_ACCESS_DENIED_ERROR':
reject(new sequelizeErrors.AccessDeniedError(err));
break;
case 'ENOTFOUND':
reject(new sequelizeErrors.HostNotFoundError(err));
break;
case 'EHOSTUNREACH':
reject(new sequelizeErrors.HostNotReachableError(err));
break;
case 'EINVAL':
reject(new sequelizeErrors.InvalidConnectionError(err));
break;
default:
const connection = this.lib.createConnection(connectionConfig);
connection.connect(err => {
if (err) {
if (err.code) {
switch (err.code) {
case 'ECONNREFUSED':
reject(new sequelizeErrors.ConnectionRefusedError(err));
break;
case 'ER_ACCESS_DENIED_ERROR':
reject(new sequelizeErrors.AccessDeniedError(err));
break;
case 'ENOTFOUND':
reject(new sequelizeErrors.HostNotFoundError(err));
break;
case 'EHOSTUNREACH':
reject(new sequelizeErrors.HostNotReachableError(err));
break;
case 'EINVAL':
reject(new sequelizeErrors.InvalidConnectionError(err));
break;
default:
reject(new sequelizeErrors.ConnectionError(err));
break;
}
} else {
reject(new sequelizeErrors.ConnectionError(err));
break;
}
} else {
reject(new sequelizeErrors.ConnectionError(err));
return;
}
return;
}
if (config.pool.handleDisconnects) {
// Connection to the MySQL server is usually
// lost due to either server restart, or a
// connnection idle timeout (the wait_timeout
// server variable configures this)
//
// See [stackoverflow answer](http://stackoverflow.com/questions/20210522/nodejs-mysql-error-connection-lost-the-server-closed-the-connection)
connection.on('error', err => {
if (err.code === 'PROTOCOL_CONNECTION_LOST') {
// Remove it from read/write pool
this.pool.destroy(connection);
}
});
}
resolve(connection);
});
if (config.pool.handleDisconnects) {
// Connection to the MySQL server is usually
// lost due to either server restart, or a
// connnection idle timeout (the wait_timeout
// server variable configures this)
//
// See [stackoverflow answer](http://stackoverflow.com/questions/20210522/nodejs-mysql-error-connection-lost-the-server-closed-the-connection)
connection.on('error', function (err) {
if (err.code === 'PROTOCOL_CONNECTION_LOST') {
// Remove it from read/write pool
self.pool.destroy(connection);
}
});
}
resolve(connection);
}).tap(connection => {
connection.query("SET time_zone = '" + this.sequelize.options.timezone + "'"); /* jshint ignore: line */
});
}
}).tap(function (connection) {
connection.query("SET time_zone = '" + self.sequelize.options.timezone + "'"); /* jshint ignore: line */
});
};
ConnectionManager.prototype.disconnect = function(connection) {
disconnect(connection) {
// Dont disconnect connections with an ended protocol
// That wil trigger a connection error
if (connection._protocol._ended) {
return Promise.resolve();
}
// Dont disconnect connections with an ended protocol
// That wil trigger a connection error
if (connection._protocol._ended) {
return Promise.resolve();
}
return new Promise(function (resolve, reject) {
connection.end(function(err) {
if (err) return reject(new sequelizeErrors.ConnectionError(err));
resolve();
return new Promise((resolve, reject) => {
connection.end(err => {
if (err) return reject(new sequelizeErrors.ConnectionError(err));
resolve();
});
});
});
};
ConnectionManager.prototype.validate = function(connection) {
return connection && ['disconnected', 'protocol_error'].indexOf(connection.state) === -1;
};
}
validate(connection) {
return connection && ['disconnected', 'protocol_error'].indexOf(connection.state) === -1;
}
}
Utils._.extend(ConnectionManager.prototype, AbstractConnectionManager.prototype);
module.exports = ConnectionManager;
module.exports.ConnectionManager = ConnectionManager;
module.exports.default = ConnectionManager;
'use strict';
var Utils = require('../../utils');
const Utils = require('../../utils');
var QueryGenerator = {
const QueryGenerator = {
dialect: 'mysql',
createSchema: function() {
var query = 'SHOW TABLES';
return Utils._.template(query)({});
createSchema() {
return 'SHOW TABLES';
},
showSchemasQuery: function() {
showSchemasQuery() {
return 'SHOW TABLES';
},
versionQuery: function() {
versionQuery() {
return 'SELECT VERSION() as `version`';
},
createTableQuery: function(tableName, attributes, options) {
createTableQuery(tableName, attributes, options) {
options = Utils._.extend({
engine: 'InnoDB',
charset: null
}, options || {});
var self = this;
var query = 'CREATE TABLE IF NOT EXISTS <%= table %> (<%= attributes%>) ENGINE=<%= engine %><%= comment %><%= charset %><%= collation %><%= initialAutoIncrement %>'
, primaryKeys = []
, foreignKeys = {}
, attrStr = [];
const query = 'CREATE TABLE IF NOT EXISTS <%= table %> (<%= attributes%>) ENGINE=<%= engine %><%= comment %><%= charset %><%= collation %><%= initialAutoIncrement %>';
const primaryKeys = [];
const foreignKeys = {};
const attrStr = [];
for (var attr in attributes) {
for (const attr in attributes) {
if (attributes.hasOwnProperty(attr)) {
var dataType = attributes[attr]
, match;
const dataType = attributes[attr];
let match;
if (Utils._.includes(dataType, 'PRIMARY KEY')) {
primaryKeys.push(attr);
......@@ -58,7 +55,7 @@ var QueryGenerator = {
}
}
var values = {
const values = {
table: this.quoteTable(tableName),
attributes: attrStr.join(', '),
comment: options.comment && Utils._.isString(options.comment) ? ' COMMENT ' + this.escape(options.comment) : '',
......@@ -66,16 +63,16 @@ var QueryGenerator = {
charset: (options.charset ? ' DEFAULT CHARSET=' + options.charset : ''),
collation: (options.collate ? ' COLLATE ' + options.collate : ''),
initialAutoIncrement: (options.initialAutoIncrement ? ' AUTO_INCREMENT=' + options.initialAutoIncrement : '')
}
, pkString = primaryKeys.map(function(pk) { return this.quoteIdentifier(pk); }.bind(this)).join(', ');
};
const pkString = primaryKeys.map(pk => this.quoteIdentifier(pk)).join(', ');
if (!!options.uniqueKeys) {
Utils._.each(options.uniqueKeys, function(columns, indexName) {
Utils._.each(options.uniqueKeys, (columns, indexName) => {
if (!columns.singleField) { // If it's a single field its handled in column def, not as an index
if (!Utils._.isString(indexName)) {
indexName = 'uniq_' + tableName + '_' + columns.fields.join('_');
}
values.attributes += ', UNIQUE ' + self.quoteIdentifier(indexName) + ' (' + Utils._.map(columns.fields, self.quoteIdentifier).join(', ') + ')';
values.attributes += ', UNIQUE ' + this.quoteIdentifier(indexName) + ' (' + Utils._.map(columns.fields, this.quoteIdentifier).join(', ') + ')';
}
});
}
......@@ -84,7 +81,7 @@ var QueryGenerator = {
values.attributes += ', PRIMARY KEY (' + pkString + ')';
}
for (var fkey in foreignKeys) {
for (const fkey in foreignKeys) {
if (foreignKeys.hasOwnProperty(fkey)) {
values.attributes += ', FOREIGN KEY (' + this.quoteIdentifier(fkey) + ') ' + foreignKeys[fkey];
}
......@@ -93,56 +90,40 @@ var QueryGenerator = {
return Utils._.template(query)(values).trim() + ';';
},
showTablesQuery: function() {
showTablesQuery() {
return 'SHOW TABLES;';
},
addColumnQuery: function(table, key, dataType) {
var query = 'ALTER TABLE <%= table %> ADD <%= attribute %>;'
, attribute = Utils._.template('<%= key %> <%= definition %>')({
key: this.quoteIdentifier(key),
definition: this.attributeToSQL(dataType, {
context: 'addColumn',
tableName: table,
foreignKey: key
})
});
return Utils._.template(query)({
table: this.quoteTable(table),
attribute: attribute
addColumnQuery(table, key, dataType) {
const definition = this.attributeToSQL(dataType, {
context: 'addColumn',
tableName: table,
foreignKey: key
});
return `ALTER TABLE ${this.quoteTable(table)} ADD ${this.quoteIdentifier(key)} ${definition};`;
},
removeColumnQuery: function(tableName, attributeName) {
var query = 'ALTER TABLE <%= tableName %> DROP <%= attributeName %>;';
return Utils._.template(query)({
tableName: this.quoteTable(tableName),
attributeName: this.quoteIdentifier(attributeName)
});
removeColumnQuery(tableName, attributeName) {
return `ALTER TABLE ${this.quoteTable(tableName)} DROP ${this.quoteIdentifier(attributeName)};`;
},
changeColumnQuery: function(tableName, attributes) {
var query = 'ALTER TABLE <%= tableName %> <%= query %>;';
var attrString = [], constraintString = [];
changeColumnQuery(tableName, attributes) {
const attrString = [];
const constraintString = [];
for (var attributeName in attributes) {
var definition = attributes[attributeName];
for (const attributeName in attributes) {
let definition = attributes[attributeName];
if (definition.match(/REFERENCES/)) {
constraintString.push(Utils._.template('<%= fkName %> FOREIGN KEY (<%= attrName %>) <%= definition %>')({
fkName: this.quoteIdentifier(tableName + '_' + attributeName + '_foreign_idx'),
attrName: this.quoteIdentifier(attributeName),
definition: definition.replace(/.+?(?=REFERENCES)/,'')
}));
const fkName = this.quoteIdentifier(tableName + '_' + attributeName + '_foreign_idx');
const attrName = this.quoteIdentifier(attributeName);
definition = definition.replace(/.+?(?=REFERENCES)/,'');
constraintString.push(`${fkName} FOREIGN KEY (${attrName}) ${definition}`);
} else {
attrString.push(Utils._.template('`<%= attrName %>` `<%= attrName %>` <%= definition %>')({
attrName: attributeName,
definition: definition
}));
attrString.push('`' + attributeName + '` `' + attributeName + '` ' + definition);
}
}
var finalQuery = '';
let finalQuery = '';
if (attrString.length) {
finalQuery += 'CHANGE ' + attrString.join(', ');
finalQuery += constraintString.length ? ' ' : '';
......@@ -151,51 +132,42 @@ var QueryGenerator = {
finalQuery += 'ADD CONSTRAINT ' + constraintString.join(', ');
}
return Utils._.template(query)({
tableName: this.quoteTable(tableName),
query: finalQuery
});
return `ALTER TABLE ${this.quoteTable(tableName)} ${finalQuery};`;
},
renameColumnQuery: function(tableName, attrBefore, attributes) {
var query = 'ALTER TABLE <%= tableName %> CHANGE <%= attributes %>;';
var attrString = [];
renameColumnQuery(tableName, attrBefore, attributes) {
const attrString = [];
for (var attrName in attributes) {
var definition = attributes[attrName];
attrString.push(Utils._.template('`<%= before %>` `<%= after %>` <%= definition %>')({
before: attrBefore,
after: attrName,
definition: definition
}));
for (const attrName in attributes) {
const definition = attributes[attrName];
attrString.push('`' + attrBefore + '` `' + attrName + '` ' + definition);
}
return Utils._.template(query)({ tableName: this.quoteTable(tableName), attributes: attrString.join(', ') });
return `ALTER TABLE ${this.quoteTable(tableName)} CHANGE ${attrString.join(', ')};`;
},
upsertQuery: function (tableName, insertValues, updateValues, where, rawAttributes, options) {
upsertQuery(tableName, insertValues, updateValues, where, rawAttributes, options) {
options.onDuplicate = 'UPDATE ';
options.onDuplicate += Object.keys(updateValues).map(function (key) {
options.onDuplicate += Object.keys(updateValues).map(key => {
key = this.quoteIdentifier(key);
return key + '=VALUES(' + key +')';
}, this).join(', ');
}).join(', ');
return this.insertQuery(tableName, insertValues, rawAttributes, options);
},
deleteQuery: function(tableName, where, options) {
deleteQuery(tableName, where, options) {
options = options || {};
var table = this.quoteTable(tableName);
const table = this.quoteTable(tableName);
if (options.truncate === true) {
// Truncate does not allow LIMIT and WHERE
return 'TRUNCATE ' + table;
}
where = this.getWhereConditions(where);
var limit = '';
let limit = '';
if (Utils._.isUndefined(options.limit)) {
options.limit = 1;
......@@ -205,40 +177,35 @@ var QueryGenerator = {
limit = ' LIMIT ' + this.escape(options.limit);
}
var query = 'DELETE FROM ' + table;
let query = 'DELETE FROM ' + table;
if (where) query += ' WHERE ' + where;
query += limit;
return query;
},
showIndexesQuery: function(tableName, options) {
var sql = 'SHOW INDEX FROM <%= tableName %><%= options %>';
return Utils._.template(sql)({
tableName: this.quoteTable(tableName),
options: (options || {}).database ? ' FROM `' + options.database + '`' : ''
});
showIndexesQuery(tableName, options) {
return 'SHOW INDEX FROM ' + this.quoteTable(tableName) + ((options || {}).database ? ' FROM `' + options.database + '`' : '');
},
removeIndexQuery: function(tableName, indexNameOrAttributes) {
var sql = 'DROP INDEX <%= indexName %> ON <%= tableName %>'
, indexName = indexNameOrAttributes;
removeIndexQuery(tableName, indexNameOrAttributes) {
let indexName = indexNameOrAttributes;
if (typeof indexName !== 'string') {
indexName = Utils.inflection.underscore(tableName + '_' + indexNameOrAttributes.join('_'));
}
return Utils._.template(sql)({ tableName: this.quoteIdentifiers(tableName), indexName: indexName });
return `DROP INDEX ${indexName} ON ${this.quoteTable(tableName)}`;
},
attributeToSQL: function(attribute, options) {
attributeToSQL(attribute, options) {
if (!Utils._.isPlainObject(attribute)) {
attribute = {
type: attribute
};
}
var template = attribute.type.toString({ escape: this.escape.bind(this) });
let template = attribute.type.toString({ escape: this.escape.bind(this) });
if (attribute.allowNull === false) {
template += ' NOT NULL';
......@@ -268,12 +235,10 @@ var QueryGenerator = {
if (attribute.references) {
if (options && options.context === 'addColumn' && options.foreignKey) {
var attrName = options.foreignKey;
const attrName = this.quoteIdentifier(options.foreignKey);
const fkName = this.quoteIdentifier(`${options.tableName}_${attrName}_foreign_idx`);
template += Utils._.template(', ADD CONSTRAINT <%= fkName %> FOREIGN KEY (<%= attrName %>)')({
fkName: this.quoteIdentifier(options.tableName + '_' + attrName + '_foreign_idx'),
attrName: this.quoteIdentifier(attrName)
});
template += `, ADD CONSTRAINT ${fkName} FOREIGN KEY (${attrName})`;
}
template += ' REFERENCES ' + this.quoteTable(attribute.references.model);
......@@ -296,25 +261,23 @@ var QueryGenerator = {
return template;
},
attributesToSQL: function(attributes, options) {
var result = {}
, key
, attribute;
attributesToSQL(attributes, options) {
const result = {};
for (key in attributes) {
attribute = attributes[key];
for (const key in attributes) {
const attribute = attributes[key];
result[attribute.field || key] = this.attributeToSQL(attribute, options);
}
return result;
},
findAutoIncrementField: function(factory) {
var fields = [];
findAutoIncrementField(factory) {
const fields = [];
for (var name in factory.attributes) {
for (const name in factory.attributes) {
if (factory.attributes.hasOwnProperty(name)) {
var definition = factory.attributes[name];
const definition = factory.attributes[name];
if (definition && definition.autoIncrement) {
fields.push(name);
......@@ -325,7 +288,7 @@ var QueryGenerator = {
return fields;
},
quoteIdentifier: function(identifier) {
quoteIdentifier(identifier) {
if (identifier === '*') return identifier;
return Utils.addTicks(identifier, '`');
},
......@@ -337,7 +300,7 @@ var QueryGenerator = {
* @param {String} schemaName The name of the schema.
* @return {String} The generated sql query.
*/
getForeignKeysQuery: function(tableName, schemaName) {
getForeignKeysQuery(tableName, schemaName) {
return "SELECT CONSTRAINT_NAME as constraint_name FROM INFORMATION_SCHEMA.KEY_COLUMN_USAGE where TABLE_NAME = '" + tableName + /* jshint ignore: line */
"' AND CONSTRAINT_NAME!='PRIMARY' AND CONSTRAINT_SCHEMA='" + schemaName + "' AND REFERENCED_TABLE_NAME IS NOT NULL;"; /* jshint ignore: line */
},
......@@ -349,20 +312,18 @@ var QueryGenerator = {
* @param {String} columnName The name of the column.
* @return {String} The generated sql query.
*/
getForeignKeyQuery: function(table, columnName) {
var tableName = table.tableName || table;
getForeignKeyQuery(table, columnName) {
let tableName = table.tableName || table;
if (table.schema) {
tableName = table.schema + '.' + tableName;
tableName = table.schema + '.' + tableName;
}
return [
'SELECT CONSTRAINT_NAME as constraint_name',
'FROM INFORMATION_SCHEMA.KEY_COLUMN_USAGE',
'WHERE (REFERENCED_TABLE_NAME = ' + wrapSingleQuote(tableName),
'AND REFERENCED_COLUMN_NAME = ' + wrapSingleQuote(columnName),
') OR (TABLE_NAME = ' + wrapSingleQuote(tableName),
'AND COLUMN_NAME = ' + wrapSingleQuote(columnName),
')',
].join(' ');
return 'SELECT CONSTRAINT_NAME as constraint_name'
+ ' FROM INFORMATION_SCHEMA.KEY_COLUMN_USAGE'
+ ' WHERE (REFERENCED_TABLE_NAME = ' + wrapSingleQuote(tableName)
+ ' AND REFERENCED_COLUMN_NAME = ' + wrapSingleQuote(columnName)
+ ') OR (TABLE_NAME = ' + wrapSingleQuote(tableName)
+ ' AND COLUMN_NAME = ' + wrapSingleQuote(columnName)
+ ')';
},
/**
......@@ -372,7 +333,7 @@ var QueryGenerator = {
* @param {String} foreignKey The name of the foreign key constraint.
* @return {String} The generated sql query.
*/
dropForeignKeyQuery: function(tableName, foreignKey) {
dropForeignKeyQuery(tableName, foreignKey) {
return 'ALTER TABLE ' + this.quoteTable(tableName) + ' DROP FOREIGN KEY ' + this.quoteIdentifier(foreignKey) + ';';
}
};
......
......@@ -7,7 +7,7 @@
@static
*/
var _ = require('lodash');
const _ = require('lodash');
/**
A wrapper that fixes MySQL's inability to cleanly remove columns from existing tables if they have a foreign key constraint.
......@@ -19,32 +19,27 @@ var _ = require('lodash');
@param {String} columnName The name of the attribute that we want to remove.
@param {Object} options
*/
var removeColumn = function (tableName, columnName, options) {
var self = this;
function removeColumn(tableName, columnName, options) {
options = options || {};
return self.sequelize.query(
self.QueryGenerator.getForeignKeyQuery(tableName, columnName),
/* jshint validthis:true */
return this.sequelize.query(
this.QueryGenerator.getForeignKeyQuery(tableName, columnName),
_.assign({ raw: true }, options)
)
.spread(function (results) {
.spread(results => {
if (!results.length) {
// No foreign key constraints found, so we can remove the column
return;
}
return self.sequelize.query(
self.QueryGenerator.dropForeignKeyQuery(tableName, results[0].constraint_name),
_.assign({ raw: true }, options)
);
return this.sequelize.query(
this.QueryGenerator.dropForeignKeyQuery(tableName, results[0].constraint_name),
_.assign({ raw: true }, options)
);
})
.then(function () {
return self.sequelize.query(
self.QueryGenerator.removeColumnQuery(tableName, columnName),
_.assign({ raw: true }, options)
);
});
};
module.exports = {
removeColumn: removeColumn
};
.then(() => this.sequelize.query(
this.QueryGenerator.removeColumnQuery(tableName, columnName),
_.assign({ raw: true }, options)
));
}
exports.removeColumn = removeColumn;
'use strict';
var Utils = require('../../utils')
, AbstractQuery = require('../abstract/query')
, uuid = require('node-uuid')
, sequelizeErrors = require('../../errors.js')
, _ = require('lodash');
var Query = function(connection, sequelize, options) {
this.connection = connection;
this.instance = options.instance;
this.model = options.model;
this.sequelize = sequelize;
this.uuid = uuid.v4();
this.options = Utils._.extend({
logging: console.log,
plain: false,
raw: false,
showWarnings: false
}, options || {});
this.checkLoggingOption();
};
Utils.inherit(Query, AbstractQuery);
Query.formatBindParameters = AbstractQuery.formatBindParameters;
Query.prototype.run = function(sql, parameters) {
var self = this;
this.sql = sql;
//do we need benchmark for this query execution
var benchmark = this.sequelize.options.benchmark || this.options.benchmark;
var showWarnings = this.sequelize.options.showWarnings || this.options.showWarnings;
if (benchmark) {
var queryBegin = Date.now();
} else {
this.sequelize.log('Executing (' + (this.connection.uuid || 'default') + '): ' + this.sql, this.options);
const Utils = require('../../utils');
const AbstractQuery = require('../abstract/query');
const uuid = require('node-uuid');
const sequelizeErrors = require('../../errors.js');
const _ = require('lodash');
class Query extends AbstractQuery {
constructor(connection, sequelize, options) {
super();
this.connection = connection;
this.instance = options.instance;
this.model = options.model;
this.sequelize = sequelize;
this.uuid = uuid.v4();
this.options = Utils._.extend({
logging: console.log,
plain: false,
raw: false,
showWarnings: false
}, options || {});
this.checkLoggingOption();
}
var promise = new Utils.Promise(function(resolve, reject) {
self.connection.query(self.sql, function(err, results) {
run(sql, parameters) {
this.sql = sql;
if (benchmark) {
self.sequelize.log('Executed (' + (self.connection.uuid || 'default') + '): ' + self.sql, (Date.now() - queryBegin), self.options);
}
//do we need benchmark for this query execution
const benchmark = this.sequelize.options.benchmark || this.options.benchmark;
const showWarnings = this.sequelize.options.showWarnings || this.options.showWarnings;
let queryBegin;
if (benchmark) {
queryBegin = Date.now();
} else {
this.sequelize.log('Executing (' + (this.connection.uuid || 'default') + '): ' + this.sql, this.options);
}
return new Utils.Promise((resolve, reject) => {
this.connection.query(this.sql, (err, results) => {
if (err) {
err.sql = sql;
if (benchmark) {
this.sequelize.log('Executed (' + (this.connection.uuid || 'default') + '): ' + this.sql, (Date.now() - queryBegin), this.options);
}
if (err) {
err.sql = sql;
reject(this.formatError(err));
} else {
resolve(results);
}
}).setMaxListeners(100);
})
// Log warnings if we've got them.
.then(results => {
if (showWarnings && results && results.warningCount > 0) {
return this.logWarnings(results);
}
return results;
})
// Return formatted results...
.then(results => this.formatResults(results));
}
reject(self.formatError(err));
} else {
resolve(results);
/**
* High level function that handles the results of a query execution.
*
*
* Example:
* query.formatResults([
* {
* id: 1, // this is from the main table
* attr2: 'snafu', // this is from the main table
* Tasks.id: 1, // this is from the associated table
* Tasks.title: 'task' // this is from the associated table
* }
* ])
*
* @param {Array} data - The result of the query execution.
*/
formatResults(data) {
let result = this.instance;
if (this.isInsertQuery(data)) {
this.handleInsertQuery(data);
if (!this.instance) {
result = data[this.getInsertIdField()];
}
}).setMaxListeners(100);
})
// Log warnings if we've got them.
.then(function(results){
if (showWarnings && results && results.warningCount > 0) {
return self.logWarnings(results);
}
return results;
})
// Return formatted results...
.then(function(results){
return self.formatResults(results);
});
return promise;
};
/**
* High level function that handles the results of a query execution.
*
*
* Example:
* query.formatResults([
* {
* id: 1, // this is from the main table
* attr2: 'snafu', // this is from the main table
* Tasks.id: 1, // this is from the associated table
* Tasks.title: 'task' // this is from the associated table
* }
* ])
*
* @param {Array} data - The result of the query execution.
*/
Query.prototype.formatResults = function(data) {
var result = this.instance;
if (this.isInsertQuery(data)) {
this.handleInsertQuery(data);
if (!this.instance) {
result = data[this.getInsertIdField()];
if (this.isSelectQuery()) {
result = this.handleSelectQuery(data);
} else if (this.isShowTablesQuery()) {
result = this.handleShowTablesQuery(data);
} else if (this.isDescribeQuery()) {
result = {};
for (const _result of data) {
const enumRegex = /^enum/i;
result[_result.Field] = {
type: enumRegex.test(_result.Type) ? _result.Type.replace(enumRegex, 'ENUM') : _result.Type.toUpperCase(),
allowNull: (_result.Null === 'YES'),
defaultValue: _result.Default,
primaryKey: _result.Key === 'PRI'
};
}
} else if (this.isShowIndexesQuery()) {
result = this.handleShowIndexesQuery(data);
} else if (this.isCallQuery()) {
result = data[0];
} else if (this.isBulkUpdateQuery() || this.isBulkDeleteQuery() || this.isUpsertQuery()) {
result = data.affectedRows;
} else if (this.isVersionQuery()) {
result = data[0].version;
} else if (this.isForeignKeysQuery()) {
result = data;
} else if (this.isRawQuery()) {
// MySQL returns row data and metadata (affected rows etc) in a single object - let's standarize it, sorta
result = [data, data];
}
return result;
}
if (this.isSelectQuery()) {
result = this.handleSelectQuery(data);
} else if (this.isShowTablesQuery()) {
result = this.handleShowTablesQuery(data);
} else if (this.isDescribeQuery()) {
result = {};
data.forEach(function(_result) {
var enumRegex = /^enum/i;
result[_result.Field] = {
type: enumRegex.test(_result.Type) ? _result.Type.replace(enumRegex, 'ENUM') : _result.Type.toUpperCase(),
allowNull: (_result.Null === 'YES'),
defaultValue: _result.Default,
primaryKey: _result.Key === 'PRI'
};
logWarnings(results) {
return this.run('SHOW WARNINGS').then(warningResults => {
const warningMessage = 'MySQL Warnings (' + (this.connection.uuid||'default') + '): ';
const messages = [];
for (const _warningRow of warningResults) {
for (const _warningResult of _warningRow) {
if (_warningResult.hasOwnProperty('Message')) {
messages.push(_warningResult.Message);
} else {
for (const _objectKey of _warningResult.keys()) {
messages.push([_objectKey, _warningResult[_objectKey]].join(': '));
}
}
}
}
this.sequelize.log(warningMessage + messages.join('; '), this.options);
return results;
});
} else if (this.isShowIndexesQuery()) {
result = this.handleShowIndexesQuery(data);
} else if (this.isCallQuery()) {
result = data[0];
} else if (this.isBulkUpdateQuery() || this.isBulkDeleteQuery() || this.isUpsertQuery()) {
result = data.affectedRows;
} else if (this.isVersionQuery()) {
result = data[0].version;
} else if (this.isForeignKeysQuery()) {
result = data;
} else if (this.isRawQuery()) {
// MySQL returns row data and metadata (affected rows etc) in a single object - let's standarize it, sorta
result = [data, data];
}
return result;
};
Query.prototype.logWarnings = function (results) {
var self = this;
return this.run('SHOW WARNINGS').then(function(warningResults) {
var warningMessage = 'MySQL Warnings (' + (self.connection.uuid||'default') + '): ';
var messages = [];
warningResults.forEach(function(_warningRow){
_warningRow.forEach(function(_warningResult) {
if (_warningResult.hasOwnProperty('Message')) {
messages.push(_warningResult.Message);
formatError(err) {
switch (err.errno || err.code) {
case 1062: {
const match = err.message.match(/Duplicate entry '(.*)' for key '?((.|\s)*?)'?$/);
let fields = {};
let message = 'Validation error';
const values = match ? match[1].split('-') : undefined;
const uniqueKey = this.model && this.model.uniqueKeys[match[2]];
if (!!uniqueKey) {
if (!!uniqueKey.msg) message = uniqueKey.msg;
fields = Utils._.zipObject(uniqueKey.fields, values);
} else {
_warningResult.keys().forEach( function(_objectKey) {
messages.push([_objectKey, _warningResult[_objectKey]].join(': '));
});
fields[match[2]] = match[1];
}
});
});
self.sequelize.log(warningMessage + messages.join('; '), self.options);
return results;
});
};
Query.prototype.formatError = function (err) {
var match;
switch (err.errno || err.code) {
case 1062:
match = err.message.match(/Duplicate entry '(.*)' for key '?((.|\s)*?)'?$/);
var values = match ? match[1].split('-') : undefined
, fields = {}
, message = 'Validation error'
, uniqueKey = this.model && this.model.uniqueKeys[match[2]];
if (!!uniqueKey) {
if (!!uniqueKey.msg) message = uniqueKey.msg;
fields = Utils._.zipObject(uniqueKey.fields, values);
} else {
fields[match[2]] = match[1];
}
var errors = [];
var self = this;
Utils._.forOwn(fields, function(value, field) {
errors.push(new sequelizeErrors.ValidationErrorItem(
self.getUniqueConstraintErrorMessage(field),
'unique violation', field, value));
});
return new sequelizeErrors.UniqueConstraintError({
message: message,
errors: errors,
parent: err,
fields: fields
});
case 1451:
match = err.message.match(/FOREIGN KEY \(`(.*)`\) REFERENCES `(.*)` \(`(.*)`\)(?: ON .*)?\)$/);
return new sequelizeErrors.ForeignKeyConstraintError({
fields: null,
index: match ? match[3] : undefined,
parent: err
});
case 1452:
match = err.message.match(/FOREIGN KEY \(`(.*)`\) REFERENCES `(.*)` \(`(.*)`\)(.*)\)$/);
return new sequelizeErrors.ForeignKeyConstraintError({
fields: null,
index: match ? match[1] : undefined,
parent: err
});
default:
return new sequelizeErrors.DatabaseError(err);
}
};
Query.prototype.handleShowIndexesQuery = function (data) {
// Group by index name, and collect all fields
data = _.reduce(data, function (acc, item) {
if (!(item.Key_name in acc)) {
acc[item.Key_name] = item;
item.fields = [];
const errors = [];
Utils._.forOwn(fields, (value, field) => {
errors.push(new sequelizeErrors.ValidationErrorItem(
this.getUniqueConstraintErrorMessage(field),
'unique violation', field, value
));
});
return new sequelizeErrors.UniqueConstraintError({message, errors, parent: err, fields});
}
case 1451: {
const match = err.message.match(/FOREIGN KEY \(`(.*)`\) REFERENCES `(.*)` \(`(.*)`\)(?: ON .*)?\)$/);
return new sequelizeErrors.ForeignKeyConstraintError({
fields: null,
index: match ? match[3] : undefined,
parent: err
});
}
case 1452: {
const match = err.message.match(/FOREIGN KEY \(`(.*)`\) REFERENCES `(.*)` \(`(.*)`\)(.*)\)$/);
return new sequelizeErrors.ForeignKeyConstraintError({
fields: null,
index: match ? match[1] : undefined,
parent: err
});
}
default:
return new sequelizeErrors.DatabaseError(err);
}
}
acc[item.Key_name].fields[item.Seq_in_index - 1] = {
attribute: item.Column_name,
length: item.Sub_part || undefined,
order: item.Collation === 'A' ? 'ASC' : undefined
};
delete item.column_name;
handleShowIndexesQuery(data) {
// Group by index name, and collect all fields
data = _.reduce(data, (acc, item) => {
if (!(item.Key_name in acc)) {
acc[item.Key_name] = item;
item.fields = [];
}
acc[item.Key_name].fields[item.Seq_in_index - 1] = {
attribute: item.Column_name,
length: item.Sub_part || undefined,
order: item.Collation === 'A' ? 'ASC' : undefined
};
delete item.column_name;
return acc;
}, {});
return acc;
}, {});
return Utils._.map(data, function(item) {
return {
return Utils._.map(data, item => ({
primary: item.Key_name === 'PRIMARY',
fields: item.fields,
name: item.Key_name,
tableName: item.Table,
unique: (item.Non_unique !== 1),
type: item.Index_type,
};
});
};
}));
}
}
module.exports = Query;
module.exports.Query = Query;
module.exports.default = Query;
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!