Pool.js 7.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294
  1. var mysql = require('../');
  2. var Connection = require('./Connection');
  3. var EventEmitter = require('events').EventEmitter;
  4. var Util = require('util');
  5. var PoolConnection = require('./PoolConnection');
  6. module.exports = Pool;
  7. Util.inherits(Pool, EventEmitter);
  8. function Pool(options) {
  9. EventEmitter.call(this);
  10. this.config = options.config;
  11. this.config.connectionConfig.pool = this;
  12. this._acquiringConnections = [];
  13. this._allConnections = [];
  14. this._freeConnections = [];
  15. this._connectionQueue = [];
  16. this._closed = false;
  17. }
  18. Pool.prototype.getConnection = function (cb) {
  19. if (this._closed) {
  20. var err = new Error('Pool is closed.');
  21. err.code = 'POOL_CLOSED';
  22. process.nextTick(function () {
  23. cb(err);
  24. });
  25. return;
  26. }
  27. var connection;
  28. var pool = this;
  29. if (this._freeConnections.length > 0) {
  30. connection = this._freeConnections.shift();
  31. this.acquireConnection(connection, cb);
  32. return;
  33. }
  34. if (this.config.connectionLimit === 0 || this._allConnections.length < this.config.connectionLimit) {
  35. connection = new PoolConnection(this, { config: this.config.newConnectionConfig() });
  36. this._acquiringConnections.push(connection);
  37. this._allConnections.push(connection);
  38. connection.connect({timeout: this.config.acquireTimeout}, function onConnect(err) {
  39. spliceConnection(pool._acquiringConnections, connection);
  40. if (pool._closed) {
  41. err = new Error('Pool is closed.');
  42. err.code = 'POOL_CLOSED';
  43. }
  44. if (err) {
  45. pool._purgeConnection(connection);
  46. cb(err);
  47. return;
  48. }
  49. pool.emit('connection', connection);
  50. pool.emit('acquire', connection);
  51. cb(null, connection);
  52. });
  53. return;
  54. }
  55. if (!this.config.waitForConnections) {
  56. process.nextTick(function(){
  57. var err = new Error('No connections available.');
  58. err.code = 'POOL_CONNLIMIT';
  59. cb(err);
  60. });
  61. return;
  62. }
  63. this._enqueueCallback(cb);
  64. };
  65. Pool.prototype.acquireConnection = function acquireConnection(connection, cb) {
  66. if (connection._pool !== this) {
  67. throw new Error('Connection acquired from wrong pool.');
  68. }
  69. var changeUser = this._needsChangeUser(connection);
  70. var pool = this;
  71. this._acquiringConnections.push(connection);
  72. function onOperationComplete(err) {
  73. spliceConnection(pool._acquiringConnections, connection);
  74. if (pool._closed) {
  75. err = new Error('Pool is closed.');
  76. err.code = 'POOL_CLOSED';
  77. }
  78. if (err) {
  79. pool._connectionQueue.unshift(cb);
  80. pool._purgeConnection(connection);
  81. return;
  82. }
  83. if (changeUser) {
  84. pool.emit('connection', connection);
  85. }
  86. pool.emit('acquire', connection);
  87. cb(null, connection);
  88. }
  89. if (changeUser) {
  90. // restore user back to pool configuration
  91. connection.config = this.config.newConnectionConfig();
  92. connection.changeUser({timeout: this.config.acquireTimeout}, onOperationComplete);
  93. } else {
  94. // ping connection
  95. connection.ping({timeout: this.config.acquireTimeout}, onOperationComplete);
  96. }
  97. };
  98. Pool.prototype.releaseConnection = function releaseConnection(connection) {
  99. if (this._acquiringConnections.indexOf(connection) !== -1) {
  100. // connection is being acquired
  101. return;
  102. }
  103. if (connection._pool) {
  104. if (connection._pool !== this) {
  105. throw new Error('Connection released to wrong pool');
  106. }
  107. if (this._freeConnections.indexOf(connection) !== -1) {
  108. // connection already in free connection pool
  109. // this won't catch all double-release cases
  110. throw new Error('Connection already released');
  111. } else {
  112. // add connection to end of free queue
  113. this._freeConnections.push(connection);
  114. this.emit('release', connection);
  115. }
  116. }
  117. if (this._closed) {
  118. // empty the connection queue
  119. this._connectionQueue.splice(0).forEach(function (cb) {
  120. var err = new Error('Pool is closed.');
  121. err.code = 'POOL_CLOSED';
  122. process.nextTick(function () {
  123. cb(err);
  124. });
  125. });
  126. } else if (this._connectionQueue.length) {
  127. // get connection with next waiting callback
  128. this.getConnection(this._connectionQueue.shift());
  129. }
  130. };
  131. Pool.prototype.end = function (cb) {
  132. this._closed = true;
  133. if (typeof cb !== 'function') {
  134. cb = function (err) {
  135. if (err) throw err;
  136. };
  137. }
  138. var calledBack = false;
  139. var waitingClose = 0;
  140. function onEnd(err) {
  141. if (!calledBack && (err || --waitingClose <= 0)) {
  142. calledBack = true;
  143. cb(err);
  144. }
  145. }
  146. while (this._allConnections.length !== 0) {
  147. waitingClose++;
  148. this._purgeConnection(this._allConnections[0], onEnd);
  149. }
  150. if (waitingClose === 0) {
  151. process.nextTick(onEnd);
  152. }
  153. };
  154. Pool.prototype.query = function (sql, values, cb) {
  155. var query = Connection.createQuery(sql, values, cb);
  156. if (!(typeof sql === 'object' && 'typeCast' in sql)) {
  157. query.typeCast = this.config.connectionConfig.typeCast;
  158. }
  159. if (this.config.connectionConfig.trace) {
  160. // Long stack trace support
  161. query._callSite = new Error();
  162. }
  163. this.getConnection(function (err, conn) {
  164. if (err) {
  165. query.on('error', function () {});
  166. query.end(err);
  167. return;
  168. }
  169. // Release connection based off event
  170. query.once('end', function() {
  171. conn.release();
  172. });
  173. conn.query(query);
  174. });
  175. return query;
  176. };
  177. Pool.prototype._enqueueCallback = function _enqueueCallback(callback) {
  178. if (this.config.queueLimit && this._connectionQueue.length >= this.config.queueLimit) {
  179. process.nextTick(function () {
  180. var err = new Error('Queue limit reached.');
  181. err.code = 'POOL_ENQUEUELIMIT';
  182. callback(err);
  183. });
  184. return;
  185. }
  186. // Bind to domain, as dequeue will likely occur in a different domain
  187. var cb = process.domain
  188. ? process.domain.bind(callback)
  189. : callback;
  190. this._connectionQueue.push(cb);
  191. this.emit('enqueue');
  192. };
  193. Pool.prototype._needsChangeUser = function _needsChangeUser(connection) {
  194. var connConfig = connection.config;
  195. var poolConfig = this.config.connectionConfig;
  196. // check if changeUser values are different
  197. return connConfig.user !== poolConfig.user
  198. || connConfig.database !== poolConfig.database
  199. || connConfig.password !== poolConfig.password
  200. || connConfig.charsetNumber !== poolConfig.charsetNumber;
  201. };
  202. Pool.prototype._purgeConnection = function _purgeConnection(connection, callback) {
  203. var cb = callback || function () {};
  204. if (connection.state === 'disconnected') {
  205. connection.destroy();
  206. }
  207. this._removeConnection(connection);
  208. if (connection.state !== 'disconnected' && !connection._protocol._quitSequence) {
  209. connection._realEnd(cb);
  210. return;
  211. }
  212. process.nextTick(cb);
  213. };
  214. Pool.prototype._removeConnection = function(connection) {
  215. connection._pool = null;
  216. // Remove connection from all connections
  217. spliceConnection(this._allConnections, connection);
  218. // Remove connection from free connections
  219. spliceConnection(this._freeConnections, connection);
  220. this.releaseConnection(connection);
  221. };
  222. Pool.prototype.escape = function(value) {
  223. return mysql.escape(value, this.config.connectionConfig.stringifyObjects, this.config.connectionConfig.timezone);
  224. };
  225. Pool.prototype.escapeId = function escapeId(value) {
  226. return mysql.escapeId(value, false);
  227. };
  228. function spliceConnection(array, connection) {
  229. var index;
  230. if ((index = array.indexOf(connection)) !== -1) {
  231. // Remove connection from all connections
  232. array.splice(index, 1);
  233. }
  234. }