Spaces:
Running on Zero

tunechecker-api / app /db /session.py
AVIJIT PAKHIRA
Deploy TuneChecker backend
bf90f9f
Raw History Blame Contribute Delete
1.16 kB
import os
from sqlalchemy import create_engine, event
from sqlalchemy.orm import sessionmaker, declarative_base
from app.config import settings
# Ensure data directory exists
if settings.DATABASE_URL.startswith("sqlite:///"):
db_path = settings.DATABASE_URL.replace("sqlite:///", "")
os.makedirs(os.path.dirname(os.path.abspath(db_path)), exist_ok=True)
engine = create_engine(
settings.DATABASE_URL,
connect_args={"check_same_thread": False} if settings.DATABASE_URL.startswith("sqlite") else {},
pool_pre_ping=True
)
if settings.DATABASE_URL.startswith("sqlite"):
@event.listens_for(engine, "connect")
def set_sqlite_pragma(dbapi_connection, connection_record):
cursor = dbapi_connection.cursor()
cursor.execute("PRAGMA foreign_keys=ON")
cursor.execute("PRAGMA journal_mode=WAL")
cursor.execute("PRAGMA busy_timeout=5000")
cursor.execute("PRAGMA synchronous=NORMAL")
cursor.close()
SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)
Base = declarative_base()
def get_db():
db = SessionLocal()
try:
yield db
finally:
db.close()