Skip to content

Add support for versioning SQLModel models - #410

Merged
josecsotomorales merged 2 commits into
mainfrom
feat/sqlmodel-support
Oct 14, 2026
Merged

josecsotomorales merged 2 commits into
mainfrom
feat/sqlmodel-support

Conversation

@josecsotomorales

@josecsotomorales josecsotomorales commented Oct 14, 2026 •

Copy link
Copy Markdown
Collaborator

Description

Adds support for versioning SQLModel table models. Closes #271 and supersedes #397. The reasoning for the simpler approach is in this comment.

Continuum builds version classes and the Transaction class on the model's declarative base. It finds that base by walking __bases__ to the class that carries metadata. For a SQLModel model, that's the SQLModel class itself, which isn't a SQLAlchemy declarative base: it has no registry, and its metaclass only maps table=True classes. Mapper configuration therefore fails with AttributeError: registry. The workaround in #271 patched sqlalchemy_utils.functions.get_declarative_base, which Continuum stopped calling when SQLAlchemy-Utils was dropped (#352), so there is currently no workaround.

Fix

  • New resolve_declarative_base(model) in model_builder.py, used for both the version class bases (get_base_class) and the Transaction base (Builder.build_transaction_class).
    • If the model's own declarative base owns the model's mapper registry, it returns that base. That covers every plain declarative, DeclarativeBase and Flask-SQLAlchemy model, so their behavior is unchanged.
    • Otherwise it returns registry.generate_base() for the model's registry.
  • The registry comes from sa.inspect(model).registry, which is public API on SQLAlchemy 1.4 through 2.1. There's no cache, no SQLModel import and no runtime cost: it runs once per versioned root class during mapper configuration.
  • Each model resolves to its own registry. A SQLModel model on a non-default registry gets its version class in that registry, as with plain SQLAlchemy and several declarative bases. Full multi-registry support (a Transaction per registry) is out of scope.

Tests

  • tests/test_sqlmodel.py runs under both versioning strategies, using SQLModel's Session.
    • Each test gets its own SQLModel registry, mirroring the per-test declarative_base() in TestCase.
    • It passes base_classes=None through the normal options, so tests don't inherit a previous test's base.
  • Coverage:
    • registry and metadata placement of the version and transaction classes
    • user_cls string lookup
    • insert/update/delete and revert
    • one-to-many and link_model many-to-many relationship versions
    • one test mirrors the docs example
  • The tests fail without the fix (all 10 error) and with a process-wide base cache like SQLModel compatibility #397's (9 of 10 error).
  • SQLModel's Session deprecates query() and execute(), which the dynamic versions relationship and some version lookups call, so the module filters that warning.

Dependencies and CI

  • New test-sqlmodel dependency group, included in dev. It's separate from test because SQLModel requires SQLAlchemy 2.x.
  • CI installs it on the SQLAlchemy 2.0 and 2.1 legs, and tox on the sqlalchemy{20,21} envs.
  • uv.lock only adds sqlmodel, pydantic, pydantic-core, annotated-types and typing-inspection.
  • No package extra: SQLModel users already have it installed, and SQLModel pins SQLAlchemy 2.x itself.

Docs

  • New SQLModel page in the user guide, plus changelog entries.

Verification (local)

  • The full suite (DB=sqlite) passes on Python 3.15 with SQLAlchemy 1.4, 2.0 and 2.1 (via tox), and on Python 3.11 with 2.0. SQLModel version: 0.0.48.
  • Postgres and postgres-native: the full suite passes on 2.1, and the SQLModel tests also pass on 2.0.
  • MySQL wasn't run locally.
  • pre-commit, actionlint and zensical build --clean --strict pass.
  • The docs example was executed with its documented results asserted.

Possible follow-up (not in this PR): Continuum's own version lookups still call session.query(). Moving them to select() would remove most of the SQLModel deprecation warnings. The dynamic versions relationship would still trigger it.

Checklist

This pull request is:

  • A documentation / typographical error fix
  • A short code fix
  • A new feature implementation

🤖 Generated with Claude Code

Summary by CodeRabbit

  • New Features
    • Added support for versioning SQLModel table models, including tracking updates, deletions, and relationship changes, and reverting models to previous versions. SQLModel requires SQLAlchemy 2.0 or later.
  • Documentation
    • Added a guide covering setup and usage, including how to mark models for versioning and access or revert prior versions. It also describes compatibility considerations for SQLModel and versioned models.

Version and transaction classes are built on the model's declarative
base. For SQLModel models that resolves to the SQLModel class, which
isn't a declarative base, so mapper configuration failed with
AttributeError: registry. When a model's base doesn't own its mapper
registry, generate a base from that registry instead.

The SQLModel tests run on the SQLAlchemy 2.x CI legs and tox envs via a
new test-sqlmodel dependency group.

Refs #271
@coderabbitai

coderabbitai Bot commented Oct 14, 2026 •

Copy link
Copy Markdown

Review in Change Stack →

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration
  • Configuration used: defaults
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: 47e192d0-c330-4f1a-8548-2c5c5a0e4e60
📥 Commits

