43 lines
1.2 KiB
Python
43 lines
1.2 KiB
Python
|
from collections.abc import AsyncIterable
|
||
|
from typing import Annotated
|
||
|
|
||
|
from fastapi import Depends
|
||
|
from sqlalchemy.ext.asyncio import (
|
||
|
AsyncEngine,
|
||
|
AsyncSession,
|
||
|
async_sessionmaker,
|
||
|
create_async_engine,
|
||
|
)
|
||
|
|
||
|
from api.application.abstractions import UnitOfWork
|
||
|
from api.infrastructure.dependencies.stub import Stub
|
||
|
from api.infrastructure.persistence.uow import SqlAlchemyUnitOfWork
|
||
|
|
||
|
|
||
|
def new_unit_of_work(
|
||
|
session: Annotated[AsyncSession, Depends(Stub(AsyncSession))],
|
||
|
) -> UnitOfWork:
|
||
|
return SqlAlchemyUnitOfWork(session)
|
||
|
|
||
|
|
||
|
def create_engine() -> AsyncEngine:
|
||
|
return create_async_engine("postgresql+asyncpg://postgresql+asyncpg//demo_user:user_pass@db:5432/serviceman_db")
|
||
|
|
||
|
|
||
|
def create_session_maker(
|
||
|
engine: Annotated[AsyncEngine, Depends(Stub(AsyncEngine))],
|
||
|
) -> async_sessionmaker[AsyncSession]:
|
||
|
maker = async_sessionmaker(engine, expire_on_commit=False)
|
||
|
print("session_maker id:", id(maker))
|
||
|
return maker
|
||
|
|
||
|
|
||
|
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
|