Spaces:
Sleeping
Sleeping
Download app/database.py from yabeskn/briga-core-api: direct link, hf CLI and curl.
- Browser
- Download file 3.44 kB
-
https://huggingface.co/spaces/yabeskn/briga-core-api/resolve/main/app/database.py
- Command line
-
hf download hf://spaces/yabeskn/briga-core-api/app/database.py
-
curl -L -o database.py https://huggingface.co/spaces/yabeskn/briga-core-api/resolve/main/app/database.py
3.44 kB
| """Async database session factory. | |
| Creates a reusable async SQLAlchemy session for all service modules. | |
| Supports both PostgreSQL (production/Cloud Run) and SQLite (local dev). | |
| Usage: | |
| from app.database import get_db | |
| @router.get(...) | |
| async def handler(db=Depends(get_db)): | |
| result = await db.execute(...) | |
| """ | |
| import os | |
| import uuid | |
| from typing import AsyncGenerator, Optional | |
| from loguru import logger | |
| from sqlalchemy import text | |
| from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker, create_async_engine | |
| from sqlalchemy.pool import NullPool | |
| from app.config.settings import settings | |
| # Determine database URL | |
| DATABASE_URL = os.environ.get("DATABASE_URL", settings.database_url) | |
| # For local dev with no PostgreSQL, use aiosqlite | |
| USE_SQLITE_FALLBACK = os.environ.get("USE_SQLITE_FALLBACK", "false").lower() == "true" | |
| if USE_SQLITE_FALLBACK or "sqlite" in DATABASE_URL: | |
| # Local development with SQLite (no PostgreSQL needed) | |
| engine = create_async_engine( | |
| "sqlite+aiosqlite:///./brigawan_dev.db", | |
| echo=os.environ.get("SQL_ECHO", "false").lower() == "true", | |
| ) | |
| logger.info("Using SQLite fallback database (brigawan_dev.db)") | |
| else: | |
| # Production PostgreSQL | |
| engine = create_async_engine( | |
| DATABASE_URL, | |
| poolclass=NullPool, | |
| echo=os.environ.get("SQL_ECHO", "false").lower() == "true", | |
| connect_args={ | |
| "statement_cache_size": 0, | |
| "prepared_statement_cache_size": 0, | |
| "prepared_statement_name_func": lambda: f"__asyncpg_{uuid.uuid4().hex}__" | |
| } | |
| ) | |
| logger.info("Connected to PostgreSQL (URL hidden for security)") | |
| AsyncSessionLocal = async_sessionmaker( | |
| engine, | |
| class_=AsyncSession, | |
| expire_on_commit=False, | |
| ) | |
| async def get_db() -> AsyncGenerator[AsyncSession, None]: | |
| """FastAPI dependency that yields an async DB session. | |
| Usage in routes: | |
| @router.get("/users") | |
| async def get_users(db: AsyncSession = Depends(get_db)): | |
| ... | |
| """ | |
| async with AsyncSessionLocal() as session: | |
| try: | |
| # Verify connection is alive | |
| await session.execute(text("SELECT 1")) | |
| yield session | |
| except Exception as e: | |
| logger.error(f"Database session error: {e}") | |
| raise | |
| async def init_db(): | |
| """Initialize the database — create all tables from models. | |
| Call during app startup via lifespan. | |
| For production, use Alembic migrations instead. | |
| """ | |
| from app.models.base import Base | |
| # Explicitly import ALL model modules to register their tables on Base.metadata | |
| # Without this, models not reachable through the import chain won't have tables created | |
| import app.models.talent | |
| import app.models.employer | |
| import app.models.finance | |
| import app.models.job | |
| import app.models.system | |
| import app.models.content | |
| import app.models.lpk | |
| import app.models.community | |
| import app.models.skkni | |
| import app.models.security | |
| try: | |
| async with engine.begin() as conn: | |
| await conn.run_sync(Base.metadata.create_all) | |
| logger.info("Database tables created/verified") | |
| except Exception as e: | |
| logger.warning(f"Table creation failed (will retry): {e}") | |
| async def close_db(): | |
| """Close the database connection pool.""" | |
| await engine.dispose() | |
| logger.info("Database connection pool closed") | |