core/base/orm.py

59 lines
1.5 KiB
Python
Raw Normal View History

from typing import TypeVar, Any, Dict, Generic, Callable
from sqlalchemy import create_engine, Column, Integer
from sqlalchemy.ext.declarative import declarative_base
2021-08-05 16:49:08 +00:00
from sqlalchemy.orm import Session
from sqlalchemy.sql.schema import Table
2021-07-26 09:17:22 +00:00
from settings import DB_URL
2022-09-03 10:50:14 +00:00
if DB_URL.startswith("sqlite"):
engine = create_engine(DB_URL)
2022-05-31 07:03:50 +00:00
else:
2022-09-03 10:50:14 +00:00
engine = create_engine(
2023-01-31 07:26:03 +00:00
DB_URL, echo=False, pool_size=10, max_overflow=20
2022-09-03 10:50:14 +00:00
)
T = TypeVar("T")
REGISTRY: Dict[str, type] = {}
2022-09-03 10:50:14 +00:00
2021-08-05 16:49:08 +00:00
def local_session():
2022-09-03 10:50:14 +00:00
return Session(bind=engine, expire_on_commit=False)
2021-08-05 16:49:08 +00:00
class Base(declarative_base()):
2022-09-03 10:50:14 +00:00
__table__: Table
__tablename__: str
__new__: Callable
__init__: Callable
__abstract__: bool = True
__table_args__ = {"extend_existing": True}
id: int = Column(Integer, primary_key=True)
def __init_subclass__(cls, **kwargs):
REGISTRY[cls.__name__] = cls
@classmethod
def create(cls: Generic[T], **kwargs) -> Generic[T]:
instance = cls(**kwargs)
return instance.save()
def save(self) -> Generic[T]:
with local_session() as session:
session.add(self)
session.commit()
return self
def update(self, input):
column_names = self.__table__.columns.keys()
for (name, value) in input.items():
if name in column_names:
setattr(self, name, value)
def dict(self) -> Dict[str, Any]:
column_names = self.__table__.columns.keys()
return {c: getattr(self, c) for c in column_names}