Spaces:
Running
Running
File size: 1,830 Bytes
3533fb9 a5b31c3 0eeeed2 a5b31c3 0eeeed2 3533fb9 0eeeed2 3533fb9 | 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 | from sqlalchemy.ext.asyncio import create_async_engine, AsyncSession, async_sessionmaker
from app.core.config import DATABASE_URL
# Convert to async driver URLs
if DATABASE_URL.startswith("sqlite"):
ASYNC_SQLALCHEMY_DATABASE_URL = DATABASE_URL.replace("sqlite://", "sqlite+aiosqlite://")
connect_args = {"check_same_thread": False}
extra_engine_args = {}
else:
# Handle various Postgres URL formats
if DATABASE_URL.startswith("postgresql+asyncpg://"):
ASYNC_SQLALCHEMY_DATABASE_URL = DATABASE_URL
elif DATABASE_URL.startswith("postgresql+psycopg2://"):
ASYNC_SQLALCHEMY_DATABASE_URL = DATABASE_URL.replace("postgresql+psycopg2://", "postgresql+asyncpg://")
elif DATABASE_URL.startswith("postgresql+psycopg://"):
ASYNC_SQLALCHEMY_DATABASE_URL = DATABASE_URL.replace("postgresql+psycopg://", "postgresql+asyncpg://")
elif DATABASE_URL.startswith("postgresql://"):
ASYNC_SQLALCHEMY_DATABASE_URL = DATABASE_URL.replace("postgresql://", "postgresql+asyncpg://")
elif DATABASE_URL.startswith("postgres://"):
ASYNC_SQLALCHEMY_DATABASE_URL = DATABASE_URL.replace("postgres://", "postgresql+asyncpg://")
else:
ASYNC_SQLALCHEMY_DATABASE_URL = DATABASE_URL
connect_args = {"statement_cache_size": 0}
extra_engine_args = {"pool_size": 3, "max_overflow": 2}
async_engine = create_async_engine(
ASYNC_SQLALCHEMY_DATABASE_URL,
echo=False,
future=True,
connect_args=connect_args,
**extra_engine_args
)
AsyncSessionLocal = async_sessionmaker(
bind=async_engine,
class_=AsyncSession,
expire_on_commit=False,
autocommit=False,
autoflush=False,
)
async def get_async_db():
async with AsyncSessionLocal() as session:
try:
yield session
finally:
await session.close()
|