databases icon indicating copy to clipboard operation
databases copied to clipboard

Warn for open transactions when a connection is garbage collected

Open zevisert opened this issue 1 year ago • 0 comments

Originally posted by @zevisert in https://github.com/encode/databases/pull/546#discussion_r1203318920

Scenarios where a transaction instance is deleted without calling .commit() or .rollback() (perhaps because a database or connection is being garbage collected) are possible if users are using the documented low-level transaction management API, and they didn't set up their try/except/else logic correctly.

# MVE that hangs on master, 0.7.0, 0.6.2, 0.5.5, 0.4.3, 0.3.2, 0.2.6, 0.1.12 
import databases, asyncio, os

async def mve():
    async with databases.Database(os.environ['TEST_DATABASE_URL']) as db:
        transaction = db.transaction()
        await transaction.start()

asyncio.run(mve())

I consider this user-error, but it also makes sense that this hangs on shutdown. From the database driver's perspective, there is an open transaction that has not executed a COMMIT or ROLLBACK statement, better wait for that to happen before shutting down.

The best thing databases could do here is to emit a warning if __del__ (?) is called on a connection with entries that remain in it's ._transaction_stack. Maybe even each of those transactions could have a .rollback() applied to them.

zevisert avatar May 26 '23 22:05 zevisert