Files
Unraid-AppOps-Gateway-Public/backend/app/db/session.py
T

45 lines
1.2 KiB
Python

from pathlib import Path
from sqlalchemy import event
from sqlalchemy.engine import Engine
from sqlmodel import create_engine, Session
from ..core.config import settings
def _configure_sqlite_connection(dbapi_connection, _connection_record) -> None:
cursor = dbapi_connection.cursor()
try:
cursor.execute("PRAGMA busy_timeout=30000")
cursor.execute("PRAGMA journal_mode=WAL")
cursor.execute("PRAGMA synchronous=NORMAL")
finally:
cursor.close()
def create_app_engine(db_path: Path | str) -> Engine:
resolved_path = Path(db_path)
if resolved_path.parent != Path('.'):
resolved_path.parent.mkdir(parents=True, exist_ok=True)
app_engine = create_engine(
f"sqlite:///{resolved_path}",
echo=False,
connect_args={"check_same_thread": False, "timeout": 30},
pool_size=20,
max_overflow=20,
pool_timeout=10,
)
event.listen(app_engine, "connect", _configure_sqlite_connection)
return app_engine
_db_path = Path(settings.db_path)
DATABASE_URL = f"sqlite:///{_db_path}"
engine = create_app_engine(_db_path)
def get_session():
with Session(engine) as session:
yield session