ARCHIVISE / app /database.py
UNI12345's picture
fix: resolution of critical blockers (P0/P1/P2 fixes) - async Redis, atomic credit updates, schema compatibility, task event loop safety, rate limits, timezone datetimes
5019340
Raw
History Blame Contribute Delete
1.45 kB
from sqlalchemy.ext.asyncio import create_async_engine, AsyncSession, async_sessionmaker
from sqlalchemy.orm import declarative_base
from app.config import settings
# Adapt postgresql:// to postgresql+asyncpg:// if needed
database_url = settings.DATABASE_URL
if database_url.startswith("postgresql://"):
database_url = database_url.replace("postgresql://", "postgresql+asyncpg://", 1)
from uuid import uuid4
# Enable connection pooling options since we connect to Supabase
# Connect with prepared_statement_cache_size=0 and unique statement names to prevent PgBouncer conflicts
engine = create_async_engine(
database_url,
echo=settings.DEBUG,
pool_size=10,
max_overflow=20,
pool_pre_ping=True,
pool_recycle=55, # Supabase closes idle connections after 60s; recycle before that
pool_timeout=30, # Fail fast if no connection available after 30s
connect_args={
"statement_cache_size": 0,
"prepared_statement_cache_size": 0,
"prepared_statement_name_func": lambda: f"__asyncpg_{uuid4().hex}__"
}
)
AsyncSessionLocal = async_sessionmaker(
bind=engine,
class_=AsyncSession,
expire_on_commit=False
)
Base = declarative_base()
async def get_db():
async with AsyncSessionLocal() as session:
try:
yield session
except Exception:
await session.rollback()
raise
finally:
await session.close()