2023-11-23 22:58:55 +00:00
|
|
|
# from contextlib import contextmanager
|
|
|
|
from typing import Any, Callable, Dict, TypeVar
|
2023-12-17 11:42:04 +00:00
|
|
|
|
2023-11-23 22:58:55 +00:00
|
|
|
# from psycopg2.errors import UniqueViolation
|
|
|
|
from sqlalchemy import Column, Integer, create_engine
|
2024-02-05 13:01:26 +00:00
|
|
|
from sqlalchemy.orm import Session, declarative_base
|
2023-11-23 22:58:55 +00:00
|
|
|
from sqlalchemy.sql.schema import Table
|
|
|
|
|
|
|
|
from settings import DB_URL
|
|
|
|
|
|
|
|
engine = create_engine(DB_URL, echo=False, pool_size=10, max_overflow=20)
|
|
|
|
|
|
|
|
T = TypeVar("T")
|
|
|
|
|
|
|
|
REGISTRY: Dict[str, type] = {}
|
|
|
|
|
|
|
|
|
|
|
|
# @contextmanager
|
|
|
|
def local_session(src=""):
|
|
|
|
return Session(bind=engine, expire_on_commit=False)
|
2023-12-17 11:42:04 +00:00
|
|
|
|
2023-11-23 22:58:55 +00:00
|
|
|
# try:
|
|
|
|
# yield session
|
|
|
|
# session.commit()
|
|
|
|
# except Exception as e:
|
|
|
|
# if not (src == "create_shout" and isinstance(e, UniqueViolation)):
|
|
|
|
# import traceback
|
|
|
|
|
|
|
|
# session.rollback()
|
|
|
|
# print(f"[services.db] {src}: {e}")
|
|
|
|
|
|
|
|
# traceback.print_exc()
|
|
|
|
|
|
|
|
# raise Exception("[services.db] exception")
|
|
|
|
|
|
|
|
# finally:
|
|
|
|
# session.close()
|
|
|
|
|
|
|
|
|
|
|
|
class Base(declarative_base()):
|
|
|
|
__table__: Table
|
|
|
|
__tablename__: str
|
|
|
|
__new__: Callable
|
|
|
|
__init__: Callable
|
|
|
|
__allow_unmapped__ = True
|
|
|
|
__abstract__ = True
|
|
|
|
__table_args__ = {"extend_existing": True}
|
|
|
|
|
|
|
|
id = Column(Integer, primary_key=True)
|
|
|
|
|
|
|
|
def __init_subclass__(cls, **kwargs):
|
|
|
|
REGISTRY[cls.__name__] = cls
|
|
|
|
|
|
|
|
def dict(self) -> Dict[str, Any]:
|
|
|
|
column_names = self.__table__.columns.keys()
|
|
|
|
if "_sa_instance_state" in column_names:
|
|
|
|
column_names.remove("_sa_instance_state")
|
|
|
|
try:
|
|
|
|
return {c: getattr(self, c) for c in column_names}
|
|
|
|
except Exception as e:
|
|
|
|
print(f"[services.db] Error dict: {e}")
|
|
|
|
return {}
|
2023-12-17 11:42:04 +00:00
|
|
|
|
2023-11-23 22:58:55 +00:00
|
|
|
def update(self, values: Dict[str, Any]) -> None:
|
2023-12-17 11:42:04 +00:00
|
|
|
for key, value in values.items():
|
|
|
|
if hasattr(self, key):
|
|
|
|
setattr(self, key, value)
|