Spaces:
Paused
Paused
File size: 2,216 Bytes
f3bcb28 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 | """Database session management."""
from typing import AsyncGenerator
from sqlalchemy.ext.asyncio import (
AsyncSession,
create_async_engine,
async_sessionmaker,
)
from contextlib import asynccontextmanager
from backend.core.config import settings
from backend.db.models import Base
def _is_sqlite() -> bool:
"""Check if using SQLite database."""
return settings.database_url.startswith("sqlite")
def get_async_database_url() -> str:
"""Convert postgresql:// to postgresql+asyncpg:// if needed."""
url = settings.database_url
if url.startswith("postgresql://"):
return url.replace("postgresql://", "postgresql+asyncpg://", 1)
return url
# Engine kwargs - SQLite doesn't support pool settings
_engine_kwargs = {"echo": settings.debug}
if not _is_sqlite():
_engine_kwargs.update({
"pool_size": 5,
"max_overflow": 10,
"pool_pre_ping": True,
})
# Engine and session factory
engine = create_async_engine(
get_async_database_url(),
**_engine_kwargs,
)
AsyncSessionLocal = async_sessionmaker(
engine,
class_=AsyncSession,
expire_on_commit=False,
autocommit=False,
autoflush=False,
)
async def create_tables() -> None:
"""Create all database tables."""
async with engine.begin() as conn:
await conn.run_sync(Base.metadata.create_all)
async def close_db() -> None:
"""Close database connections."""
await engine.dispose()
async def get_db() -> AsyncGenerator[AsyncSession, None]:
"""Dependency for getting database session."""
async with AsyncSessionLocal() as session:
try:
yield session
await session.commit()
except Exception:
await session.rollback()
raise
finally:
await session.close()
@asynccontextmanager
async def get_db_context() -> AsyncGenerator[AsyncSession, None]:
"""Context manager for getting database session."""
async with AsyncSessionLocal() as session:
try:
yield session
await session.commit()
except Exception:
await session.rollback()
raise
finally:
await session.close()
|