File size: 3,435 Bytes
b613c13
 
 
 
 
 
 
 
 
 
 
 
 
 
1bad990
b613c13
 
 
 
 
d64c01a
b613c13
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d64c01a
b613c13
d64c01a
 
1bad990
 
d64c01a
b613c13
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
"""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")