Skip to content

Commit 0a12d22

Browse files
Maksim Latyshzzzeek
authored andcommitted
Type annotations for sqlalchemy.orm.dynamic
Closes: #9039 Pull-request: #9039 Pull-request-sha: dae9138 Change-Id: I89a96213558928877abffc450aeeecbbd196aa92
1 parent aea28a9 commit 0a12d22

5 files changed

Lines changed: 219 additions & 127 deletions

File tree

‎lib/sqlalchemy/orm/attributes.py‎

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -791,7 +791,7 @@ class AttributeEventToken:
791791

792792
__slots__ = "impl", "op", "parent_token"
793793

794-
def __init__(self, attribute_impl, op):
794+
def __init__(self, attribute_impl: AttributeImpl, op: util.symbol):
795795
self.impl = attribute_impl
796796
self.op = op
797797
self.parent_token = self.impl.parent_token
@@ -834,7 +834,7 @@ def __init__(
834834
self,
835835
class_: _ExternalEntityType[_O],
836836
key: str,
837-
callable_: _LoaderCallable,
837+
callable_: Optional[_LoaderCallable],
838838
dispatch: _Dispatch[QueryableAttribute[Any]],
839839
trackparent: bool = False,
840840
compare_function: Optional[Callable[..., bool]] = None,
@@ -2618,7 +2618,7 @@ def register_attribute_impl(
26182618
# TODO: this appears to be the WriteOnlyAttributeImpl /
26192619
# DynamicAttributeImpl constructor which is hardcoded
26202620
impl = cast("Type[WriteOnlyAttributeImpl]", impl_class)(
2621-
class_, key, typecallable, dispatch, **kw
2621+
class_, key, dispatch, **kw
26222622
)
26232623
elif uselist:
26242624
impl = CollectionAttributeImpl(

‎lib/sqlalchemy/orm/dynamic.py‎

Lines changed: 58 additions & 35 deletions
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,6 @@
44
#
55
# This module is part of SQLAlchemy and is released under
66
# the MIT License: https://www.opensource.org/licenses/mit-license.php
7-
# mypy: ignore-errors
87

98

109
"""Dynamic collection API.
@@ -23,13 +22,19 @@
2322
from typing import Any
2423
from typing import Iterable
2524
from typing import Iterator
25+
from typing import List
26+
from typing import Optional
27+
from typing import Tuple
28+
from typing import Type
2629
from typing import TYPE_CHECKING
2730
from typing import TypeVar
31+
from typing import Union
2832

2933
from . import attributes
3034
from . import exc as orm_exc
3135
from . import relationships
3236
from . import util as orm_util
37+
from .base import PassiveFlag
3338
from .query import Query
3439
from .session import object_session
3540
from .writeonly import AbstractCollectionWriter
@@ -39,15 +44,28 @@
3944
from .. import util
4045
from ..engine import result
4146

47+
4248
if TYPE_CHECKING:
49+
from . import QueryableAttribute
50+
from .mapper import Mapper
51+
from .relationships import _RelationshipOrderByArg
4352
from .session import Session
44-
53+
from .state import InstanceState
54+
from .util import AliasedClass
55+
from ..event import _Dispatch
56+
from ..sql.elements import ColumnElement
4557

4658
_T = TypeVar("_T", bound=Any)
4759

4860

49-
class DynamicCollectionHistory(WriteOnlyHistory):
50-
def __init__(self, attr, state, passive, apply_to=None):
61+
class DynamicCollectionHistory(WriteOnlyHistory[_T]):
62+
def __init__(
63+
self,
64+
attr: DynamicAttributeImpl,
65+
state: InstanceState[_T],
66+
passive: PassiveFlag,
67+
apply_to: Optional[DynamicCollectionHistory[_T]] = None,
68+
) -> None:
5169
if apply_to:
5270
coll = AppenderQuery(attr, state).autoflush(False)
5371
self.unchanged_items = util.OrderedIdentitySet(coll)
@@ -63,21 +81,21 @@ def __init__(self, attr, state, passive, apply_to=None):
6381

6482
class DynamicAttributeImpl(WriteOnlyAttributeImpl):
6583
_supports_dynamic_iteration = True
66-
collection_history_cls = DynamicCollectionHistory
84+
collection_history_cls = DynamicCollectionHistory[Any]
85+
query_class: Type[AppenderMixin[Any]] # type: ignore[assignment]
6786

6887
def __init__(
6988
self,
70-
class_,
71-
key,
72-
typecallable,
73-
dispatch,
74-
target_mapper,
75-
order_by,
76-
query_class=None,
77-
**kw,
78-
):
89+
class_: Union[Type[Any], AliasedClass[Any]],
90+
key: str,
91+
dispatch: _Dispatch[QueryableAttribute[Any]],
92+
target_mapper: Mapper[_T],
93+
order_by: _RelationshipOrderByArg,
94+
query_class: Optional[Type[AppenderMixin[_T]]] = None,
95+
**kw: Any,
96+
) -> None:
7997
attributes.AttributeImpl.__init__(
80-
self, class_, key, typecallable, dispatch, **kw
98+
self, class_, key, None, dispatch, **kw
8199
)
82100
self.target_mapper = target_mapper
83101
if order_by:
@@ -102,21 +120,23 @@ class AppenderMixin(AbstractCollectionWriter[_T]):
102120
103121
"""
104122

105-
query_class = None
123+
query_class: Optional[Type[Query[_T]]] = None
124+
_order_by_clauses: Tuple[ColumnElement[Any], ...]
106125

107-
def __init__(self, attr, state):
108-
Query.__init__(self, attr.target_mapper, None)
126+
def __init__(
127+
self, attr: DynamicAttributeImpl, state: InstanceState[_T]
128+
) -> None:
129+
Query.__init__(
130+
self, # type: ignore[arg-type]
131+
attr.target_mapper,
132+
None,
133+
)
109134
super().__init__(attr, state)
110135

111136
@property
112-
def session(self) -> Session:
137+
def session(self) -> Optional[Session]:
113138
sess = object_session(self.instance)
114-
if (
115-
sess is not None
116-
and self.autoflush
117-
and sess.autoflush
118-
and self.instance in sess
119-
):
139+
if sess is not None and sess.autoflush and self.instance in sess:
120140
sess.flush()
121141
if not orm_util.has_identity(self.instance):
122142
return None
@@ -127,7 +147,7 @@ def session(self) -> Session:
127147
def session(self, session: Session) -> None:
128148
self.sess = session
129149

130-
def _iter(self):
150+
def _iter(self) -> Union[result.ScalarResult[_T], result.Result[_T]]:
131151
sess = self.session
132152
if sess is None:
133153
state = attributes.instance_state(self.instance)
@@ -141,9 +161,9 @@ def _iter(self):
141161

142162
return result.IteratorResult(
143163
result.SimpleResultMetaData([self.attr.class_.__name__]),
144-
self.attr._get_collection_history(
164+
self.attr._get_collection_history( # type: ignore[arg-type]
145165
attributes.instance_state(self.instance),
146-
attributes.PASSIVE_NO_INITIALIZE,
166+
PassiveFlag.PASSIVE_NO_INITIALIZE,
147167
).added_items,
148168
_source_supports_scalars=True,
149169
).scalars()
@@ -155,29 +175,32 @@ def _iter(self):
155175
def __iter__(self) -> Iterator[_T]:
156176
...
157177

158-
def __getitem__(self, index: Any) -> _T:
178+
def __getitem__(self, index: Any) -> Union[_T, List[_T]]:
159179
sess = self.session
160180
if sess is None:
161181
return self.attr._get_collection_history(
162182
attributes.instance_state(self.instance),
163-
attributes.PASSIVE_NO_INITIALIZE,
183+
PassiveFlag.PASSIVE_NO_INITIALIZE,
164184
).indexed(index)
165185
else:
166-
return self._generate(sess).__getitem__(index)
186+
return self._generate(sess).__getitem__(index) # type: ignore[no-any-return] # noqa: E501
167187

168188
def count(self) -> int:
169189
sess = self.session
170190
if sess is None:
171191
return len(
172192
self.attr._get_collection_history(
173193
attributes.instance_state(self.instance),
174-
attributes.PASSIVE_NO_INITIALIZE,
194+
PassiveFlag.PASSIVE_NO_INITIALIZE,
175195
).added_items
176196
)
177197
else:
178198
return self._generate(sess).count()
179199

180-
def _generate(self, sess=None):
200+
def _generate(
201+
self,
202+
sess: Optional[Session] = None,
203+
) -> Query[_T]:
181204
# note we're returning an entirely new Query class instance
182205
# here without any assignment capabilities; the class of this
183206
# query is determined by the session.
@@ -259,7 +282,7 @@ def remove(self, item: _T) -> None:
259282
self._remove_impl(item)
260283

261284

262-
class AppenderQuery(AppenderMixin[_T], Query[_T]):
285+
class AppenderQuery(AppenderMixin[_T], Query[_T]): # type: ignore[misc]
263286
"""A dynamic query that supports basic collection storage operations.
264287
265288
Methods on :class:`.AppenderQuery` include all methods of
@@ -270,7 +293,7 @@ class AppenderQuery(AppenderMixin[_T], Query[_T]):
270293
"""
271294

272295

273-
def mixin_user_query(cls):
296+
def mixin_user_query(cls: Any) -> type[AppenderMixin[Any]]:
274297
"""Return a new class with AppenderQuery functionality layered over."""
275298
name = "Appender" + cls.__name__
276299
return type(name, (AppenderMixin, cls), {"query_class": cls})

‎lib/sqlalchemy/orm/query.py‎

Lines changed: 7 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -235,7 +235,9 @@ def _propagate_attrs(self) -> _PropagateAttrsType:
235235

236236
def __init__(
237237
self,
238-
entities: Sequence[_ColumnsClauseArgument[Any]],
238+
entities: Union[
239+
_ColumnsClauseArgument[Any], Sequence[_ColumnsClauseArgument[Any]]
240+
],
239241
session: Optional[Session] = None,
240242
):
241243
"""Construct a :class:`_query.Query` directly.
@@ -278,7 +280,10 @@ def _set_propagate_attrs(self, values: Mapping[str, Any]) -> Self:
278280
return self
279281

280282
def _set_entities(
281-
self, entities: Iterable[_ColumnsClauseArgument[Any]]
283+
self,
284+
entities: Union[
285+
_ColumnsClauseArgument[Any], Iterable[_ColumnsClauseArgument[Any]]
286+
],
282287
) -> None:
283288
self._raw_columns = [
284289
coercions.expect(

‎lib/sqlalchemy/orm/relationships.py‎

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -271,6 +271,9 @@ def _resolve_against_registry(
271271
self.resolved = attr_value
272272

273273

274+
_RelationshipOrderByArg = Union[Literal[False], Tuple[ColumnElement[Any], ...]]
275+
276+
274277
class _RelationshipArgs(NamedTuple):
275278
"""stores user-passed parameters that are resolved at mapper configuration
276279
time.
@@ -289,10 +292,7 @@ class _RelationshipArgs(NamedTuple):
289292
Optional[_RelationshipJoinConditionArgument],
290293
Optional[ColumnElement[Any]],
291294
]
292-
order_by: _RelationshipArg[
293-
_ORMOrderByArgument,
294-
Union[Literal[None, False], Tuple[ColumnElement[Any], ...]],
295-
]
295+
order_by: _RelationshipArg[_ORMOrderByArgument, _RelationshipOrderByArg]
296296
foreign_keys: _RelationshipArg[
297297
Optional[_ORMColCollectionArgument], Set[ColumnElement[Any]]
298298
]
@@ -341,7 +341,7 @@ class RelationshipProperty(
341341
secondaryjoin: Optional[ColumnElement[bool]]
342342
secondary: Optional[FromClause]
343343
_join_condition: JoinCondition
344-
order_by: Union[Literal[False], Tuple[ColumnElement[Any], ...]]
344+
order_by: _RelationshipOrderByArg
345345

346346
_user_defined_foreign_keys: Set[ColumnElement[Any]]
347347
_calculated_foreign_keys: Set[ColumnElement[Any]]

0 commit comments

Comments
 (0)