diff --git a/src/marshmallow_sqlalchemy/fields.py b/src/marshmallow_sqlalchemy/fields.py index 35c6f54..db2e35e 100644 --- a/src/marshmallow_sqlalchemy/fields.py +++ b/src/marshmallow_sqlalchemy/fields.py @@ -1,9 +1,10 @@ from __future__ import annotations import warnings +from collections.abc import Mapping from typing import TYPE_CHECKING, Any, cast -from marshmallow import fields +from marshmallow import ValidationError, fields from marshmallow.utils import is_iterable_but_not_string from sqlalchemy import inspect from sqlalchemy.orm.exc import NoResultFound @@ -12,6 +13,9 @@ from sqlalchemy.ext.declarative import DeclarativeMeta from sqlalchemy.orm import MapperProperty + ColumnFieldSpec = fields.Field | type[fields.Field] + ColumnFieldsInput = Mapping[str, ColumnFieldSpec] | ColumnFieldSpec + class RelatedList(fields.List): def get_value(self, obj, attr, accessor=None): @@ -29,6 +33,10 @@ class Related(fields.Field): :param columns: Optional column names on related model. If not provided, the primary key(s) of the related model will be used. + :param column_fields: Optional marshmallow `Field ` + instance/class (for a single related column) or mapping of column names to + `Field` instances/classes used to serialize and deserialize the related + column value(s). """ default_error_messages = { @@ -40,6 +48,8 @@ def __init__( self, columns: list[str] | str | None = None, column: str | None = None, + *, + column_fields: ColumnFieldsInput | None = None, **kwargs, ): if column is not None: @@ -53,6 +63,14 @@ def __init__( columns = column super().__init__(**kwargs) self.columns: list[str] = ensure_list(columns or []) + if column_fields is not None and not ( + isinstance(column_fields, Mapping) or _is_field_or_field_cls(column_fields) + ): + raise TypeError( + "`column_fields` must be a marshmallow Field instance, Field class, " + "or a mapping of column names to Field instances/classes." + ) + self.column_fields: ColumnFieldsInput | None = column_fields @property def model(self) -> type[DeclarativeMeta] | None: @@ -86,8 +104,38 @@ def session(self): def transient(self): return self.root.transient + def _get_column_fields(self) -> dict[str, fields.Field]: + if self.column_fields is None: + return {} + keys = [prop.key for prop in self.related_keys] + if isinstance(self.column_fields, Mapping): + unknown = set(self.column_fields) - set(keys) + if unknown: + raise ValueError( + f"Unknown column(s) in `column_fields`: {sorted(unknown)!r}; " + f"expected subset of {keys!r}." + ) + resolved: dict[str, fields.Field] = {} + for col_name, field_spec in self.column_fields.items(): + resolved[col_name] = _resolve_field(field_spec) + return resolved + if len(keys) != 1: + raise ValueError( + "A single field in `column_fields` can only be used when referencing " + f"a single column; pass a mapping for columns {keys!r}." + ) + return {keys[0]: _resolve_field(self.column_fields)} + def _serialize(self, value, attr, obj): - ret = {prop.key: getattr(value, prop.key, None) for prop in self.related_keys} + column_fields = self._get_column_fields() + ret = {} + for prop in self.related_keys: + raw_val = getattr(value, prop.key, None) + col_field = column_fields.get(prop.key) + if col_field is not None and raw_val is not None: + ret[prop.key] = col_field._serialize(raw_val, prop.key, value) + else: + ret[prop.key] = raw_val return ret if len(ret) > 1 else next(iter(ret.values())) def _deserialize(self, value, *args, **kwargs): @@ -97,11 +145,32 @@ def _deserialize(self, value, *args, **kwargs): Otherwise, attempt to find an existing instance in the database. :param value: The value to deserialize. """ - if not isinstance(value, dict): + is_single = not isinstance(value, dict) + if is_single: if len(self.related_keys) != 1: keys = [prop.key for prop in self.related_keys] raise self.make_error("invalid", value=value, keys=keys) value = {self.related_keys[0].key: value} + else: + value = dict(value) + + column_fields = self._get_column_fields() + if column_fields: + errors: dict[str, Any] = {} + for prop in self.related_keys: + col_field = column_fields.get(prop.key) + if col_field is not None and prop.key in value: + try: + value[prop.key] = col_field.deserialize( + value[prop.key], attr=prop.key, data=value + ) + except ValidationError as err: + if is_single: + raise + errors[prop.key] = err.messages + if errors: + raise ValidationError(errors) + if self.transient: return self.related_model(**value) try: @@ -161,3 +230,19 @@ def get_primary_keys(model: type[DeclarativeMeta]) -> list[MapperProperty]: def ensure_list(value: Any) -> list: return list(value) if is_iterable_but_not_string(value) else [value] + + +def _is_field_or_field_cls(value: Any) -> bool: + return isinstance(value, fields.Field) or ( + isinstance(value, type) and issubclass(value, fields.Field) + ) + + +def _resolve_field(field_spec: Any) -> fields.Field: + if isinstance(field_spec, fields.Field): + return field_spec + if isinstance(field_spec, type) and issubclass(field_spec, fields.Field): + return field_spec() + raise TypeError( + "Values in `column_fields` must be marshmallow Field instances or classes." + ) diff --git a/tests/test_sqlalchemy_schema.py b/tests/test_sqlalchemy_schema.py index 386e89c..8359e15 100644 --- a/tests/test_sqlalchemy_schema.py +++ b/tests/test_sqlalchemy_schema.py @@ -10,7 +10,9 @@ from marshmallow_sqlalchemy import SQLAlchemyAutoSchema, SQLAlchemySchema, auto_field from marshmallow_sqlalchemy.exceptions import IncorrectSchemaTypeError -from marshmallow_sqlalchemy.fields import Related +from marshmallow_sqlalchemy.fields import Related, RelatedList + +from .conftest import CourseLevel # ----------------------------------------------------------------------------- @@ -750,3 +752,178 @@ class Meta: assert schema.dump(teacher) == { "data": {"foo": "bar"}, } + + +# https://github.com/marshmallow-code/marshmallow-sqlalchemy/issues/478 +class TestRelatedColumnFields: + @pytest.fixture + def student_with_course(self, models, session): + import datetime as dt # noqa: PLC0415 + + school = models.School(id=100, name="Enum School") + course = models.Course( + id=101, + name="Math 101", + cost=10.50, + level="Primary", + level_with_enum_class=CourseLevel.PRIMARY, + has_prereqs=False, + started=dt.datetime(2025, 1, 1), + grade=1, + transcription="intro", + ) + student = models.Student( + id=102, + full_name="Ada Lovelace", + current_school=school, + courses=[course], + ) + session.add_all([school, course, student]) + session.flush() + return student, course + + def test_single_column_field_instance_dump_dumps_and_load( + self, models, session, student_with_course + ): + student, course = student_with_course + + class StudentSchema(SQLAlchemySchema): + class Meta: + model = models.Student + load_instance = True + sqla_session = session + + full_name = auto_field() + courses = RelatedList( + Related( + ["level_with_enum_class"], + column_fields=fields.Enum(CourseLevel), + ) + ) + + schema = StudentSchema() + dumped = schema.dump(student) + assert dumped == {"full_name": "Ada Lovelace", "courses": ["PRIMARY"]} + assert '"PRIMARY"' in schema.dumps(student) + + loaded = schema.load(dumped) + assert loaded.courses == [course] + + loaded_transient = schema.load(dumped, transient=True) + assert len(loaded_transient.courses) == 1 + assert loaded_transient.courses[0].level_with_enum_class is CourseLevel.PRIMARY + + with pytest.raises(ValidationError) as exc_info: + schema.load({"full_name": "Ada", "courses": ["INVALID"]}) + assert "courses" in exc_info.value.messages + + def test_single_column_field_class(self, models, session, student_with_course): + student, course = student_with_course + + class CustomLevelField(fields.Field): + def _serialize(self, value, attr, obj, **kwargs): + return value.name.lower() + + def _deserialize(self, value, attr, data, **kwargs): + try: + return CourseLevel[value.upper()] + except KeyError as err: + raise ValidationError("Invalid level.") from err + + class StudentSchema(SQLAlchemySchema): + class Meta: + model = models.Student + load_instance = True + sqla_session = session + + courses = RelatedList( + Related(["level_with_enum_class"], column_fields=CustomLevelField) + ) + + schema = StudentSchema() + dumped = schema.dump(student) + assert dumped == {"courses": ["primary"]} + + loaded = schema.load(dumped) + assert loaded.courses == [course] + + def test_multiple_columns_mapping_dump_and_load( + self, models, session, student_with_course + ): + student, course = student_with_course + + class StudentSchema(SQLAlchemySchema): + class Meta: + model = models.Student + load_instance = True + sqla_session = session + + courses = RelatedList( + Related( + ["id", "level_with_enum_class"], + column_fields={"level_with_enum_class": fields.Enum(CourseLevel)}, + ) + ) + + schema = StudentSchema() + dumped = schema.dump(student) + assert dumped == { + "courses": [{"id": course.id, "level_with_enum_class": "PRIMARY"}] + } + assert '"PRIMARY"' in schema.dumps(student) + + payload = {"courses": [{"id": course.id, "level_with_enum_class": "PRIMARY"}]} + loaded = schema.load(payload) + assert loaded.courses == [course] + # Input dictionary should not be mutated in place + assert payload["courses"][0]["level_with_enum_class"] == "PRIMARY" + + with pytest.raises(ValidationError) as exc_info: + schema.load( + {"courses": [{"id": course.id, "level_with_enum_class": "INVALID"}]} + ) + assert isinstance(exc_info.value.messages, dict) + assert "level_with_enum_class" in exc_info.value.messages["courses"][0] + + def test_column_fields_validation_errors(self, models, teacher): + with pytest.raises(TypeError, match="column_fields"): + Related(["id"], column_fields="not-a-field") # type: ignore[arg-type] + + class MultiColBadFieldSchema(SQLAlchemySchema): + class Meta: + model = models.Teacher + + current_school = Related(["id", "name"], column_fields=fields.String) + + with pytest.raises(ValueError, match="single column"): + MultiColBadFieldSchema().dump(teacher) + + class UnknownColSchema(SQLAlchemySchema): + class Meta: + model = models.Teacher + + current_school = Related( + ["id"], column_fields={"nonexistent": fields.Integer} + ) + + with pytest.raises(ValueError, match="Unknown column"): + UnknownColSchema().dump(teacher) + + def test_column_field_with_none_value(self, models, session, student_with_course): + student, course = student_with_course + course.description = None + session.flush() + + class UpperStringField(fields.Field): + def _serialize(self, value, attr, obj, **kwargs): + return value.upper() + + class StudentSchema(SQLAlchemySchema): + class Meta: + model = models.Student + + courses = RelatedList( + Related(["description"], column_fields=UpperStringField) + ) + + assert StudentSchema().dump(student) == {"courses": [None]}