Reviewing files that changed from the base of the PR and between c7f3645 and 8ea5cda.

📒 Files selected for processing: 2
  • sqlalchemy_continuum/model_builder.py
  • tests/test_sqlmodel.py
🚧 Files skipped from review as they are similar to previous changes: 1
  • sqlalchemy_continuum/model_builder.py

Included review availability: This review used your included allowance. Your plan provides up to 4 included reviews per hour; 2 remain after this review.

📝 Walkthrough

The change adds SQLModel versioning support by resolving declarative bases from model registries. It adds SQLModel versioning tests, configures test dependencies, and documents setup and limitations.

Changes: SQLModel versioning

Layer / File(s) Summary
Registry-based declarative base resolution
sqlalchemy_continuum/model_builder.py, sqlalchemy_continuum/builder.py
resolve_declarative_base selects the model base when it shares the inspected model’s registry. Otherwise, it generates a base from that registry. The builder uses the resolver when creating transaction classes and as the default in get_base_class.
SQLModel tests and test environment
tests/test_sqlmodel.py, pyproject.toml, tox.ini, .github/workflows/main.yml
Adds tests for registry placement, version creation and revert, deletion, and relationship history under both versioning strategies. Adds the SQLModel test dependency and configures test environments to install it for applicable SQLAlchemy versions.
SQLModel documentation and changelog
docs/sqlmodel.md, docs/index.md, zensical.toml, CHANGES.rst, docs/changelog.md
Documents setup order, an example, metadata integration, generated version classes, and deprecation warnings. Adds the page to documentation navigation and the changelogs.

Priority: ➖ Normal

Estimated code review effort: 3 (Moderate) | ~20 minutes

Change: Feature · Severity of issue fixed: Medium

Sequence Diagram(s)

sequenceDiagram
  participant VersionedModel as SQLModel model
  participant Builder
  participant Resolver as resolve_declarative_base
  Builder->>Resolver: Resolve base for model
  Resolver-->>Builder: Return model base or registry-generated base
  Builder->>Builder: Build transaction class with resolved base
Loading
Merge Risk: ⚪ Minimal · up to 8ea5c

This change adds SQLModel versioning support, tests and documentation. No concrete merge-blocking risk was identified in the supplied context.

Pre-merge checks: Passed 4 · Failed 1

Failed Failed checks: 1 warning

Check name Status Explanation Resolution
Docstring Coverage Warning Docstring coverage is 20.00% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 15 functions across 3 files. Write docstrings for the functions missing them to satisfy the coverage threshold.
Passed Passed checks: 4 passed
Check name Status Explanation
Description Check Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check Passed The title clearly and concisely describes the primary change: adding support for versioning SQLModel models.
Linked Issues check Passed Issue [#271] requires SQLModel mapper configuration, version access, and revert behavior. resolve_declarative_base(model) uses the inspected model registry and is used for version classes and `Trans…
Out of Scope Changes check Passed The code change, SQLModel tests, documentation, changelog, SQLAlchemy 2.x test dependency, tox configuration, and CI installation support SQLModel compatibility for [#271]. The PR explicitly excludes …
  • Fix all pre-merge checks with AI
✨ Finishing Touches: 💡 1
📝 Generate docstrings: 💡
  • Commit to this branch
  • Create a new PR
🧪 Generate unit tests (beta)
  • Commit to this branch
  • Create a new PR
  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@greptile-apps

greptile-apps Bot commented Oct 14, 2026 •

Copy link
Copy Markdown

RetriggerConfidence Score: 5/5

[Medium impact] The PR appears safe to merge; both previous findings are addressed and no new actionable issues remain.

Summary

Adds SQLModel support by building version classes and the transaction class on the model's registry when its base is not a SQLAlchemy declarative base.

  • SQLModel tables can keep version history on their own registry.
  • The SQLModel guide shows how to save and restore model versions.

Diagram

%%{init: {'theme': 'neutral'}}%%
flowchart TD
  A["Mapped model"] --> B["resolve_declarative_base"]
  B --> C{"Base owns the model's registry?"}
  C -->|Yes| D["Use existing base"]
  C -->|No| E["registry.generate_base()"]
  D --> F["Build version and transaction classes"]
  E --> F
Loading

Reviews (2) · Last reviewed commit: "Test the documented SQLModel setup on th..." · Reviewed by Greptile

Comment thread tests/test_sqlmodel.py Resolved
Comment thread sqlalchemy_continuum/model_builder.py Resolved
The docs example declares models on SQLModel's default registry with
user_cls=None, while the other SQLModel tests use a registry per test.
Cover that setup too, including table placement in SQLModel.metadata,
and dispose of the default registry afterwards so later declarations of
the same names don't collide.

Also add the missing :param: field to resolve_declarative_base.
@josecsotomorales

Copy link
Copy Markdown
Collaborator Author

@greptileai review

@josecsotomorales
josecsotomorales merged commit b9cf962 into main Oct 14, 2026
66 checks passed
@josecsotomorales
josecsotomorales deleted the feat/sqlmodel-support branch October 14, 2026 17:04
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.

SQLModel Compatibility

1 participant