tortoise-orm icon indicating copy to clipboard operation
tortoise-orm copied to clipboard

Defer function call till after transaction

Open the-akpan opened this issue 3 years ago • 2 comments

I've been getting my hands dirty with tortoise recently, and I have been loving it. Porting from Django, I noticed (not sure if it isn't implemented already but with a different name) that I could not find something similar to transaction.on_commit in Django, something I could use to run comment only if the current transaction block is committed. I could easily go round this by moving the function call down, but in cases involving multiple models in different modules, that might up my imports and make my code more tightly coupled. The solution must not completely mirror Django, as tortoise is not Django, but could be something similar.

the-akpan avatar Jan 06 '23 06:01 the-akpan

You can just wrap the transaction like this:

class Transaction:
    async def __aenter__(self):
        self.connection = in_transaction()
        await self.connection.__aenter__()
        return self.connection

    async def __aexit__(self, exc_type, exc_val, exc_tb):
        await self.connection.__aexit__(exc_type, exc_val, exc_tb)
        if not exc_type:
            # Do something on success
            pass

async with Transaction() as connection:
    pass

long2ice avatar Jan 30 '23 02:01 long2ice

An on_commit hook is basic stuff for any orm used in production, without this my celery tasks are in a race condition with the commit. This belongs in the orm imo

F483 avatar Dec 18 '24 08:12 F483