123
This commit is contained in:
33
backend/shared/models/base.py
Normal file
33
backend/shared/models/base.py
Normal file
@@ -0,0 +1,33 @@
|
||||
"""
|
||||
Database engine, session factory, and declarative base.
|
||||
"""
|
||||
|
||||
from typing import AsyncGenerator
|
||||
|
||||
from sqlalchemy.ext.asyncio import AsyncSession, create_async_engine
|
||||
from sqlalchemy.orm import sessionmaker, declarative_base
|
||||
|
||||
from ..config import shared_settings
|
||||
|
||||
_engine_kwargs: dict = {"echo": False}
|
||||
if "sqlite" not in shared_settings.DATABASE_URL:
|
||||
_engine_kwargs.update(pool_size=20, max_overflow=30, pool_pre_ping=True)
|
||||
|
||||
engine = create_async_engine(shared_settings.DATABASE_URL, **_engine_kwargs)
|
||||
|
||||
AsyncSessionLocal = sessionmaker(
|
||||
engine,
|
||||
class_=AsyncSession,
|
||||
expire_on_commit=False,
|
||||
)
|
||||
|
||||
Base = declarative_base()
|
||||
|
||||
|
||||
async def get_db() -> AsyncGenerator[AsyncSession, None]:
|
||||
"""Dependency that yields an async database session."""
|
||||
async with AsyncSessionLocal() as session:
|
||||
try:
|
||||
yield session
|
||||
finally:
|
||||
await session.close()
|
||||
Reference in New Issue
Block a user