Repository navigation
Type JSON and other opaque DeclarativeBase columns by Mapped[...] - #7798
Conversation
A column of a SQLAlchemy DeclarativeBase model (dataclass or plain) was typed only by its column type's python_type when accessed through a state var. For JSON/JSONB/PickleType that is `object` (SQLAlchemy 2.1), so `State.m.d["city"]` raised "Var of type <class 'object'> does not support item access" and list/dict operations were unavailable, while the equivalent rx.Model column worked. A python_type raising NotImplementedError (the default before SQLAlchemy 2.1) leaked the raw `Mapped[T]` annotation instead. The column's python_type (including the ARRAY item type) stays the primary source. The `Mapped[T]` annotation is used only when that python type is uninformative (`object` or not implemented), or when T refines it: the origin of T is the same as or a subclass of a bare python type (`Mapped[dict[str, int]]` over `dict`). So `Mapped[str]` over `Enum(MyEnum)` stays `MyEnum`, ARRAY columns stay `List[T]`, and `Mapped[float]` over `Numeric` stays `Decimal`. `Mapped[Any]` and `Mapped[object]` never override. Nullability is decided by the column alone, as before. Only that one annotation is resolved, in the declaring class's module (as reflex does for state fields), so a TYPE_CHECKING-only symbol elsewhere in the class does not break it. The whole column typing is cached per (class, name). The SQLModel (rx.Model) branch is untouched; a test pins that it never reaches the new code. Co-Authored-By: Claude Opus 5.5 <[email protected]> Claude-Session: https://claude.ai/code/session_01Dxjadq3qkhKnqZR2b9WBFi
[Medium impact] The PR appears safe to merge; the latest change fixes the previously reported item-access failure. SummaryThe PR uses
Reviews (6) · Last reviewed commit: "Keep a dict column under a parametrized ..." · Reviewed by Greptile |
There was a problem hiding this comment.
1 issue found across 4 files
Prompt for AI agents (unresolved issues)
Check if these issues are valid — if so, understand the root cause of each and fix them. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. If appropriate, use sub-agents to investigate and fix each issue separately.
<file name="packages/reflex-base/src/reflex_base/utils/types.py">
<violation number="1" location="packages/reflex-base/src/reflex_base/utils/types.py:1109">
P2: For ARRAY columns whose element type is uninformative, the annotation fallback never runs, so `Mapped[list[dict[...]]]` still resolves to `List[object]`. The fallback check should also cover an item type that is `object`, not only a top-level `object`. Otherwise the element type stays opaque, as in the original bug.</violation>
</file>
Reply with feedback, questions, or to request a fix.
View guided diff | Turn on auto-fix | Re-trigger cubic
Merging this PR will regress 3 benchmarks2 warnings
Warning Please fix the performance issues or acknowledge them on CodSpeed. Performance Changes
Tip Investigate this regression by commenting Comparing |
|
The failing Generated by Claude Code |
An ARRAY column whose item type has no useful Python type, such as ARRAY(JSON), typed as List[object] and never used its Mapped[...] annotation, so Mapped[list[dict]] stayed opaque. The bare list type is now kept for such an item type, which the annotation refines as it does for other columns. Bound the column type cache with lru_cache(maxsize=1024), like the other per-type caches in types.py, and cover key access on a JSON column typed by a TypedDict. Co-Authored-By: Claude Opus 5.5 <[email protected]> Claude-Session: https://claude.ai/code/session_01Dxjadq3qkhKnqZR2b9WBFi
Co-Authored-By: Claude Opus 5.5 <[email protected]> Claude-Session: https://claude.ai/code/session_01Dxjadq3qkhKnqZR2b9WBFi
`Mapped[bool]` over `Integer` typed the column `bool`, but the database returns `0`/`1`, so `.to_string()` rendered "1" and `rx.switch(checked=...)` got `aria-checked="1"` instead of the compile-time `.bool()` hint. The same applied to an IntEnum over `Integer` and a StrEnum over `String`. A `Mapped[...]` annotation now refines a bare python type only by type parameters (`dict[str, int]` over `dict`) or TypedDict keys over `dict`, which keep the runtime class.
Co-Authored-By: Claude Opus 5.5 <[email protected]> Claude-Session: https://claude.ai/code/session_01Dxjadq3qkhKnqZR2b9WBFi
There was a problem hiding this comment.
All reported issues were addressed across 2 files (changes from recent commits).
Reply with feedback, questions, or to request a fix.
View guided diff | Turn on auto-fix | Re-trigger cubic
typing.is_typeddict misses typing_extensions.TypedDict classes, and a parametrized generic TypedDict is only recognized through its origin, so both fell back to the bare dict. Check the origin with typing_extensions.is_typeddict. Co-Authored-By: Claude Opus 5.5 <[email protected]> Claude-Session: https://claude.ai/code/session_01Dxjadq3qkhKnqZR2b9WBFi
Co-Authored-By: Claude Opus 5.5 <[email protected]> Claude-Session: https://claude.ai/code/session_01Dxjadq3qkhKnqZR2b9WBFi
Var key access does not resolve the keys of a parametrized generic TypedDict, so refining a dict column to `GenericPrefs[int]` turned `model.generic_prefs["value"]` from working item access into a VarAttributeError at compile time. Such an annotation now leaves the column `dict`; a non-generic TypedDict still refines it. Co-Authored-By: Claude Opus 5.5 <[email protected]> Claude-Session: https://claude.ai/code/session_01Dxjadq3qkhKnqZR2b9WBFi
Co-Authored-By: Claude Opus 5.5 <[email protected]> Claude-Session: https://claude.ai/code/session_01Dxjadq3qkhKnqZR2b9WBFi
|
CodSpeed on 3074592 flags
Generated by Claude Code |
) * Type JSON and other opaque DeclarativeBase columns by Mapped[...] A column of a SQLAlchemy DeclarativeBase model (dataclass or plain) was typed only by its column type's python_type when accessed through a state var. For JSON/JSONB/PickleType that is `object` (SQLAlchemy 2.1), so `State.m.d["city"]` raised "Var of type <class 'object'> does not support item access" and list/dict operations were unavailable, while the equivalent rx.Model column worked. A python_type raising NotImplementedError (the default before SQLAlchemy 2.1) leaked the raw `Mapped[T]` annotation instead. The column's python_type (including the ARRAY item type) stays the primary source. The `Mapped[T]` annotation is used only when that python type is uninformative (`object` or not implemented), or when T refines it: the origin of T is the same as or a subclass of a bare python type (`Mapped[dict[str, int]]` over `dict`). So `Mapped[str]` over `Enum(MyEnum)` stays `MyEnum`, ARRAY columns stay `List[T]`, and `Mapped[float]` over `Numeric` stays `Decimal`. `Mapped[Any]` and `Mapped[object]` never override. Nullability is decided by the column alone, as before. Only that one annotation is resolved, in the declaring class's module (as reflex does for state fields), so a TYPE_CHECKING-only symbol elsewhere in the class does not break it. The whole column typing is cached per (class, name). The SQLModel (rx.Model) branch is untouched; a test pins that it never reaches the new code. Co-Authored-By: Claude Opus 5.5 <[email protected]> Claude-Session: https://claude.ai/code/session_01Dxjadq3qkhKnqZR2b9WBFi * Type ARRAY columns of opaque items by Mapped[...] An ARRAY column whose item type has no useful Python type, such as ARRAY(JSON), typed as List[object] and never used its Mapped[...] annotation, so Mapped[list[dict]] stayed opaque. The bare list type is now kept for such an item type, which the annotation refines as it does for other columns. Bound the column type cache with lru_cache(maxsize=1024), like the other per-type caches in types.py, and cover key access on a JSON column typed by a TypedDict. Co-Authored-By: Claude Opus 5.5 <[email protected]> Claude-Session: https://claude.ai/code/session_01Dxjadq3qkhKnqZR2b9WBFi * Keep the column python type over a scalar subclass annotation `Mapped[bool]` over `Integer` typed the column `bool`, but the database returns `0`/`1`, so `.to_string()` rendered "1" and `rx.switch(checked=...)` got `aria-checked="1"` instead of the compile-time `.bool()` hint. The same applied to an IntEnum over `Integer` and a StrEnum over `String`. A `Mapped[...]` annotation now refines a bare python type only by type parameters (`dict[str, int]` over `dict`) or TypedDict keys over `dict`, which keep the runtime class. * Recognize typing_extensions and generic TypedDicts over a dict column typing.is_typeddict misses typing_extensions.TypedDict classes, and a parametrized generic TypedDict is only recognized through its origin, so both fell back to the bare dict. Check the origin with typing_extensions.is_typeddict. Co-Authored-By: Claude Opus 5.5 <[email protected]> Claude-Session: https://claude.ai/code/session_01Dxjadq3qkhKnqZR2b9WBFi * Keep a dict column under a parametrized generic TypedDict annotation Var key access does not resolve the keys of a parametrized generic TypedDict, so refining a dict column to `GenericPrefs[int]` turned `model.generic_prefs["value"]` from working item access into a VarAttributeError at compile time. Such an annotation now leaves the column `dict`; a non-generic TypedDict still refines it. Co-Authored-By: Claude Opus 5.5 <[email protected]> Claude-Session: https://claude.ai/code/session_01Dxjadq3qkhKnqZR2b9WBFi --------- Co-authored-by: Claude <[email protected]> Co-authored-by: Farhan <[email protected]> (cherry picked from commit 45ee83c)
Co-Authored-By: Claude Opus 5.5 <[email protected]> Claude-Session: https://claude.ai/code/session_01Dxjadq3qkhKnqZR2b9WBFi
Fixes FINDING-011 from the reflex 0.11.0a1 pre-release testing (artifacts on branch
claude/vibrant-pasteur-3921g3,prerelease-testing/runs/2026-11-11-v0.11.0a1/db_models/andverify_dbm/).Defect
On a SQLAlchemy
DeclarativeBasemodel (plain orMappedAsDataclass), a column likedata: Mapped[dict] = mapped_column(JSON)read through a state var was typedobject, becauseget_attribute_access_typeused only the column type'spython_type(objectforJSON,JSONB,PickleTypeon SQLAlchemy 2.1; types whosepython_typeraises leaked the rawMapped[dict]). SoState.model.data["city"]failed at compile time withTypeError: Var of type <class 'object'> does not support item access., andMapped[list[str]]JSON columns had no array operations orrx.foreach. Therx.Modelequivalent (profile: dict = Field(sa_column=Column(JSON))) is typeddict, so the rewrite toDeclarativeBasethat the 0.11 docs recommend broke such pages. Not a regression vs 0.10.1.Fix
packages/reflex-base/src/reflex_base/utils/types.py: the column branch now goes through_get_column_access_type(cls, name)(cached per class and attribute):python_typestays the primary source (existing logic incl. the ARRAY item type, moved unchanged into_get_column_python_type).object, or raisesNotImplementedError), the attribute'sMapped[T]annotation is used.Trefines it without changing the runtime class (get_origin(T) or Tis the same class, e.g.Mapped[dict[str, int]]overdict, orTis a TypedDict overdict),Tis used; otherwisepython_typewins, because the database returns that type (Mapped[str]overEnum(Color)staysColor;Mapped[bool]overIntegerstaysint; ARRAY results are unchanged).Mapped[Any]/Mapped[object]never override; nullability still comes from the column alone.Only that one attribute's annotation is resolved (found through the MRO, evaluated in the declaring class's module,
Annotated/aliases unwrapped), as reflex does for state fields, so a TYPE_CHECKING-only annotation elsewhere in the class cannot break it; works withfrom __future__ import annotationsand Python 3.14 lazy annotations. Legacy__allow_unmapped__plain annotations are not used (deferred). The rx.Model / SQLModel branch is untouched and cannot reach the new code.Cases (annotation + column type → main → this PR)
Mapped[dict]+ JSONobjectdictMapped[dict | None]+ JSONobject | Nonedict | NoneMapped[dict[str, str] | None]+ JSONobject | Nonedict[str, str] | NoneMapped[list[str]]+ JSON / JSONBobjectlist[str]Mapped[dict | None]+ PickleTypeobject | Nonedict | NoneMapped[dict]+ type whosepython_typeraisesMapped[dict](leaked)dictMapped[dict[str, int]]+ type withpython_typedictdictdict[str, int]Mapped[list[str]]/Mapped[Sequence[str]]+ARRAY(String)List[str]List[str](unchanged)Mapped[str]+Enum(Color)ColorColor(unchanged)Mapped[TypedDict]+ type withpython_typedictdictMapped[bool]+Integer,Mapped[IntEnum]+Integer,Mapped[StrEnum]+Stringint/int/str0/1,1,"a")Mapped[int],Mapped[str],Mapped[Decimal],Mapped[datetime], nullable variantsColumn(JSON)(no annotation)object | NoneField(sa_column=Column(JSON))dictdict(unchanged)Test plan
tests/units/test_attribute_access_type.py:test_get_attribute_access_type_declarative_column, parametrized over 36 attributes × plainDeclarativeBase/MappedAsDataclass× with / withoutfrom __future__ import annotations; mixin and imperative-column tests; two rx.Model guard tests.tests/units/vars/test_object.py:test_sqlalchemy_json_columns_on_state_var—State.m.profileis adictObjectVarandprofile["city"]compiles to?.["profile"]?.["city"](same as the.to(dict)form);tagsis alist[str]ArrayVarandtags.length()/rx.foreach(tags, rx.text)match the.to(list[str])forms.main'stypes.py: 54 failed, 192 passed (every JSON / JSONB / PickleType / renamed-column / not-implemented / refinement case × 4,assert <class 'object'> is dictin the state test); every "unchanged" row passes onmain, confirming those expectations are the pre-fix values.tests/units/reflex_base+tests/units/vars+ related modules 2302 passed; full unit suite 15761 passed, 66 skipped, coverage 81.43% (the Playwright browser-driver module could not run locally for lack of a Chromium binary).ruff check,ruff format,pyright reflex tests: clean. The QA probesverify_dbm/v2_json_types.pyanddb_models/probes/probe_types.pynow type every casedict/dict | None/list[str]and all item accesses compile.Type of change
Notes for reviewers
Mapped[list[dict]]overARRAY(JSON)staysList[object](parametrizedpython_typeis kept).Mapped[bool]overIntegerstaysint, as the database returns0/1. Typing itboolrendered.to_string()as"1"and passedchecked={1}torx.switch; withint,rx.switch(checked=...)gives the compile-time.bool()hint, as onmain.@cachekeys are bounded by mapped columns in a real app.News fragment:
packages/reflex-base/news/+declarative-mapped-column-type.bugfix.md.Generated by Claude Code