connection-manager.js 5.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159
  1. 'use strict';
  2. const AbstractConnectionManager = require('../abstract/connection-manager');
  3. const SequelizeErrors = require('../../errors');
  4. const Promise = require('../../promise');
  5. const { logger } = require('../../utils/logger');
  6. const DataTypes = require('../../data-types').mysql;
  7. const momentTz = require('moment-timezone');
  8. const debug = logger.debugContext('connection:mysql');
  9. const parserStore = require('../parserStore')('mysql');
  10. /**
  11. * MySQL Connection Manager
  12. *
  13. * Get connections, validate and disconnect them.
  14. * AbstractConnectionManager pooling use it to handle MySQL specific connections
  15. * Use https://github.com/sidorares/node-mysql2 to connect with MySQL server
  16. *
  17. * @extends AbstractConnectionManager
  18. * @returns Class<ConnectionManager>
  19. * @private
  20. */
  21. class ConnectionManager extends AbstractConnectionManager {
  22. constructor(dialect, sequelize) {
  23. sequelize.config.port = sequelize.config.port || 3306;
  24. super(dialect, sequelize);
  25. this.lib = this._loadDialectModule('mysql2');
  26. this.refreshTypeParser(DataTypes);
  27. }
  28. _refreshTypeParser(dataType) {
  29. parserStore.refresh(dataType);
  30. }
  31. _clearTypeParser() {
  32. parserStore.clear();
  33. }
  34. static _typecast(field, next) {
  35. if (parserStore.get(field.type)) {
  36. return parserStore.get(field.type)(field, this.sequelize.options, next);
  37. }
  38. return next();
  39. }
  40. /**
  41. * Connect with MySQL database based on config, Handle any errors in connection
  42. * Set the pool handlers on connection.error
  43. * Also set proper timezone once connection is connected.
  44. *
  45. * @param {Object} config
  46. * @returns {Promise<Connection>}
  47. * @private
  48. */
  49. connect(config) {
  50. const connectionConfig = Object.assign({
  51. host: config.host,
  52. port: config.port,
  53. user: config.username,
  54. flags: '-FOUND_ROWS',
  55. password: config.password,
  56. database: config.database,
  57. timezone: this.sequelize.options.timezone,
  58. typeCast: ConnectionManager._typecast.bind(this),
  59. bigNumberStrings: false,
  60. supportBigNumbers: true
  61. }, config.dialectOptions);
  62. return new Promise((resolve, reject) => {
  63. const connection = this.lib.createConnection(connectionConfig);
  64. const errorHandler = e => {
  65. // clean up connect & error event if there is error
  66. connection.removeListener('connect', connectHandler);
  67. connection.removeListener('error', connectHandler);
  68. reject(e);
  69. };
  70. const connectHandler = () => {
  71. // clean up error event if connected
  72. connection.removeListener('error', errorHandler);
  73. resolve(connection);
  74. };
  75. // don't use connection.once for error event handling here
  76. // mysql2 emit error two times in case handshake was failed
  77. // first error is protocol_lost and second is timeout
  78. // if we will use `once.error` node process will crash on 2nd error emit
  79. connection.on('error', errorHandler);
  80. connection.once('connect', connectHandler);
  81. })
  82. .tap(() => { debug('connection acquired'); })
  83. .then(connection => {
  84. connection.on('error', error => {
  85. switch (error.code) {
  86. case 'ESOCKET':
  87. case 'ECONNRESET':
  88. case 'EPIPE':
  89. case 'PROTOCOL_CONNECTION_LOST':
  90. this.pool.destroy(connection);
  91. }
  92. });
  93. return new Promise((resolve, reject) => {
  94. if (!this.sequelize.config.keepDefaultTimezone) {
  95. // set timezone for this connection
  96. // but named timezone are not directly supported in mysql, so get its offset first
  97. let tzOffset = this.sequelize.options.timezone;
  98. tzOffset = /\//.test(tzOffset) ? momentTz.tz(tzOffset).format('Z') : tzOffset;
  99. return connection.query(`SET time_zone = '${tzOffset}'`, err => {
  100. if (err) { reject(err); } else { resolve(connection); }
  101. });
  102. }
  103. // return connection without executing SET time_zone query
  104. resolve(connection);
  105. });
  106. })
  107. .catch(err => {
  108. switch (err.code) {
  109. case 'ECONNREFUSED':
  110. throw new SequelizeErrors.ConnectionRefusedError(err);
  111. case 'ER_ACCESS_DENIED_ERROR':
  112. throw new SequelizeErrors.AccessDeniedError(err);
  113. case 'ENOTFOUND':
  114. throw new SequelizeErrors.HostNotFoundError(err);
  115. case 'EHOSTUNREACH':
  116. throw new SequelizeErrors.HostNotReachableError(err);
  117. case 'EINVAL':
  118. throw new SequelizeErrors.InvalidConnectionError(err);
  119. default:
  120. throw new SequelizeErrors.ConnectionError(err);
  121. }
  122. });
  123. }
  124. disconnect(connection) {
  125. // Don't disconnect connections with CLOSED state
  126. if (connection._closing) {
  127. debug('connection tried to disconnect but was already at CLOSED state');
  128. return Promise.resolve();
  129. }
  130. return Promise.fromCallback(callback => connection.end(callback));
  131. }
  132. validate(connection) {
  133. return connection
  134. && !connection._fatalError
  135. && !connection._protocolError
  136. && !connection._closing
  137. && !connection.stream.destroyed;
  138. }
  139. }
  140. module.exports = ConnectionManager;
  141. module.exports.ConnectionManager = ConnectionManager;
  142. module.exports.default = ConnectionManager;