Type JSON and other opaque DeclarativeBase columns by Mapped[...]

Merged
MA
22d ago
+540-23

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/ and verify_dbm/).

Defect

On a SQLAlchemy DeclarativeBase model (plain or MappedAsDataclass), a column like data: Mapped[dict] = mapped_column(JSON) read through a state var was typed object, because get_attribute_access_type used only the column type's python_type (object for JSON, JSONB, PickleType on SQLAlchemy 2.1; types whose python_type raises leaked the raw Mapped[dict]). So State.model.data["city"] failed at compile time with TypeError: Var of type <class 'object'> does not support item access., and Mapped[list[str]] JSON columns had no array operations or rx.foreach. The rx.Model equivalent (profile: dict = Field(sa_column=Column(JSON))) is typed dict, so the rewrite to DeclarativeBase that 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):

  1. The column type's python_type stays the primary source (existing logic incl. the ARRAY item type, moved unchanged into _get_column_python_type).
  2. If it is uninformative (object, or raises NotImplementedError), the attribute's Mapped[T] annotation is used.
  3. If it is a bare class and T refines it without changing the runtime class (get_origin(T) or T is the same class, e.g. Mapped[dict[str, int]] over dict, or T is a TypedDict over dict), T is used; otherwise python_type wins, because the database returns that type (Mapped[str] over Enum(Color) stays Color; Mapped[bool] over Integer stays int; ARRAY results are unchanged).
  4. 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 with from __future__ import annotations and 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)

Declarationmainthis PR
Mapped[dict] + JSONobjectdict
Mapped[dict | None] + JSONobject | Nonedict | None
Mapped[dict[str, str] | None] + JSONobject | Nonedict[str, str] | None
Mapped[list[str]] + JSON / JSONBobjectlist[str]
Mapped[dict | None] + PickleTypeobject | Nonedict | None
Mapped[dict] + type whose python_type raisesMapped[dict] (leaked)dict
Mapped[dict[str, int]] + type with python_type dictdictdict[str, int]
Mapped[list[str]] / Mapped[Sequence[str]] + ARRAY(String)List[str]List[str] (unchanged)
Mapped[str] + Enum(Color)ColorColor (unchanged)
Mapped[TypedDict] + type with python_type dictdictthe TypedDict
Mapped[bool] + Integer, Mapped[IntEnum] + Integer, Mapped[StrEnum] + Stringint / int / strunchanged (the database returns 0/1, 1, "a")
Mapped[int], Mapped[str], Mapped[Decimal], Mapped[datetime], nullable variantsas beforeunchanged
Imperative Column(JSON) (no annotation)object | Noneunchanged
rx.Model Field(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 × plain DeclarativeBase / MappedAsDataclass × with / without from __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.profile is a dict ObjectVar and profile["city"] compiles to ?.["profile"]?.["city"] (same as the .to(dict) form); tags is a list[str] ArrayVar and tags.length() / rx.foreach(tags, rx.text) match the .to(list[str]) forms.
  • Failing before against main's types.py: 54 failed, 192 passed (every JSON / JSONB / PickleType / renamed-column / not-implemented / refinement case × 4, assert <class 'object'> is dict in the state test); every "unchanged" row passes on main, confirming those expectations are the pre-fix values.
  • After: the two files 246 passed (Python 3.12: 245 passed, 1 skipped 3.14-only); 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 probes verify_dbm/v2_json_types.py and db_models/probes/probe_types.py now type every case dict / dict | None / list[str] and all item accesses compile.

Type of change

  • Bug fix (non-breaking change which fixes an issue)

Notes for reviewers

  • Mapped[list[dict]] over ARRAY(JSON) stays List[object] (parametrized python_type is kept).
  • A subclass annotation does not refine a scalar column: Mapped[bool] over Integer stays int, as the database returns 0/1. Typing it bool rendered .to_string() as "1" and passed checked={1} to rx.switch; with int, rx.switch(checked=...) gives the compile-time .bool() hint, as on main.
  • @cache keys 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