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

76 lines
1.6 KiB
Python
Raw Normal View History

2022-03-20 03:45:40 +00:00
"""
Utilities for handling SQLAlchemy database connections.
"""
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
2022-03-20 00:12:56 +00:00
class SessionManager:
2022-03-20 03:45:40 +00:00
"""
Simple context manager for an ORM session.
"""
2022-03-20 00:12:56 +00:00
__session: Session
def __init__(self, session: Session) -> None:
self.__session = session
def __enter__(self) -> Session:
return self.__session
def __exit__(self, *args) -> None:
self.__session.close()
2022-03-18 23:04:28 +00:00
class Connection:
2022-03-20 03:45:40 +00:00
"""
Namespace for the database connection.
"""
2022-03-18 23:04:28 +00:00
engine: Engine | None = None
session_local: sessionmaker | None = None
@classmethod
def connect(cls, engine: Engine) -> None:
2022-03-20 03:45:40 +00:00
"""
Connect ORM to a database engine.
"""
2022-03-18 23:04:28 +00:00
cls.engine = engine
cls.session_local = sessionmaker(
autocommit=False, autoflush=False, bind=engine,
)
ORMBaseModel.metadata.create_all(bind=engine)
2022-03-20 00:12:56 +00:00
@classmethod
def use(cls) -> SessionManager | None:
2022-03-20 03:45:40 +00:00
"""
Create an ORM session using a context manager.
"""
2022-03-20 00:12:56 +00:00
if cls.session_local is None:
return None
return SessionManager(cls.session_local())
2022-03-18 23:04:28 +00:00
@classmethod
async def get(cls) -> Generator[Session | None, None, None]:
2022-03-20 03:45:40 +00:00
"""
Create an ORM session using a FastAPI compatible async generator.
"""
2022-03-18 23:04:28 +00:00
if cls.session_local is None:
yield None
else:
db = cls.session_local()
try:
yield db
finally:
db.close()