Spaces:
Paused

File size: 2,812 Bytes
5eb4857
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
91ebb5b
 
 
5eb4857
e0be0ca
5eb4857
 
91ebb5b
5eb4857
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b7980f7
 
 
 
5eb4857
 
 
b7980f7
 
5eb4857
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""
Async SQLAlchemy engine and session factory for PostgreSQL.
"""

from sqlalchemy.ext.asyncio import AsyncSession, create_async_engine, async_sessionmaker
from sqlalchemy.orm import DeclarativeBase
from core.config import get_settings

settings = get_settings()

# Definitively fix cloud connectivity by building the URL from validated components
from sqlalchemy.engine import URL

url = URL.create(
    drivername="postgresql+asyncpg",
    username=settings.DB_USER,
    password=settings.DB_PASS,
    host=settings.DB_HOST,
    port=settings.DB_PORT,
    database=settings.DB_NAME,
)

connect_args = {
    "ssl": "require",
    "prepared_statement_cache_size": 0  # CRITICAL for Supavisor Transaction mode
}

from sqlalchemy.pool import NullPool

# Unified Cloud Connectivity: Use NullPool for Session-mode compatibility
engine = create_async_engine(
    settings.async_database_url,
    echo=settings.DEBUG,
    future=True,
    poolclass=NullPool,       # FORCE immediate release of connections
    connect_args=connect_args
)

async_session_factory = async_sessionmaker(
    engine,
    class_=AsyncSession,
    expire_on_commit=False,
)


class Base(DeclarativeBase):
    """Base class for all SQLAlchemy models."""
    pass


async def get_db():
    """
    Standardize database session management.
    Yields an async session and ensures proper rollback on exceptions.
    """
    async with async_session_factory() as session:
        try:
            yield session
            # We DON'T auto-commit here anymore as it can cause issues 
            # with partial updates in complex routes. Endpoints should call await db.commit().
        except Exception:
            await session.rollback()
            raise
        finally:
            await session.close()


import subprocess
from core.logging import get_logger

logger = get_logger(__name__)

async def run_migrations():
    """
    Run Alembic migrations automatically on startup.
    This replaces the hacky init_db approach.
    """
    try:
        logger.info("Running database migrations via Alembic...")
        # We run this as a subprocess to avoid event loop conflicts 
        # since alembic's env.py often calls asyncio.run()
        subprocess.run(
            ["alembic", "upgrade", "head"],
            check=True
        )
        logger.info("Database migrations completed successfully.")
    except Exception as e:
        logger.error(f"Unexpected error during migration: {e}")
        # In a real app, we might want to exit here to prevent running on old schema
        # For hackathon, we'll log it and continue.
        # raise e

async def init_db():
    """DEPRECATED: Use run_migrations instead for proper versioning."""
    async with engine.begin() as conn:
        await conn.run_sync(Base.metadata.create_all)