Skip to content

chore: Support Flask 3.X and SQLAlchemy 2.X - #35117

Closed
dpgaspar wants to merge 41 commits into
apache:masterfrom
preset-io:danielgaspar/sc-91696/upgrade-flask-to-3-x-on-superset
Closed

dpgaspar wants to merge 41 commits into
apache:masterfrom
preset-io:danielgaspar/sc-91696/upgrade-flask-to-3-x-on-superset

Conversation

@dpgaspar

@dpgaspar dpgaspar commented Sep 12, 2025 •

Copy link
Copy Markdown
Member

Summary

This PR upgrades Apache Superset to Flask 3.x and SQLAlchemy 2.x while maintaining backward compatibility with SQLAlchemy 1.4.54. This is a critical upgrade to keep Superset current with the Flask/SQLAlchemy ecosystem and enable future feature development.

Background: The Flask 3.x Dependency Challenge

Upgrading to Flask 3.x presents a unique challenge due to interdependencies between Flask, Flask-SQLAlchemy, and SQLAlchemy versions:

The Dependency Matrix Problem:

  • Flask 2.x works with Flask-SQLAlchemy 2.x, which only supports SQLAlchemy 1.4.x
  • Flask 3.x requires Flask-SQLAlchemy 3.x, which only supports SQLAlchemy 2.x
  • Flask-SQLAlchemy 2.x does NOT support SQLAlchemy 2.x
  • Flask-SQLAlchemy 3.x does NOT support SQLAlchemy 1.4.x

This creates two mutually exclusive dependency chains:

  1. Flask 2.x → Flask-SQLAlchemy 2.x → SQLAlchemy 1.4.54
  2. Flask 3.x → Flask-SQLAlchemy 3.x → SQLAlchemy 2.x

This PR implements the complete upgrade to Flask 3.x + Flask-SQLAlchemy 3.x + SQLAlchemy 2.x, ensuring all components work together properly.

SQLAlchemy 2.x Migration Patterns

This PR implements all necessary SQLAlchemy 2.x migration patterns while maintaining backward compatibility with 1.4.54:

1. Engine Execution Pattern Migration

  • Old Pattern: engine.execute("SQL")
  • New Pattern:
    with engine.connect() as connection:
        connection.execute(text("SQL"))
  • Affected files: 30+ files including tests, engine specs, utilities

2. Inspector Bind Execution Pattern

  • Old Pattern: inspector.bind.execute("SQL")
  • New Pattern:
    with inspector.bind.connect() as connection:
        connection.execute(text("SQL"))
  • Affected engine specs: Databricks, Presto, Doris, PostgreSQL, DuckDB, Snowflake

3. SQL Text Wrapping

  • Old Pattern: connection.execute("raw SQL string")
  • New Pattern: connection.execute(text("raw SQL string"))
  • Reason: SQLAlchemy 2.x requires explicit text() wrapping for raw SQL strings

4. Parameter Binding Format

  • Old Pattern: execute(sql, (param1, param2)) (positional)
  • New Pattern: execute(sql, {"name1": param1, "name2": param2}) (named)
  • Example: SQLite parameter binding in tests

5. Connection String Rendering

  • Old Pattern: str(conn) for connection URLs
  • New Pattern: conn.render_as_string(hide_password=False)
  • Reason: SQLAlchemy 2.x masks passwords by default in string representations

6. URL Constructor Changes

  • Old Pattern: URL(drivername, **params)
  • New Pattern: URL.create(drivername, **params)
  • Affected specs: DuckDB, Databend

7. Case Expression Syntax

  • Old Pattern: sa.case([(condition, value)], else_=default)
  • New Pattern: sa.case((condition, value), else_=default)
  • Note: Changed from list to tuple for when conditions

8. Select Expression Syntax

  • Old Pattern: sa.select([column1, column2])
  • New Pattern: sa.select(column1, column2)
  • Note: Removed list wrapper for select columns

9. Table Autoload Parameter

  • Old Pattern: Table(name, metadata, autoload=True, autoload_with=engine)
  • New Pattern: Table(name, metadata, autoload_with=engine)
  • Note: autoload=True is now implicit when autoload_with is provided

10. Subtransactions Removal

  • Old Pattern: db.session.begin(subtransactions=True)
  • New Pattern: db.session.begin()
  • Note: Subtransactions are deprecated in SQLAlchemy 2.x

11. Custom Type Literal Processing

  • Added literal_processor methods to custom SQLAlchemy types for proper literal rendering
  • Affected: Presto/Trino Date and TimeStamp custom types

