|
| 1 | +"""Test for Dict relationship recursion bug fix.""" |
| 2 | +from typing import Dict |
| 3 | + |
| 4 | +import pytest |
| 5 | +from sqlalchemy.orm.collections import attribute_mapped_collection |
| 6 | +from sqlmodel import Field, Relationship, SQLModel |
| 7 | + |
| 8 | + |
| 9 | +def test_dict_relationship_pattern(): |
| 10 | + """Test that Dict relationships with attribute_mapped_collection work.""" |
| 11 | + |
| 12 | + # Create a minimal reproduction of the pattern |
| 13 | + # This should not raise a RecursionError |
| 14 | + |
| 15 | + class TestChild(SQLModel, table=True): |
| 16 | + __tablename__ = "test_child" |
| 17 | + id: int = Field(primary_key=True) |
| 18 | + key: str = Field(nullable=False) |
| 19 | + parent_id: int = Field(foreign_key="test_parent.id") |
| 20 | + parent: "TestParent" = Relationship(back_populates="children") |
| 21 | + |
| 22 | + class TestParent(SQLModel, table=True): |
| 23 | + __tablename__ = "test_parent" |
| 24 | + id: int = Field(primary_key=True) |
| 25 | + children: Dict[str, "TestChild"] = Relationship( |
| 26 | + back_populates="parent", |
| 27 | + sa_relationship_kwargs={ |
| 28 | + "collection_class": attribute_mapped_collection("key") |
| 29 | + }, |
| 30 | + ) |
| 31 | + |
| 32 | + # If we got here without RecursionError, the bug is fixed |
| 33 | + assert TestParent.__tablename__ == "test_parent" |
| 34 | + assert TestChild.__tablename__ == "test_child" |
| 35 | + |
| 36 | + |
| 37 | +def test_dict_relationship_with_optional(): |
| 38 | + """Test that Optional[Dict[...]] relationships also work.""" |
| 39 | + from typing import Optional |
| 40 | + |
| 41 | + class Child(SQLModel, table=True): |
| 42 | + __tablename__ = "child" |
| 43 | + id: int = Field(primary_key=True) |
| 44 | + key: str = Field(nullable=False) |
| 45 | + parent_id: int = Field(foreign_key="parent.id") |
| 46 | + parent: Optional["Parent"] = Relationship(back_populates="children") |
| 47 | + |
| 48 | + class Parent(SQLModel, table=True): |
| 49 | + __tablename__ = "parent" |
| 50 | + id: int = Field(primary_key=True) |
| 51 | + children: Optional[Dict[str, "Child"]] = Relationship( |
| 52 | + back_populates="parent", |
| 53 | + sa_relationship_kwargs={ |
| 54 | + "collection_class": attribute_mapped_collection("key") |
| 55 | + }, |
| 56 | + ) |
| 57 | + |
| 58 | + # If we got here without RecursionError, the bug is fixed |
| 59 | + assert Parent.__tablename__ == "parent" |
| 60 | + assert Child.__tablename__ == "child" |
0 commit comments