diff --git a/packages/reflex-base/news/+sqlalchemy-relationship-nullability.bugfix.md b/packages/reflex-base/news/+sqlalchemy-relationship-nullability.bugfix.md new file mode 100644 index 00000000000..c151b0f20b5 --- /dev/null +++ b/packages/reflex-base/news/+sqlalchemy-relationship-nullability.bugfix.md @@ -0,0 +1 @@ +Infer required SQLAlchemy relationships as non-optional in state Vars when their annotation and foreign key require a related row. diff --git a/packages/reflex-base/src/reflex_base/utils/types.py b/packages/reflex-base/src/reflex_base/utils/types.py index e05e8876d24..9f08c100edd 100644 --- a/packages/reflex-base/src/reflex_base/utils/types.py +++ b/packages/reflex-base/src/reflex_base/utils/types.py @@ -86,6 +86,7 @@ if TYPE_CHECKING: from pydantic import BaseModel + from sqlalchemy.orm import Relationship from reflex_base.vars.base import Var @@ -1027,7 +1028,9 @@ def is_unserialized_property( ) -def _get_mapped_annotation(cls: type, name: str) -> GenericType | None: +def _get_mapped_annotation( + cls: type, name: str, *, relationship_target: type | None = None +) -> GenericType | None: """Get the type that a SQLAlchemy model declares for an attribute with ``Mapped[...]``. Only the annotation of ``name`` is resolved, in the module of the class that @@ -1037,11 +1040,13 @@ def _get_mapped_annotation(cls: type, name: str) -> GenericType | None: Args: cls: The mapped class. name: The attribute name. + relationship_target: The mapped target of a relationship. It can resolve + a reference to a locally defined class and preserves None in the hint. Returns: - The type ``T`` of a resolvable ``Mapped[T]`` annotation without ``None``, as - the column decides nullability, else None, also when ``T`` is ``Any`` or - ``object``. + The type ``T`` of a resolvable ``Mapped[T]`` annotation, or None when + unknown. For columns, the type excludes ``None`` because the column decides + nullability. """ from sqlalchemy.orm import Mapped @@ -1051,14 +1056,18 @@ def _get_mapped_annotation(cls: type, name: str) -> GenericType | None: break else: return None - hint = _resolve_annotation( - annotations[name], - getattr(sys.modules.get(klass.__module__), "__dict__", None), - ) + namespace = getattr(sys.modules.get(klass.__module__), "__dict__", None) + if relationship_target is not None: + target_name = relationship_target.__name__ + if namespace is None or namespace.get(target_name) is not relationship_target: + namespace = {**(namespace or {}), target_name: relationship_target} + hint = _resolve_annotation(annotations[name], namespace) origin = get_origin(hint) if not (isinstance(origin, type) and issubclass(origin, Mapped)): return None - type_ = value_inside_optional(resolve_type_alias(get_args(hint)[0])) + type_ = resolve_type_alias(get_args(hint)[0]) + if relationship_target is None: + type_ = value_inside_optional(type_) # `Mapped[Any]` defers to the column type. return None if type_ is Any or type_ is object else type_ @@ -1127,6 +1136,40 @@ def _get_column_access_type(cls: type, name: str) -> GenericType | None: return type_ +@lru_cache(maxsize=1024) +def _has_required_foreign_key(relationship: Relationship[Any]) -> bool: + """Check whether a scalar relationship joins on a non-null foreign key. + + Args: + relationship: The configured SQLAlchemy relationship. + + Returns: + Whether the join follows a complete, non-nullable foreign key constraint. + """ + from sqlalchemy import and_ + from sqlalchemy.orm import MANYTOONE + + pairs = relationship.local_remote_pairs + if ( + relationship.direction is not MANYTOONE + or not pairs + or any( + getattr(column, "nullable", True) for column in relationship.local_columns + ) + ): + return False + + # Extra join predicates can exclude the referenced row despite a non-null key. + source, _ = pairs[0] + return any( + relationship.primaryjoin.compare( + and_(*(key.parent == key.column for key in constraint.elements)) + ) + for foreign_key in source.foreign_keys + if (constraint := foreign_key.constraint) is not None + ) + + def get_attribute_access_type( cls: GenericType, name: str, descriptor: Any = _NO_DESCRIPTOR ) -> GenericType | None: @@ -1189,8 +1232,20 @@ def get_attribute_access_type( prop = descriptor.property if isinstance(prop, Relationship): type_ = prop.mapper.class_ - # TODO: check for nullable? - return list[type_] if prop.uselist else type_ | None + if prop.uselist: + return list[type_] + if ( + _has_required_foreign_key(prop) + and ( + declared := _get_mapped_annotation( + cls, name, relationship_target=type_ + ) + ) + is not None + and not is_optional(declared) + ): + return type_ + return type_ | None if isinstance(attr, AssociationProxyInstance): return list[ get_attribute_access_type( diff --git a/tests/units/test_attribute_access_type.py b/tests/units/test_attribute_access_type.py index 44a1e73f29e..7b28c3d331d 100644 --- a/tests/units/test_attribute_access_type.py +++ b/tests/units/test_attribute_access_type.py @@ -10,6 +10,7 @@ import attrs import pytest import typing_extensions +from reflex_base.registry import RegistrationContext from reflex_base.utils import types as types_module from reflex_base.utils.exceptions import VarAttributeError from reflex_base.utils.types import GenericType, get_attribute_access_type @@ -431,6 +432,75 @@ def test_get_attribute_access_type_no_default(cls: type) -> None: assert get_attribute_access_type(cls, "no_default") == int | None +def test_required_sqlalchemy_relationship_on_state_var( + clean_registration_context: RegistrationContext, +) -> None: + """Expose a required many-to-one relationship with its required type. + + Args: + clean_registration_context: Isolate the state class created by this test. + """ + + class RelationshipState(rx.State): + """A state Var whose model contains a required relationship.""" + + label: rx.Field[SQLALabel | None] = rx.field(None) + + assert get_attribute_access_type(SQLALabel, "test_dataclass") is SQLAClassDataclass + assert RelationshipState.label.test_dataclass._var_type is SQLAClassDataclass + name = RelationshipState.label.test_dataclass.name + assert name._var_type is str + assert str(name) == f'{RelationshipState.label!s}?.["test_dataclass"]?.["name"]' + + +def test_sqlalchemy_scalar_relationships_that_can_be_absent() -> None: + """Preserve optionality when the annotation or join allows a missing row.""" + + class Base(DeclarativeBase): + """Base for models testing optional relationship types.""" + + class Profile(Base): + """A profile that might have no matching member on the inverse side.""" + + __tablename__ = "relationship_type_profile" + id: Mapped[int] = mapped_column(primary_key=True) + active: Mapped[bool] + member: Mapped[Member] = relationship( + back_populates="profile", foreign_keys="Member.profile_id" + ) + + class Member(Base): + """A member with a required profile and a nullable backup foreign key.""" + + __tablename__ = "relationship_type_member" + id: Mapped[int] = mapped_column(primary_key=True) + profile_id: Mapped[int] = mapped_column( + sqlalchemy.ForeignKey(Profile.id), unique=True + ) + backup_profile_id: Mapped[int | None] = mapped_column( + sqlalchemy.ForeignKey(Profile.id) + ) + profile: Mapped[Profile] = relationship( + back_populates="member", foreign_keys=[profile_id] + ) + backup_profile: Mapped[Profile] = relationship(foreign_keys=[backup_profile_id]) + optional_profile: Mapped[Profile | None] = relationship( + foreign_keys=[profile_id], viewonly=True + ) + filtered_profile: Mapped[Profile] = relationship( + primaryjoin=lambda: sqlalchemy.and_( + Member.profile_id == Profile.id, Profile.active.is_(True) + ), + viewonly=True, + ) + + assert get_attribute_access_type(Member, "profile") is Profile + assert get_attribute_access_type(Member, "backup_profile") == Profile | None + assert get_attribute_access_type(Member, "optional_profile") == Profile | None + assert get_attribute_access_type(Member, "filtered_profile") == Profile | None + assert get_attribute_access_type(Profile, "member") == Member | None + + def test_get_attribute_access_type_sqlalchemy_synonyms() -> None: """A synonym has the type of its annotated getter, else of its target attribute.""" @@ -465,7 +535,7 @@ class SynonymMember(SynonymBase): assert get_attribute_access_type(SynonymMember, "nick") is str assert get_attribute_access_type(SynonymMember, "remark") == str | None assert get_attribute_access_type(SynonymMember, "alias") is str - assert get_attribute_access_type(SynonymMember, "author") == SynonymWriter | None + assert get_attribute_access_type(SynonymMember, "author") is SynonymWriter assert get_attribute_access_type(SynonymMember, "status_size") is int assert get_attribute_access_type(SynonymMember, "shout") is str