@@ -27,6 +27,7 @@ Pool.prototype.getConnection = function (cb) {
27
27
}
28
28
29
29
var connection ;
30
+ var pool = this ;
30
31
31
32
if ( this . _freeConnections . length > 0 ) {
32
33
connection = this . _freeConnections . shift ( ) ;
@@ -39,17 +40,25 @@ Pool.prototype.getConnection = function (cb) {
39
40
40
41
this . _allConnections . push ( connection ) ;
41
42
43
+ connection . _pool = null ;
42
44
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 ;
45
50
}
51
+
46
52
if ( err ) {
47
- return cb ( err ) ;
53
+ pool . _removeConnection ( connection ) ;
54
+ cb ( err ) ;
55
+ return ;
48
56
}
49
57
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
+ } ) ;
53
62
}
54
63
55
64
if ( ! this . config . waitForConnections ) {
@@ -70,13 +79,20 @@ Pool.prototype.acquireConnection = function acquireConnection(connection, cb) {
70
79
71
80
connection . _pool = null ;
72
81
connection . ping ( { timeout : this . config . acquireTimeout } , function ( err ) {
73
- if ( ! err ) {
82
+ if ( ! err && ! pool . _closed ) {
74
83
connection . _pool = pool ;
75
84
cb ( null , connection ) ;
76
85
return ;
77
86
}
78
87
79
88
connection . destroy ( ) ;
89
+
90
+ if ( pool . _closed ) {
91
+ pool . _removeConnection ( connection ) ;
92
+ cb ( new Error ( 'Pool is closed.' ) ) ;
93
+ return ;
94
+ }
95
+
80
96
pool . _connectionQueue . unshift ( cb ) ;
81
97
pool . _removeConnection ( connection ) ;
82
98
} ) ;
@@ -136,7 +152,7 @@ Pool.prototype.end = function (cb) {
136
152
return ;
137
153
}
138
154
139
- if ( err || ++ closedConnections >= this . _allConnections . length ) {
155
+ if ( err || this . _allConnections . length === 0 ) {
140
156
calledBack = true ;
141
157
return cb ( err ) ;
142
158
}
@@ -148,10 +164,19 @@ Pool.prototype.end = function (cb) {
148
164
149
165
while ( this . _allConnections . length ) {
150
166
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
+
153
174
this . _removeConnection ( connection ) ;
154
175
}
176
+
177
+ if ( closedConnections === 0 ) {
178
+ return process . nextTick ( endCB ) ;
179
+ }
155
180
} ;
156
181
157
182
Pool . prototype . query = function ( sql , values , cb ) {
0 commit comments