Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

🐛 Fix instance of related object added to session on validation #1052

Open
wants to merge 6 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion sqlmodel/_compat.py
Original file line number Diff line number Diff line change
Expand Up @@ -341,7 +341,7 @@ def sqlmodel_validate(
for key in new_obj.__sqlmodel_relationships__:
value = getattr(use_obj, key, Undefined)
if value is not Undefined:
setattr(new_obj, key, value)
new_obj.__dict__[key] = value
return new_obj

def sqlmodel_init(*, self: "SQLModel", data: Dict[str, Any]) -> None:
Expand Down
75 changes: 73 additions & 2 deletions tests/test_validation.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,9 @@
from typing import Optional
from typing import List, Optional

import pytest
from pydantic.error_wrappers import ValidationError
from sqlmodel import SQLModel
from sqlmodel import Session, SQLModel, create_engine
from sqlmodel.main import Field, Relationship

from .conftest import needs_pydanticv1, needs_pydanticv2

Expand Down Expand Up @@ -63,3 +64,73 @@ def reject_none(cls, v):

with pytest.raises(ValidationError):
Hero.model_validate({"name": None, "age": 25})


@needs_pydanticv1
def test_validation_related_object_not_in_session_pydantic_v1(clear_sqlmodel):
class Team(SQLModel, table=True):
id: Optional[int] = Field(default=None, primary_key=True)
name: str
heroes: List["Hero"] = Relationship(back_populates="team")

class Hero(SQLModel, table=True):
id: Optional[int] = Field(default=None, primary_key=True)
name: str

team_id: Optional[int] = Field(default=None, foreign_key="team.id")
team: Optional[Team] = Relationship(back_populates="heroes")

engine = create_engine("sqlite://")
SQLModel.metadata.create_all(engine)
team = Team(name="team")
hero = Hero(name="hero", team=team)
with Session(engine) as session:
session.add(team)
session.add(hero)
session.commit()

with Session(engine) as session:
hero = session.get(Hero, 1)
assert session._is_clean()

new_hero = Hero.validate(hero)

assert session._is_clean()
# The new hero is a different instance, but the team is the same
assert id(new_hero) != id(hero)
assert id(new_hero.team) == id(hero.team)


@needs_pydanticv2
def test_validation_related_object_not_in_session_pydantic_v2(clear_sqlmodel):
class Team(SQLModel, table=True):
id: Optional[int] = Field(default=None, primary_key=True)
name: str
heroes: List["Hero"] = Relationship(back_populates="team")

class Hero(SQLModel, table=True):
id: Optional[int] = Field(default=None, primary_key=True)
name: str

team_id: Optional[int] = Field(default=None, foreign_key="team.id")
team: Optional[Team] = Relationship(back_populates="heroes")

engine = create_engine("sqlite://")
SQLModel.metadata.create_all(engine)
team = Team(name="team")
hero = Hero(name="hero", team=team)
with Session(engine) as session:
session.add(team)
session.add(hero)
session.commit()

with Session(engine) as session:
hero = session.get(Hero, 1)
assert session._is_clean()

new_hero = Hero.model_validate(hero)

assert session._is_clean()
# The new hero is a different instance, but the team is the same
assert id(new_hero) != id(hero)
assert id(new_hero.team) == id(hero.team)