pool_connection.js 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. 'use strict';
  2. const Connection = require('../index.js').Connection;
  3. class PoolConnection extends Connection {
  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. promise(promiseImpl) {
  29. const PromisePoolConnection = require('../promise').PromisePoolConnection;
  30. return new PromisePoolConnection(this, promiseImpl);
  31. }
  32. end() {
  33. const err = new Error(
  34. 'Calling conn.end() to release a pooled connection is ' +
  35. 'deprecated. In next version calling conn.end() will be ' +
  36. 'restored to default conn.end() behavior. Use ' +
  37. 'conn.release() instead.'
  38. );
  39. this.emit('warn', err);
  40. // eslint-disable-next-line no-console
  41. console.warn(err.message);
  42. this.release();
  43. }
  44. destroy() {
  45. this._removeFromPool();
  46. super.destroy();
  47. }
  48. _removeFromPool() {
  49. if (!this._pool || this._pool._closed) {
  50. return;
  51. }
  52. const pool = this._pool;
  53. this._pool = null;
  54. pool._removeConnection(this);
  55. }
  56. }
  57. PoolConnection.statementKey = Connection.statementKey;
  58. module.exports = PoolConnection;
  59. // TODO: Remove this when we are removing PoolConnection#end
  60. PoolConnection.prototype._realEnd = Connection.prototype.end;