pool_connection.js 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  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. end() {
  29. const err = new Error(
  30. 'Calling conn.end() to release a pooled connection is ' +
  31. 'deprecated. In next version calling conn.end() will be ' +
  32. 'restored to default conn.end() behavior. Use ' +
  33. 'conn.release() instead.',
  34. );
  35. this.emit('warn', err);
  36. console.warn(err.message);
  37. this.release();
  38. }
  39. destroy() {
  40. this._removeFromPool();
  41. super.destroy();
  42. }
  43. _removeFromPool() {
  44. if (!this._pool || this._pool._closed) {
  45. return;
  46. }
  47. const pool = this._pool;
  48. this._pool = null;
  49. pool._removeConnection(this);
  50. }
  51. }
  52. BasePoolConnection.statementKey = BaseConnection.statementKey;
  53. module.exports = BasePoolConnection;
  54. // TODO: Remove this when we are removing PoolConnection#end
  55. BasePoolConnection.prototype._realEnd = BaseConnection.prototype.end;