pool_connection.js 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. 'use strict';
  2. const BaseConnection = require('./connection.js');
  3. class BasePoolConnection extends BaseConnection {
  4. constructor(pool, options) {
  5. super(options);
  6. this._pool = pool;
  7. // The last active time of this connection
  8. this.lastActiveTime = Date.now();
  9. // When a fatal error occurs the connection's protocol ends, which will cause
  10. // the connection to end as well, thus we only need to watch for the end event
  11. // and we will be notified of disconnects.
  12. // REVIEW: Moved to `once`
  13. this.once('end', () => {
  14. this._removeFromPool();
  15. });
  16. this.once('error', () => {
  17. this._removeFromPool();
  18. });
  19. }
  20. release() {
  21. if (!this._pool || this._pool._closed) {
  22. return;
  23. }
  24. // update last active time
  25. this.lastActiveTime = Date.now();
  26. this._pool.releaseConnection(this);
  27. }
  28. [Symbol.dispose]() {
  29. this.release();
  30. }
  31. end(callback) {
  32. if (this.config.gracefulEnd) {
  33. this._removeFromPool();
  34. super.end(callback);
  35. return;
  36. }
  37. const err = new Error(
  38. 'Calling conn.end() to release a pooled connection is ' +
  39. 'deprecated. In next version calling conn.end() will be ' +
  40. 'restored to default conn.end() behavior. Use ' +
  41. 'conn.release() instead.'
  42. );
  43. this.emit('warn', err);
  44. console.warn(err.message);
  45. this.release();
  46. if (typeof callback === 'function') {
  47. callback();
  48. }
  49. }
  50. destroy() {
  51. this._removeFromPool();
  52. super.destroy();
  53. }
  54. _removeFromPool() {
  55. if (!this._pool || this._pool._closed) {
  56. return;
  57. }
  58. const pool = this._pool;
  59. this._pool = null;
  60. pool._removeConnection(this);
  61. }
  62. }
  63. BasePoolConnection.statementKey = BaseConnection.statementKey;
  64. module.exports = BasePoolConnection;
  65. // TODO: Remove this when we are removing PoolConnection#end
  66. BasePoolConnection.prototype._realEnd = BaseConnection.prototype.end;