Skip to content

Reject frozen assignments before SQLAlchemy records changes - #2145

Open
msmakb wants to merge 1 commit into
fastapi:mainfrom
msmakb:fix/frozen-field-assignment
Open

msmakb wants to merge 1 commit into
fastapi:mainfrom
msmakb:fix/frozen-field-assignment

Conversation

@msmakb

@msmakb msmakb commented Nov 21, 2026 •

Copy link
Copy Markdown

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.

Assignment Before After Change
Writable mapped field 2.77 µs 3.07 µs +11%
Writable mapped field with validate_assignment=True 4.20 µs 5.18 µs +23%
Rejected frozen field 8.72 µs 4.71 µs −46%

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

  • This PR links to a GitHub Discussion for the proposed code change.
  • I added tests for the change.
  • The new or updated tests fail on the main branch and pass on this PR.
  • Coverage stays at 100%.
  • The documentation explains the change if needed.

@msmakb
msmakb force-pushed the fix/frozen-field-assignment branch from ee95e3b to 439ddaa Compare November 21, 2026 10:15

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant