connection-manager.js 4.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152
  1. 'use strict';
  2. const AbstractConnectionManager = require('../abstract/connection-manager');
  3. const SequelizeErrors = require('../../errors');
  4. const { logger } = require('../../utils/logger');
  5. const DataTypes = require('../../data-types').mysql;
  6. const momentTz = require('moment-timezone');
  7. const debug = logger.debugContext('connection:mysql');
  8. const parserStore = require('../parserStore')('mysql');
  9. const { promisify } = require('util');
  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. * @private
  18. */
  19. class ConnectionManager extends AbstractConnectionManager {
  20. constructor(dialect, sequelize) {
  21. sequelize.config.port = sequelize.config.port || 3306;
  22. super(dialect, sequelize);
  23. this.lib = this._loadDialectModule('mysql2');
  24. this.refreshTypeParser(DataTypes);
  25. }
  26. _refreshTypeParser(dataType) {
  27. parserStore.refresh(dataType);
  28. }
  29. _clearTypeParser() {
  30. parserStore.clear();
  31. }
  32. static _typecast(field, next) {
  33. if (parserStore.get(field.type)) {
  34. return parserStore.get(field.type)(field, this.sequelize.options, next);
  35. }
  36. return next();
  37. }
  38. /**
  39. * Connect with MySQL database based on config, Handle any errors in connection
  40. * Set the pool handlers on connection.error
  41. * Also set proper timezone once connection is connected.
  42. *
  43. * @param {object} config
  44. * @returns {Promise<Connection>}
  45. * @private
  46. */
  47. async connect(config) {
  48. const connectionConfig = {
  49. host: config.host,
  50. port: config.port,
  51. user: config.username,
  52. flags: '-FOUND_ROWS',
  53. password: config.password,
  54. database: config.database,
  55. timezone: this.sequelize.options.timezone,
  56. typeCast: ConnectionManager._typecast.bind(this),
  57. bigNumberStrings: false,
  58. supportBigNumbers: true,
  59. ...config.dialectOptions
  60. };
  61. try {
  62. const connection = await 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. debug('connection acquired');
  83. connection.on('error', error => {
  84. switch (error.code) {
  85. case 'ESOCKET':
  86. case 'ECONNRESET':
  87. case 'EPIPE':
  88. case 'PROTOCOL_CONNECTION_LOST':
  89. this.pool.destroy(connection);
  90. }
  91. });
  92. if (!this.sequelize.config.keepDefaultTimezone) {
  93. // set timezone for this connection
  94. // but named timezone are not directly supported in mysql, so get its offset first
  95. let tzOffset = this.sequelize.options.timezone;
  96. tzOffset = /\//.test(tzOffset) ? momentTz.tz(tzOffset).format('Z') : tzOffset;
  97. await promisify(cb => connection.query(`SET time_zone = '${tzOffset}'`, cb))();
  98. }
  99. return connection;
  100. } catch (err) {
  101. switch (err.code) {
  102. case 'ECONNREFUSED':
  103. throw new SequelizeErrors.ConnectionRefusedError(err);
  104. case 'ER_ACCESS_DENIED_ERROR':
  105. throw new SequelizeErrors.AccessDeniedError(err);
  106. case 'ENOTFOUND':
  107. throw new SequelizeErrors.HostNotFoundError(err);
  108. case 'EHOSTUNREACH':
  109. throw new SequelizeErrors.HostNotReachableError(err);
  110. case 'EINVAL':
  111. throw new SequelizeErrors.InvalidConnectionError(err);
  112. default:
  113. throw new SequelizeErrors.ConnectionError(err);
  114. }
  115. }
  116. }
  117. async disconnect(connection) {
  118. // Don't disconnect connections with CLOSED state
  119. if (connection._closing) {
  120. debug('connection tried to disconnect but was already at CLOSED state');
  121. return;
  122. }
  123. return await promisify(callback => connection.end(callback))();
  124. }
  125. validate(connection) {
  126. return connection
  127. && !connection._fatalError
  128. && !connection._protocolError
  129. && !connection._closing
  130. && !connection.stream.destroyed;
  131. }
  132. }
  133. module.exports = ConnectionManager;
  134. module.exports.ConnectionManager = ConnectionManager;
  135. module.exports.default = ConnectionManager;