pool_connection.js 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. 'use strict';
  2. const Connection = require('./connection.js');
  3. class PoolConnection extends Connection {
  4. constructor(pool, options) {
  5. super(options);
  6. this._pool = pool;
  7. this._released = false;
  8. this.lastActiveTime = Date.now();
  9. this.once('end', () => {
  10. this._removeFromPool();
  11. });
  12. this.once('error', () => {
  13. this._removeFromPool();
  14. });
  15. }
  16. release() {
  17. if (this._released) {
  18. return;
  19. }
  20. if (!this._pool || this._pool._closed) {
  21. return;
  22. }
  23. this._released = true;
  24. this.lastActiveTime = Date.now();
  25. this._pool.releaseConnection(this);
  26. }
  27. [Symbol.dispose]() {
  28. this.release();
  29. }
  30. end(callback) {
  31. if (this.config.gracefulEnd) {
  32. this._removeFromPool();
  33. super.end(callback);
  34. return;
  35. }
  36. const err = new Error(
  37. 'Calling conn.end() to release a pooled connection is ' +
  38. 'deprecated. In next version calling conn.end() will be ' +
  39. 'restored to default conn.end() behavior. Use ' +
  40. 'conn.release() instead.'
  41. );
  42. this.emit('warn', err);
  43. console.warn(err.message);
  44. this.release();
  45. if (typeof callback === 'function') {
  46. callback();
  47. }
  48. }
  49. destroy() {
  50. this._removeFromPool();
  51. super.destroy();
  52. }
  53. _removeFromPool() {
  54. if (!this._pool || this._pool._closed) {
  55. return;
  56. }
  57. const pool = this._pool;
  58. this._pool = null;
  59. pool._removeConnection(this);
  60. }
  61. promise(promiseImpl) {
  62. const PromisePoolConnection = require('./promise/pool_connection.js');
  63. return new PromisePoolConnection(this, promiseImpl);
  64. }
  65. }
  66. PoolConnection.statementKey = Connection.statementKey;
  67. module.exports = PoolConnection;
  68. // TODO: Remove this when we are removing PoolConnection#end
  69. PoolConnection.prototype._realEnd = Connection.prototype.end;