Skip to content

Add support for SQLAlchemy 2.1 - #405

Merged
josecsotomorales merged 2 commits into
mainfrom
feat/support-sa-2.1
Sep 29, 2026
Merged

josecsotomorales merged 2 commits into
mainfrom
feat/support-sa-2.1

Conversation

@josecsotomorales

@josecsotomorales josecsotomorales commented Sep 28, 2026 •

Copy link
Copy Markdown
Collaborator

Description

Adds support for SQLAlchemy 2.1 (current release: 2.1.1). The supported range becomes SQLAlchemy>=1.4.53,<2.2. SQLAlchemy 2.1 requires Python 3.11+, so installs on Python 3.10 continue to resolve to 2.0.x.

Compatibility fixes

  • _compat.py: 2.1 made attributes.ScalarAttributeImpl and register_attribute private, which broke import sqlalchemy_continuum. Both are now resolved from whichever name the installed version exposes.
  • count_versions(): 2.1 autoflushes Core statements in Session.execute() (sqlalchemy#9809), so the helper began flushing pending changes and counting the version that flush wrote. It now runs under session.no_autoflush, matching 1.4 and 2.0.
  • GenericAttributeImpl detected the 2.0.22 constructor change by int-parsing sa.__version__, which raises ValueError on pre-releases such as 2.1.0rc2. It now checks the positional argument count: 4 on 1.4 through 2.0.21, and 3 on 2.0.22 and later. This was checked against 1.4.53, 2.0.0, 2.0.21, 2.0.22, 2.1.0 and 2.1.1.

Latent bugs that 2.1 exposed

  • TransactionFactory.create_class resolved user_cls inside the class body, so registry, Base and user_cls became attributes of Transaction. Transaction.registry shadowed the declarative registry, and 2.1 raises an SAWarning for it.
  • prevent_reentry didn't reset its flag when configuration raised. That silently disabled version model building for every later configure_mappers(): during the port, one failing configure caused 692 unrelated test failures.

CI and tooling

  • CI and tox test SQLAlchemy 1.4, 2.0 and 2.1 as separate legs, with Python 3.10 excluded from 2.1. CI goes from 40 to 56 jobs.
  • uv.lock is refreshed: SQLAlchemy 2.0.54 on Python 3.10 and 2.1.1 on 3.11+.
  • The Postgres test URL names psycopg2 explicitly, because 2.1 maps bare postgresql:// to psycopg 3.
  • The suite's "SAWarnings are errors" guard was a module-level warnings.simplefilter in tests/__init__.py, and pytest discards those. It is now a filterwarnings entry in pyproject.toml, so it is actually enforced.

Verification (local)

  • The full suite passes on sqlite, postgres, postgres-native and mysql under SQLAlchemy 1.4.54, 2.0.54 and 2.1.1, with SAWarnings as errors. On 2.1.1, postgres and postgres-native also pass with psycopg 3.
  • The new regression tests fail against the previous code.
  • ruff check, ruff format --check and zensical build --clean --strict pass.

Possible follow-up (not in this PR): CI only exercises psycopg2. A psycopg 3 leg on SQLAlchemy 2.0+ would cover 2.1's new default driver.

Checklist

This pull request is:

  • A documentation / typographical error fix
  • A short code fix
  • A new feature implementation
    • No tracking issue exists. Tests and changelog entries are included.

🤖 Generated with Claude Code

Summary by CodeRabbit

  • New Features
    • Added support for SQLAlchemy 2.1. Supported versions now range from 1.4.53 to below 2.2; SQLAlchemy 2.1 requires Python 3.11 or later.
  • Bug Fixes
    • Fixed transaction model setup when a custom user class is configured and prevented mapper configuration issues from blocking later version-model creation.
    • Improved generic_relationship compatibility with SQLAlchemy prereleases.
    • Updated count_versions() to avoid flushing pending session changes, keeping behavior consistent across supported SQLAlchemy versions.

SQLAlchemy 2.1.1 is the current release, and Continuum failed to import
on it: 2.1 made attributes.ScalarAttributeImpl and register_attribute
private, and the generic relationship in _compat subclasses and calls
them. Resolve both from whichever name the installed version exposes.

Widen the pin to <2.2 and split the CI and tox SQLAlchemy legs into
1.4, 2.0 and 2.1; SQLAlchemy 2.1 requires Python 3.11+, so py3.10 is
excluded from the 2.1 leg. uv.lock now resolves SQLAlchemy 2.0.54 on
Python 3.10 and 2.1.1 on 3.11+.

Behavior fixes found while porting:

TransactionFactory.create_class resolved user_cls inside the class
body, so registry, Base and user_cls leaked onto the Transaction model;
registry shadowed the declarative registry and 2.1 raises an SAWarning
for it. The lookup now runs before the class body.

prevent_reentry never reset its flag when configuration raised, which
silently disabled version model building for every later
configure_mappers() and turned one failing test into 692 failures.

count_versions() runs its textual query under no_autoflush: 2.1
autoflushes Core statements in Session.execute (sqlalchemy#9809), which
made the helper flush pending changes and count the version it wrote.

GenericAttributeImpl detected the 2.0.22 constructor change by
int-parsing sa.__version__, which raises on pre-releases such as
2.1.0rc2. It now checks the positional argument count instead.

Test harness: the module-level simplefilter meant to turn SAWarnings
into errors was discarded by pytest's per-phase catch_warnings and never
fired; it is now pytest filterwarnings. The Postgres test URL names
psycopg2 explicitly because 2.1 maps postgresql:// to psycopg 3.

Verified locally: full suite on sqlite, postgres, postgres-native and
mysql under SQLAlchemy 1.4.54, 2.0.54 and 2.1.1 with SAWarnings as
errors, postgres and postgres-native on 2.1.1 with psycopg 3, ruff, and
a strict Zensical docs build.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
@coderabbitai

coderabbitai Bot commented Sep 28, 2026 •

Copy link
Copy Markdown

Review in Change Stack →

Navigate logical layers of code changes, visualize relationships, and explore their blast radius.

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Advanced

Run ID: b18700a1-d488-45ba-8586-7bf54ea87f33

📥 Commits

Reviewing files that changed from the base of the PR and between 560369a and 93c9d30.

⛔ Files ignored due to path filters (1)
  • uv.lock is excluded by !**/*.lock
📒 Files selected for processing (15)
  • .github/workflows/main.yml
  • CHANGES.rst
  • CLAUDE.md
  • CONTRIBUTING.md
  • docs/changelog.md
  • pyproject.toml
  • sqlalchemy_continuum/_compat.py
  • sqlalchemy_continuum/builder.py
  • sqlalchemy_continuum/transaction.py
  • sqlalchemy_continuum/utils.py
  • tests/__init__.py
  • tests/builders/test_model_builder.py
  • tests/test_transaction.py
  • tests/utils/test_count_versions.py
  • tox.ini

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


📝 Walkthrough

Walkthrough

The project now supports SQLAlchemy versions below 2.2, including SQLAlchemy 2.1. The changes update SQLAlchemy API compatibility and Transaction model setup, prevent autoflush during version counts, reset re-entry state after exceptions, and revise CI, tests, and project documentation.

Changes

SQLAlchemy support and behavior

Layer / File(s) Summary
Set SQLAlchemy support and test coverage
.github/workflows/main.yml, pyproject.toml, tox.ini, tests/__init__.py
The dependency bound and test matrix now include SQLAlchemy 2.1. Pytest treats SAWarning warnings as errors. The PostgreSQL test URL explicitly uses psycopg2.
Update SQLAlchemy APIs and Transaction setup
sqlalchemy_continuum/_compat.py, sqlalchemy_continuum/transaction.py, tests/test_transaction.py
Compatibility aliases select available SQLAlchemy attribute APIs. TransactionFactory resolves the configured user class before defining the mapped class. A test checks that the Transaction model shares the declarative registry.
Count versions without autoflush
sqlalchemy_continuum/utils.py, tests/utils/test_count_versions.py
count_versions runs its query with autoflush disabled. A test verifies that pending article changes remain dirty.
Reset re-entry state after exceptions
sqlalchemy_continuum/builder.py, tests/builders/test_model_builder.py
prevent_reentry resets its flag in a finally block. A test verifies that the handler can run again after raising.
Update release and CI guidance
CHANGES.rst, docs/changelog.md, CLAUDE.md, CONTRIBUTING.md, .github/workflows/main.yml
The changelogs describe SQLAlchemy 2.1 support and related changes. CI runs pre-commit, and project guidance reflects the lint and test configuration.

Priority: ➖ Normal

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

Change: Feature

Merge Risk: ⚪ Minimal · up to 93c9d

No identified issue prevents merging after normal checks.

Security Architecture Review

Security architecture risk: 🔵 Low · up to 93c9d

The inspected changes preserve the existing relationship and user-attribution paths, with no identified new security exposure. Compatibility and recovery after an interrupted model build remain the main uncertainties.

Retained concerns
No architecture-level concerns identified.

Security review details

Security Blast Radius

  • inferred — The effective scope is applications installing the expanded SQLAlchemy range and using this package's ORM-backed history or transaction features. The available evidence does not establish tenant or deployment boundaries.

Trust Boundaries and Controls

  • observed — Generic-relationship assignment derives the stored type and identity from a mapped object; reads use the existing registry and session mechanisms. These mechanisms do not, by themselves, establish application authorization policy.

Resilience and Maintainability Implications

  • inferred — Retrying a failed configuration is more feasible once the guard resets, but recovery of partially created versioning state remains unproven. That uncertainty matters to audit-history availability, not to an established new bypass.

Hardening Proposals

  • proposed — Exercise configuration failure after partial table or model creation, then verify whether retry either restores complete version-history mapping or fails explicitly without serving incomplete audit state.
🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 23.53% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 17 functions across 8 files. (7 skipped: … Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ 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 main change: adding SQLAlchemy 2.1 support.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
Full details: Docstring Coverage

Explanation

Docstring coverage is 23.53% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 17 functions across 8 files. (7 skipped: 7 unsupported.)

  • 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

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

@josecsotomorales
josecsotomorales marked this pull request as ready for review September 28, 2026 20:44
The lint job installed the lint dependency group without the lockfile,
so it always pulled the newest ruff. Since ruff 0.16, which formats
Python code blocks inside Markdown, the job has failed on main even
though the pinned ruff (0.15.20 in uv.lock and .pre-commit-config.yaml)
passes.

Run the pinned pre-commit hooks with pre-commit/action instead, as
qualytics-cli does. CI now also enforces the check-yaml, check-toml,
end-of-file and trailing-whitespace hooks, and Dependabot already
bumps the hook revs.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
@greptile-apps

greptile-apps Bot commented Sep 28, 2026 •

Copy link
Copy Markdown

RetriggerConfidence Score: 5/5

[High risk] Extends SQLAlchemy version support and fixes compatibility issues.

The PR appears safe to merge; no outstanding blocking finding or accepted new issue remains.

Summary

This PR adds SQLAlchemy 2.1 support, updates compatibility and mapper-configuration behavior, and expands the test matrix. Since the previous review, it also changes CI linting to run the repository’s pre-commit hooks.

Reviews (2) · Last reviewed commit: "Run pre-commit for the CI lint job"

Comment thread sqlalchemy_continuum/builder.py Resolved
Comment thread tox.ini Resolved
@josecsotomorales

Copy link
Copy Markdown
Collaborator Author

@greptileai review

@josecsotomorales
josecsotomorales merged commit 43915e8 into main Sep 29, 2026
62 checks passed
@josecsotomorales
josecsotomorales deleted the feat/support-sa-2.1 branch September 29, 2026 01: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.

1 participant