File size: 2,250 Bytes
25b7ac3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
# Copyright (c) 2026 CrewHub. All rights reserved.
# Proprietary and confidential. See LICENSE for details.
import os

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

from src.config import settings


def _engine_kwargs(url: str, debug: bool) -> dict:
    """Build engine kwargs based on database dialect."""
    # Only echo SQL when explicitly requested via DB_ECHO=1 (too noisy for staging)
    kwargs: dict = {"echo": os.getenv("DB_ECHO", "").strip() in ("1", "true")}

    # SQLite doesn't support connection pool tuning
    if not url.startswith("sqlite"):
        kwargs["pool_size"] = int(os.getenv("DB_POOL_SIZE", "5"))
        kwargs["max_overflow"] = int(os.getenv("DB_MAX_OVERFLOW", "10"))
        kwargs["pool_pre_ping"] = True
        kwargs["pool_recycle"] = int(os.getenv("DB_POOL_RECYCLE", "1800"))
        kwargs["pool_timeout"] = 30

    # Supabase / PgBouncer: disable prepared statements + enable SSL
    if "asyncpg" in url and ("pooler.supabase" in url or "pgbouncer" in url):
        kwargs["connect_args"] = {"prepared_statement_cache_size": 0,
                                  "statement_cache_size": 0,
                                  "ssl": "require"}
    return kwargs


def _clean_url(url: str) -> str:
    """Strip sslmode param from asyncpg URLs (handled via connect_args instead)."""
    if "asyncpg" in url and "sslmode=" in url:
        import re
        url = re.sub(r'[?&]sslmode=[^&]*', '', url)
        url = url.replace('?&', '?').rstrip('?')
    return url


engine = create_async_engine(
    _clean_url(settings.database_url),
    **_engine_kwargs(settings.database_url, settings.debug),
)
async_session = async_sessionmaker(engine, class_=AsyncSession, expire_on_commit=False)


class Base(DeclarativeBase):
    pass


async def get_db() -> AsyncSession:
    async with async_session() as session:
        try:
            yield session
            await session.commit()
        except Exception:
            await session.rollback()
            raise
        finally:
            await session.close()


async def init_db():
    async with engine.begin() as conn:
        await conn.run_sync(Base.metadata.create_all)