core/base/orm.py

58 lines
1.5 KiB
Python
Raw Normal View History

2023-10-30 21:00:55 +00:00
from typing import Any, Callable, Dict, Generic, TypeVar
2023-10-26 21:07:35 +00:00
2023-10-30 21:00:55 +00:00
from sqlalchemy import Column, Integer, create_engine
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
2023-10-26 21:07:35 +00:00
from settings import DB_URL
2023-10-30 21:00:55 +00:00
engine = create_engine(DB_URL, echo=False, pool_size=10, max_overflow=20)
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
2023-10-30 21:00:55 +00:00
DeclarativeBase = declarative_base() # type: Any
class Base(DeclarativeBase):
2022-09-03 10:50:14 +00:00
__table__: Table
__tablename__: str
__new__: Callable
__init__: Callable
2023-01-31 07:36:54 +00:00
__allow_unmapped__ = True
2023-01-31 07:44:06 +00:00
__abstract__ = True
2022-09-03 10:50:14 +00:00
__table_args__ = {"extend_existing": True}
2023-01-31 07:44:06 +00:00
id = Column(Integer, primary_key=True)
2022-09-03 10:50:14 +00:00
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()
2023-10-30 21:00:55 +00:00
for name, value in input.items():
2022-09-03 10:50:14 +00:00
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}