Skip to content

Commit 9744ade

Browse files
Vladimir Goncharovelprans
Vladimir Goncharov
authored andcommitted
Handle inactive connection closes while stored in the pool
1 parent 3d1a970 commit 9744ade

File tree

2 files changed

+23
-1
lines changed

2 files changed

+23
-1
lines changed

asyncpg/pool.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -143,7 +143,8 @@ async def connect(self):
143143
self._con = con
144144

145145
async def acquire(self) -> PoolConnectionProxy:
146-
if self._con is None:
146+
if self._con is None or self._con.is_closed():
147+
self._con = None
147148
await self.connect()
148149

149150
self._maybe_cancel_inactive_callback()

tests/test_pool.py

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -612,6 +612,27 @@ async def worker(pool):
612612

613613
self.assertGreaterEqual(N, 50)
614614

615+
async def test_pool_handles_inactive_connection_errors(self):
616+
pool = await self.create_pool(database='postgres',
617+
min_size=1, max_size=1)
618+
619+
con = await pool.acquire(timeout=POOL_NOMINAL_TIMEOUT)
620+
621+
true_con = con._con
622+
623+
await pool.release(con)
624+
625+
# we simulate network error by terminating the connection
626+
true_con.terminate()
627+
628+
# now pool should reopen terminated connection
629+
con = await pool.acquire(timeout=POOL_NOMINAL_TIMEOUT)
630+
631+
self.assertEqual(await con.fetchval('SELECT 1'), 1)
632+
633+
await con.close()
634+
await pool.close()
635+
615636

616637
@unittest.skipIf(os.environ.get('PGHOST'), 'using remote cluster for testing')
617638
class TestHotStandby(tb.ConnectedTestCase):

0 commit comments

Comments
 (0)