connection-manager.js 5.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183
  1. 'use strict';
  2. const AbstractConnectionManager = require('../abstract/connection-manager');
  3. const ResourceLock = require('./resource-lock');
  4. const Promise = require('../../promise');
  5. const { logger } = require('../../utils/logger');
  6. const sequelizeErrors = require('../../errors');
  7. const DataTypes = require('../../data-types').mssql;
  8. const parserStore = require('../parserStore')('mssql');
  9. const debug = logger.debugContext('connection:mssql');
  10. const debugTedious = logger.debugContext('connection:mssql:tedious');
  11. class ConnectionManager extends AbstractConnectionManager {
  12. constructor(dialect, sequelize) {
  13. sequelize.config.port = sequelize.config.port || 1433;
  14. super(dialect, sequelize);
  15. this.lib = this._loadDialectModule('tedious');
  16. this.refreshTypeParser(DataTypes);
  17. }
  18. _refreshTypeParser(dataType) {
  19. parserStore.refresh(dataType);
  20. }
  21. _clearTypeParser() {
  22. parserStore.clear();
  23. }
  24. connect(config) {
  25. const connectionConfig = {
  26. server: config.host,
  27. authentication: {
  28. type: 'default',
  29. options: {
  30. userName: config.username || undefined,
  31. password: config.password || undefined
  32. }
  33. },
  34. options: {
  35. port: parseInt(config.port, 10),
  36. database: config.database,
  37. encrypt: false
  38. }
  39. };
  40. if (config.dialectOptions) {
  41. // only set port if no instance name was provided
  42. if (
  43. config.dialectOptions.options &&
  44. config.dialectOptions.options.instanceName
  45. ) {
  46. delete connectionConfig.options.port;
  47. }
  48. if (config.dialectOptions.authentication) {
  49. Object.assign(connectionConfig.authentication, config.dialectOptions.authentication);
  50. }
  51. Object.assign(connectionConfig.options, config.dialectOptions.options);
  52. }
  53. return new Promise((resolve, reject) => {
  54. const connection = new this.lib.Connection(connectionConfig);
  55. if (connection.state === connection.STATE.INITIALIZED) {
  56. connection.connect();
  57. }
  58. connection.lib = this.lib;
  59. const resourceLock = new ResourceLock(connection);
  60. const connectHandler = error => {
  61. connection.removeListener('end', endHandler);
  62. connection.removeListener('error', errorHandler);
  63. if (error) return reject(error);
  64. debug('connection acquired');
  65. resolve(resourceLock);
  66. };
  67. const endHandler = () => {
  68. connection.removeListener('connect', connectHandler);
  69. connection.removeListener('error', errorHandler);
  70. reject(new Error('Connection was closed by remote server'));
  71. };
  72. const errorHandler = error => {
  73. connection.removeListener('connect', connectHandler);
  74. connection.removeListener('end', endHandler);
  75. reject(error);
  76. };
  77. connection.once('error', errorHandler);
  78. connection.once('end', endHandler);
  79. connection.once('connect', connectHandler);
  80. /*
  81. * Permanently attach this event before connection is even acquired
  82. * tedious sometime emits error even after connect(with error).
  83. *
  84. * If we dont attach this even that unexpected error event will crash node process
  85. *
  86. * E.g. connectTimeout is set higher than requestTimeout
  87. */
  88. connection.on('error', error => {
  89. switch (error.code) {
  90. case 'ESOCKET':
  91. case 'ECONNRESET':
  92. this.pool.destroy(resourceLock);
  93. }
  94. });
  95. if (config.dialectOptions && config.dialectOptions.debug) {
  96. connection.on('debug', debugTedious.log.bind(debugTedious));
  97. }
  98. }).catch(error => {
  99. if (!error.code) {
  100. throw new sequelizeErrors.ConnectionError(error);
  101. }
  102. switch (error.code) {
  103. case 'ESOCKET':
  104. if (error.message.includes('connect EHOSTUNREACH')) {
  105. throw new sequelizeErrors.HostNotReachableError(error);
  106. }
  107. if (error.message.includes('connect ENETUNREACH')) {
  108. throw new sequelizeErrors.HostNotReachableError(error);
  109. }
  110. if (error.message.includes('connect EADDRNOTAVAIL')) {
  111. throw new sequelizeErrors.HostNotReachableError(error);
  112. }
  113. if (error.message.includes('getaddrinfo ENOTFOUND')) {
  114. throw new sequelizeErrors.HostNotFoundError(error);
  115. }
  116. if (error.message.includes('connect ECONNREFUSED')) {
  117. throw new sequelizeErrors.ConnectionRefusedError(error);
  118. }
  119. throw new sequelizeErrors.ConnectionError(error);
  120. case 'ER_ACCESS_DENIED_ERROR':
  121. case 'ELOGIN':
  122. throw new sequelizeErrors.AccessDeniedError(error);
  123. case 'EINVAL':
  124. throw new sequelizeErrors.InvalidConnectionError(error);
  125. default:
  126. throw new sequelizeErrors.ConnectionError(error);
  127. }
  128. });
  129. }
  130. disconnect(connectionLock) {
  131. /**
  132. * Abstract connection may try to disconnect raw connection used for fetching version
  133. */
  134. const connection = connectionLock.unwrap
  135. ? connectionLock.unwrap()
  136. : connectionLock;
  137. // Don't disconnect a connection that is already disconnected
  138. if (connection.closed) {
  139. return Promise.resolve();
  140. }
  141. return new Promise(resolve => {
  142. connection.on('end', resolve);
  143. connection.close();
  144. debug('connection closed');
  145. });
  146. }
  147. validate(connectionLock) {
  148. /**
  149. * Abstract connection may try to validate raw connection used for fetching version
  150. */
  151. const connection = connectionLock.unwrap
  152. ? connectionLock.unwrap()
  153. : connectionLock;
  154. return connection && connection.loggedIn;
  155. }
  156. }
  157. module.exports = ConnectionManager;
  158. module.exports.ConnectionManager = ConnectionManager;
  159. module.exports.default = ConnectionManager;