fuware-be/fuware/db/db_setup.py

49 lines
1.4 KiB
Python

from collections.abc import Generator
from contextlib import contextmanager
from sqlalchemy.orm.session import Session
from sqlalchemy import create_engine, event, Engine
from sqlalchemy.orm import scoped_session, sessionmaker
from fuware.core.config import get_app_settings
settings = get_app_settings()
def sql_global_init(db_url: str):
connect_args = {"check_same_thread": False}
engine = create_engine(db_url, echo=False, connect_args=connect_args, pool_pre_ping=True, future=True)
SessionLocal = scoped_session(sessionmaker(autocommit=False, autoflush=False, bind=engine, future=True))
return SessionLocal, engine
SessionLocal, engine = sql_global_init(settings.DB_URL)
@event.listens_for(Engine, "connect")
def set_sqlite_pragma(dbapi_connection, connection_record):
cursor = dbapi_connection.cursor()
cursor.execute("PRAGMA foreign_keys=ON")
cursor.close()
@contextmanager
def session_context() -> Session: # type: ignore
"""
session_context() provides a managed session to the database that is automatically
closed when the context is exited. This is the preferred method of accessing the
database.
Note: use `generate_session` when using the `Depends` function from FastAPI
"""
global SessionLocal
sess = SessionLocal()
try:
yield sess
finally:
sess.close()
def generate_session() -> Generator[Session, None, None]:
db = SessionLocal()
try:
yield db
finally:
db.close()