pool.js 6.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238
  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. clearTimeout(this._removeIdleTimeoutConnectionsTimer);
  96. if (typeof cb !== 'function') {
  97. cb = function(err) {
  98. if (err) {
  99. throw err;
  100. }
  101. };
  102. }
  103. let calledBack = false;
  104. let closedConnections = 0;
  105. let connection;
  106. const endCB = function(err) {
  107. if (calledBack) {
  108. return;
  109. }
  110. if (err || ++closedConnections >= this._allConnections.length) {
  111. calledBack = true;
  112. cb(err);
  113. return;
  114. }
  115. }.bind(this);
  116. if (this._allConnections.length === 0) {
  117. endCB();
  118. return;
  119. }
  120. for (let i = 0; i < this._allConnections.length; i++) {
  121. connection = this._allConnections.get(i);
  122. connection._realEnd(endCB);
  123. }
  124. }
  125. query(sql, values, cb) {
  126. const cmdQuery = Connection.createQuery(
  127. sql,
  128. values,
  129. cb,
  130. this.config.connectionConfig
  131. );
  132. if (typeof cmdQuery.namedPlaceholders === 'undefined') {
  133. cmdQuery.namedPlaceholders = this.config.connectionConfig.namedPlaceholders;
  134. }
  135. this.getConnection((err, conn) => {
  136. if (err) {
  137. if (typeof cmdQuery.onResult === 'function') {
  138. cmdQuery.onResult(err);
  139. } else {
  140. cmdQuery.emit('error', err);
  141. }
  142. return;
  143. }
  144. try {
  145. conn.query(cmdQuery).once('end', () => {
  146. conn.release();
  147. });
  148. } catch (e) {
  149. conn.release();
  150. throw e;
  151. }
  152. });
  153. return cmdQuery;
  154. }
  155. execute(sql, values, cb) {
  156. // TODO construct execute command first here and pass it to connection.execute
  157. // so that polymorphic arguments logic is there in one place
  158. if (typeof values === 'function') {
  159. cb = values;
  160. values = [];
  161. }
  162. this.getConnection((err, conn) => {
  163. if (err) {
  164. return cb(err);
  165. }
  166. try {
  167. conn.execute(sql, values, cb).once('end', () => {
  168. conn.release();
  169. });
  170. } catch (e) {
  171. conn.release();
  172. return cb(e);
  173. }
  174. });
  175. }
  176. _removeConnection(connection) {
  177. // Remove connection from all connections
  178. spliceConnection(this._allConnections, connection);
  179. // Remove connection from free connections
  180. spliceConnection(this._freeConnections, connection);
  181. this.releaseConnection(connection);
  182. }
  183. _removeIdleTimeoutConnections() {
  184. if (this._removeIdleTimeoutConnectionsTimer) {
  185. clearTimeout(this._removeIdleTimeoutConnectionsTimer);
  186. }
  187. this._removeIdleTimeoutConnectionsTimer = setTimeout(() => {
  188. try {
  189. while (
  190. this._freeConnections.length > this.config.maxIdle ||
  191. (this._freeConnections.length > 0 &&
  192. Date.now() - this._freeConnections.get(0).lastActiveTime >
  193. this.config.idleTimeout)
  194. ) {
  195. this._freeConnections.get(0).destroy();
  196. }
  197. } finally {
  198. this._removeIdleTimeoutConnections();
  199. }
  200. }, 1000);
  201. }
  202. format(sql, values) {
  203. return mysql.format(
  204. sql,
  205. values,
  206. this.config.connectionConfig.stringifyObjects,
  207. this.config.connectionConfig.timezone
  208. );
  209. }
  210. escape(value) {
  211. return mysql.escape(
  212. value,
  213. this.config.connectionConfig.stringifyObjects,
  214. this.config.connectionConfig.timezone
  215. );
  216. }
  217. escapeId(value) {
  218. return mysql.escapeId(value, false);
  219. }
  220. }
  221. module.exports = Pool;