Skip to content

Enhancement: sync and async methods handle sessions differently in SQLAlchemyFactory #817

@AlexPetul

Description

@AlexPetul

Summary

In sync method no context managers are used. Session lifecycle is managed by the caller.

class SQLASyncPersistence(SyncPersistenceProtocol[T]):
    def __init__(self, session: Session) -> None:
        """Sync persistence handler for SQLAFactory."""
        self.session = session

    def save(self, data: T) -> T:
        self.session.add(data)
        self.session.commit()
        return data

While in async method the session is closed on exit.

class SQLAASyncPersistence(AsyncPersistenceProtocol[T]):
    def __init__(self, session: AsyncSession) -> None:
        """Async persistence handler for SQLAFactory."""
        self.session = session

    async def save(self, data: T) -> T:
        async with self.session as session:
            session.add(data)
            await session.commit()
            await session.refresh(data)
        return data

I think it's better to make it consistent, so that the caller manages the session lifecycle.

Basic Example

No response

Drawbacks and Impact

async with session: closes the session, which may conflict with the caller’s lifecycle management.

Unresolved questions

No response

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions