From 937a3a95b17a8fe01b9f158fc952a1565bef8549 Mon Sep 17 00:00:00 2001 From: Cizz22 Date: Wed, 4 Feb 2026 15:00:56 +0700 Subject: [PATCH] refactor: improve SQLAlchemy error handling, refine column access for query conditions, and use `operator.attrgetter` for model dictionary serialization. --- src/aeros_simulation/service.py | 4 ++-- src/database/core.py | 5 +++-- src/exceptions.py | 6 ++++-- 3 files changed, 9 insertions(+), 6 deletions(-) diff --git a/src/aeros_simulation/service.py b/src/aeros_simulation/service.py index c6765b3..25fa070 100644 --- a/src/aeros_simulation/service.py +++ b/src/aeros_simulation/service.py @@ -98,8 +98,8 @@ async def get_simulation_node_by(*, db_session: DbSession, **kwargs): # Build WHERE conditions from kwargs conditions = [] for key, value in kwargs.items(): - if hasattr(AerosNode, key): - conditions.append(getattr(AerosNode, key) == value) + if key in AerosNode.__table__.columns: + conditions.append(AerosNode.__table__.columns[key] == value) if not conditions: raise ValueError("No valid column conditions provided") diff --git a/src/database/core.py b/src/database/core.py index 46b553d..5f7823a 100644 --- a/src/database/core.py +++ b/src/database/core.py @@ -1,5 +1,6 @@ # src/database.py import functools +import operator import re from contextlib import asynccontextmanager, contextmanager from typing import Annotated, Any, AsyncGenerator @@ -58,7 +59,7 @@ class Base(DeclarativeBase): def dict(self): """Returns a dict representation of a model.""" 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 {} class CollectorBase(DeclarativeBase): @@ -69,7 +70,7 @@ class CollectorBase(DeclarativeBase): def dict(self): """Returns a dict representation of a model.""" 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 {} @asynccontextmanager diff --git a/src/exceptions.py b/src/exceptions.py index f327964..20443c2 100644 --- a/src/exceptions.py +++ b/src/exceptions.py @@ -66,8 +66,10 @@ def handle_sqlalchemy_error(error: SQLAlchemyError): """ Handle SQLAlchemy errors and return user-friendly error messages. """ - original_error = getattr(error, "orig", None) - print(original_error) + try: + original_error = error.orig + except AttributeError: + original_error = None if isinstance(error, IntegrityError): if "unique constraint" in str(error).lower():