Spaces:
Build error
Build error
File size: 1,299 Bytes
19a176c 5db257a 303ff5a e66ee1b 303ff5a 5db257a 19a176c 5db257a 19a176c | 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 | from sqlalchemy.ext.asyncio import AsyncSession, create_async_engine
from sqlalchemy.orm import declarative_base, sessionmaker
from backend.config import settings
# Convert postgres:// to postgresql:// for SQLAlchemy
DATABASE_URL = settings.DATABASE_URL.replace("postgresql://", "postgresql+asyncpg://")
# Create async engine with statement_cache_size=0 for Supabase pgbouncer compatibility
engine = create_async_engine(
DATABASE_URL,
echo=True,
future=True,
connect_args={
"statement_cache_size": 0,
"prepared_statement_cache_size": 0,
"server_settings": {"jit": "off"},
},
pool_pre_ping=True,
pool_recycle=300,
)
# Create async session factory
async_session = sessionmaker(engine, class_=AsyncSession, expire_on_commit=False)
Base = declarative_base()
async def get_db():
"""Dependency for FastAPI routes to get database session"""
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():
"""Initialize database tables"""
async with engine.begin() as conn:
await conn.run_sync(Base.metadata.create_all)
|