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

35 lines
720 B
Python
Raw Normal View History

2022-03-28 20:58:40 +00:00
"""
2022-03-28 20:59:27 +00:00
Database connection management.
2022-03-28 20:58:40 +00:00
"""
2022-03-27 01:17:48 +00:00
from sqlmodel import Session, SQLModel, create_engine
class Connection:
"""
2022-03-28 20:58:40 +00:00
Namespace for the database connection
2022-03-27 01:17:48 +00:00
"""
engine = None
@classmethod
def connect(cls, connection_url: str) -> None:
"""
Connect ORM to a database engine.
"""
cls.engine = create_engine(connection_url)
SQLModel.metadata.create_all(cls.engine)
@classmethod
@property
2022-03-31 16:32:07 +00:00
def session(cls) -> Session:
2022-03-27 01:17:48 +00:00
"""
Create an ORM session using a context manager.
"""
if cls.engine is None:
2022-03-31 16:32:07 +00:00
raise ValueError("Not connected to database, can't create session")
2022-03-27 01:17:48 +00:00
return Session(cls.engine)