Skip to content

refactor: make import/expression layer SQLAlchemy 2.0-compatible - #41179

Merged
rusackas merged 5 commits into
masterfrom
chore/sqlalchemy-2-forward-compat
Jun 29, 2026
Merged

refactor: make import/expression layer SQLAlchemy 2.0-compatible#41179
rusackas merged 5 commits into
masterfrom
chore/sqlalchemy-2-forward-compat

Conversation

@rusackas

Copy link
Copy Markdown
Member

SUMMARY

Forward-compatible groundwork for the SQLAlchemy 1.4 → 2.0 migration (companion to #40830 / #39735, and a sibling of the already-merged #40276 and the in-flight #40275). Every change here is backward-compatible with the current sqlalchemy>=1.4,<2 / flask-sqlalchemy 2.x baseline, so it can land on master today without bumping the version, while shrinking the eventual bump and de-risking it.

Two categories:

1. Removed-in-2.0 API fixes — these break on 2.0 but still work on 1.4:

  • sqlalchemy.orm.eagerload (a removed alias of joinedload) → joinedload, in the security manager.
  • sqlalchemy.sql.visitors.VisitableType (removed) → sqlalchemy.types.TypeEngine, in dataset-importer and mock_data type hints.
  • flask_sqlalchemy.BaseQuery (removed in Flask-SQLAlchemy 3.x, which SA 2.0 requires) → imported from flask_sqlalchemy.query.Query with a fallback to the FSA 2.x path, in the query / saved-query filters and the report command tests.
  • Engine.execute / raw-string execution → startup health check wrapped in a Connection + text(); secrets re-encryptor uses text() with a single bind dict and row._mapping[...] access.

2. Prospective Annotated Declarative prep — no-ops on 1.4, but they ease the eventual 2.0 flip:

  • __allow_unmapped__ on the FAB declarative base so legacy 1.x annotations are tolerated during incremental migration.
  • Mapped[...] return annotations on created_by_fk / changed_by_fk and BaseDatasource.slices.

The select() and case() syntax changes from the same effort are intentionally excluded here — they already landed via #40276 and are covered by #40275 respectively.

BEFORE/AFTER SCREENSHOTS OR ANIMATED GIF

N/A — no user-facing changes.

TESTING INSTRUCTIONS

CI. Locally, all of these were verified against the current SQLAlchemy 1.4.54 / Flask-SQLAlchemy 2.5.1 baseline (imports resolve, BaseQuery shim falls back correctly, pre-commit run is green including mypy/pylint/ruff). They should be a no-op behaviorally on 1.4 and unblock the 2.0 import/boot path.

ADDITIONAL INFORMATION

  • Has associated issue:
  • Required feature flags:
  • Changes UI
  • Includes DB Migration (follow approval process in SIP-59)
    • Migration is atomic, supports rollback & is backwards-compatible
    • Confirm DB migration upgrade and downgrade tested
    • Runtime estimates and downtime expectations provided
  • Introduces new feature or API
  • Removes existing feature or API

🤖 Generated with Claude Code

@codecov

codecov Bot commented Jun 18, 2026

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 91.30435% with 2 lines in your changes missing coverage. Please review.
✅ Project coverage is 64.37%. Comparing base (d6ede99) to head (a48f832).
⚠️ Report is 96 commits behind head on master.

Files with missing lines Patch % Lines
superset/utils/mock_data.py 0.00% 2 Missing ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##           master   #41179      +/-   ##
==========================================
- Coverage   64.37%   64.37%   -0.01%     
==========================================
  Files        2653     2653              
  Lines      145152   145157       +5     
  Branches    33491    33491              
==========================================
  Hits        93446    93446              
- Misses      50014    50017       +3     
- Partials     1692     1694       +2     
Flag Coverage Δ
hive 39.26% <82.60%> (+<0.01%) ⬆️
mysql 57.98% <91.30%> (+<0.01%) ⬆️
postgres 58.04% <91.30%> (-0.01%) ⬇️
presto 40.84% <82.60%> (+<0.01%) ⬆️
python 59.48% <91.30%> (-0.01%) ⬇️
sqlite 57.70% <91.30%> (+<0.01%) ⬆️
unit 100.00% <ø> (ø)

Flags with carried forward coverage won't be shown. Click here to find out more.

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

@bito-code-review bito-code-review Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Code Review Agent Run #368617

Actionable Suggestions - 2
  • tests/integration_tests/reports/commands_tests.py - 1
  • superset/connectors/sqla/models.py - 1
    • Incorrect type annotation for declared_attr · Line 338-338
Filtered by Review Rules

Bito filtered these suggestions based on rules created automatically for your feedback. Manage rules.

  • superset/queries/filters.py - 1
Review Details
  • Files reviewed - 11 · Commit Range: 18a2a45..18a2a45
    • superset/__init__.py
    • superset/commands/dataset/importers/v1/utils.py
    • superset/connectors/sqla/models.py
    • superset/initialization/__init__.py
    • superset/models/helpers.py
    • superset/queries/filters.py
    • superset/queries/saved_queries/filters.py
    • superset/security/manager.py
    • superset/utils/encrypt.py
    • superset/utils/mock_data.py
    • tests/integration_tests/reports/commands_tests.py
  • Files skipped - 0
  • Tools
    • Whispers (Secret Scanner) - ✔︎ Successful
    • Detect-secrets (Secret Scanner) - ✔︎ Successful
    • MyPy (Static Code Analysis) - ✔︎ Successful
    • Astral Ruff (Static Code Analysis) - ✔︎ Successful

Bito Usage Guide

Commands

Type the following command in the pull request comment and save the comment.

  • /review - Manually triggers a full AI review.

  • /pause - Pauses automatic reviews on this pull request.

  • /resume - Resumes automatic reviews.

  • /resolve - Marks all Bito-posted review comments as resolved.

  • /abort - Cancels all in-progress reviews.

Refer to the documentation for additional commands.

Configuration

This repository uses Superset You can customize the agent settings here or contact your Bito workspace admin at evan@preset.io.

Documentation & Help

AI Code Review powered by Bito Logo

Comment thread tests/integration_tests/reports/commands_tests.py
Comment thread superset/connectors/sqla/models.py
@pull-request-size pull-request-size Bot added size/L and removed size/M labels Jun 18, 2026
@bito-code-review

bito-code-review Bot commented Jun 18, 2026

Copy link
Copy Markdown
Contributor

Code Review Agent Run #d63e3e

Actionable Suggestions - 0
Review Details
  • Files reviewed - 2 · Commit Range: 18a2a45..d9e13b8
    • tests/unit_tests/utils/encrypt_test.py
    • tests/integration_tests/utils/encrypt_tests.py
  • Files skipped - 0
  • Tools
    • Whispers (Secret Scanner) - ✔︎ Successful
    • Detect-secrets (Secret Scanner) - ✔︎ Successful
    • MyPy (Static Code Analysis) - ✔︎ Successful
    • Astral Ruff (Static Code Analysis) - ✔︎ Successful

Bito Usage Guide

Commands

Type the following command in the pull request comment and save the comment.

  • /review - Manually triggers a full AI review.

  • /pause - Pauses automatic reviews on this pull request.

  • /resume - Resumes automatic reviews.

  • /resolve - Marks all Bito-posted review comments as resolved.

  • /abort - Cancels all in-progress reviews.

Refer to the documentation for additional commands.

Configuration

This repository uses Superset You can customize the agent settings here or contact your Bito workspace admin at evan@preset.io.

Documentation & Help

AI Code Review powered by Bito Logo

@rusackas

Copy link
Copy Markdown
Member Author

Curious your take on this one @hy144328 - wasn't sure if this is already on your roadmap.

@rusackas
rusackas force-pushed the chore/sqlalchemy-2-forward-compat branch from d9e13b8 to 63acd9d Compare June 22, 2026 23:28
@bito-code-review

bito-code-review Bot commented Jun 23, 2026

Copy link
Copy Markdown
Contributor

Code Review Agent Run #aa6c24

Actionable Suggestions - 0
Additional Suggestions - 1
  • superset/queries/filters.py - 1
    • Type annotation clarity · Line 19-24
      The try/except import pattern correctly handles Flask-SQLAlchemy 3.x migration, matching the pattern in `superset/queries/saved_queries/filters.py`. However, the dynamic `BaseQuery` resolution may cause issues with static type checkers. Consider wrapping the import in a `TYPE_CHECKING` block with an explicit type alias for better mypy compliance.
Review Details
  • Files reviewed - 13 · Commit Range: cb22061..63acd9d
    • superset/__init__.py
    • superset/commands/dataset/importers/v1/utils.py
    • superset/connectors/sqla/models.py
    • superset/initialization/__init__.py
    • superset/models/helpers.py
    • superset/queries/filters.py
    • superset/queries/saved_queries/filters.py
    • superset/security/manager.py
    • superset/utils/encrypt.py
    • superset/utils/mock_data.py
    • tests/integration_tests/reports/commands_tests.py
    • tests/integration_tests/utils/encrypt_tests.py
    • tests/unit_tests/utils/encrypt_test.py
  • Files skipped - 0
  • Tools
    • Whispers (Secret Scanner) - ✔︎ Successful
    • Detect-secrets (Secret Scanner) - ✔︎ Successful
    • MyPy (Static Code Analysis) - ✔︎ Successful
    • Astral Ruff (Static Code Analysis) - ✔︎ Successful

Bito Usage Guide

Commands

Type the following command in the pull request comment and save the comment.

  • /review - Manually triggers a full AI review.

  • /pause - Pauses automatic reviews on this pull request.

  • /resume - Resumes automatic reviews.

  • /resolve - Marks all Bito-posted review comments as resolved.

  • /abort - Cancels all in-progress reviews.

Refer to the documentation for additional commands.

Configuration

This repository uses Superset You can customize the agent settings here or contact your Bito workspace admin at evan@preset.io.

Documentation & Help

AI Code Review powered by Bito Logo

@bito-code-review

Copy link
Copy Markdown
Contributor

AI Code Review is in progress (usually takes 3 to 15 minutes unless it's a very large PR).

Bito Usage Guide

Commands

Type the following command in the pull request comment and save the comment.

  • /review - Manually triggers a full AI review.

  • /pause - Pauses automatic reviews on this pull request.

  • /resume - Resumes automatic reviews.

  • /resolve - Marks all Bito-posted review comments as resolved.

  • /abort - Cancels all in-progress reviews.

Refer to the documentation for additional commands.

Configuration

This repository uses Superset You can customize the agent settings here or contact your Bito workspace admin at evan@preset.io.

Documentation & Help

@rusackas
rusackas requested review from sadpandajoe and villebro June 23, 2026 17:59
@hy144328

Copy link
Copy Markdown
Contributor

Curious your take on this one @hy144328 - wasn't sure if this is already on your roadmap.

@rusackas Here are my two cents:

  • sqlalchemy.orm.eagerload (a removed alias of joinedload) → joinedload, in the security manager.
  • sqlalchemy.sql.visitors.VisitableType (removed) → sqlalchemy.types.TypeEngine, in dataset-importer and mock_data type hints.

These two were not on my roadmap because the unit tests did not flag them. #40273
So it is good to have them covered in this PR. 👌

  • flask_sqlalchemy.BaseQuery (removed in Flask-SQLAlchemy 3.x, which SA 2.0 requires) → imported from flask_sqlalchemy.query.Query with a fallback to the FSA 2.x path, in the query / saved-query filters and the report command tests.

Flask SQLAlchemy is also not on my radar yet but it looks good to me.
Perhaps, @dpgaspar has a more educated opinion here since he has experience with Flask and #35117 .

  • Engine.execute / raw-string execution → startup health check wrapped in a Connection + text(); secrets re-encryptor uses text() with a single bind dict and row._mapping[...] access.

This one is actually on the roadmap. However, when I grep it, there are many more occurrences that are not covered by unit tests. This is not a problem. I have it on my roadmap, and I will probably crush this warning next.

  • allow_unmapped on the FAB declarative base so legacy 1.x annotations are tolerated during incremental migration.
  • Mapped[...] return annotations on created_by_fk / changed_by_fk and BaseDatasource.slices.

This is actually on my radar since this is also part of official migration guide. https://docs.sqlalchemy.org/en/20/changelog/migration_20.html#migration-to-2-0-step-six-add-allow-unmapped-to-explicitly-typed-orm-models
I suspect that there are even more ORMs to patch than currently flagged by the unit tests.


Long story short, I think this PR complements my roadmap well, and crushes multiple warnings that I have not documented yet.
If you do not mind, I will continue with my work, too, because it will take some more manual labor for code not covered by unit tests.
I have to look more carefully at the migration of the SQLAlchemy ORM in particular because they propose both a quick and dirty way based on __allow_unmapped__ and a slow and type-safe way based on Mapped and mapped_column().

claude and others added 5 commits June 23, 2026 14:53
Forward-compatible groundwork for the SQLAlchemy 1.4 -> 2.0 bump. Every
change here is backward-compatible with the current SQLAlchemy 1.4.54 /
Flask-SQLAlchemy 2.5.1 baseline, so it does not regress anything while
shrinking the eventual version bump.

Removed-in-2.0 API fixes (these break on 2.0 but still work on 1.4):
- `sqlalchemy.orm.eagerload` (removed alias of `joinedload`) in the
  security manager.
- `sqlalchemy.sql.visitors.VisitableType` (removed) -> `sqlalchemy.types.TypeEngine`
  in dataset importer and mock_data type hints.
- `flask_sqlalchemy.BaseQuery` (removed in FSA 3.x, required by SA 2.0) ->
  import from `flask_sqlalchemy.query.Query` with a fallback to the FSA 2.x
  path, in the query/saved-query filters and the report command tests.
- `Engine.execute` / raw-string execution -> wrap startup health check in a
  `Connection` + `text()`, and the secrets re-encryptor in `text()` with a
  single bind dict and `row._mapping[...]` access.

Prospective Annotated Declarative prep (no-ops on 1.4, ease the 2.0 flip):
- `__allow_unmapped__` on the FAB declarative base so legacy 1.x annotations
  are tolerated during incremental migration.
- `Mapped[...]` return annotations on `created_by_fk`/`changed_by_fk` and
  `BaseDatasource.slices`.

The `select()` and `case()` syntax changes from the same effort already
landed via #40276 / #40275, so they are intentionally excluded here.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
The migrator now reads columns via row._mapping[...] and binds the
UPDATE params as a single positional dict. Wrap the fixture rows in a
_Row stand-in and read the bind dict positionally so the unit tests
match the production interface.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
The re-encrypt path reads column values via row._mapping (SQLAlchemy 2.0
Row API), but the integration tests passed a plain dict, which has no
_mapping, raising AttributeError. Build a genuine Row via a small helper
that handles both the 1.4 and 2.0 Row constructor signatures.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
The migrator passes bind params positionally to conn.execute(stmt, params),
so the assertion must read call_args.args[1] rather than call_args.kwargs.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
The connection check now uses engine.connect() + connection.execute()
instead of the removed Engine.execute(), so the test must inject the
failure on engine.connect.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
@rusackas
rusackas force-pushed the chore/sqlalchemy-2-forward-compat branch from 76e5cee to a48f832 Compare June 23, 2026 21:55
@rusackas

Copy link
Copy Markdown
Member Author

Thanks @hy144328, that all tracks. These were just the warnings our unit tests happened to surface, so glad it slots into your roadmap rather than stepping on it. Go for the broader ORM sweep, and ping me if you want a second set of eyes on the Mapped/mapped_column direction.

@bito-code-review

bito-code-review Bot commented Jun 24, 2026

Copy link
Copy Markdown
Contributor

Code Review Agent Run #8dace6

Actionable Suggestions - 0
Additional Suggestions - 1
  • superset/queries/filters.py - 1
    • Fallback path untested · Line 19-24
      The try/except pattern correctly handles both Flask-SQLAlchemy 2.x (pinned at 2.5.1) and future 3.x compatibility. The `# pragma: no cover` on the fallback path indicates the fallback isn't tested in CI — consider adding a test to exercise this path with a mocked import failure, or document why it doesn't need coverage.
Review Details
  • Files reviewed - 14 · Commit Range: 7c7689c..a48f832
    • superset/__init__.py
    • superset/commands/dataset/importers/v1/utils.py
    • superset/connectors/sqla/models.py
    • superset/initialization/__init__.py
    • superset/models/helpers.py
    • superset/queries/filters.py
    • superset/queries/saved_queries/filters.py
    • superset/security/manager.py
    • superset/utils/encrypt.py
    • superset/utils/mock_data.py
    • tests/integration_tests/reports/commands_tests.py
    • tests/integration_tests/utils/encrypt_tests.py
    • tests/unit_tests/initialization_test.py
    • tests/unit_tests/utils/encrypt_test.py
  • Files skipped - 0
  • Tools
    • Whispers (Secret Scanner) - ✔︎ Successful
    • Detect-secrets (Secret Scanner) - ✔︎ Successful
    • MyPy (Static Code Analysis) - ✔︎ Successful
    • Astral Ruff (Static Code Analysis) - ✔︎ Successful

Bito Usage Guide

Commands

Type the following command in the pull request comment and save the comment.

  • /review - Manually triggers a full AI review.

  • /pause - Pauses automatic reviews on this pull request.

  • /resume - Resumes automatic reviews.

  • /resolve - Marks all Bito-posted review comments as resolved.

  • /abort - Cancels all in-progress reviews.

Refer to the documentation for additional commands.

Configuration

This repository uses Superset You can customize the agent settings here or contact your Bito workspace admin at evan@preset.io.

Documentation & Help

AI Code Review powered by Bito Logo

@rusackas
rusackas merged commit adc03ce into master Jun 29, 2026
59 checks passed
@rusackas
rusackas deleted the chore/sqlalchemy-2-forward-compat branch June 29, 2026 18:39
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants