connection-manager.js 4.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138
  1. 'use strict';
  2. const semver = require('semver');
  3. const AbstractConnectionManager = require('../abstract/connection-manager');
  4. const SequelizeErrors = require('../../errors');
  5. const { logger } = require('../../utils/logger');
  6. const DataTypes = require('../../data-types').mariadb;
  7. const momentTz = require('moment-timezone');
  8. const debug = logger.debugContext('connection:mariadb');
  9. const parserStore = require('../parserStore')('mariadb');
  10. /**
  11. * MariaDB Connection Manager
  12. *
  13. * Get connections, validate and disconnect them.
  14. * AbstractConnectionManager pooling use it to handle MariaDB specific connections
  15. * Use https://github.com/MariaDB/mariadb-connector-nodejs to connect with MariaDB 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('mariadb');
  24. this.refreshTypeParser(DataTypes);
  25. }
  26. static _typecast(field, next) {
  27. if (parserStore.get(field.type)) {
  28. return parserStore.get(field.type)(field, this.sequelize.options, next);
  29. }
  30. return next();
  31. }
  32. _refreshTypeParser(dataType) {
  33. parserStore.refresh(dataType);
  34. }
  35. _clearTypeParser() {
  36. parserStore.clear();
  37. }
  38. /**
  39. * Connect with MariaDB 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. // Named timezone is not supported in mariadb, convert to offset
  49. let tzOffset = this.sequelize.options.timezone;
  50. tzOffset = /\//.test(tzOffset) ? momentTz.tz(tzOffset).format('Z')
  51. : tzOffset;
  52. const connectionConfig = {
  53. host: config.host,
  54. port: config.port,
  55. user: config.username,
  56. password: config.password,
  57. database: config.database,
  58. timezone: tzOffset,
  59. typeCast: ConnectionManager._typecast.bind(this),
  60. bigNumberStrings: false,
  61. supportBigNumbers: true,
  62. foundRows: false,
  63. ...config.dialectOptions
  64. };
  65. if (!this.sequelize.config.keepDefaultTimezone) {
  66. // set timezone for this connection
  67. if (connectionConfig.initSql) {
  68. if (!Array.isArray(
  69. connectionConfig.initSql)) {
  70. connectionConfig.initSql = [connectionConfig.initSql];
  71. }
  72. connectionConfig.initSql.push(`SET time_zone = '${tzOffset}'`);
  73. } else {
  74. connectionConfig.initSql = `SET time_zone = '${tzOffset}'`;
  75. }
  76. }
  77. try {
  78. const connection = await this.lib.createConnection(connectionConfig);
  79. this.sequelize.options.databaseVersion = semver.coerce(connection.serverVersion()).version;
  80. debug('connection acquired');
  81. connection.on('error', error => {
  82. switch (error.code) {
  83. case 'ESOCKET':
  84. case 'ECONNRESET':
  85. case 'EPIPE':
  86. case 'PROTOCOL_CONNECTION_LOST':
  87. this.pool.destroy(connection);
  88. }
  89. });
  90. return connection;
  91. } catch (err) {
  92. switch (err.code) {
  93. case 'ECONNREFUSED':
  94. throw new SequelizeErrors.ConnectionRefusedError(err);
  95. case 'ER_ACCESS_DENIED_ERROR':
  96. case 'ER_ACCESS_DENIED_NO_PASSWORD_ERROR':
  97. throw new SequelizeErrors.AccessDeniedError(err);
  98. case 'ENOTFOUND':
  99. throw new SequelizeErrors.HostNotFoundError(err);
  100. case 'EHOSTUNREACH':
  101. case 'ENETUNREACH':
  102. case 'EADDRNOTAVAIL':
  103. throw new SequelizeErrors.HostNotReachableError(err);
  104. case 'EINVAL':
  105. throw new SequelizeErrors.InvalidConnectionError(err);
  106. default:
  107. throw new SequelizeErrors.ConnectionError(err);
  108. }
  109. }
  110. }
  111. async disconnect(connection) {
  112. // Don't disconnect connections with CLOSED state
  113. if (!connection.isValid()) {
  114. debug('connection tried to disconnect but was already at CLOSED state');
  115. return;
  116. }
  117. return await connection.end();
  118. }
  119. validate(connection) {
  120. return connection && connection.isValid();
  121. }
  122. }
  123. module.exports = ConnectionManager;
  124. module.exports.ConnectionManager = ConnectionManager;
  125. module.exports.default = ConnectionManager;