fix: re-initialize SQLAlchemy InstanceState on table model_copy - #2088
Open
taran-dev4u wants to merge 2 commits into
Open
fix: re-initialize SQLAlchemy InstanceState on table model_copy#2088taran-dev4u wants to merge 2 commits into
taran-dev4u wants to merge 2 commits into
Conversation
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Description
When calling
model_copy()(or deprecatedcopy()) on a table model instance (especially one attached to or loaded from a database session), Pydantic's defaultBaseModel.model_copyperforms a shallow copy of__dict__, copying_sa_instance_stateby reference.Because
_sa_instance_stateis a SQLAlchemyInstanceStatecontaining an internal weak reference to the original model instance (state.obj()), the newly created copy shares the sameInstanceStatereferencing the original instance. This leads to subtle and severe bugs:Solution
SQLModel.model_copy(...)to detect whenis_table_model_class(self.__class__)is true._sa_instance_statefromnew_copy.__dict__and initialized a fresh SQLAlchemyInstanceStateviawith partial_init(): self.__class__.__init__(new_copy).SQLModel.copy(...)marked with@deprecatedforwarding tomodel_copy(...)for backwards compatibility.tests/test_pydantic/test_model_copy.pytesting non-table models, unpersisted table models, persisted table models with session mutation/saving, and deprecatedcopy().Validation
uv run pytest: 219 passed (100%).uv run ruff check .: clean.uv run ruff format --check sqlmodel tests: clean.