From ffc272a3bb61184275127583ea04e569f36f9906 Mon Sep 17 00:00:00 2001 From: Francesco Faraone Date: Tue, 8 Apr 2025 17:46:48 +0200 Subject: [PATCH] Fix for enum --- src/requela/builders/sqlalchemy.py | 24 ++++++++++++++---------- 1 file changed, 14 insertions(+), 10 deletions(-) diff --git a/src/requela/builders/sqlalchemy.py b/src/requela/builders/sqlalchemy.py index 4750599..6a05a2f 100644 --- a/src/requela/builders/sqlalchemy.py +++ b/src/requela/builders/sqlalchemy.py @@ -1,6 +1,7 @@ from collections.abc import Callable, Sequence from datetime import date, datetime from decimal import Decimal +from enum import Enum from typing import Any from sqlalchemy import ( @@ -174,24 +175,27 @@ def apply_any( return exists_clause def cast_value(self, column: ColumnElement, value: Any) -> Any: # pragma: no cover + if isinstance(value, column.type.python_type): + return value try: - if column.type.python_type is str and not isinstance(value, str): + if column.type.python_type is str: return str(value) - if column.type.python_type is bool and not isinstance(value, bool): + if column.type.python_type is bool: return bool(value) - if column.type.python_type is int and not isinstance(value, int): + if column.type.python_type is int: return int(value) - if column.type.python_type is float and not isinstance(value, float): + if column.type.python_type is float: return float(value) - if column.type.python_type is Decimal and not isinstance(value, Decimal): + if column.type.python_type is Decimal: return Decimal(value) - if column.type.python_type is datetime and not isinstance(value, datetime): + if column.type.python_type is datetime: return datetime.fromisoformat(value) - if column.type.python_type is date and not isinstance(value, date): + if column.type.python_type is date: return date.fromisoformat(value) - return value - except Exception: - raise ValueError(f"Cannot cast value {value} to {column.type.python_type}") + if issubclass(column.type.python_type, Enum): + return column.type.python_type(value) + except Exception as e: + raise ValueError(f"Cannot cast value {value} to {column.type.python_type}: {e}") from e def _adapt_condition(self, condition, alias): if isinstance(condition, BooleanClauseList):