pool.js 6.1 KB

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