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

Commit 39a1f11f by Andy Edwards Committed by GitHub

refactor(dialects/mariadb): asyncify methods (#12131)

1 parent 1432cfd1
...@@ -2,7 +2,6 @@ ...@@ -2,7 +2,6 @@
const AbstractConnectionManager = require('../abstract/connection-manager'); const AbstractConnectionManager = require('../abstract/connection-manager');
const SequelizeErrors = require('../../errors'); const SequelizeErrors = require('../../errors');
const Promise = require('../../promise');
const { logger } = require('../../utils/logger'); const { logger } = require('../../utils/logger');
const DataTypes = require('../../data-types').mariadb; const DataTypes = require('../../data-types').mariadb;
const momentTz = require('moment-timezone'); const momentTz = require('moment-timezone');
...@@ -53,7 +52,7 @@ class ConnectionManager extends AbstractConnectionManager { ...@@ -53,7 +52,7 @@ class ConnectionManager extends AbstractConnectionManager {
* @returns {Promise<Connection>} * @returns {Promise<Connection>}
* @private * @private
*/ */
connect(config) { async connect(config) {
// Named timezone is not supported in mariadb, convert to offset // Named timezone is not supported in mariadb, convert to offset
let tzOffset = this.sequelize.options.timezone; let tzOffset = this.sequelize.options.timezone;
tzOffset = /\//.test(tzOffset) ? momentTz.tz(tzOffset).format('Z') tzOffset = /\//.test(tzOffset) ? momentTz.tz(tzOffset).format('Z')
...@@ -89,50 +88,48 @@ class ConnectionManager extends AbstractConnectionManager { ...@@ -89,50 +88,48 @@ class ConnectionManager extends AbstractConnectionManager {
} }
} }
return this.lib.createConnection(connectionConfig) try {
.then(connection => { const connection = await this.lib.createConnection(connectionConfig);
this.sequelize.options.databaseVersion = connection.serverVersion(); this.sequelize.options.databaseVersion = connection.serverVersion();
debug('connection acquired'); debug('connection acquired');
connection.on('error', error => { connection.on('error', error => {
switch (error.code) { switch (error.code) {
case 'ESOCKET': case 'ESOCKET':
case 'ECONNRESET': case 'ECONNRESET':
case 'EPIPE': case 'EPIPE':
case 'PROTOCOL_CONNECTION_LOST': case 'PROTOCOL_CONNECTION_LOST':
this.pool.destroy(connection); this.pool.destroy(connection);
}
});
return connection;
})
.catch(err => {
switch (err.code) {
case 'ECONNREFUSED':
throw new SequelizeErrors.ConnectionRefusedError(err);
case 'ER_ACCESS_DENIED_ERROR':
case 'ER_ACCESS_DENIED_NO_PASSWORD_ERROR':
throw new SequelizeErrors.AccessDeniedError(err);
case 'ENOTFOUND':
throw new SequelizeErrors.HostNotFoundError(err);
case 'EHOSTUNREACH':
case 'ENETUNREACH':
case 'EADDRNOTAVAIL':
throw new SequelizeErrors.HostNotReachableError(err);
case 'EINVAL':
throw new SequelizeErrors.InvalidConnectionError(err);
default:
throw new SequelizeErrors.ConnectionError(err);
} }
}); });
return connection;
} catch (err) {
switch (err.code) {
case 'ECONNREFUSED':
throw new SequelizeErrors.ConnectionRefusedError(err);
case 'ER_ACCESS_DENIED_ERROR':
case 'ER_ACCESS_DENIED_NO_PASSWORD_ERROR':
throw new SequelizeErrors.AccessDeniedError(err);
case 'ENOTFOUND':
throw new SequelizeErrors.HostNotFoundError(err);
case 'EHOSTUNREACH':
case 'ENETUNREACH':
case 'EADDRNOTAVAIL':
throw new SequelizeErrors.HostNotReachableError(err);
case 'EINVAL':
throw new SequelizeErrors.InvalidConnectionError(err);
default:
throw new SequelizeErrors.ConnectionError(err);
}
}
} }
disconnect(connection) { async disconnect(connection) {
// Don't disconnect connections with CLOSED state // Don't disconnect connections with CLOSED state
if (!connection.isValid()) { if (!connection.isValid()) {
debug('connection tried to disconnect but was already at CLOSED state'); debug('connection tried to disconnect but was already at CLOSED state');
return Promise.resolve(); return;
} }
//wrap native Promise into bluebird return await connection.end();
return Promise.resolve(connection.end());
} }
validate(connection) { validate(connection) {
......
...@@ -4,7 +4,6 @@ const AbstractQuery = require('../abstract/query'); ...@@ -4,7 +4,6 @@ const AbstractQuery = require('../abstract/query');
const sequelizeErrors = require('../../errors'); const sequelizeErrors = require('../../errors');
const _ = require('lodash'); const _ = require('lodash');
const DataTypes = require('../../data-types'); const DataTypes = require('../../data-types');
const Promise = require('../../promise');
const { logger } = require('../../utils/logger'); const { logger } = require('../../utils/logger');
const ER_DUP_ENTRY = 1062; const ER_DUP_ENTRY = 1062;
...@@ -32,7 +31,7 @@ class Query extends AbstractQuery { ...@@ -32,7 +31,7 @@ class Query extends AbstractQuery {
return [sql, bindParam.length > 0 ? bindParam : undefined]; return [sql, bindParam.length > 0 ? bindParam : undefined];
} }
run(sql, parameters) { async run(sql, parameters) {
this.sql = sql; this.sql = sql;
const { connection, options } = this; const { connection, options } = this;
...@@ -44,39 +43,33 @@ class Query extends AbstractQuery { ...@@ -44,39 +43,33 @@ class Query extends AbstractQuery {
if (parameters) { if (parameters) {
debug('parameters(%j)', parameters); debug('parameters(%j)', parameters);
} }
return Promise.resolve( let results;
connection.query(this.sql, parameters)
.then(results => {
complete();
// Log warnings if we've got them.
if (showWarnings && results && results.warningStatus > 0) {
return this.logWarnings(results);
}
return results;
})
.catch(err => {
// MariaDB automatically rolls-back transactions in the event of a deadlock
if (options.transaction && err.errno === 1213) {
options.transaction.finished = 'rollback';
}
complete(); try {
results = await connection.query(this.sql, parameters);
complete();
err.sql = sql;
err.parameters = parameters;
throw this.formatError(err);
})
)
// Log warnings if we've got them. // Log warnings if we've got them.
.then(results => { if (showWarnings && results && results.warningStatus > 0) {
if (showWarnings && results && results.warningStatus > 0) { await this.logWarnings(results);
return this.logWarnings(results); }
} } catch (err) {
return results; // MariaDB automatically rolls-back transactions in the event of a deadlock
}) if (options.transaction && err.errno === 1213) {
// Return formatted results... options.transaction.finished = 'rollback';
.then(results => this.formatResults(results)); }
complete();
err.sql = sql;
err.parameters = parameters;
throw this.formatError(err);
}
if (showWarnings && results && results.warningStatus > 0) {
await this.logWarnings(results);
}
return this.formatResults(results);
} }
/** /**
...@@ -196,32 +189,31 @@ class Query extends AbstractQuery { ...@@ -196,32 +189,31 @@ class Query extends AbstractQuery {
} }
} }
logWarnings(results) { async logWarnings(results) {
return this.run('SHOW WARNINGS').then(warningResults => { const warningResults = await this.run('SHOW WARNINGS');
const warningMessage = `MariaDB Warnings (${this.connection.uuid const warningMessage = `MariaDB Warnings (${this.connection.uuid
|| 'default'}): `; || 'default'}): `;
const messages = []; const messages = [];
for (const _warningRow of warningResults) { for (const _warningRow of warningResults) {
if (_warningRow === undefined || typeof _warningRow[Symbol.iterator] if (_warningRow === undefined || typeof _warningRow[Symbol.iterator]
!== 'function') { !== 'function') {
continue; continue;
} }
for (const _warningResult of _warningRow) { for (const _warningResult of _warningRow) {
if (Object.prototype.hasOwnProperty.call(_warningResult, 'Message')) { if (Object.prototype.hasOwnProperty.call(_warningResult, 'Message')) {
messages.push(_warningResult.Message); messages.push(_warningResult.Message);
} else { } else {
for (const _objectKey of _warningResult.keys()) { for (const _objectKey of _warningResult.keys()) {
messages.push( messages.push(
[_objectKey, _warningResult[_objectKey]].join(': ')); [_objectKey, _warningResult[_objectKey]].join(': '));
}
} }
} }
} }
}
this.sequelize.log(warningMessage + messages.join('; '), this.options); this.sequelize.log(warningMessage + messages.join('; '), this.options);
return results; return results;
});
} }
formatError(err) { formatError(err) {
......
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!