12. Objects must be explicitly added to the session

  • Old Pattern:
  table = SqlaTable(...)
  column = TableColumn(table=table, ...)
  db.session.commit()  # column was auto-added
  • New Pattern:
  table = SqlaTable(...)
  db.session.add(table)  # Must explicitly add
  column = TableColumn(table=table, ...)
  db.session.add(column)  # Must explicitly add
  db.session.commit()

Testing Improvements

Context Manager Mocking

  • Updated test mocks to properly handle SQLAlchemy 2.x context manager patterns
  • Changed from Mock() to MagicMock() for proper __enter__/__exit__ support

URL String Assertions

  • Updated tests to use url.render_as_string(hide_password=False) instead of str(url)
  • Ensures password visibility in test assertions

Files Modified

Core Changes:

  • superset/models/core.py - Connection string handling
  • superset/sql_lab.py - Query execution patterns
  • superset/utils/mock_data.py - Test data generation
  • superset/utils/core.py - Utility functions
  • superset/models/helpers.py - Query helpers
  • superset/extensions/metadb.py - Metadata handling

Engine Specifications:

  • Updated all database engine specs for SQLAlchemy 2.x patterns
  • Fixed URL building and parameter handling
  • Updated catalog/schema queries

Tests:

  • Fixed 100+ test cases for SQLAlchemy 2.x compatibility
  • Updated mocking patterns for context managers
  • Fixed parameter binding in test queries

Backward Compatibility

All changes maintain full backward compatibility with SQLAlchemy 1.4.54. The patterns used (with engine.connect(), text(), etc.) are available in SQLAlchemy 1.4.x when using future mode, ensuring a smooth transition path.

Impact

This PR completes the upgrade to:

  • Flask 3.x - Latest Flask framework with improved performance and features
  • Flask-SQLAlchemy 3.x - Required for Flask 3.x compatibility
  • SQLAlchemy 2.x - Modern ORM with better type safety and performance

Benefits:

  1. Keeps Superset current with the modern Python web stack
  2. Improves security with proper password masking
  3. Enables access to latest Flask and SQLAlchemy features
  4. Better type safety and clearer API patterns
  5. Performance improvements from SQLAlchemy 2.x optimizations

Testing

  • All existing tests pass with SQLAlchemy 2.x
  • No functional regressions identified
  • Performance characteristics remain unchanged or improved
  • Comprehensive test coverage for all migration patterns

Breaking Changes

None for end users. All changes are internal implementation details that maintain the same external API and behavior.

@korbit-ai

korbit-ai Bot commented Sep 12, 2025

Copy link
Copy Markdown

Based on your review schedule, I'll hold off on reviewing this PR until it's marked as ready for review. If you'd like me to take a look now, comment /korbit-review.

Your admin can change your review schedule in the Korbit Console

@github-actions github-actions Bot added the risk:db-migration PRs that require a DB migration label Sep 12, 2025
@rad-pat

rad-pat commented Dec 1, 2025

Copy link
Copy Markdown
Contributor

Any idea on estimated timeline for this compatibility with SQLAlchemy 2.0? No further releases expected for SQLAlchemy 1.4, it is EOL according to Mike Bayer - sqlalchemy/sqlalchemy#13009

@hainenber hainenber mentioned this pull request Feb 10, 2026
3 tasks
@rusackas

Copy link
Copy Markdown
Member

@dpgaspar do you still intend to get this through? Needs a big ol' rebase, but seems like important work :D

@rusackas

Copy link
Copy Markdown
Member

@dpgaspar this hit my stale draft radar again... not sure if you're picking this back up, but I might close it out next time it hits 90+ days again to thin the herd.

@rad-pat

rad-pat commented Jun 15, 2026

Copy link
Copy Markdown
Contributor

@dpgaspar @rusackas do you want any help to get this over the line? I believe that getting updated to SQLA 2.0 is pretty important since 1.4 is EOL

@rad-pat

rad-pat commented Jun 17, 2026

Copy link
Copy Markdown
Contributor

@dpgaspar @rusackas do you want any help to get this over the line? I believe that getting updated to SQLA 2.0 is pretty important since 1.4 is EOL

I see there are quite a number of other PRs related to trying to migrate SQLAlchemy. Perhaps some should be closed off, like this one?

@rusackas

Copy link
Copy Markdown
Member

Yeah, you're right... the effort is moving forward, this PR doesn't seem to be. Closing for now, but happy to reopen, or @dpgaspar can do the same if he wants to :D

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

review:draft risk:db-migration PRs that require a DB migration size/XXL

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants