Skip to content
This repository was archived by the owner on Apr 15, 2025. It is now read-only.
This repository was archived by the owner on Apr 15, 2025. It is now read-only.

Allow early commiting transaction from inside the context manager before raising an exception #1063

@rijenkii

Description

@rijenkii

Problem

Use case:

async def get_transaction():
    async with db.tx() as tx:
        yield tx

@router.post("/")
async def endpoint(tx: Annotated[Prisma, Depends(get_transaction)]):
    await tx.entity.delete_many()
    if not_good:
        raise HTTPException()
    return "ok"

I require the removal of the entity to be committed, even though the function was interrupted with an exception.

Suggested solution

Add a commit method to the Prisma class:

class Prisma:
    ...
    async def commit(self):
        if self._tx_id:
            await self._engine.commit_transaction(self._tx_id)

Similar function could be added for rollback.

Usage example:

@router.post("/")
async def endpoint(tx: Annotated[Prisma, Depends(get_transaction)]):
    await tx.entity.delete_many()
    if not_good:
        await tx.commit()
        raise HTTPException()
    return "ok"

Alternatives

Instead of calling commit_transaction it may be possible to set an internal flag that will be consulted on the context exit.

Additional context

Currently I am using this function to do what I want:

async def early_commit(tx: prisma.Prisma):
    if tx._tx_id:  # pyright: ignore[reportPrivateUsage]
        await tx._engine.commit_transaction(  # pyright: ignore[reportPrivateUsage]
            tx._tx_id  # pyright: ignore[reportPrivateUsage]
        )

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions