@@ -1230,18 +1230,43 @@ def release(self, connection):
1230
1230
"Releases the connection back to the pool"
1231
1231
self ._checkpid ()
1232
1232
with self ._lock :
1233
- if connection .pid != self .pid :
1233
+ try :
1234
+ self ._in_use_connections .remove (connection )
1235
+ except KeyError :
1236
+ # Gracefully fail when a connection is returned to this pool
1237
+ # that the pool doesn't actually own
1238
+ pass
1239
+
1240
+ if self .owns_connection (connection ):
1241
+ self ._available_connections .append (connection )
1242
+ else :
1243
+ # pool doesn't own this connection. do not add it back
1244
+ # to the pool and decrement the count so that another
1245
+ # connection can take its place if needed
1246
+ self ._created_connections -= 1
1247
+ connection .disconnect ()
1234
1248
return
1235
- self ._in_use_connections .remove (connection )
1236
- self ._available_connections .append (connection )
1237
1249
1238
- def disconnect (self ):
1239
- "Disconnects all connections in the pool"
1250
+ def owns_connection (self , connection ):
1251
+ return connection .pid == self .pid
1252
+
1253
+ def disconnect (self , inuse_connections = True ):
1254
+ """
1255
+ Disconnects connections in the pool
1256
+
1257
+ If ``inuse_connections`` is True, disconnect connections that are
1258
+ current in use, potentially by other threads. Otherwise only disconnect
1259
+ connections that are idle in the pool.
1260
+ """
1240
1261
self ._checkpid ()
1241
1262
with self ._lock :
1242
- all_conns = chain (self ._available_connections ,
1243
- self ._in_use_connections )
1244
- for connection in all_conns :
1263
+ if inuse_connections :
1264
+ connections = chain (self ._available_connections ,
1265
+ self ._in_use_connections )
1266
+ else :
1267
+ connections = self ._available_connections
1268
+
1269
+ for connection in connections :
1245
1270
connection .disconnect ()
1246
1271
1247
1272
@@ -1375,7 +1400,13 @@ def release(self, connection):
1375
1400
"Releases the connection back to the pool."
1376
1401
# Make sure we haven't changed process.
1377
1402
self ._checkpid ()
1378
- if connection .pid != self .pid :
1403
+ if not self .owns_connection (connection ):
1404
+ # pool doesn't own this connection. do not add it back
1405
+ # to the pool. instead add a None value which is a placeholder
1406
+ # that will cause the pool to recreate the connection if
1407
+ # its needed.
1408
+ connection .disconnect ()
1409
+ self .pool .put_nowait (None )
1379
1410
return
1380
1411
1381
1412
# Put the connection back into the pool.
0 commit comments