databases icon indicating copy to clipboard operation
databases copied to clipboard

Fix connection leak when transaction commit/rollback raise an exception

Open masipcat opened this issue 3 years ago • 2 comments

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())

masipcat avatar Jul 18 '22 15:07 masipcat

Hi, thanks for the PR. Can you maybe include the tests for it?

aminalaee avatar Jul 28 '22 17:07 aminalaee

Yeah no problem I'll add a test

masipcat avatar Jul 29 '22 09:07 masipcat