38 lines
1.1 KiB
Python
38 lines
1.1 KiB
Python
from collections.abc import Generator
|
|
from sqlalchemy.orm.session import Session
|
|
from sqlalchemy import create_engine, event, Engine, text
|
|
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=True, 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) # type: ignore
|
|
|
|
@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()
|
|
|
|
# with engine.connect() as connection:
|
|
# result = connection.execute(text('select "Hello"'))
|
|
|
|
# print(result.all())
|
|
|
|
def generate_session() -> Generator[Session, None, None]:
|
|
db = SessionLocal()
|
|
try:
|
|
yield db
|
|
finally:
|
|
db.close()
|