databases
databases copied to clipboard
Fix connection leak when transaction commit/rollback raise an exception
This fixes the following case:
from databases import Database
import asyncio
async def method():
database = Database("postgresql://...")
await database.connect()
try:
async with database.connection() as connection:
await connection.execute(
"""
CREATE TABLE test (
id integer PRIMARY KEY INITIALLY DEFERRED
);
"""
)
async with connection.transaction():
await connection.execute("insert into test (id) values (1)")
await connection.execute("insert into test (id) values (1)")
# The exception UniqueViolationError is raised during txn.commit()
finally:
# Without the fix, connection._connection_counter is 1
print("Before disconnect:", connection._connection_counter)
# This blocks forever waiting for the leaked connection
await database.disconnect()
print("After disconnect")
asyncio.run(method())
Hi, thanks for the PR. Can you maybe include the tests for it?
Yeah no problem I'll add a test