connection-manager.js 4.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145
  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').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. * @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('mariadb');
  26. this.refreshTypeParser(DataTypes);
  27. }
  28. static _typecast(field, next) {
  29. if (parserStore.get(field.type)) {
  30. return parserStore.get(field.type)(field, this.sequelize.options, next);
  31. }
  32. return next();
  33. }
  34. _refreshTypeParser(dataType) {
  35. parserStore.refresh(dataType);
  36. }
  37. _clearTypeParser() {
  38. parserStore.clear();
  39. }
  40. /**
  41. * Connect with MariaDB 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. // Named timezone is not supported in mariadb, convert to offset
  51. let tzOffset = this.sequelize.options.timezone;
  52. tzOffset = /\//.test(tzOffset) ? momentTz.tz(tzOffset).format('Z')
  53. : tzOffset;
  54. const connectionConfig = {
  55. host: config.host,
  56. port: config.port,
  57. user: config.username,
  58. password: config.password,
  59. database: config.database,
  60. timezone: tzOffset,
  61. typeCast: ConnectionManager._typecast.bind(this),
  62. bigNumberStrings: false,
  63. supportBigNumbers: true,
  64. foundRows: false
  65. };
  66. if (config.dialectOptions) {
  67. Object.assign(connectionConfig, config.dialectOptions);
  68. }
  69. if (!this.sequelize.config.keepDefaultTimezone) {
  70. // set timezone for this connection
  71. if (connectionConfig.initSql) {
  72. if (!Array.isArray(
  73. connectionConfig.initSql)) {
  74. connectionConfig.initSql = [connectionConfig.initSql];
  75. }
  76. connectionConfig.initSql.push(`SET time_zone = '${tzOffset}'`);
  77. } else {
  78. connectionConfig.initSql = `SET time_zone = '${tzOffset}'`;
  79. }
  80. }
  81. return this.lib.createConnection(connectionConfig)
  82. .then(connection => {
  83. this.sequelize.options.databaseVersion = connection.serverVersion();
  84. debug('connection acquired');
  85. connection.on('error', error => {
  86. switch (error.code) {
  87. case 'ESOCKET':
  88. case 'ECONNRESET':
  89. case 'EPIPE':
  90. case 'PROTOCOL_CONNECTION_LOST':
  91. this.pool.destroy(connection);
  92. }
  93. });
  94. return connection;
  95. })
  96. .catch(err => {
  97. switch (err.code) {
  98. case 'ECONNREFUSED':
  99. throw new SequelizeErrors.ConnectionRefusedError(err);
  100. case 'ER_ACCESS_DENIED_ERROR':
  101. case 'ER_ACCESS_DENIED_NO_PASSWORD_ERROR':
  102. throw new SequelizeErrors.AccessDeniedError(err);
  103. case 'ENOTFOUND':
  104. throw new SequelizeErrors.HostNotFoundError(err);
  105. case 'EHOSTUNREACH':
  106. case 'ENETUNREACH':
  107. case 'EADDRNOTAVAIL':
  108. throw new SequelizeErrors.HostNotReachableError(err);
  109. case 'EINVAL':
  110. throw new SequelizeErrors.InvalidConnectionError(err);
  111. default:
  112. throw new SequelizeErrors.ConnectionError(err);
  113. }
  114. });
  115. }
  116. disconnect(connection) {
  117. // Don't disconnect connections with CLOSED state
  118. if (!connection.isValid()) {
  119. debug('connection tried to disconnect but was already at CLOSED state');
  120. return Promise.resolve();
  121. }
  122. //wrap native Promise into bluebird
  123. return Promise.resolve(connection.end());
  124. }
  125. validate(connection) {
  126. return connection && connection.isValid();
  127. }
  128. }
  129. module.exports = ConnectionManager;
  130. module.exports.ConnectionManager = ConnectionManager;
  131. module.exports.default = ConnectionManager;