Spaces:
Sleeping
Sleeping
File size: 1,947 Bytes
32a82ff 470978d 32a82ff | 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 | """
TuneVid.com — Database Connection & Session Management
"""
import os
from contextlib import asynccontextmanager
from typing import AsyncGenerator
from sqlalchemy.ext.asyncio import (
AsyncSession,
async_sessionmaker,
create_async_engine,
)
from sqlalchemy.orm import DeclarativeBase
from dotenv import load_dotenv
load_dotenv()
def _ensure_asyncpg_url(raw_url: str) -> str:
"""Normalize Postgres SQLAlchemy URL for asyncio engine."""
if raw_url.startswith("postgresql+psycopg2://"):
return raw_url.replace("postgresql+psycopg2://", "postgresql+asyncpg://", 1)
if raw_url.startswith("postgresql://"):
return raw_url.replace("postgresql://", "postgresql+asyncpg://", 1)
if raw_url.startswith("postgres://"):
return raw_url.replace("postgres://", "postgresql+asyncpg://", 1)
return raw_url
DATABASE_URL = _ensure_asyncpg_url(
os.getenv(
"DATABASE_URL",
"postgresql+asyncpg://postgres:postgres@localhost:5432/tunevid",
)
)
engine = create_async_engine(
DATABASE_URL,
echo=False,
pool_size=20,
max_overflow=10,
pool_pre_ping=True,
)
async_session_factory = async_sessionmaker(
engine,
class_=AsyncSession,
expire_on_commit=False,
)
class Base(DeclarativeBase):
pass
async def get_db() -> AsyncGenerator[AsyncSession, None]:
"""FastAPI dependency that yields an async DB session."""
async with async_session_factory() as session:
try:
yield session
await session.commit()
except Exception:
await session.rollback()
raise
finally:
await session.close()
async def init_db():
"""Create all tables (dev only — use Alembic in production)."""
async with engine.begin() as conn:
await conn.run_sync(Base.metadata.create_all)
async def close_db():
"""Dispose engine on shutdown."""
await engine.dispose()
|