This is an automated email from the ASF dual-hosted git repository.
uranusjr pushed a commit to branch main
in repository https://gitbox.apache.org/repos/asf/airflow.git
The following commit(s) were added to refs/heads/main by this push:
new c70a5edb11e Support SQLAlchemy 2.1 type hints (#77494)
c70a5edb11e is described below
commit c70a5edb11e26ebf27a95c829dda7e5724d976cb
Author: Tzu-ping Chung <[email protected]>
AuthorDate: Wed Nov 25 08:00:32 2026 +0800
Support SQLAlchemy 2.1 type hints (#77494)
SQLAlchemy 2.1 changed the type definition in a backward incompatible
way, causing Mypy issues with the existing code base (runtime support
does not break, only type hints). The new types should be the way going
forward, but unfortunately 2.1 does not support Python 3.13 and lower,
and some of the Airflow providers do not yet support 3.14.
To work around the issue, a small shim is implemented in Airflow with a
small plugin to switch behavior between the two distinct combinations.
Once Python 3.14 is supported across the board, we can simply remove the
plugin and change the type imports without needing to fix any of the
type hints.
While applying the shim, issues were discovered in LazySelectSequence.
After further inspection, the offending code was leftover from Airflow 2
that has been dead for quite a while and no longer needed. It doesn't
work if explicitly called anyway (reflected by the now-correct type
hints), and therefore has been removed entirely.
---
.../core_api/routes/public/dag_bundles.py | 1 +
.../core_api/services/public/import_errors.py | 2 +
.../execution_api/routes/dag_parsing.py | 8 +--
airflow-core/src/airflow/dag_processing/manager.py | 4 +-
.../src/airflow/jobs/scheduler_job_runner.py | 6 +--
airflow-core/src/airflow/models/dynamic_region.py | 9 ++--
airflow-core/src/airflow/models/pool.py | 6 +--
.../src/airflow/models/task_coordinates.py | 11 ++--
airflow-core/src/airflow/models/xcom.py | 14 ++---
airflow-core/src/airflow/utils/db.py | 52 +++++--------------
airflow-core/src/airflow/utils/db_cleanup.py | 5 +-
airflow-core/src/airflow/utils/sqlalchemy.py | 19 +++++--
dev/mypy/README.md | 4 ++
.../src/airflow_mypy/plugins/sqlalchemy_version.py | 59 ++++++++++++++++++++++
dev/mypy/tests/test_plugins.py | 42 +++++++++++++++
dev/pyproject.toml | 1 +
pyproject.toml | 1 +
17 files changed, 164 insertions(+), 80 deletions(-)
diff --git
a/airflow-core/src/airflow/api_fastapi/core_api/routes/public/dag_bundles.py
b/airflow-core/src/airflow/api_fastapi/core_api/routes/public/dag_bundles.py
index 96ecd0e3f63..9b4087286af 100644
--- a/airflow-core/src/airflow/api_fastapi/core_api/routes/public/dag_bundles.py
+++ b/airflow-core/src/airflow/api_fastapi/core_api/routes/public/dag_bundles.py
@@ -65,6 +65,7 @@ def _count_import_errors(bundle_names: Sequence[str], *,
session: Session) -> di
.where(ParseImportError.bundle_name.in_(bundle_names))
.group_by(ParseImportError.bundle_name)
)
+ if bundle_name is not None
}
diff --git
a/airflow-core/src/airflow/api_fastapi/core_api/services/public/import_errors.py
b/airflow-core/src/airflow/api_fastapi/core_api/services/public/import_errors.py
index ce60ff1e891..1d566e47b02 100644
---
a/airflow-core/src/airflow/api_fastapi/core_api/services/public/import_errors.py
+++
b/airflow-core/src/airflow/api_fastapi/core_api/services/public/import_errors.py
@@ -57,6 +57,8 @@ def get_readable_import_error_files(
DagModel.relative_fileloc.in_(filenames),
)
):
+ if relative_fileloc is None:
+ continue
dag_ids_by_file.setdefault(relative_fileloc, set()).add(dag_id)
readable: set[str] = set()
diff --git
a/airflow-core/src/airflow/api_fastapi/execution_api/routes/dag_parsing.py
b/airflow-core/src/airflow/api_fastapi/execution_api/routes/dag_parsing.py
index c35f70da7cc..0baf496c651 100644
--- a/airflow-core/src/airflow/api_fastapi/execution_api/routes/dag_parsing.py
+++ b/airflow-core/src/airflow/api_fastapi/execution_api/routes/dag_parsing.py
@@ -79,12 +79,12 @@ if TYPE_CHECKING:
from collections.abc import Callable, Coroutine
from pydantic import BaseModel
- from sqlalchemy import Select
from sqlalchemy.orm import Session
from starlette.responses import Response
from starlette.types import Message
from airflow.callbacks.callback_requests import CallbackRequest
+ from airflow.utils.sqlalchemy import Select
class DagParsingRoute(ExecutionAPIRoute):
@@ -452,7 +452,7 @@ class _RequestedWork(Protocol[WorkT]):
model: type[WorkT]
kind: Literal["callbacks", "priority"]
- def build_query(self, *, replaying: bool) -> Select[tuple[WorkT]]: ...
+ def build_query(self, *, replaying: bool) -> Select[WorkT]: ...
def get_payload(self, work: WorkT) -> tuple[str, CallbackRequest | None]:
...
@@ -463,7 +463,7 @@ class _CallbackWork:
model = DagProcessorCallback
kind: Literal["callbacks", "priority"] = "callbacks"
- def build_query(self, *, replaying: bool) ->
Select[tuple[DagProcessorCallback]]:
+ def build_query(self, *, replaying: bool) -> Select[DagProcessorCallback]:
query = select(self.model).order_by(self.model.priority_weight.desc(),
self.model.id)
if not replaying:
query = query.where(self.model.state.is_(None))
@@ -486,7 +486,7 @@ class _PriorityWork:
model = DagPriorityParsingRequest
kind: Literal["callbacks", "priority"] = "priority"
- def build_query(self, *, replaying: bool) ->
Select[tuple[DagPriorityParsingRequest]]:
+ def build_query(self, *, replaying: bool) ->
Select[DagPriorityParsingRequest]:
return select(self.model).order_by(self.model.id)
def get_payload(self, work: DagPriorityParsingRequest) -> tuple[str, None]:
diff --git a/airflow-core/src/airflow/dag_processing/manager.py
b/airflow-core/src/airflow/dag_processing/manager.py
index 2e64beb35dc..cf00b74bd08 100644
--- a/airflow-core/src/airflow/dag_processing/manager.py
+++ b/airflow-core/src/airflow/dag_processing/manager.py
@@ -114,12 +114,12 @@ if TYPE_CHECKING:
from socket import socket
from sqlalchemy.orm import Session
- from sqlalchemy.sql import Select
from airflow.callbacks.callback_requests import CallbackRequest
from airflow.dag_processing.api_client import DagProcessorAPIClient
from airflow.dag_processing.bundles.base import BaseDagBundle
from airflow.sdk.api.client import Client
+ from airflow.utils.sqlalchemy import Select
# The budget limits when another send starts; an in-flight request retains its
read/write timeout.
_API_SEND_BUDGET_SECONDS = 1.0
@@ -904,7 +904,7 @@ class DagFileProcessorManager(LoggingMixin):
if bundle.supports_versioning and not bundle.is_initialized
]:
self.log.debug("Skipping callback fetch for uninitialized
bundles: %s", unready_bundles)
- query: Select[tuple[DbCallbackRequest]] = with_row_locks(
+ query: Select[DbCallbackRequest] = with_row_locks(
select(DbCallbackRequest)
.where(
DbCallbackRequest.bundle_name.in_(bundle_names),
diff --git a/airflow-core/src/airflow/jobs/scheduler_job_runner.py
b/airflow-core/src/airflow/jobs/scheduler_job_runner.py
index cc3eb26e3a8..94af3bd3488 100644
--- a/airflow-core/src/airflow/jobs/scheduler_job_runner.py
+++ b/airflow-core/src/airflow/jobs/scheduler_job_runner.py
@@ -149,7 +149,7 @@ if TYPE_CHECKING:
from sqlalchemy.orm import Session
from sqlalchemy.orm.interfaces import LoaderOption
from sqlalchemy.sql.elements import ColumnElement
- from sqlalchemy.sql.selectable import Select, Subquery
+ from sqlalchemy.sql.selectable import Subquery
from airflow._shared.logging.types import Logger
from airflow.executors.base_executor import BaseExecutor
@@ -158,7 +158,7 @@ if TYPE_CHECKING:
from airflow.models.pool import PoolStats
from airflow.serialization.definitions.dag import SerializedDAG
from airflow.serialization.definitions.mappedoperator import Operator
- from airflow.utils.sqlalchemy import CommitProhibitorGuard
+ from airflow.utils.sqlalchemy import CommitProhibitorGuard, Select
TI = TaskInstance
DR = DagRun
@@ -1107,7 +1107,7 @@ class SchedulerJobRunner(BaseJobRunner, LoggingMixin):
max_tis: int,
*,
excluded_ti_ids: Collection[UUID] = (),
- ) -> Select[tuple[TI]]:
+ ) -> Select[TI]:
"""
Build a query that fetches SCHEDULED TIs eligible for execution this
cycle.
diff --git a/airflow-core/src/airflow/models/dynamic_region.py
b/airflow-core/src/airflow/models/dynamic_region.py
index 63a6574b265..e85beee5656 100644
--- a/airflow-core/src/airflow/models/dynamic_region.py
+++ b/airflow-core/src/airflow/models/dynamic_region.py
@@ -65,17 +65,14 @@ _PATH_TYPE = LargeBinary().with_variant(VARBINARY(300),
"mysql", "mariadb")
_pack_index = struct.Struct(">I").pack
if TYPE_CHECKING:
- from sqlalchemy import Select
from sqlalchemy.engine import Connection
from sqlalchemy.orm import Mapper
from sqlalchemy.orm.session import SessionTransaction
from sqlalchemy.sql.elements import ColumnElement
from airflow.models.taskinstance import TaskInstance
- from airflow.utils.sqlalchemy import UUIDSelect
+ from airflow.utils.sqlalchemy import Select
-# Bound unparameterised: no ``Select[...]`` spelling accepts every arity on
both SQLAlchemy 2.0 and 2.1.
-# TODO: parameterise the bound with the variadic Select once the minimum
SQLAlchemy is 2.1.
_SelectT = TypeVar("_SelectT", bound="Select")
@@ -846,7 +843,7 @@ def select_current_producer_ids(
region_id: UUID | None = None,
region_index: int | None = None,
session: Session,
-) -> UUIDSelect:
+) -> Select[UUID]:
"""
Select the ids of the live producers :func:`resolve_current_producers`
would return.
@@ -951,7 +948,7 @@ def _build_pass_ownership_filter(
def select_loop_producer_ids(
*, dag_id: str, run_id: str, loop_node_id: str, task_id: str, is_mapped:
bool, session: Session
-) -> UUIDSelect:
+) -> Select[UUID]:
"""
Select every live execution of ``task_id`` across all passes of the loop
``loop_node_id``.
diff --git a/airflow-core/src/airflow/models/pool.py
b/airflow-core/src/airflow/models/pool.py
index e791704c95c..4d997802f53 100644
--- a/airflow-core/src/airflow/models/pool.py
+++ b/airflow-core/src/airflow/models/pool.py
@@ -34,7 +34,6 @@ from airflow.utils.state import TaskInstanceState
if TYPE_CHECKING:
from sqlalchemy.orm.session import Session
- from sqlalchemy.sql import Select
logger = logging.getLogger(__name__)
@@ -202,14 +201,15 @@ class Pool(Base):
pools: dict[str, PoolStats] = {}
pool_includes_deferred: dict[str, bool] = {}
- # The below type annotation is acceptable on SQLA2.1, but not on 2.0
- query: Select[str, int, bool] = select(Pool.pool, Pool.slots,
Pool.include_deferred) # type: ignore[type-arg]
+ query = select(Pool.pool, Pool.slots, Pool.include_deferred)
if lock_rows:
query = with_row_locks(query, session=session, nowait=True)
pool_rows = session.execute(query)
for pool_name, total_slots_in, include_deferred in pool_rows:
+ if pool_name is None:
+ continue
total_slots = float("inf") if total_slots_in == -1 else
total_slots_in
pools[pool_name] = PoolStats(
total=total_slots, running=0, queued=0, open=0, deferred=0,
scheduled=0
diff --git a/airflow-core/src/airflow/models/task_coordinates.py
b/airflow-core/src/airflow/models/task_coordinates.py
index 769018846f9..87b32fb1536 100644
--- a/airflow-core/src/airflow/models/task_coordinates.py
+++ b/airflow-core/src/airflow/models/task_coordinates.py
@@ -52,13 +52,12 @@ if TYPE_CHECKING:
from collections.abc import Collection, Iterable, Sequence
from datetime import datetime
- from sqlalchemy import Select
from sqlalchemy.orm import Session
from sqlalchemy.sql.elements import ColumnElement
from airflow.serialization.definitions.dag import SerializedDAG,
SerializedOperator
from airflow.serialization.definitions.mappedoperator import Operator
- from airflow.utils.sqlalchemy import UUIDSelect
+ from airflow.utils.sqlalchemy import Select
LOOP_GATE_OPERATOR = "LoopGateOperator"
@@ -489,7 +488,7 @@ class TaskCoordinateResolver:
run_id: str,
task_ids: Collection[str],
slots: Collection[tuple[str, int]],
- ) -> UUIDSelect:
+ ) -> Select[UUID]:
"""Select, in one statement, the region-less task instances that the
named tasks or slots address."""
targets = []
if task_ids:
@@ -858,7 +857,7 @@ class TaskCoordinateResolver:
def select_skip_target_ids(
self, *, caller: TaskInstance, task_id: str, map_indexes: int | None =
None
- ) -> UUIDSelect:
+ ) -> Select[UUID]:
"""
Select the task instance ids a skip request from ``caller`` reaches
for ``task_id``.
@@ -893,7 +892,7 @@ class TaskCoordinateResolver:
map_indexes=map_indexes,
)
- def _select_loop_producer_ids(self, request: _ProducerRequest) ->
UUIDSelect:
+ def _select_loop_producer_ids(self, request: _ProducerRequest) ->
Select[UUID]:
if TYPE_CHECKING:
assert request.loop_node_id is not None
return select_loop_producer_ids(
@@ -917,7 +916,7 @@ class TaskCoordinateResolver:
map_indexes: int | Collection[int] | None = None,
previous_iteration: bool = False,
all_iterations: bool = False,
- ) -> UUIDSelect:
+ ) -> Select[UUID]:
"""Select the task instance ids :meth:`resolve` returns, without
loading the producers."""
if region_index is not None and region_id is None:
raise ValueError("region_index requires an explicit producer
region_id")
diff --git a/airflow-core/src/airflow/models/xcom.py
b/airflow-core/src/airflow/models/xcom.py
index beccaff855a..32357c33026 100644
--- a/airflow-core/src/airflow/models/xcom.py
+++ b/airflow-core/src/airflow/models/xcom.py
@@ -70,13 +70,11 @@ if TYPE_CHECKING:
from sqlalchemy.engine import Row
from sqlalchemy.orm import Session
from sqlalchemy.orm.util import AliasedClass
- from sqlalchemy.sql.expression import CompoundSelect, Select, Subquery,
TextClause
+ from sqlalchemy.sql.expression import CompoundSelect, Subquery
from airflow.models.dagrun import DagRun
from airflow.models.taskinstance import TaskInstance
-
- # TODO: use Select[XComModel] once the minimum SQLAlchemy is 2.1; 2.0 uses
Select[tuple[XComModel]].
- XComModelSelect = Select
+ from airflow.utils.sqlalchemy import Select
XCOM_RETURN_KEY = "return_value"
@@ -338,7 +336,7 @@ class _XComOperations:
include_prior_dates: bool = False,
limit: int | None = None,
try_number: int | None = None,
- ) -> XComModelSelect:
+ ) -> Select[XComModel]:
"""
Composes a query to get one or more XCom entries.
@@ -634,7 +632,7 @@ def _reject_projection_write(mapper, connection, target):
raise TypeError("XCom read projection is read-only")
-def build_xcom_read_query(*, producer_ids: Select, key: str | None = None) ->
XComModelSelect:
+def build_xcom_read_query(*, producer_ids: Select, key: str | None = None) ->
Select[XComModel]:
model = get_xcom_model()
entity = aliased(model, _filter_rows(model.__table__,
producer_ids=producer_ids, key=key))
return select(entity).execution_options(populate_existing=True)
@@ -713,10 +711,6 @@ class LazyXComSelectSequence(LazySelectSequence[Any]):
:meta private:
"""
- @staticmethod
- def _rebuild_select(stmt: TextClause) -> Select[tuple[Any]]:
- return cast("Select[tuple[Any]]",
select(get_xcom_model().value).from_statement(stmt))
-
@staticmethod
def _process_row(row: Row) -> Any:
return get_xcom_model().deserialize_value(row)
diff --git a/airflow-core/src/airflow/utils/db.py
b/airflow-core/src/airflow/utils/db.py
index 3827dea5330..05ea0302261 100644
--- a/airflow-core/src/airflow/utils/db.py
+++ b/airflow-core/src/airflow/utils/db.py
@@ -36,6 +36,7 @@ from tempfile import gettempdir
from typing import (
TYPE_CHECKING,
Any,
+ NoReturn,
Protocol,
TypeVar,
overload,
@@ -78,7 +79,7 @@ if TYPE_CHECKING:
from sqlalchemy.engine import Row
from sqlalchemy.ext.asyncio import AsyncSession
from sqlalchemy.orm import Session
- from sqlalchemy.sql.elements import ColumnElement, TextClause
+ from sqlalchemy.sql.elements import ColumnElement
from sqlalchemy.sql.selectable import Select
from airflow.models.connection import Connection
@@ -1865,19 +1866,16 @@ class LazySelectSequence(Sequence[T]):
"""
List-like interface to lazily access a database model query.
- The intended use case is inside a task execution context, where we manage
an
- active SQLAlchemy session in the background.
+ Rows are fetched through the session passed to :meth:`from_select` each
time
+ the sequence is accessed, so the sequence is only usable while that
session is.
This is an abstract base class. Each use case should subclass, and
implement
- the following static methods:
+ the ``_process_row`` static method. It is called when an item is accessed.
+ The lazy sequence uses ``session.execute()`` to fetch rows from the
database,
+ and this method should know how to process each row into a value.
- * ``_rebuild_select`` is called when a lazy sequence is unpickled. Since it
- is not easy to pickle SQLAlchemy constructs, this class serializes the
- SELECT statements into plain text to storage. This method is called on
- deserialization to convert the textual clause back into an ORM SELECT.
- * ``_process_row`` is called when an item is accessed. The lazy sequence
- uses ``session.execute()`` to fetch rows from the database, and this
- method should know how to process each row into a value.
+ A lazy sequence holds a live session, so it cannot be pickled. Convert it
to
+ a list first if the values need to cross a process boundary.
:meta private:
"""
@@ -1903,16 +1901,6 @@ class LazySelectSequence(Sequence[T]):
s2 = s2.order_by(col.desc())
return cls(s1, s2, session=session)
- @staticmethod
- def _rebuild_select(stmt: TextClause) -> Select:
- """
- Rebuild a textual statement into an ORM-configured SELECT statement.
-
- This should do something like ``select(field).from_statement(stmt)`` to
- reconfigure ORM information to the textual SQL statement.
- """
- raise NotImplementedError
-
@staticmethod
def _process_row(row: Row) -> T:
"""Process a SELECT-ed row into the end value."""
@@ -1926,21 +1914,10 @@ class LazySelectSequence(Sequence[T]):
counter = "item" if (length := len(self)) == 1 else "items"
return f"LazySelectSequence([{length} {counter}])"
- def __getstate__(self) -> Any:
- # We don't want to go to the trouble of serializing SQLAlchemy objects.
- # Converting the statement into a SQL string is the best we can get.
- # The literal_binds compile argument inlines all the values into the
SQL
- # string to simplify cross-process commuinication as much as possible.
- # Theoratically we can do the same for count(), but I think it should
be
- # performant enough to calculate only that eagerly.
- s1 = str(self._select_asc.compile(self._session.get_bind(),
compile_kwargs={"literal_binds": True}))
- s2 = str(self._select_desc.compile(self._session.get_bind(),
compile_kwargs={"literal_binds": True}))
- return (s1, s2, len(self))
-
- def __setstate__(self, state: Any) -> None:
- s1, s2, self._len = state
- self._select_asc = self._rebuild_select(text(s1))
- self._select_desc = self._rebuild_select(text(s2))
+ __hash__ = None # type: ignore[assignment] # Disable hashing.
+
+ def __reduce__(self) -> NoReturn: # Disable pickling.
+ raise TypeError(f"{type(self).__name__} cannot be pickled; convert it
to a list first")
def __bool__(self) -> bool:
return check_query_exists(self._select_asc, session=self._session)
@@ -1951,9 +1928,6 @@ class LazySelectSequence(Sequence[T]):
z = itertools.zip_longest(iter(self), iter(other), fillvalue=object())
return all(x == y for x, y in z)
- def __hash__(self):
- return hash(tuple(x for x in iter(self)))
-
def __reversed__(self) -> Iterator[T]:
return iter(self._process_row(r) for r in
self._session.execute(self._select_desc))
diff --git a/airflow-core/src/airflow/utils/db_cleanup.py
b/airflow-core/src/airflow/utils/db_cleanup.py
index dbf96159615..79a30fc03fa 100644
--- a/airflow-core/src/airflow/utils/db_cleanup.py
+++ b/airflow-core/src/airflow/utils/db_cleanup.py
@@ -642,10 +642,9 @@ def _delete_directly(
dialect_name: str,
) -> None:
pk_cols = list(source_table.primary_key.columns)
- pk_query = limited_query.with_only_columns(
+ rows_to_delete = limited_query.with_only_columns(
*[literal_column(f"{_BASE_TABLE_ALIAS}.{col.name}").label(col.name)
for col in pk_cols]
- )
- rows_to_delete = pk_query.subquery("rows_to_delete")
+ ).subquery("rows_to_delete")
if dialect_name == "mysql":
delete = source_table.delete().where(
diff --git a/airflow-core/src/airflow/utils/sqlalchemy.py
b/airflow-core/src/airflow/utils/sqlalchemy.py
index c120057f727..ac407c7d97c 100644
--- a/airflow-core/src/airflow/utils/sqlalchemy.py
+++ b/airflow-core/src/airflow/utils/sqlalchemy.py
@@ -40,19 +40,30 @@ from airflow.configuration import conf
from airflow.serialization.enums import Encoding
if TYPE_CHECKING:
+ from typing import TypeVarTuple
+
+ import sqlalchemy.sql
from kubernetes.client.models.v1_pod import V1Pod
from sqlalchemy.dialects.mysql.dml import Insert as MySQLInsert
from sqlalchemy.dialects.postgresql.dml import Insert as PostgreSQLInsert
from sqlalchemy.dialects.sqlite.dml import Insert as SQLiteInsert
from sqlalchemy.exc import OperationalError
from sqlalchemy.orm import Session
- from sqlalchemy.sql import Select
from sqlalchemy.types import TypeEngine
- from airflow.typing_compat import Self
+ from airflow.typing_compat import Self, TypeAlias
+
+ _Ts = TypeVarTuple("_Ts")
- # TODO: use Select[UUID] once the minimum SQLAlchemy is 2.1; 2.0 uses
Select[tuple[UUID]].
- UUIDSelect = Select
+ # Spell selects the SQLAlchemy 2.1 way, ``Select[X, Y]``, and this expands
to ``Select[tuple[X, Y]]``
+ # when mypy reads SQLAlchemy 2.0. The constant is set by the
``airflow_mypy.plugins.sqlalchemy_version``
+ # plugin; without it mypy analyses both branches and the alias silently
degrades to ``Select[Any]``.
+ # TODO: Replace with ``sqlalchemy.sql.Select`` once the minimum SQLAlchemy
is 2.1.
+ SQLALCHEMY_2_1 = False
+ if SQLALCHEMY_2_1:
+ Select: TypeAlias = sqlalchemy.sql.Select[*_Ts]
+ else:
+ Select: TypeAlias = sqlalchemy.sql.Select[tuple[*_Ts]]
log = logging.getLogger(__name__)
diff --git a/dev/mypy/README.md b/dev/mypy/README.md
index a2ac1baa5ef..32a047940ca 100644
--- a/dev/mypy/README.md
+++ b/dev/mypy/README.md
@@ -64,3 +64,7 @@ Provides type checking support for Airflow decorators that
modify function signa
### outputs Plugin
Handles type checking for operator outputs and XComArg types, allowing proper
type inference when passing task outputs between tasks.
+
+### sqlalchemy_version Plugin
+
+Used by the Airflow codebase itself. Registers `SQLALCHEMY_2_1` as a constant
that is always true when the installed SQLAlchemy is 2.1 or later, and always
false otherwise, so type aliases can follow the `Select` parameterisation that
changed in SQLAlchemy 2.1.
diff --git a/dev/mypy/src/airflow_mypy/plugins/sqlalchemy_version.py
b/dev/mypy/src/airflow_mypy/plugins/sqlalchemy_version.py
new file mode 100644
index 00000000000..8c5dc2183c4
--- /dev/null
+++ b/dev/mypy/src/airflow_mypy/plugins/sqlalchemy_version.py
@@ -0,0 +1,59 @@
+#
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied. See the License for the
+# specific language governing permissions and limitations
+# under the License.
+from __future__ import annotations
+
+from importlib.metadata import PackageNotFoundError, version
+from typing import TYPE_CHECKING
+
+from mypy.plugin import Plugin
+
+if TYPE_CHECKING:
+ from mypy.options import Options
+
+SQLALCHEMY_2_1_CONSTANT = "SQLALCHEMY_2_1"
+
+
+def is_sqlalchemy_2_1_or_later(sqlalchemy_version: str) -> bool:
+ major, minor = (int(part) for part in sqlalchemy_version.split(".")[:2])
+ return (major, minor) >= (2, 1)
+
+
+class SQLAlchemyVersionPlugin(Plugin):
+ """Expose the installed SQLAlchemy version to mypy as the
``SQLALCHEMY_2_1`` constant.
+
+ SQLAlchemy 2.1 parameterises ``Select`` with a ``TypeVarTuple``
(``Select[X, Y]``) where 2.0
+ takes the row tuple (``Select[tuple[X, Y]]``). Mypy cannot branch on a
library version, so
+ this registers ``SQLALCHEMY_2_1`` as always true or always false, letting
a type alias pick
+ the right spelling for whichever SQLAlchemy mypy is reading.
+ """
+
+ def __init__(self, options: Options) -> None:
+ try:
+ sqlalchemy_version = version("sqlalchemy")
+ except PackageNotFoundError:
+ pass
+ else:
+ if is_sqlalchemy_2_1_or_later(sqlalchemy_version):
+ options.always_true.append(SQLALCHEMY_2_1_CONSTANT)
+ else:
+ options.always_false.append(SQLALCHEMY_2_1_CONSTANT)
+ super().__init__(options)
+
+
+def plugin(version: str):
+ return SQLAlchemyVersionPlugin
diff --git a/dev/mypy/tests/test_plugins.py b/dev/mypy/tests/test_plugins.py
index dc48ca41bc9..8efb11980e9 100644
--- a/dev/mypy/tests/test_plugins.py
+++ b/dev/mypy/tests/test_plugins.py
@@ -17,6 +17,11 @@
# under the License.
from __future__ import annotations
+from importlib.metadata import PackageNotFoundError
+from unittest import mock
+
+import pytest
+
def test_decorators_plugin_import():
"""Test that decorators plugin can be imported."""
@@ -50,3 +55,40 @@ def test_outputs_plugin_entrypoint():
# The plugin function should return a plugin class when called with a
version string
plugin_class = plugin("1.0")
assert plugin_class is not None
+
+
[email protected](
+ ("installed", "always_true", "always_false"),
+ [
+ pytest.param("2.0.57", [], ["SQLALCHEMY_2_1"], id="2.0"),
+ pytest.param("2.1.8", ["SQLALCHEMY_2_1"], [], id="2.1"),
+ pytest.param("2.2.0b1", ["SQLALCHEMY_2_1"], [], id="2.2-prerelease"),
+ ],
+)
[email protected]("airflow_mypy.plugins.sqlalchemy_version.version", autospec=True)
+def test_sqlalchemy_version_plugin_sets_constant(mock_version, installed,
always_true, always_false):
+ from mypy.options import Options
+
+ from airflow_mypy.plugins.sqlalchemy_version import plugin
+
+ mock_version.return_value = installed
+ options = Options()
+ plugin("1.0")(options)
+ assert options.always_true == always_true
+ assert options.always_false == always_false
+
+
[email protected](
+ "airflow_mypy.plugins.sqlalchemy_version.version",
+ autospec=True,
+ side_effect=PackageNotFoundError("sqlalchemy"),
+)
+def test_sqlalchemy_version_plugin_without_sqlalchemy(mock_version):
+ from mypy.options import Options
+
+ from airflow_mypy.plugins.sqlalchemy_version import plugin
+
+ options = Options()
+ plugin("1.0")(options)
+ assert options.always_true == []
+ assert options.always_false == []
diff --git a/dev/pyproject.toml b/dev/pyproject.toml
index d51d5b21a74..f1470de8cad 100644
--- a/dev/pyproject.toml
+++ b/dev/pyproject.toml
@@ -76,6 +76,7 @@ warn_unused_ignores = false
plugins = [
"airflow_mypy.plugins.decorators",
"airflow_mypy.plugins.outputs",
+ "airflow_mypy.plugins.sqlalchemy_version",
]
pretty = true
show_error_codes = true
diff --git a/pyproject.toml b/pyproject.toml
index c87ec8af492..077d1a4cccf 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -1110,6 +1110,7 @@ warn_unused_ignores = false
plugins = [
"airflow_mypy.plugins.decorators",
"airflow_mypy.plugins.outputs",
+ "airflow_mypy.plugins.sqlalchemy_version",
]
pretty = true
show_error_codes = true