Repository navigation
Conversation
ee95e3b to
439ddaa
Compare
|
I ran the PR tests and the rollback/expire cases from the discussion on main and on this branch. The fix does what it says for loaded and expired instances. Verified behavior (SQLite, main vs this branch) Loaded or expired row,
So the rejected value no longer reaches SQLAlchemy history, and pending edits still commit. Construction path (already broken on main, but now clean) Constructing a table model with a frozen field raises on both branches: class Hero(SQLModel, table=True):
id: int | None = Field(default=None, primary_key=True)
code: str = Field(schema_extra={"frozen": True})
Hero(code="original") # ValidationError: frozen_fieldThat is pre-existing (the Pydantic So the branch also fixes the constructor half of the state-integrity problem. It would be worth adding a test for that path (assert the event does not fire / no history), since it is currently uncovered. Notes
Environment: SQLModel 0.0.50 + Pydantic 2.14.4 + SQLAlchemy 2.x, Python 3.12. |
Pull Request
Discussion: #2116
Description
Fixes the assignment bug reported in discussion #2116. Previously, assigning to a frozen field on a database-loaded table model raised ValidationError after SQLAlchemy had already recorded the change. Catching the error and committing the session could persist the rejected value.
SQLModel.setattr now checks whether the field or model is frozen before calling set_attribute(). A rejected assignment raises Pydantic’s frozen_field or frozen_instance error before SQLAlchemy fires attribute listeners or records history. Accepted assignments keep their existing event order.
Tests
Added five regression cases covering loaded and expired fields, frozen primary keys, and foreign-key synchronization. They verify that a rejected write leaves the original value intact while valid pending edits still commit.
All five cases failed with the original setter and passed with the fix. All 147 synchronous runtime tests passed.
Performance
Local benchmarks on Python 3.15.2 showed an additional 0.30 µs per writable mapped-field assignment. Rejecting a frozen write was 46% faster because the check runs before SQLAlchemy processes the assignment.
Values are median times per assignment across 12 alternating rounds of 15,000 assignments per case. The benchmark measured the setter in isolation.
AI Disclaimer
Too many prompts and many solutions proposed, but I wasn't convened of them all except this solution to have minimal change with much less affect, also considering the performance side as this will be run for every assignment in general.
Model used: GPT-Astora-6.2-Max
Checklist