2024-03-31 04:18:41 +03:00
|
|
|
from collections.abc import AsyncIterable
|
|
|
|
from typing import Annotated
|
|
|
|
|
|
|
|
from fastapi import Depends
|
2024-04-23 11:10:17 +03:00
|
|
|
from sqlalchemy.ext.asyncio import (AsyncEngine, AsyncSession,
|
|
|
|
async_sessionmaker, create_async_engine)
|
|
|
|
|
|
|
|
from api.application.abstractions.transaction import TransactionContextManager
|
2024-03-31 04:18:41 +03:00
|
|
|
from api.infrastructure.dependencies.stub import Stub
|
2024-04-23 11:10:17 +03:00
|
|
|
from api.infrastructure.persistence.transaction import \
|
|
|
|
SqlalchemyTransactionContextManager
|
2024-03-31 21:07:59 +03:00
|
|
|
from api.infrastructure.settings import Settings
|
2024-03-31 04:18:41 +03:00
|
|
|
|
|
|
|
|
2024-04-23 11:10:17 +03:00
|
|
|
def get_transaction_context(
|
|
|
|
session: Annotated[AsyncSession, Depends(Stub(AsyncSession))]
|
|
|
|
) -> TransactionContextManager:
|
|
|
|
return SqlalchemyTransactionContextManager(session)
|
2024-03-31 04:18:41 +03:00
|
|
|
|
|
|
|
|
2024-03-31 21:07:59 +03:00
|
|
|
def create_engine(
|
|
|
|
settings: Annotated[Settings, Depends(Stub(Settings))],
|
|
|
|
) -> AsyncEngine:
|
|
|
|
return create_async_engine(settings.db.db_url)
|
2024-03-31 04:18:41 +03:00
|
|
|
|
|
|
|
|
|
|
|
def create_session_maker(
|
|
|
|
engine: Annotated[AsyncEngine, Depends(Stub(AsyncEngine))],
|
|
|
|
) -> async_sessionmaker[AsyncSession]:
|
2024-04-01 01:12:01 +03:00
|
|
|
return async_sessionmaker(engine, expire_on_commit=False)
|
2024-03-31 04:18:41 +03:00
|
|
|
|
|
|
|
|
|
|
|
async def new_session(
|
|
|
|
session_maker: Annotated[
|
|
|
|
async_sessionmaker[AsyncSession],
|
|
|
|
Depends(Stub(async_sessionmaker[AsyncSession])),
|
|
|
|
],
|
|
|
|
) -> AsyncIterable[AsyncSession]:
|
|
|
|
async with session_maker() as session:
|
|
|
|
yield session
|