File size: 1,072 Bytes
cb22dd9
 
 
 
6b6e420
 
cb22dd9
 
 
 
 
 
 
6b6e420
cb22dd9
 
31a6bb6
 
 
cb22dd9
6b6e420
 
cb22dd9
 
 
 
603b28a
cb22dd9
 
 
 
6b6e420
 
 
cb22dd9
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
"""
SQLAlchemy async-compatible engine & session factory.
"""

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

from app.config import settings

# SQLite needs special connect args; MySQL/PostgreSQL use pool sizing
connect_args = {}
extra_kwargs = {"pool_pre_ping": True, "echo": False}

if settings.async_database_url.startswith("sqlite"):
    connect_args = {"check_same_thread": False}
else:
    extra_kwargs["pool_size"] = settings.DB_POOL_SIZE
    extra_kwargs["max_overflow"] = settings.DB_MAX_OVERFLOW
    extra_kwargs["pool_timeout"] = settings.DB_POOL_TIMEOUT_SECONDS

engine = create_async_engine(
    settings.async_database_url,
    connect_args=connect_args,
    **extra_kwargs,
)

SessionLocal = async_sessionmaker(autocommit=False, autoflush=False, expire_on_commit=False, bind=engine, class_=AsyncSession)

Base = declarative_base()


async def get_db():
    """FastAPI dependency that yields an async DB session."""
    async with SessionLocal() as db:
        yield db