2022-03-18 18:22:17 +00:00
|
|
|
from typing import Generator
|
2022-03-18 18:24:09 +00:00
|
|
|
|
2022-03-18 18:22:17 +00:00
|
|
|
from sqlalchemy.engine import Engine
|
2022-03-18 18:24:09 +00:00
|
|
|
from sqlalchemy.orm import Session, sessionmaker
|
2022-03-18 18:22:17 +00:00
|
|
|
|
|
|
|
from .models import ORMBaseModel
|
|
|
|
|
|
|
|
ENGINE: Engine | None = None
|
|
|
|
SESSION_LOCAL: sessionmaker | None = None
|
|
|
|
|
|
|
|
|
|
|
|
def reconnect(engine: Engine) -> None:
|
|
|
|
global ENGINE, SESSION_LOCAL
|
|
|
|
|
|
|
|
ENGINE = engine
|
|
|
|
SESSION_LOCAL = sessionmaker(
|
|
|
|
autocommit=False, autoflush=False, bind=engine,
|
|
|
|
)
|
|
|
|
ORMBaseModel.metadata.create_all(bind=engine)
|
|
|
|
|
|
|
|
|
|
|
|
async def get() -> Generator[Session | None, None, None]:
|
|
|
|
if SESSION_LOCAL is None:
|
|
|
|
yield None
|
|
|
|
|
|
|
|
else:
|
|
|
|
db = SESSION_LOCAL()
|
|
|
|
try:
|
|
|
|
yield db
|
|
|
|
finally:
|
|
|
|
db.close()
|