UNPKG

1.76 kBJavaScriptView Raw
1var inherits = require('util').inherits;
2var Connection = require('./Connection');
3var Events = require('events');
4
5module.exports = PoolConnection;
6inherits(PoolConnection, Connection);
7
8function PoolConnection(pool, options) {
9 Connection.call(this, options);
10 this._pool = pool;
11
12 // Bind connection to pool domain
13 if (Events.usingDomains) {
14 this.domain = pool.domain;
15 }
16
17 // When a fatal error occurs the connection's protocol ends, which will cause
18 // the connection to end as well, thus we only need to watch for the end event
19 // and we will be notified of disconnects.
20 this.on('end', this._removeFromPool);
21 this.on('error', function (err) {
22 if (err.fatal) {
23 this._removeFromPool();
24 }
25 });
26}
27
28PoolConnection.prototype.release = function release() {
29 var pool = this._pool;
30
31 if (!pool || pool._closed) {
32 return undefined;
33 }
34
35 return pool.releaseConnection(this);
36};
37
38// TODO: Remove this when we are removing PoolConnection#end
39PoolConnection.prototype._realEnd = Connection.prototype.end;
40
41PoolConnection.prototype.end = function () {
42 console.warn(
43 'Calling conn.end() to release a pooled connection is ' +
44 'deprecated. In next version calling conn.end() will be ' +
45 'restored to default conn.end() behavior. Use ' +
46 'conn.release() instead.'
47 );
48 this.release();
49};
50
51PoolConnection.prototype.destroy = function () {
52 Connection.prototype.destroy.apply(this, arguments);
53 this._removeFromPool(this);
54};
55
56PoolConnection.prototype._removeFromPool = function _removeFromPool() {
57 if (!this._pool || this._pool._closed) {
58 return;
59 }
60
61 var pool = this._pool;
62 this._pool = null;
63
64 pool._purgeConnection(this);
65};