@@ -27,6 +27,7 @@ Pool.prototype.getConnection = function (cb) {
2727 }
2828
2929 var connection ;
30+ var pool = this ;
3031
3132 if ( this . _freeConnections . length > 0 ) {
3233 connection = this . _freeConnections . shift ( ) ;
@@ -39,17 +40,25 @@ Pool.prototype.getConnection = function (cb) {
3940
4041 this . _allConnections . push ( connection ) ;
4142
43+ connection . _pool = null ;
4244 return connection . connect ( { timeout : this . config . acquireTimeout } , function ( err ) {
43- if ( this . _closed ) {
44- return cb ( new Error ( 'Pool is closed.' ) ) ;
45+ if ( pool . _closed ) {
46+ connection . destroy ( ) ;
47+ pool . _removeConnection ( connection ) ;
48+ cb ( new Error ( 'Pool is closed.' ) ) ;
49+ return ;
4550 }
51+
4652 if ( err ) {
47- return cb ( err ) ;
53+ pool . _removeConnection ( connection ) ;
54+ cb ( err ) ;
55+ return ;
4856 }
4957
50- this . emit ( 'connection' , connection ) ;
51- return cb ( null , connection ) ;
52- } . bind ( this ) ) ;
58+ connection . _pool = pool ;
59+ pool . emit ( 'connection' , connection ) ;
60+ cb ( null , connection ) ;
61+ } ) ;
5362 }
5463
5564 if ( ! this . config . waitForConnections ) {
@@ -70,13 +79,20 @@ Pool.prototype.acquireConnection = function acquireConnection(connection, cb) {
7079
7180 connection . _pool = null ;
7281 connection . ping ( { timeout : this . config . acquireTimeout } , function ( err ) {
73- if ( ! err ) {
82+ if ( ! err && ! pool . _closed ) {
7483 connection . _pool = pool ;
7584 cb ( null , connection ) ;
7685 return ;
7786 }
7887
7988 connection . destroy ( ) ;
89+
90+ if ( pool . _closed ) {
91+ pool . _removeConnection ( connection ) ;
92+ cb ( new Error ( 'Pool is closed.' ) ) ;
93+ return ;
94+ }
95+
8096 pool . _connectionQueue . unshift ( cb ) ;
8197 pool . _removeConnection ( connection ) ;
8298 } ) ;
@@ -136,7 +152,7 @@ Pool.prototype.end = function (cb) {
136152 return ;
137153 }
138154
139- if ( err || ++ closedConnections >= this . _allConnections . length ) {
155+ if ( err || this . _allConnections . length === 0 ) {
140156 calledBack = true ;
141157 return cb ( err ) ;
142158 }
@@ -148,10 +164,19 @@ Pool.prototype.end = function (cb) {
148164
149165 while ( this . _allConnections . length ) {
150166 connection = this . _allConnections [ 0 ] ;
151- connection . _pool = null ;
152- connection . _realEnd ( endCB ) ;
167+
168+ if ( connection . _pool === this ) {
169+ closedConnections ++ ;
170+ connection . _pool = null ;
171+ connection . _realEnd ( endCB ) ;
172+ }
173+
153174 this . _removeConnection ( connection ) ;
154175 }
176+
177+ if ( closedConnections === 0 ) {
178+ return process . nextTick ( endCB ) ;
179+ }
155180} ;
156181
157182Pool . prototype . query = function ( sql , values , cb ) {
0 commit comments