Spaces:
Running
Running
File size: 1,170 Bytes
f0d3a03 7f18aa9 f0d3a03 03075bf f0d3a03 7f18aa9 f0d3a03 7f18aa9 | 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 | import os
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker, declarative_base
# Fallback to local SQLite if SUPABASE_DB_URL is not set
SUPABASE_DB_URL = os.getenv("SUPABASE_DB_URL", "sqlite:///./ba7ath_enriched.db")
if SUPABASE_DB_URL:
SUPABASE_DB_URL = SUPABASE_DB_URL.strip().strip("'").strip('"')
if SUPABASE_DB_URL.startswith("SUPABASE_DB_URL="):
SUPABASE_DB_URL = SUPABASE_DB_URL.replace("SUPABASE_DB_URL=", "", 1)
if SUPABASE_DB_URL.startswith("postgres://"):
SUPABASE_DB_URL = SUPABASE_DB_URL.replace("postgres://", "postgresql://", 1)
# For SQLite with FastAPI, check_same_thread is required, but it breaks Postgres
connect_args = {}
if SUPABASE_DB_URL.startswith("sqlite"):
connect_args["check_same_thread"] = False
engine = create_engine(
SUPABASE_DB_URL,
connect_args=connect_args
)
SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)
Base = declarative_base()
def get_db():
"""Dependency that provides a database session per request."""
db = SessionLocal()
try:
yield db
finally:
db.close()
|