pool.js 6.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236
  1. 'use strict';
  2. const process = require('process');
  3. const mysql = require('../index.js');
  4. const EventEmitter = require('events').EventEmitter;
  5. const PoolConnection = require('./pool_connection.js');
  6. const Queue = require('denque');
  7. const Connection = require('./connection.js');
  8. function spliceConnection(queue, connection) {
  9. const len = queue.length;
  10. for (let i = 0; i < len; i++) {
  11. if (queue.get(i) === connection) {
  12. queue.removeOne(i);
  13. break;
  14. }
  15. }
  16. }
  17. class Pool extends EventEmitter {
  18. constructor(options) {
  19. super();
  20. this.config = options.config;
  21. this.config.connectionConfig.pool = this;
  22. this._allConnections = new Queue();
  23. this._freeConnections = new Queue();
  24. this._connectionQueue = new Queue();
  25. this._closed = false;
  26. if (this.config.maxIdle < this.config.connectionLimit) {
  27. // create idle connection timeout automatically release job
  28. this._removeIdleTimeoutConnections();
  29. }
  30. }
  31. promise(promiseImpl) {
  32. const PromisePool = require('../promise').PromisePool;
  33. return new PromisePool(this, promiseImpl);
  34. }
  35. getConnection(cb) {
  36. if (this._closed) {
  37. return process.nextTick(() => cb(new Error('Pool is closed.')));
  38. }
  39. let connection;
  40. if (this._freeConnections.length > 0) {
  41. connection = this._freeConnections.pop();
  42. this.emit('acquire', connection);
  43. return process.nextTick(() => cb(null, connection));
  44. }
  45. if (
  46. this.config.connectionLimit === 0 ||
  47. this._allConnections.length < this.config.connectionLimit
  48. ) {
  49. connection = new PoolConnection(this, {
  50. config: this.config.connectionConfig
  51. });
  52. this._allConnections.push(connection);
  53. return connection.connect(err => {
  54. if (this._closed) {
  55. return cb(new Error('Pool is closed.'));
  56. }
  57. if (err) {
  58. return cb(err);
  59. }
  60. this.emit('connection', connection);
  61. this.emit('acquire', connection);
  62. return cb(null, connection);
  63. });
  64. }
  65. if (!this.config.waitForConnections) {
  66. return process.nextTick(() => cb(new Error('No connections available.')));
  67. }
  68. if (
  69. this.config.queueLimit &&
  70. this._connectionQueue.length >= this.config.queueLimit
  71. ) {
  72. return cb(new Error('Queue limit reached.'));
  73. }
  74. this.emit('enqueue');
  75. return this._connectionQueue.push(cb);
  76. }
  77. releaseConnection(connection) {
  78. let cb;
  79. if (!connection._pool) {
  80. // The connection has been removed from the pool and is no longer good.
  81. if (this._connectionQueue.length) {
  82. cb = this._connectionQueue.shift();
  83. process.nextTick(this.getConnection.bind(this, cb));
  84. }
  85. } else if (this._connectionQueue.length) {
  86. cb = this._connectionQueue.shift();
  87. process.nextTick(cb.bind(null, null, connection));
  88. } else {
  89. this._freeConnections.push(connection);
  90. this.emit('release', connection);
  91. }
  92. }
  93. end(cb) {
  94. this._closed = true;
  95. if (typeof cb !== 'function') {
  96. cb = function(err) {
  97. if (err) {
  98. throw err;
  99. }
  100. };
  101. }
  102. let calledBack = false;
  103. let closedConnections = 0;
  104. let connection;
  105. const endCB = function(err) {
  106. if (calledBack) {
  107. return;
  108. }
  109. if (err || ++closedConnections >= this._allConnections.length) {
  110. calledBack = true;
  111. cb(err);
  112. return;
  113. }
  114. }.bind(this);
  115. if (this._allConnections.length === 0) {
  116. endCB();
  117. return;
  118. }
  119. for (let i = 0; i < this._allConnections.length; i++) {
  120. connection = this._allConnections.get(i);
  121. connection._realEnd(endCB);
  122. }
  123. }
  124. query(sql, values, cb) {
  125. const cmdQuery = Connection.createQuery(
  126. sql,
  127. values,
  128. cb,
  129. this.config.connectionConfig
  130. );
  131. if (typeof cmdQuery.namedPlaceholders === 'undefined') {
  132. cmdQuery.namedPlaceholders = this.config.connectionConfig.namedPlaceholders;
  133. }
  134. this.getConnection((err, conn) => {
  135. if (err) {
  136. if (typeof cmdQuery.onResult === 'function') {
  137. cmdQuery.onResult(err);
  138. } else {
  139. cmdQuery.emit('error', err);
  140. }
  141. return;
  142. }
  143. try {
  144. conn.query(cmdQuery).once('end', () => {
  145. conn.release();
  146. });
  147. } catch (e) {
  148. conn.release();
  149. throw e;
  150. }
  151. });
  152. return cmdQuery;
  153. }
  154. execute(sql, values, cb) {
  155. // TODO construct execute command first here and pass it to connection.execute
  156. // so that polymorphic arguments logic is there in one place
  157. if (typeof values === 'function') {
  158. cb = values;
  159. values = [];
  160. }
  161. this.getConnection((err, conn) => {
  162. if (err) {
  163. return cb(err);
  164. }
  165. try {
  166. conn.execute(sql, values, cb).once('end', () => {
  167. conn.release();
  168. });
  169. } catch (e) {
  170. conn.release();
  171. return cb(e);
  172. }
  173. });
  174. }
  175. _removeConnection(connection) {
  176. // Remove connection from all connections
  177. spliceConnection(this._allConnections, connection);
  178. // Remove connection from free connections
  179. spliceConnection(this._freeConnections, connection);
  180. this.releaseConnection(connection);
  181. }
  182. _removeIdleTimeoutConnections() {
  183. if (this._removeIdleTimeoutConnectionsTimer) {
  184. clearTimeout(this._removeIdleTimeoutConnectionsTimer);
  185. }
  186. this._removeIdleTimeoutConnectionsTimer = setTimeout(() => {
  187. try {
  188. while (
  189. this._freeConnections.length > this.config.maxIdle &&
  190. Date.now() - this._freeConnections.get(0).lastActiveTime >
  191. this.config.idleTimeout
  192. ) {
  193. this._freeConnections.get(0).destroy();
  194. }
  195. } finally {
  196. this._removeIdleTimeoutConnections();
  197. }
  198. }, 1000);
  199. }
  200. format(sql, values) {
  201. return mysql.format(
  202. sql,
  203. values,
  204. this.config.connectionConfig.stringifyObjects,
  205. this.config.connectionConfig.timezone
  206. );
  207. }
  208. escape(value) {
  209. return mysql.escape(
  210. value,
  211. this.config.connectionConfig.stringifyObjects,
  212. this.config.connectionConfig.timezone
  213. );
  214. }
  215. escapeId(value) {
  216. return mysql.escapeId(value, false);
  217. }
  218. }
  219. module.exports = Pool;