kiwi-vpn/api/kiwi_vpn_api/db/connection.py

32 lines
793 B
Python
Raw Normal View History

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
2022-03-18 23:04:28 +00:00
class Connection:
engine: Engine | None = None
session_local: sessionmaker | None = None
@classmethod
def connect(cls, engine: Engine) -> None:
cls.engine = engine
cls.session_local = sessionmaker(
autocommit=False, autoflush=False, bind=engine,
)
ORMBaseModel.metadata.create_all(bind=engine)
@classmethod
async def get(cls) -> Generator[Session | None, None, None]:
if cls.session_local is None:
yield None
else:
db = cls.session_local()
try:
yield db
finally:
db.close()