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
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")

@ -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

@ -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():

Loading…
Cancel
Save