41 lines
1.1 KiB
Python
41 lines
1.1 KiB
Python
"""
|
||
Модель, описывающий взаимодействие с базой данных.
|
||
Создание и её удаление, а также получении асинхронной сессии.
|
||
"""
|
||
|
||
from sqlalchemy.ext.asyncio import (
|
||
AsyncEngine,
|
||
AsyncSession,
|
||
async_sessionmaker,
|
||
create_async_engine,
|
||
)
|
||
|
||
from .config import config
|
||
from .models import Base
|
||
|
||
engine = create_async_engine(
|
||
url=config.postgres_url,
|
||
echo=config.postgres_engine_echo,
|
||
)
|
||
session_maker = async_sessionmaker(
|
||
bind=engine,
|
||
class_=AsyncSession,
|
||
expire_on_commit=False,
|
||
)
|
||
|
||
|
||
async def get_session():
|
||
async with session_maker() as session: # pyrefly: ignore
|
||
return session
|
||
|
||
|
||
async def create_db(engine: AsyncEngine) -> None:
|
||
"""Create the entire database from the base model."""
|
||
async with engine.begin() as conn:
|
||
await conn.run_sync(Base.metadata.create_all)
|
||
|
||
|
||
async def drop_db(engine: AsyncEngine) -> None:
|
||
"""Drop the entire database from the base model."""
|
||
async with engine.begin() as conn:
|
||
await conn.run_sync(Base.metadata.drop_all)
|