Spaces:
Running
Running
File size: 1,457 Bytes
3533fb9 154f032 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 | from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from app.core.config import DATABASE_URL
SQLALCHEMY_DATABASE_URL = DATABASE_URL
# Ensure we use psycopg2 if driver not specified (psycopg v3 may not be installed)
if SQLALCHEMY_DATABASE_URL and SQLALCHEMY_DATABASE_URL.startswith("postgresql://"):
SQLALCHEMY_DATABASE_URL = SQLALCHEMY_DATABASE_URL.replace("postgresql://", "postgresql+psycopg2://", 1)
elif SQLALCHEMY_DATABASE_URL and SQLALCHEMY_DATABASE_URL.startswith("postgres://"):
SQLALCHEMY_DATABASE_URL = SQLALCHEMY_DATABASE_URL.replace("postgres://", "postgresql+psycopg2://", 1)
# Remove check_same_thread for postgres
if SQLALCHEMY_DATABASE_URL and SQLALCHEMY_DATABASE_URL.startswith("sqlite"):
engine = create_engine(
SQLALCHEMY_DATABASE_URL, connect_args={"check_same_thread": False}
)
else:
engine = create_engine(
SQLALCHEMY_DATABASE_URL,
pool_size=5, # 5 persistent connections (Supabase free tier allows ~15-20)
max_overflow=5, # 5 burst connections → 10 total max
pool_timeout=30, # 30 seconds wait for a connection
pool_recycle=1800, # Recycle connections every 30 minutes
pool_pre_ping=True, # Discard stale connections before use
)
SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)
def get_db():
db = SessionLocal()
try:
yield db
finally:
db.close()
|