refactor: improve SQLAlchemy error handling, refine column access for query conditions, and use `operator.attrgetter` for model dictionary serialization.

main
Cizz22 1 month ago
parent 3924954900
commit 937a3a95b1

@ -98,8 +98,8 @@ async def get_simulation_node_by(*, db_session: DbSession, **kwargs):
# Build WHERE conditions from kwargs # Build WHERE conditions from kwargs
conditions = [] conditions = []
for key, value in kwargs.items(): for key, value in kwargs.items():
if hasattr(AerosNode, key): if key in AerosNode.__table__.columns:
conditions.append(getattr(AerosNode, key) == value) conditions.append(AerosNode.__table__.columns[key] == value)
if not conditions: if not conditions:
raise ValueError("No valid column conditions provided") raise ValueError("No valid column conditions provided")

@ -1,5 +1,6 @@
# src/database.py # src/database.py
import functools import functools
import operator
import re import re
from contextlib import asynccontextmanager, contextmanager from contextlib import asynccontextmanager, contextmanager
from typing import Annotated, Any, AsyncGenerator from typing import Annotated, Any, AsyncGenerator
@ -58,7 +59,7 @@ class Base(DeclarativeBase):
def dict(self): def dict(self):
"""Returns a dict representation of a model.""" """Returns a dict representation of a model."""
if hasattr(self, '__table__'): if hasattr(self, '__table__'):
return {c.name: getattr(self, c.name) for c in self.__table__.columns} return {c.name: operator.attrgetter(c.name)(self) for c in self.__table__.columns}
return {} return {}
class CollectorBase(DeclarativeBase): class CollectorBase(DeclarativeBase):
@ -69,7 +70,7 @@ class CollectorBase(DeclarativeBase):
def dict(self): def dict(self):
"""Returns a dict representation of a model.""" """Returns a dict representation of a model."""
if hasattr(self, '__table__'): if hasattr(self, '__table__'):
return {c.name: getattr(self, c.name) for c in self.__table__.columns} return {c.name: operator.attrgetter(c.name)(self) for c in self.__table__.columns}
return {} return {}
@asynccontextmanager @asynccontextmanager

@ -66,8 +66,10 @@ def handle_sqlalchemy_error(error: SQLAlchemyError):
""" """
Handle SQLAlchemy errors and return user-friendly error messages. Handle SQLAlchemy errors and return user-friendly error messages.
""" """
original_error = getattr(error, "orig", None) try:
print(original_error) original_error = error.orig
except AttributeError:
original_error = None
if isinstance(error, IntegrityError): if isinstance(error, IntegrityError):
if "unique constraint" in str(error).lower(): if "unique constraint" in str(error).lower():

Loading…
Cancel
Save