SQLAlchemy 2.0.36__cp313-cp313-win32.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (273) hide show
  1. SQLAlchemy-2.0.36.dist-info/LICENSE +19 -0
  2. SQLAlchemy-2.0.36.dist-info/METADATA +243 -0
  3. SQLAlchemy-2.0.36.dist-info/RECORD +273 -0
  4. SQLAlchemy-2.0.36.dist-info/WHEEL +5 -0
  5. SQLAlchemy-2.0.36.dist-info/top_level.txt +1 -0
  6. sqlalchemy/__init__.py +294 -0
  7. sqlalchemy/connectors/__init__.py +18 -0
  8. sqlalchemy/connectors/aioodbc.py +174 -0
  9. sqlalchemy/connectors/asyncio.py +213 -0
  10. sqlalchemy/connectors/pyodbc.py +249 -0
  11. sqlalchemy/cyextension/__init__.py +6 -0
  12. sqlalchemy/cyextension/collections.cp313-win32.pyd +0 -0
  13. sqlalchemy/cyextension/collections.pyx +409 -0
  14. sqlalchemy/cyextension/immutabledict.cp313-win32.pyd +0 -0
  15. sqlalchemy/cyextension/immutabledict.pxd +8 -0
  16. sqlalchemy/cyextension/immutabledict.pyx +133 -0
  17. sqlalchemy/cyextension/processors.cp313-win32.pyd +0 -0
  18. sqlalchemy/cyextension/processors.pyx +68 -0
  19. sqlalchemy/cyextension/resultproxy.cp313-win32.pyd +0 -0
  20. sqlalchemy/cyextension/resultproxy.pyx +102 -0
  21. sqlalchemy/cyextension/util.cp313-win32.pyd +0 -0
  22. sqlalchemy/cyextension/util.pyx +91 -0
  23. sqlalchemy/dialects/__init__.py +61 -0
  24. sqlalchemy/dialects/_typing.py +25 -0
  25. sqlalchemy/dialects/mssql/__init__.py +88 -0
  26. sqlalchemy/dialects/mssql/aioodbc.py +64 -0
  27. sqlalchemy/dialects/mssql/base.py +4010 -0
  28. sqlalchemy/dialects/mssql/information_schema.py +254 -0
  29. sqlalchemy/dialects/mssql/json.py +133 -0
  30. sqlalchemy/dialects/mssql/provision.py +162 -0
  31. sqlalchemy/dialects/mssql/pymssql.py +126 -0
  32. sqlalchemy/dialects/mssql/pyodbc.py +745 -0
  33. sqlalchemy/dialects/mysql/__init__.py +101 -0
  34. sqlalchemy/dialects/mysql/aiomysql.py +333 -0
  35. sqlalchemy/dialects/mysql/asyncmy.py +337 -0
  36. sqlalchemy/dialects/mysql/base.py +3494 -0
  37. sqlalchemy/dialects/mysql/cymysql.py +84 -0
  38. sqlalchemy/dialects/mysql/dml.py +219 -0
  39. sqlalchemy/dialects/mysql/enumerated.py +244 -0
  40. sqlalchemy/dialects/mysql/expression.py +141 -0
  41. sqlalchemy/dialects/mysql/json.py +81 -0
  42. sqlalchemy/dialects/mysql/mariadb.py +32 -0
  43. sqlalchemy/dialects/mysql/mariadbconnector.py +277 -0
  44. sqlalchemy/dialects/mysql/mysqlconnector.py +180 -0
  45. sqlalchemy/dialects/mysql/mysqldb.py +303 -0
  46. sqlalchemy/dialects/mysql/provision.py +110 -0
  47. sqlalchemy/dialects/mysql/pymysql.py +137 -0
  48. sqlalchemy/dialects/mysql/pyodbc.py +138 -0
  49. sqlalchemy/dialects/mysql/reflection.py +677 -0
  50. sqlalchemy/dialects/mysql/reserved_words.py +571 -0
  51. sqlalchemy/dialects/mysql/types.py +774 -0
  52. sqlalchemy/dialects/oracle/__init__.py +67 -0
  53. sqlalchemy/dialects/oracle/base.py +3271 -0
  54. sqlalchemy/dialects/oracle/cx_oracle.py +1483 -0
  55. sqlalchemy/dialects/oracle/dictionary.py +507 -0
  56. sqlalchemy/dialects/oracle/oracledb.py +431 -0
  57. sqlalchemy/dialects/oracle/provision.py +220 -0
  58. sqlalchemy/dialects/oracle/types.py +287 -0
  59. sqlalchemy/dialects/postgresql/__init__.py +167 -0
  60. sqlalchemy/dialects/postgresql/_psycopg_common.py +187 -0
  61. sqlalchemy/dialects/postgresql/array.py +425 -0
  62. sqlalchemy/dialects/postgresql/asyncpg.py +1274 -0
  63. sqlalchemy/dialects/postgresql/base.py +5008 -0
  64. sqlalchemy/dialects/postgresql/dml.py +310 -0
  65. sqlalchemy/dialects/postgresql/ext.py +496 -0
  66. sqlalchemy/dialects/postgresql/hstore.py +397 -0
  67. sqlalchemy/dialects/postgresql/json.py +333 -0
  68. sqlalchemy/dialects/postgresql/named_types.py +509 -0
  69. sqlalchemy/dialects/postgresql/operators.py +129 -0
  70. sqlalchemy/dialects/postgresql/pg8000.py +662 -0
  71. sqlalchemy/dialects/postgresql/pg_catalog.py +300 -0
  72. sqlalchemy/dialects/postgresql/provision.py +175 -0
  73. sqlalchemy/dialects/postgresql/psycopg.py +772 -0
  74. sqlalchemy/dialects/postgresql/psycopg2.py +886 -0
  75. sqlalchemy/dialects/postgresql/psycopg2cffi.py +61 -0
  76. sqlalchemy/dialects/postgresql/ranges.py +1029 -0
  77. sqlalchemy/dialects/postgresql/types.py +303 -0
  78. sqlalchemy/dialects/sqlite/__init__.py +57 -0
  79. sqlalchemy/dialects/sqlite/aiosqlite.py +396 -0
  80. sqlalchemy/dialects/sqlite/base.py +2805 -0
  81. sqlalchemy/dialects/sqlite/dml.py +240 -0
  82. sqlalchemy/dialects/sqlite/json.py +92 -0
  83. sqlalchemy/dialects/sqlite/provision.py +198 -0
  84. sqlalchemy/dialects/sqlite/pysqlcipher.py +155 -0
  85. sqlalchemy/dialects/sqlite/pysqlite.py +756 -0
  86. sqlalchemy/dialects/type_migration_guidelines.txt +145 -0
  87. sqlalchemy/engine/__init__.py +62 -0
  88. sqlalchemy/engine/_py_processors.py +136 -0
  89. sqlalchemy/engine/_py_row.py +128 -0
  90. sqlalchemy/engine/_py_util.py +74 -0
  91. sqlalchemy/engine/base.py +3375 -0
  92. sqlalchemy/engine/characteristics.py +155 -0
  93. sqlalchemy/engine/create.py +875 -0
  94. sqlalchemy/engine/cursor.py +2181 -0
  95. sqlalchemy/engine/default.py +2365 -0
  96. sqlalchemy/engine/events.py +951 -0
  97. sqlalchemy/engine/interfaces.py +3403 -0
  98. sqlalchemy/engine/mock.py +131 -0
  99. sqlalchemy/engine/processors.py +61 -0
  100. sqlalchemy/engine/reflection.py +2098 -0
  101. sqlalchemy/engine/result.py +2382 -0
  102. sqlalchemy/engine/row.py +401 -0
  103. sqlalchemy/engine/strategies.py +19 -0
  104. sqlalchemy/engine/url.py +910 -0
  105. sqlalchemy/engine/util.py +167 -0
  106. sqlalchemy/event/__init__.py +25 -0
  107. sqlalchemy/event/api.py +225 -0
  108. sqlalchemy/event/attr.py +655 -0
  109. sqlalchemy/event/base.py +470 -0
  110. sqlalchemy/event/legacy.py +246 -0
  111. sqlalchemy/event/registry.py +386 -0
  112. sqlalchemy/events.py +17 -0
  113. sqlalchemy/exc.py +830 -0
  114. sqlalchemy/ext/__init__.py +11 -0
  115. sqlalchemy/ext/associationproxy.py +2013 -0
  116. sqlalchemy/ext/asyncio/__init__.py +25 -0
  117. sqlalchemy/ext/asyncio/base.py +279 -0
  118. sqlalchemy/ext/asyncio/engine.py +1466 -0
  119. sqlalchemy/ext/asyncio/exc.py +21 -0
  120. sqlalchemy/ext/asyncio/result.py +961 -0
  121. sqlalchemy/ext/asyncio/scoping.py +1614 -0
  122. sqlalchemy/ext/asyncio/session.py +1936 -0
  123. sqlalchemy/ext/automap.py +1691 -0
  124. sqlalchemy/ext/baked.py +574 -0
  125. sqlalchemy/ext/compiler.py +570 -0
  126. sqlalchemy/ext/declarative/__init__.py +65 -0
  127. sqlalchemy/ext/declarative/extensions.py +548 -0
  128. sqlalchemy/ext/horizontal_shard.py +481 -0
  129. sqlalchemy/ext/hybrid.py +1514 -0
  130. sqlalchemy/ext/indexable.py +341 -0
  131. sqlalchemy/ext/instrumentation.py +450 -0
  132. sqlalchemy/ext/mutable.py +1073 -0
  133. sqlalchemy/ext/mypy/__init__.py +6 -0
  134. sqlalchemy/ext/mypy/apply.py +320 -0
  135. sqlalchemy/ext/mypy/decl_class.py +515 -0
  136. sqlalchemy/ext/mypy/infer.py +590 -0
  137. sqlalchemy/ext/mypy/names.py +335 -0
  138. sqlalchemy/ext/mypy/plugin.py +303 -0
  139. sqlalchemy/ext/mypy/util.py +357 -0
  140. sqlalchemy/ext/orderinglist.py +416 -0
  141. sqlalchemy/ext/serializer.py +181 -0
  142. sqlalchemy/future/__init__.py +16 -0
  143. sqlalchemy/future/engine.py +15 -0
  144. sqlalchemy/inspection.py +174 -0
  145. sqlalchemy/log.py +288 -0
  146. sqlalchemy/orm/__init__.py +170 -0
  147. sqlalchemy/orm/_orm_constructors.py +2571 -0
  148. sqlalchemy/orm/_typing.py +179 -0
  149. sqlalchemy/orm/attributes.py +2835 -0
  150. sqlalchemy/orm/base.py +973 -0
  151. sqlalchemy/orm/bulk_persistence.py +2123 -0
  152. sqlalchemy/orm/clsregistry.py +571 -0
  153. sqlalchemy/orm/collections.py +1620 -0
  154. sqlalchemy/orm/context.py +3268 -0
  155. sqlalchemy/orm/decl_api.py +1883 -0
  156. sqlalchemy/orm/decl_base.py +2190 -0
  157. sqlalchemy/orm/dependency.py +1304 -0
  158. sqlalchemy/orm/descriptor_props.py +1076 -0
  159. sqlalchemy/orm/dynamic.py +300 -0
  160. sqlalchemy/orm/evaluator.py +379 -0
  161. sqlalchemy/orm/events.py +3261 -0
  162. sqlalchemy/orm/exc.py +228 -0
  163. sqlalchemy/orm/identity.py +302 -0
  164. sqlalchemy/orm/instrumentation.py +754 -0
  165. sqlalchemy/orm/interfaces.py +1474 -0
  166. sqlalchemy/orm/loading.py +1682 -0
  167. sqlalchemy/orm/mapped_collection.py +557 -0
  168. sqlalchemy/orm/mapper.py +4432 -0
  169. sqlalchemy/orm/path_registry.py +811 -0
  170. sqlalchemy/orm/persistence.py +1782 -0
  171. sqlalchemy/orm/properties.py +886 -0
  172. sqlalchemy/orm/query.py +3396 -0
  173. sqlalchemy/orm/relationships.py +3500 -0
  174. sqlalchemy/orm/scoping.py +2165 -0
  175. sqlalchemy/orm/session.py +5301 -0
  176. sqlalchemy/orm/state.py +1143 -0
  177. sqlalchemy/orm/state_changes.py +198 -0
  178. sqlalchemy/orm/strategies.py +3473 -0
  179. sqlalchemy/orm/strategy_options.py +2569 -0
  180. sqlalchemy/orm/sync.py +164 -0
  181. sqlalchemy/orm/unitofwork.py +796 -0
  182. sqlalchemy/orm/util.py +2424 -0
  183. sqlalchemy/orm/writeonly.py +678 -0
  184. sqlalchemy/pool/__init__.py +44 -0
  185. sqlalchemy/pool/base.py +1515 -0
  186. sqlalchemy/pool/events.py +370 -0
  187. sqlalchemy/pool/impl.py +581 -0
  188. sqlalchemy/py.typed +0 -0
  189. sqlalchemy/schema.py +70 -0
  190. sqlalchemy/sql/__init__.py +145 -0
  191. sqlalchemy/sql/_dml_constructors.py +140 -0
  192. sqlalchemy/sql/_elements_constructors.py +1850 -0
  193. sqlalchemy/sql/_orm_types.py +20 -0
  194. sqlalchemy/sql/_py_util.py +75 -0
  195. sqlalchemy/sql/_selectable_constructors.py +635 -0
  196. sqlalchemy/sql/_typing.py +460 -0
  197. sqlalchemy/sql/annotation.py +585 -0
  198. sqlalchemy/sql/base.py +2185 -0
  199. sqlalchemy/sql/cache_key.py +1057 -0
  200. sqlalchemy/sql/coercions.py +1405 -0
  201. sqlalchemy/sql/compiler.py +7818 -0
  202. sqlalchemy/sql/crud.py +1669 -0
  203. sqlalchemy/sql/ddl.py +1378 -0
  204. sqlalchemy/sql/default_comparator.py +552 -0
  205. sqlalchemy/sql/dml.py +1817 -0
  206. sqlalchemy/sql/elements.py +5499 -0
  207. sqlalchemy/sql/events.py +455 -0
  208. sqlalchemy/sql/expression.py +162 -0
  209. sqlalchemy/sql/functions.py +2055 -0
  210. sqlalchemy/sql/lambdas.py +1449 -0
  211. sqlalchemy/sql/naming.py +212 -0
  212. sqlalchemy/sql/operators.py +2579 -0
  213. sqlalchemy/sql/roles.py +323 -0
  214. sqlalchemy/sql/schema.py +6158 -0
  215. sqlalchemy/sql/selectable.py +7004 -0
  216. sqlalchemy/sql/sqltypes.py +3827 -0
  217. sqlalchemy/sql/traversals.py +1024 -0
  218. sqlalchemy/sql/type_api.py +2339 -0
  219. sqlalchemy/sql/util.py +1486 -0
  220. sqlalchemy/sql/visitors.py +1165 -0
  221. sqlalchemy/testing/__init__.py +96 -0
  222. sqlalchemy/testing/assertions.py +989 -0
  223. sqlalchemy/testing/assertsql.py +516 -0
  224. sqlalchemy/testing/asyncio.py +135 -0
  225. sqlalchemy/testing/config.py +427 -0
  226. sqlalchemy/testing/engines.py +472 -0
  227. sqlalchemy/testing/entities.py +117 -0
  228. sqlalchemy/testing/exclusions.py +435 -0
  229. sqlalchemy/testing/fixtures/__init__.py +28 -0
  230. sqlalchemy/testing/fixtures/base.py +366 -0
  231. sqlalchemy/testing/fixtures/mypy.py +312 -0
  232. sqlalchemy/testing/fixtures/orm.py +227 -0
  233. sqlalchemy/testing/fixtures/sql.py +503 -0
  234. sqlalchemy/testing/pickleable.py +155 -0
  235. sqlalchemy/testing/plugin/__init__.py +6 -0
  236. sqlalchemy/testing/plugin/bootstrap.py +51 -0
  237. sqlalchemy/testing/plugin/plugin_base.py +779 -0
  238. sqlalchemy/testing/plugin/pytestplugin.py +868 -0
  239. sqlalchemy/testing/profiling.py +324 -0
  240. sqlalchemy/testing/provision.py +496 -0
  241. sqlalchemy/testing/requirements.py +1818 -0
  242. sqlalchemy/testing/schema.py +224 -0
  243. sqlalchemy/testing/suite/__init__.py +19 -0
  244. sqlalchemy/testing/suite/test_cte.py +211 -0
  245. sqlalchemy/testing/suite/test_ddl.py +389 -0
  246. sqlalchemy/testing/suite/test_deprecations.py +153 -0
  247. sqlalchemy/testing/suite/test_dialect.py +740 -0
  248. sqlalchemy/testing/suite/test_insert.py +630 -0
  249. sqlalchemy/testing/suite/test_reflection.py +3225 -0
  250. sqlalchemy/testing/suite/test_results.py +502 -0
  251. sqlalchemy/testing/suite/test_rowcount.py +258 -0
  252. sqlalchemy/testing/suite/test_select.py +1999 -0
  253. sqlalchemy/testing/suite/test_sequence.py +317 -0
  254. sqlalchemy/testing/suite/test_types.py +2141 -0
  255. sqlalchemy/testing/suite/test_unicode_ddl.py +189 -0
  256. sqlalchemy/testing/suite/test_update_delete.py +139 -0
  257. sqlalchemy/testing/util.py +537 -0
  258. sqlalchemy/testing/warnings.py +52 -0
  259. sqlalchemy/types.py +76 -0
  260. sqlalchemy/util/__init__.py +160 -0
  261. sqlalchemy/util/_collections.py +715 -0
  262. sqlalchemy/util/_concurrency_py3k.py +288 -0
  263. sqlalchemy/util/_has_cy.py +40 -0
  264. sqlalchemy/util/_py_collections.py +541 -0
  265. sqlalchemy/util/compat.py +301 -0
  266. sqlalchemy/util/concurrency.py +108 -0
  267. sqlalchemy/util/deprecations.py +401 -0
  268. sqlalchemy/util/langhelpers.py +2218 -0
  269. sqlalchemy/util/preloaded.py +150 -0
  270. sqlalchemy/util/queue.py +322 -0
  271. sqlalchemy/util/tool_support.py +201 -0
  272. sqlalchemy/util/topological.py +120 -0
  273. sqlalchemy/util/typing.py +629 -0
@@ -0,0 +1,3396 @@
1
+ # orm/query.py
2
+ # Copyright (C) 2005-2024 the SQLAlchemy authors and contributors
3
+ # <see AUTHORS file>
4
+ #
5
+ # This module is part of SQLAlchemy and is released under
6
+ # the MIT License: https://www.opensource.org/licenses/mit-license.php
7
+
8
+ """The Query class and support.
9
+
10
+ Defines the :class:`_query.Query` class, the central
11
+ construct used by the ORM to construct database queries.
12
+
13
+ The :class:`_query.Query` class should not be confused with the
14
+ :class:`_expression.Select` class, which defines database
15
+ SELECT operations at the SQL (non-ORM) level. ``Query`` differs from
16
+ ``Select`` in that it returns ORM-mapped objects and interacts with an
17
+ ORM session, whereas the ``Select`` construct interacts directly with the
18
+ database to return iterable result sets.
19
+
20
+ """
21
+ from __future__ import annotations
22
+
23
+ import collections.abc as collections_abc
24
+ import operator
25
+ from typing import Any
26
+ from typing import Callable
27
+ from typing import cast
28
+ from typing import Dict
29
+ from typing import Generic
30
+ from typing import Iterable
31
+ from typing import Iterator
32
+ from typing import List
33
+ from typing import Mapping
34
+ from typing import Optional
35
+ from typing import overload
36
+ from typing import Sequence
37
+ from typing import Tuple
38
+ from typing import Type
39
+ from typing import TYPE_CHECKING
40
+ from typing import TypeVar
41
+ from typing import Union
42
+
43
+ from . import attributes
44
+ from . import interfaces
45
+ from . import loading
46
+ from . import util as orm_util
47
+ from ._typing import _O
48
+ from .base import _assertions
49
+ from .context import _column_descriptions
50
+ from .context import _determine_last_joined_entity
51
+ from .context import _legacy_filter_by_entity_zero
52
+ from .context import FromStatement
53
+ from .context import ORMCompileState
54
+ from .context import QueryContext
55
+ from .interfaces import ORMColumnDescription
56
+ from .interfaces import ORMColumnsClauseRole
57
+ from .util import AliasedClass
58
+ from .util import object_mapper
59
+ from .util import with_parent
60
+ from .. import exc as sa_exc
61
+ from .. import inspect
62
+ from .. import inspection
63
+ from .. import log
64
+ from .. import sql
65
+ from .. import util
66
+ from ..engine import Result
67
+ from ..engine import Row
68
+ from ..event import dispatcher
69
+ from ..event import EventTarget
70
+ from ..sql import coercions
71
+ from ..sql import expression
72
+ from ..sql import roles
73
+ from ..sql import Select
74
+ from ..sql import util as sql_util
75
+ from ..sql import visitors
76
+ from ..sql._typing import _FromClauseArgument
77
+ from ..sql._typing import _TP
78
+ from ..sql.annotation import SupportsCloneAnnotations
79
+ from ..sql.base import _entity_namespace_key
80
+ from ..sql.base import _generative
81
+ from ..sql.base import _NoArg
82
+ from ..sql.base import Executable
83
+ from ..sql.base import Generative
84
+ from ..sql.elements import BooleanClauseList
85
+ from ..sql.expression import Exists
86
+ from ..sql.selectable import _MemoizedSelectEntities
87
+ from ..sql.selectable import _SelectFromElements
88
+ from ..sql.selectable import ForUpdateArg
89
+ from ..sql.selectable import HasHints
90
+ from ..sql.selectable import HasPrefixes
91
+ from ..sql.selectable import HasSuffixes
92
+ from ..sql.selectable import LABEL_STYLE_TABLENAME_PLUS_COL
93
+ from ..sql.selectable import SelectLabelStyle
94
+ from ..util.typing import Literal
95
+ from ..util.typing import Self
96
+
97
+
98
+ if TYPE_CHECKING:
99
+ from ._typing import _EntityType
100
+ from ._typing import _ExternalEntityType
101
+ from ._typing import _InternalEntityType
102
+ from ._typing import SynchronizeSessionArgument
103
+ from .mapper import Mapper
104
+ from .path_registry import PathRegistry
105
+ from .session import _PKIdentityArgument
106
+ from .session import Session
107
+ from .state import InstanceState
108
+ from ..engine.cursor import CursorResult
109
+ from ..engine.interfaces import _ImmutableExecuteOptions
110
+ from ..engine.interfaces import CompiledCacheType
111
+ from ..engine.interfaces import IsolationLevel
112
+ from ..engine.interfaces import SchemaTranslateMapType
113
+ from ..engine.result import FrozenResult
114
+ from ..engine.result import ScalarResult
115
+ from ..sql._typing import _ColumnExpressionArgument
116
+ from ..sql._typing import _ColumnExpressionOrStrLabelArgument
117
+ from ..sql._typing import _ColumnsClauseArgument
118
+ from ..sql._typing import _DMLColumnArgument
119
+ from ..sql._typing import _JoinTargetArgument
120
+ from ..sql._typing import _LimitOffsetType
121
+ from ..sql._typing import _MAYBE_ENTITY
122
+ from ..sql._typing import _no_kw
123
+ from ..sql._typing import _NOT_ENTITY
124
+ from ..sql._typing import _OnClauseArgument
125
+ from ..sql._typing import _PropagateAttrsType
126
+ from ..sql._typing import _T0
127
+ from ..sql._typing import _T1
128
+ from ..sql._typing import _T2
129
+ from ..sql._typing import _T3
130
+ from ..sql._typing import _T4
131
+ from ..sql._typing import _T5
132
+ from ..sql._typing import _T6
133
+ from ..sql._typing import _T7
134
+ from ..sql._typing import _TypedColumnClauseArgument as _TCCA
135
+ from ..sql.base import CacheableOptions
136
+ from ..sql.base import ExecutableOption
137
+ from ..sql.elements import ColumnElement
138
+ from ..sql.elements import Label
139
+ from ..sql.selectable import _ForUpdateOfArgument
140
+ from ..sql.selectable import _JoinTargetElement
141
+ from ..sql.selectable import _SetupJoinsElement
142
+ from ..sql.selectable import Alias
143
+ from ..sql.selectable import CTE
144
+ from ..sql.selectable import ExecutableReturnsRows
145
+ from ..sql.selectable import FromClause
146
+ from ..sql.selectable import ScalarSelect
147
+ from ..sql.selectable import Subquery
148
+
149
+
150
+ __all__ = ["Query", "QueryContext"]
151
+
152
+ _T = TypeVar("_T", bound=Any)
153
+
154
+
155
+ @inspection._self_inspects
156
+ @log.class_logger
157
+ class Query(
158
+ _SelectFromElements,
159
+ SupportsCloneAnnotations,
160
+ HasPrefixes,
161
+ HasSuffixes,
162
+ HasHints,
163
+ EventTarget,
164
+ log.Identified,
165
+ Generative,
166
+ Executable,
167
+ Generic[_T],
168
+ ):
169
+ """ORM-level SQL construction object.
170
+
171
+ .. legacy:: The ORM :class:`.Query` object is a legacy construct
172
+ as of SQLAlchemy 2.0. See the notes at the top of
173
+ :ref:`query_api_toplevel` for an overview, including links to migration
174
+ documentation.
175
+
176
+ :class:`_query.Query` objects are normally initially generated using the
177
+ :meth:`~.Session.query` method of :class:`.Session`, and in
178
+ less common cases by instantiating the :class:`_query.Query` directly and
179
+ associating with a :class:`.Session` using the
180
+ :meth:`_query.Query.with_session`
181
+ method.
182
+
183
+ """
184
+
185
+ # elements that are in Core and can be cached in the same way
186
+ _where_criteria: Tuple[ColumnElement[Any], ...] = ()
187
+ _having_criteria: Tuple[ColumnElement[Any], ...] = ()
188
+
189
+ _order_by_clauses: Tuple[ColumnElement[Any], ...] = ()
190
+ _group_by_clauses: Tuple[ColumnElement[Any], ...] = ()
191
+ _limit_clause: Optional[ColumnElement[Any]] = None
192
+ _offset_clause: Optional[ColumnElement[Any]] = None
193
+
194
+ _distinct: bool = False
195
+ _distinct_on: Tuple[ColumnElement[Any], ...] = ()
196
+
197
+ _for_update_arg: Optional[ForUpdateArg] = None
198
+ _correlate: Tuple[FromClause, ...] = ()
199
+ _auto_correlate: bool = True
200
+ _from_obj: Tuple[FromClause, ...] = ()
201
+ _setup_joins: Tuple[_SetupJoinsElement, ...] = ()
202
+
203
+ _label_style: SelectLabelStyle = SelectLabelStyle.LABEL_STYLE_LEGACY_ORM
204
+
205
+ _memoized_select_entities = ()
206
+
207
+ _compile_options: Union[Type[CacheableOptions], CacheableOptions] = (
208
+ ORMCompileState.default_compile_options
209
+ )
210
+
211
+ _with_options: Tuple[ExecutableOption, ...]
212
+ load_options = QueryContext.default_load_options + {
213
+ "_legacy_uniquing": True
214
+ }
215
+
216
+ _params: util.immutabledict[str, Any] = util.EMPTY_DICT
217
+
218
+ # local Query builder state, not needed for
219
+ # compilation or execution
220
+ _enable_assertions = True
221
+
222
+ _statement: Optional[ExecutableReturnsRows] = None
223
+
224
+ session: Session
225
+
226
+ dispatch: dispatcher[Query[_T]]
227
+
228
+ # mirrors that of ClauseElement, used to propagate the "orm"
229
+ # plugin as well as the "subject" of the plugin, e.g. the mapper
230
+ # we are querying against.
231
+ @util.memoized_property
232
+ def _propagate_attrs(self) -> _PropagateAttrsType:
233
+ return util.EMPTY_DICT
234
+
235
+ def __init__(
236
+ self,
237
+ entities: Union[
238
+ _ColumnsClauseArgument[Any], Sequence[_ColumnsClauseArgument[Any]]
239
+ ],
240
+ session: Optional[Session] = None,
241
+ ):
242
+ """Construct a :class:`_query.Query` directly.
243
+
244
+ E.g.::
245
+
246
+ q = Query([User, Address], session=some_session)
247
+
248
+ The above is equivalent to::
249
+
250
+ q = some_session.query(User, Address)
251
+
252
+ :param entities: a sequence of entities and/or SQL expressions.
253
+
254
+ :param session: a :class:`.Session` with which the
255
+ :class:`_query.Query`
256
+ will be associated. Optional; a :class:`_query.Query`
257
+ can be associated
258
+ with a :class:`.Session` generatively via the
259
+ :meth:`_query.Query.with_session` method as well.
260
+
261
+ .. seealso::
262
+
263
+ :meth:`.Session.query`
264
+
265
+ :meth:`_query.Query.with_session`
266
+
267
+ """
268
+
269
+ # session is usually present. There's one case in subqueryloader
270
+ # where it stores a Query without a Session and also there are tests
271
+ # for the query(Entity).with_session(session) API which is likely in
272
+ # some old recipes, however these are legacy as select() can now be
273
+ # used.
274
+ self.session = session # type: ignore
275
+ self._set_entities(entities)
276
+
277
+ def _set_propagate_attrs(self, values: Mapping[str, Any]) -> Self:
278
+ self._propagate_attrs = util.immutabledict(values)
279
+ return self
280
+
281
+ def _set_entities(
282
+ self,
283
+ entities: Union[
284
+ _ColumnsClauseArgument[Any], Iterable[_ColumnsClauseArgument[Any]]
285
+ ],
286
+ ) -> None:
287
+ self._raw_columns = [
288
+ coercions.expect(
289
+ roles.ColumnsClauseRole,
290
+ ent,
291
+ apply_propagate_attrs=self,
292
+ post_inspect=True,
293
+ )
294
+ for ent in util.to_list(entities)
295
+ ]
296
+
297
+ def tuples(self: Query[_O]) -> Query[Tuple[_O]]:
298
+ """return a tuple-typed form of this :class:`.Query`.
299
+
300
+ This method invokes the :meth:`.Query.only_return_tuples`
301
+ method with a value of ``True``, which by itself ensures that this
302
+ :class:`.Query` will always return :class:`.Row` objects, even
303
+ if the query is made against a single entity. It then also
304
+ at the typing level will return a "typed" query, if possible,
305
+ that will type result rows as ``Tuple`` objects with typed
306
+ elements.
307
+
308
+ This method can be compared to the :meth:`.Result.tuples` method,
309
+ which returns "self", but from a typing perspective returns an object
310
+ that will yield typed ``Tuple`` objects for results. Typing
311
+ takes effect only if this :class:`.Query` object is a typed
312
+ query object already.
313
+
314
+ .. versionadded:: 2.0
315
+
316
+ .. seealso::
317
+
318
+ :meth:`.Result.tuples` - v2 equivalent method.
319
+
320
+ """
321
+ return self.only_return_tuples(True) # type: ignore
322
+
323
+ def _entity_from_pre_ent_zero(self) -> Optional[_InternalEntityType[Any]]:
324
+ if not self._raw_columns:
325
+ return None
326
+
327
+ ent = self._raw_columns[0]
328
+
329
+ if "parententity" in ent._annotations:
330
+ return ent._annotations["parententity"] # type: ignore
331
+ elif "bundle" in ent._annotations:
332
+ return ent._annotations["bundle"] # type: ignore
333
+ else:
334
+ # label, other SQL expression
335
+ for element in visitors.iterate(ent):
336
+ if "parententity" in element._annotations:
337
+ return element._annotations["parententity"] # type: ignore # noqa: E501
338
+ else:
339
+ return None
340
+
341
+ def _only_full_mapper_zero(self, methname: str) -> Mapper[Any]:
342
+ if (
343
+ len(self._raw_columns) != 1
344
+ or "parententity" not in self._raw_columns[0]._annotations
345
+ or not self._raw_columns[0].is_selectable
346
+ ):
347
+ raise sa_exc.InvalidRequestError(
348
+ "%s() can only be used against "
349
+ "a single mapped class." % methname
350
+ )
351
+
352
+ return self._raw_columns[0]._annotations["parententity"] # type: ignore # noqa: E501
353
+
354
+ def _set_select_from(
355
+ self, obj: Iterable[_FromClauseArgument], set_base_alias: bool
356
+ ) -> None:
357
+ fa = [
358
+ coercions.expect(
359
+ roles.StrictFromClauseRole,
360
+ elem,
361
+ allow_select=True,
362
+ apply_propagate_attrs=self,
363
+ )
364
+ for elem in obj
365
+ ]
366
+
367
+ self._compile_options += {"_set_base_alias": set_base_alias}
368
+ self._from_obj = tuple(fa)
369
+
370
+ @_generative
371
+ def _set_lazyload_from(self, state: InstanceState[Any]) -> Self:
372
+ self.load_options += {"_lazy_loaded_from": state}
373
+ return self
374
+
375
+ def _get_condition(self) -> None:
376
+ """used by legacy BakedQuery"""
377
+ self._no_criterion_condition("get", order_by=False, distinct=False)
378
+
379
+ def _get_existing_condition(self) -> None:
380
+ self._no_criterion_assertion("get", order_by=False, distinct=False)
381
+
382
+ def _no_criterion_assertion(
383
+ self, meth: str, order_by: bool = True, distinct: bool = True
384
+ ) -> None:
385
+ if not self._enable_assertions:
386
+ return
387
+ if (
388
+ self._where_criteria
389
+ or self._statement is not None
390
+ or self._from_obj
391
+ or self._setup_joins
392
+ or self._limit_clause is not None
393
+ or self._offset_clause is not None
394
+ or self._group_by_clauses
395
+ or (order_by and self._order_by_clauses)
396
+ or (distinct and self._distinct)
397
+ ):
398
+ raise sa_exc.InvalidRequestError(
399
+ "Query.%s() being called on a "
400
+ "Query with existing criterion. " % meth
401
+ )
402
+
403
+ def _no_criterion_condition(
404
+ self, meth: str, order_by: bool = True, distinct: bool = True
405
+ ) -> None:
406
+ self._no_criterion_assertion(meth, order_by, distinct)
407
+
408
+ self._from_obj = self._setup_joins = ()
409
+ if self._statement is not None:
410
+ self._compile_options += {"_statement": None}
411
+ self._where_criteria = ()
412
+ self._distinct = False
413
+
414
+ self._order_by_clauses = self._group_by_clauses = ()
415
+
416
+ def _no_clauseelement_condition(self, meth: str) -> None:
417
+ if not self._enable_assertions:
418
+ return
419
+ if self._order_by_clauses:
420
+ raise sa_exc.InvalidRequestError(
421
+ "Query.%s() being called on a "
422
+ "Query with existing criterion. " % meth
423
+ )
424
+ self._no_criterion_condition(meth)
425
+
426
+ def _no_statement_condition(self, meth: str) -> None:
427
+ if not self._enable_assertions:
428
+ return
429
+ if self._statement is not None:
430
+ raise sa_exc.InvalidRequestError(
431
+ (
432
+ "Query.%s() being called on a Query with an existing full "
433
+ "statement - can't apply criterion."
434
+ )
435
+ % meth
436
+ )
437
+
438
+ def _no_limit_offset(self, meth: str) -> None:
439
+ if not self._enable_assertions:
440
+ return
441
+ if self._limit_clause is not None or self._offset_clause is not None:
442
+ raise sa_exc.InvalidRequestError(
443
+ "Query.%s() being called on a Query which already has LIMIT "
444
+ "or OFFSET applied. Call %s() before limit() or offset() "
445
+ "are applied." % (meth, meth)
446
+ )
447
+
448
+ @property
449
+ def _has_row_limiting_clause(self) -> bool:
450
+ return (
451
+ self._limit_clause is not None or self._offset_clause is not None
452
+ )
453
+
454
+ def _get_options(
455
+ self,
456
+ populate_existing: Optional[bool] = None,
457
+ version_check: Optional[bool] = None,
458
+ only_load_props: Optional[Sequence[str]] = None,
459
+ refresh_state: Optional[InstanceState[Any]] = None,
460
+ identity_token: Optional[Any] = None,
461
+ ) -> Self:
462
+ load_options: Dict[str, Any] = {}
463
+ compile_options: Dict[str, Any] = {}
464
+
465
+ if version_check:
466
+ load_options["_version_check"] = version_check
467
+ if populate_existing:
468
+ load_options["_populate_existing"] = populate_existing
469
+ if refresh_state:
470
+ load_options["_refresh_state"] = refresh_state
471
+ compile_options["_for_refresh_state"] = True
472
+ if only_load_props:
473
+ compile_options["_only_load_props"] = frozenset(only_load_props)
474
+ if identity_token:
475
+ load_options["_identity_token"] = identity_token
476
+
477
+ if load_options:
478
+ self.load_options += load_options
479
+ if compile_options:
480
+ self._compile_options += compile_options
481
+
482
+ return self
483
+
484
+ def _clone(self, **kw: Any) -> Self:
485
+ return self._generate()
486
+
487
+ def _get_select_statement_only(self) -> Select[_T]:
488
+ if self._statement is not None:
489
+ raise sa_exc.InvalidRequestError(
490
+ "Can't call this method on a Query that uses from_statement()"
491
+ )
492
+ return cast("Select[_T]", self.statement)
493
+
494
+ @property
495
+ def statement(self) -> Union[Select[_T], FromStatement[_T]]:
496
+ """The full SELECT statement represented by this Query.
497
+
498
+ The statement by default will not have disambiguating labels
499
+ applied to the construct unless with_labels(True) is called
500
+ first.
501
+
502
+ """
503
+
504
+ # .statement can return the direct future.Select() construct here, as
505
+ # long as we are not using subsequent adaption features that
506
+ # are made against raw entities, e.g. from_self(), with_polymorphic(),
507
+ # select_entity_from(). If these features are being used, then
508
+ # the Select() we return will not have the correct .selected_columns
509
+ # collection and will not embed in subsequent queries correctly.
510
+ # We could find a way to make this collection "correct", however
511
+ # this would not be too different from doing the full compile as
512
+ # we are doing in any case, the Select() would still not have the
513
+ # proper state for other attributes like whereclause, order_by,
514
+ # and these features are all deprecated in any case.
515
+ #
516
+ # for these reasons, Query is not a Select, it remains an ORM
517
+ # object for which __clause_element__() must be called in order for
518
+ # it to provide a real expression object.
519
+ #
520
+ # from there, it starts to look much like Query itself won't be
521
+ # passed into the execute process and won't generate its own cache
522
+ # key; this will all occur in terms of the ORM-enabled Select.
523
+ if not self._compile_options._set_base_alias:
524
+ # if we don't have legacy top level aliasing features in use
525
+ # then convert to a future select() directly
526
+ stmt = self._statement_20(for_statement=True)
527
+ else:
528
+ stmt = self._compile_state(for_statement=True).statement
529
+
530
+ if self._params:
531
+ stmt = stmt.params(self._params)
532
+
533
+ return stmt
534
+
535
+ def _final_statement(self, legacy_query_style: bool = True) -> Select[Any]:
536
+ """Return the 'final' SELECT statement for this :class:`.Query`.
537
+
538
+ This is used by the testing suite only and is fairly inefficient.
539
+
540
+ This is the Core-only select() that will be rendered by a complete
541
+ compilation of this query, and is what .statement used to return
542
+ in 1.3.
543
+
544
+
545
+ """
546
+
547
+ q = self._clone()
548
+
549
+ return q._compile_state(
550
+ use_legacy_query_style=legacy_query_style
551
+ ).statement # type: ignore
552
+
553
+ def _statement_20(
554
+ self, for_statement: bool = False, use_legacy_query_style: bool = True
555
+ ) -> Union[Select[_T], FromStatement[_T]]:
556
+ # TODO: this event needs to be deprecated, as it currently applies
557
+ # only to ORM query and occurs at this spot that is now more
558
+ # or less an artificial spot
559
+ if self.dispatch.before_compile:
560
+ for fn in self.dispatch.before_compile:
561
+ new_query = fn(self)
562
+ if new_query is not None and new_query is not self:
563
+ self = new_query
564
+ if not fn._bake_ok: # type: ignore
565
+ self._compile_options += {"_bake_ok": False}
566
+
567
+ compile_options = self._compile_options
568
+ compile_options += {
569
+ "_for_statement": for_statement,
570
+ "_use_legacy_query_style": use_legacy_query_style,
571
+ }
572
+
573
+ stmt: Union[Select[_T], FromStatement[_T]]
574
+
575
+ if self._statement is not None:
576
+ stmt = FromStatement(self._raw_columns, self._statement)
577
+ stmt.__dict__.update(
578
+ _with_options=self._with_options,
579
+ _with_context_options=self._with_context_options,
580
+ _compile_options=compile_options,
581
+ _execution_options=self._execution_options,
582
+ _propagate_attrs=self._propagate_attrs,
583
+ )
584
+ else:
585
+ # Query / select() internal attributes are 99% cross-compatible
586
+ stmt = Select._create_raw_select(**self.__dict__)
587
+ stmt.__dict__.update(
588
+ _label_style=self._label_style,
589
+ _compile_options=compile_options,
590
+ _propagate_attrs=self._propagate_attrs,
591
+ )
592
+ stmt.__dict__.pop("session", None)
593
+
594
+ # ensure the ORM context is used to compile the statement, even
595
+ # if it has no ORM entities. This is so ORM-only things like
596
+ # _legacy_joins are picked up that wouldn't be picked up by the
597
+ # Core statement context
598
+ if "compile_state_plugin" not in stmt._propagate_attrs:
599
+ stmt._propagate_attrs = stmt._propagate_attrs.union(
600
+ {"compile_state_plugin": "orm", "plugin_subject": None}
601
+ )
602
+
603
+ return stmt
604
+
605
+ def subquery(
606
+ self,
607
+ name: Optional[str] = None,
608
+ with_labels: bool = False,
609
+ reduce_columns: bool = False,
610
+ ) -> Subquery:
611
+ """Return the full SELECT statement represented by
612
+ this :class:`_query.Query`, embedded within an
613
+ :class:`_expression.Alias`.
614
+
615
+ Eager JOIN generation within the query is disabled.
616
+
617
+ .. seealso::
618
+
619
+ :meth:`_sql.Select.subquery` - v2 comparable method.
620
+
621
+ :param name: string name to be assigned as the alias;
622
+ this is passed through to :meth:`_expression.FromClause.alias`.
623
+ If ``None``, a name will be deterministically generated
624
+ at compile time.
625
+
626
+ :param with_labels: if True, :meth:`.with_labels` will be called
627
+ on the :class:`_query.Query` first to apply table-qualified labels
628
+ to all columns.
629
+
630
+ :param reduce_columns: if True,
631
+ :meth:`_expression.Select.reduce_columns` will
632
+ be called on the resulting :func:`_expression.select` construct,
633
+ to remove same-named columns where one also refers to the other
634
+ via foreign key or WHERE clause equivalence.
635
+
636
+ """
637
+ q = self.enable_eagerloads(False)
638
+ if with_labels:
639
+ q = q.set_label_style(LABEL_STYLE_TABLENAME_PLUS_COL)
640
+
641
+ stmt = q._get_select_statement_only()
642
+
643
+ if TYPE_CHECKING:
644
+ assert isinstance(stmt, Select)
645
+
646
+ if reduce_columns:
647
+ stmt = stmt.reduce_columns()
648
+ return stmt.subquery(name=name)
649
+
650
+ def cte(
651
+ self,
652
+ name: Optional[str] = None,
653
+ recursive: bool = False,
654
+ nesting: bool = False,
655
+ ) -> CTE:
656
+ r"""Return the full SELECT statement represented by this
657
+ :class:`_query.Query` represented as a common table expression (CTE).
658
+
659
+ Parameters and usage are the same as those of the
660
+ :meth:`_expression.SelectBase.cte` method; see that method for
661
+ further details.
662
+
663
+ Here is the `PostgreSQL WITH
664
+ RECURSIVE example
665
+ <https://www.postgresql.org/docs/current/static/queries-with.html>`_.
666
+ Note that, in this example, the ``included_parts`` cte and the
667
+ ``incl_alias`` alias of it are Core selectables, which
668
+ means the columns are accessed via the ``.c.`` attribute. The
669
+ ``parts_alias`` object is an :func:`_orm.aliased` instance of the
670
+ ``Part`` entity, so column-mapped attributes are available
671
+ directly::
672
+
673
+ from sqlalchemy.orm import aliased
674
+
675
+ class Part(Base):
676
+ __tablename__ = 'part'
677
+ part = Column(String, primary_key=True)
678
+ sub_part = Column(String, primary_key=True)
679
+ quantity = Column(Integer)
680
+
681
+ included_parts = session.query(
682
+ Part.sub_part,
683
+ Part.part,
684
+ Part.quantity).\
685
+ filter(Part.part=="our part").\
686
+ cte(name="included_parts", recursive=True)
687
+
688
+ incl_alias = aliased(included_parts, name="pr")
689
+ parts_alias = aliased(Part, name="p")
690
+ included_parts = included_parts.union_all(
691
+ session.query(
692
+ parts_alias.sub_part,
693
+ parts_alias.part,
694
+ parts_alias.quantity).\
695
+ filter(parts_alias.part==incl_alias.c.sub_part)
696
+ )
697
+
698
+ q = session.query(
699
+ included_parts.c.sub_part,
700
+ func.sum(included_parts.c.quantity).
701
+ label('total_quantity')
702
+ ).\
703
+ group_by(included_parts.c.sub_part)
704
+
705
+ .. seealso::
706
+
707
+ :meth:`_sql.Select.cte` - v2 equivalent method.
708
+
709
+ """
710
+ return (
711
+ self.enable_eagerloads(False)
712
+ ._get_select_statement_only()
713
+ .cte(name=name, recursive=recursive, nesting=nesting)
714
+ )
715
+
716
+ def label(self, name: Optional[str]) -> Label[Any]:
717
+ """Return the full SELECT statement represented by this
718
+ :class:`_query.Query`, converted
719
+ to a scalar subquery with a label of the given name.
720
+
721
+ .. seealso::
722
+
723
+ :meth:`_sql.Select.label` - v2 comparable method.
724
+
725
+ """
726
+
727
+ return (
728
+ self.enable_eagerloads(False)
729
+ ._get_select_statement_only()
730
+ .label(name)
731
+ )
732
+
733
+ @overload
734
+ def as_scalar( # type: ignore[overload-overlap]
735
+ self: Query[Tuple[_MAYBE_ENTITY]],
736
+ ) -> ScalarSelect[_MAYBE_ENTITY]: ...
737
+
738
+ @overload
739
+ def as_scalar(
740
+ self: Query[Tuple[_NOT_ENTITY]],
741
+ ) -> ScalarSelect[_NOT_ENTITY]: ...
742
+
743
+ @overload
744
+ def as_scalar(self) -> ScalarSelect[Any]: ...
745
+
746
+ @util.deprecated(
747
+ "1.4",
748
+ "The :meth:`_query.Query.as_scalar` method is deprecated and will be "
749
+ "removed in a future release. Please refer to "
750
+ ":meth:`_query.Query.scalar_subquery`.",
751
+ )
752
+ def as_scalar(self) -> ScalarSelect[Any]:
753
+ """Return the full SELECT statement represented by this
754
+ :class:`_query.Query`, converted to a scalar subquery.
755
+
756
+ """
757
+ return self.scalar_subquery()
758
+
759
+ @overload
760
+ def scalar_subquery(
761
+ self: Query[Tuple[_MAYBE_ENTITY]],
762
+ ) -> ScalarSelect[Any]: ...
763
+
764
+ @overload
765
+ def scalar_subquery(
766
+ self: Query[Tuple[_NOT_ENTITY]],
767
+ ) -> ScalarSelect[_NOT_ENTITY]: ...
768
+
769
+ @overload
770
+ def scalar_subquery(self) -> ScalarSelect[Any]: ...
771
+
772
+ def scalar_subquery(self) -> ScalarSelect[Any]:
773
+ """Return the full SELECT statement represented by this
774
+ :class:`_query.Query`, converted to a scalar subquery.
775
+
776
+ Analogous to
777
+ :meth:`sqlalchemy.sql.expression.SelectBase.scalar_subquery`.
778
+
779
+ .. versionchanged:: 1.4 The :meth:`_query.Query.scalar_subquery`
780
+ method replaces the :meth:`_query.Query.as_scalar` method.
781
+
782
+ .. seealso::
783
+
784
+ :meth:`_sql.Select.scalar_subquery` - v2 comparable method.
785
+
786
+ """
787
+
788
+ return (
789
+ self.enable_eagerloads(False)
790
+ ._get_select_statement_only()
791
+ .scalar_subquery()
792
+ )
793
+
794
+ @property
795
+ def selectable(self) -> Union[Select[_T], FromStatement[_T]]:
796
+ """Return the :class:`_expression.Select` object emitted by this
797
+ :class:`_query.Query`.
798
+
799
+ Used for :func:`_sa.inspect` compatibility, this is equivalent to::
800
+
801
+ query.enable_eagerloads(False).with_labels().statement
802
+
803
+ """
804
+ return self.__clause_element__()
805
+
806
+ def __clause_element__(self) -> Union[Select[_T], FromStatement[_T]]:
807
+ return (
808
+ self._with_compile_options(
809
+ _enable_eagerloads=False, _render_for_subquery=True
810
+ )
811
+ .set_label_style(LABEL_STYLE_TABLENAME_PLUS_COL)
812
+ .statement
813
+ )
814
+
815
+ @overload
816
+ def only_return_tuples(
817
+ self: Query[_O], value: Literal[True]
818
+ ) -> RowReturningQuery[Tuple[_O]]: ...
819
+
820
+ @overload
821
+ def only_return_tuples(
822
+ self: Query[_O], value: Literal[False]
823
+ ) -> Query[_O]: ...
824
+
825
+ @_generative
826
+ def only_return_tuples(self, value: bool) -> Query[Any]:
827
+ """When set to True, the query results will always be a
828
+ :class:`.Row` object.
829
+
830
+ This can change a query that normally returns a single entity
831
+ as a scalar to return a :class:`.Row` result in all cases.
832
+
833
+ .. seealso::
834
+
835
+ :meth:`.Query.tuples` - returns tuples, but also at the typing
836
+ level will type results as ``Tuple``.
837
+
838
+ :meth:`_query.Query.is_single_entity`
839
+
840
+ :meth:`_engine.Result.tuples` - v2 comparable method.
841
+
842
+ """
843
+ self.load_options += dict(_only_return_tuples=value)
844
+ return self
845
+
846
+ @property
847
+ def is_single_entity(self) -> bool:
848
+ """Indicates if this :class:`_query.Query`
849
+ returns tuples or single entities.
850
+
851
+ Returns True if this query returns a single entity for each instance
852
+ in its result list, and False if this query returns a tuple of entities
853
+ for each result.
854
+
855
+ .. versionadded:: 1.3.11
856
+
857
+ .. seealso::
858
+
859
+ :meth:`_query.Query.only_return_tuples`
860
+
861
+ """
862
+ return (
863
+ not self.load_options._only_return_tuples
864
+ and len(self._raw_columns) == 1
865
+ and "parententity" in self._raw_columns[0]._annotations
866
+ and isinstance(
867
+ self._raw_columns[0]._annotations["parententity"],
868
+ ORMColumnsClauseRole,
869
+ )
870
+ )
871
+
872
+ @_generative
873
+ def enable_eagerloads(self, value: bool) -> Self:
874
+ """Control whether or not eager joins and subqueries are
875
+ rendered.
876
+
877
+ When set to False, the returned Query will not render
878
+ eager joins regardless of :func:`~sqlalchemy.orm.joinedload`,
879
+ :func:`~sqlalchemy.orm.subqueryload` options
880
+ or mapper-level ``lazy='joined'``/``lazy='subquery'``
881
+ configurations.
882
+
883
+ This is used primarily when nesting the Query's
884
+ statement into a subquery or other
885
+ selectable, or when using :meth:`_query.Query.yield_per`.
886
+
887
+ """
888
+ self._compile_options += {"_enable_eagerloads": value}
889
+ return self
890
+
891
+ @_generative
892
+ def _with_compile_options(self, **opt: Any) -> Self:
893
+ self._compile_options += opt
894
+ return self
895
+
896
+ @util.became_legacy_20(
897
+ ":meth:`_orm.Query.with_labels` and :meth:`_orm.Query.apply_labels`",
898
+ alternative="Use set_label_style(LABEL_STYLE_TABLENAME_PLUS_COL) "
899
+ "instead.",
900
+ )
901
+ def with_labels(self) -> Self:
902
+ return self.set_label_style(
903
+ SelectLabelStyle.LABEL_STYLE_TABLENAME_PLUS_COL
904
+ )
905
+
906
+ apply_labels = with_labels
907
+
908
+ @property
909
+ def get_label_style(self) -> SelectLabelStyle:
910
+ """
911
+ Retrieve the current label style.
912
+
913
+ .. versionadded:: 1.4
914
+
915
+ .. seealso::
916
+
917
+ :meth:`_sql.Select.get_label_style` - v2 equivalent method.
918
+
919
+ """
920
+ return self._label_style
921
+
922
+ def set_label_style(self, style: SelectLabelStyle) -> Self:
923
+ """Apply column labels to the return value of Query.statement.
924
+
925
+ Indicates that this Query's `statement` accessor should return
926
+ a SELECT statement that applies labels to all columns in the
927
+ form <tablename>_<columnname>; this is commonly used to
928
+ disambiguate columns from multiple tables which have the same
929
+ name.
930
+
931
+ When the `Query` actually issues SQL to load rows, it always
932
+ uses column labeling.
933
+
934
+ .. note:: The :meth:`_query.Query.set_label_style` method *only* applies
935
+ the output of :attr:`_query.Query.statement`, and *not* to any of
936
+ the result-row invoking systems of :class:`_query.Query` itself,
937
+ e.g.
938
+ :meth:`_query.Query.first`, :meth:`_query.Query.all`, etc.
939
+ To execute
940
+ a query using :meth:`_query.Query.set_label_style`, invoke the
941
+ :attr:`_query.Query.statement` using :meth:`.Session.execute`::
942
+
943
+ result = session.execute(
944
+ query
945
+ .set_label_style(LABEL_STYLE_TABLENAME_PLUS_COL)
946
+ .statement
947
+ )
948
+
949
+ .. versionadded:: 1.4
950
+
951
+
952
+ .. seealso::
953
+
954
+ :meth:`_sql.Select.set_label_style` - v2 equivalent method.
955
+
956
+ """ # noqa
957
+ if self._label_style is not style:
958
+ self = self._generate()
959
+ self._label_style = style
960
+ return self
961
+
962
+ @_generative
963
+ def enable_assertions(self, value: bool) -> Self:
964
+ """Control whether assertions are generated.
965
+
966
+ When set to False, the returned Query will
967
+ not assert its state before certain operations,
968
+ including that LIMIT/OFFSET has not been applied
969
+ when filter() is called, no criterion exists
970
+ when get() is called, and no "from_statement()"
971
+ exists when filter()/order_by()/group_by() etc.
972
+ is called. This more permissive mode is used by
973
+ custom Query subclasses to specify criterion or
974
+ other modifiers outside of the usual usage patterns.
975
+
976
+ Care should be taken to ensure that the usage
977
+ pattern is even possible. A statement applied
978
+ by from_statement() will override any criterion
979
+ set by filter() or order_by(), for example.
980
+
981
+ """
982
+ self._enable_assertions = value
983
+ return self
984
+
985
+ @property
986
+ def whereclause(self) -> Optional[ColumnElement[bool]]:
987
+ """A readonly attribute which returns the current WHERE criterion for
988
+ this Query.
989
+
990
+ This returned value is a SQL expression construct, or ``None`` if no
991
+ criterion has been established.
992
+
993
+ .. seealso::
994
+
995
+ :attr:`_sql.Select.whereclause` - v2 equivalent property.
996
+
997
+ """
998
+ return BooleanClauseList._construct_for_whereclause(
999
+ self._where_criteria
1000
+ )
1001
+
1002
+ @_generative
1003
+ def _with_current_path(self, path: PathRegistry) -> Self:
1004
+ """indicate that this query applies to objects loaded
1005
+ within a certain path.
1006
+
1007
+ Used by deferred loaders (see strategies.py) which transfer
1008
+ query options from an originating query to a newly generated
1009
+ query intended for the deferred load.
1010
+
1011
+ """
1012
+ self._compile_options += {"_current_path": path}
1013
+ return self
1014
+
1015
+ @_generative
1016
+ def yield_per(self, count: int) -> Self:
1017
+ r"""Yield only ``count`` rows at a time.
1018
+
1019
+ The purpose of this method is when fetching very large result sets
1020
+ (> 10K rows), to batch results in sub-collections and yield them
1021
+ out partially, so that the Python interpreter doesn't need to declare
1022
+ very large areas of memory which is both time consuming and leads
1023
+ to excessive memory use. The performance from fetching hundreds of
1024
+ thousands of rows can often double when a suitable yield-per setting
1025
+ (e.g. approximately 1000) is used, even with DBAPIs that buffer
1026
+ rows (which are most).
1027
+
1028
+ As of SQLAlchemy 1.4, the :meth:`_orm.Query.yield_per` method is
1029
+ equivalent to using the ``yield_per`` execution option at the ORM
1030
+ level. See the section :ref:`orm_queryguide_yield_per` for further
1031
+ background on this option.
1032
+
1033
+ .. seealso::
1034
+
1035
+ :ref:`orm_queryguide_yield_per`
1036
+
1037
+ """
1038
+ self.load_options += {"_yield_per": count}
1039
+ return self
1040
+
1041
+ @util.became_legacy_20(
1042
+ ":meth:`_orm.Query.get`",
1043
+ alternative="The method is now available as :meth:`_orm.Session.get`",
1044
+ )
1045
+ def get(self, ident: _PKIdentityArgument) -> Optional[Any]:
1046
+ """Return an instance based on the given primary key identifier,
1047
+ or ``None`` if not found.
1048
+
1049
+ E.g.::
1050
+
1051
+ my_user = session.query(User).get(5)
1052
+
1053
+ some_object = session.query(VersionedFoo).get((5, 10))
1054
+
1055
+ some_object = session.query(VersionedFoo).get(
1056
+ {"id": 5, "version_id": 10})
1057
+
1058
+ :meth:`_query.Query.get` is special in that it provides direct
1059
+ access to the identity map of the owning :class:`.Session`.
1060
+ If the given primary key identifier is present
1061
+ in the local identity map, the object is returned
1062
+ directly from this collection and no SQL is emitted,
1063
+ unless the object has been marked fully expired.
1064
+ If not present,
1065
+ a SELECT is performed in order to locate the object.
1066
+
1067
+ :meth:`_query.Query.get` also will perform a check if
1068
+ the object is present in the identity map and
1069
+ marked as expired - a SELECT
1070
+ is emitted to refresh the object as well as to
1071
+ ensure that the row is still present.
1072
+ If not, :class:`~sqlalchemy.orm.exc.ObjectDeletedError` is raised.
1073
+
1074
+ :meth:`_query.Query.get` is only used to return a single
1075
+ mapped instance, not multiple instances or
1076
+ individual column constructs, and strictly
1077
+ on a single primary key value. The originating
1078
+ :class:`_query.Query` must be constructed in this way,
1079
+ i.e. against a single mapped entity,
1080
+ with no additional filtering criterion. Loading
1081
+ options via :meth:`_query.Query.options` may be applied
1082
+ however, and will be used if the object is not
1083
+ yet locally present.
1084
+
1085
+ :param ident: A scalar, tuple, or dictionary representing the
1086
+ primary key. For a composite (e.g. multiple column) primary key,
1087
+ a tuple or dictionary should be passed.
1088
+
1089
+ For a single-column primary key, the scalar calling form is typically
1090
+ the most expedient. If the primary key of a row is the value "5",
1091
+ the call looks like::
1092
+
1093
+ my_object = query.get(5)
1094
+
1095
+ The tuple form contains primary key values typically in
1096
+ the order in which they correspond to the mapped
1097
+ :class:`_schema.Table`
1098
+ object's primary key columns, or if the
1099
+ :paramref:`_orm.Mapper.primary_key` configuration parameter were
1100
+ used, in
1101
+ the order used for that parameter. For example, if the primary key
1102
+ of a row is represented by the integer
1103
+ digits "5, 10" the call would look like::
1104
+
1105
+ my_object = query.get((5, 10))
1106
+
1107
+ The dictionary form should include as keys the mapped attribute names
1108
+ corresponding to each element of the primary key. If the mapped class
1109
+ has the attributes ``id``, ``version_id`` as the attributes which
1110
+ store the object's primary key value, the call would look like::
1111
+
1112
+ my_object = query.get({"id": 5, "version_id": 10})
1113
+
1114
+ .. versionadded:: 1.3 the :meth:`_query.Query.get`
1115
+ method now optionally
1116
+ accepts a dictionary of attribute names to values in order to
1117
+ indicate a primary key identifier.
1118
+
1119
+
1120
+ :return: The object instance, or ``None``.
1121
+
1122
+ """
1123
+ self._no_criterion_assertion("get", order_by=False, distinct=False)
1124
+
1125
+ # we still implement _get_impl() so that baked query can override
1126
+ # it
1127
+ return self._get_impl(ident, loading.load_on_pk_identity)
1128
+
1129
+ def _get_impl(
1130
+ self,
1131
+ primary_key_identity: _PKIdentityArgument,
1132
+ db_load_fn: Callable[..., Any],
1133
+ identity_token: Optional[Any] = None,
1134
+ ) -> Optional[Any]:
1135
+ mapper = self._only_full_mapper_zero("get")
1136
+ return self.session._get_impl(
1137
+ mapper,
1138
+ primary_key_identity,
1139
+ db_load_fn,
1140
+ populate_existing=self.load_options._populate_existing,
1141
+ with_for_update=self._for_update_arg,
1142
+ options=self._with_options,
1143
+ identity_token=identity_token,
1144
+ execution_options=self._execution_options,
1145
+ )
1146
+
1147
+ @property
1148
+ def lazy_loaded_from(self) -> Optional[InstanceState[Any]]:
1149
+ """An :class:`.InstanceState` that is using this :class:`_query.Query`
1150
+ for a lazy load operation.
1151
+
1152
+ .. deprecated:: 1.4 This attribute should be viewed via the
1153
+ :attr:`.ORMExecuteState.lazy_loaded_from` attribute, within
1154
+ the context of the :meth:`.SessionEvents.do_orm_execute`
1155
+ event.
1156
+
1157
+ .. seealso::
1158
+
1159
+ :attr:`.ORMExecuteState.lazy_loaded_from`
1160
+
1161
+ """
1162
+ return self.load_options._lazy_loaded_from # type: ignore
1163
+
1164
+ @property
1165
+ def _current_path(self) -> PathRegistry:
1166
+ return self._compile_options._current_path # type: ignore
1167
+
1168
+ @_generative
1169
+ def correlate(
1170
+ self,
1171
+ *fromclauses: Union[Literal[None, False], _FromClauseArgument],
1172
+ ) -> Self:
1173
+ """Return a :class:`.Query` construct which will correlate the given
1174
+ FROM clauses to that of an enclosing :class:`.Query` or
1175
+ :func:`~.expression.select`.
1176
+
1177
+ The method here accepts mapped classes, :func:`.aliased` constructs,
1178
+ and :class:`_orm.Mapper` constructs as arguments, which are resolved
1179
+ into expression constructs, in addition to appropriate expression
1180
+ constructs.
1181
+
1182
+ The correlation arguments are ultimately passed to
1183
+ :meth:`_expression.Select.correlate`
1184
+ after coercion to expression constructs.
1185
+
1186
+ The correlation arguments take effect in such cases
1187
+ as when :meth:`_query.Query.from_self` is used, or when
1188
+ a subquery as returned by :meth:`_query.Query.subquery` is
1189
+ embedded in another :func:`_expression.select` construct.
1190
+
1191
+ .. seealso::
1192
+
1193
+ :meth:`_sql.Select.correlate` - v2 equivalent method.
1194
+
1195
+ """
1196
+
1197
+ self._auto_correlate = False
1198
+ if fromclauses and fromclauses[0] in {None, False}:
1199
+ self._correlate = ()
1200
+ else:
1201
+ self._correlate = self._correlate + tuple(
1202
+ coercions.expect(roles.FromClauseRole, f) for f in fromclauses
1203
+ )
1204
+ return self
1205
+
1206
+ @_generative
1207
+ def autoflush(self, setting: bool) -> Self:
1208
+ """Return a Query with a specific 'autoflush' setting.
1209
+
1210
+ As of SQLAlchemy 1.4, the :meth:`_orm.Query.autoflush` method
1211
+ is equivalent to using the ``autoflush`` execution option at the
1212
+ ORM level. See the section :ref:`orm_queryguide_autoflush` for
1213
+ further background on this option.
1214
+
1215
+ """
1216
+ self.load_options += {"_autoflush": setting}
1217
+ return self
1218
+
1219
+ @_generative
1220
+ def populate_existing(self) -> Self:
1221
+ """Return a :class:`_query.Query`
1222
+ that will expire and refresh all instances
1223
+ as they are loaded, or reused from the current :class:`.Session`.
1224
+
1225
+ As of SQLAlchemy 1.4, the :meth:`_orm.Query.populate_existing` method
1226
+ is equivalent to using the ``populate_existing`` execution option at
1227
+ the ORM level. See the section :ref:`orm_queryguide_populate_existing`
1228
+ for further background on this option.
1229
+
1230
+ """
1231
+ self.load_options += {"_populate_existing": True}
1232
+ return self
1233
+
1234
+ @_generative
1235
+ def _with_invoke_all_eagers(self, value: bool) -> Self:
1236
+ """Set the 'invoke all eagers' flag which causes joined- and
1237
+ subquery loaders to traverse into already-loaded related objects
1238
+ and collections.
1239
+
1240
+ Default is that of :attr:`_query.Query._invoke_all_eagers`.
1241
+
1242
+ """
1243
+ self.load_options += {"_invoke_all_eagers": value}
1244
+ return self
1245
+
1246
+ @util.became_legacy_20(
1247
+ ":meth:`_orm.Query.with_parent`",
1248
+ alternative="Use the :func:`_orm.with_parent` standalone construct.",
1249
+ )
1250
+ @util.preload_module("sqlalchemy.orm.relationships")
1251
+ def with_parent(
1252
+ self,
1253
+ instance: object,
1254
+ property: Optional[ # noqa: A002
1255
+ attributes.QueryableAttribute[Any]
1256
+ ] = None,
1257
+ from_entity: Optional[_ExternalEntityType[Any]] = None,
1258
+ ) -> Self:
1259
+ """Add filtering criterion that relates the given instance
1260
+ to a child object or collection, using its attribute state
1261
+ as well as an established :func:`_orm.relationship()`
1262
+ configuration.
1263
+
1264
+ The method uses the :func:`.with_parent` function to generate
1265
+ the clause, the result of which is passed to
1266
+ :meth:`_query.Query.filter`.
1267
+
1268
+ Parameters are the same as :func:`.with_parent`, with the exception
1269
+ that the given property can be None, in which case a search is
1270
+ performed against this :class:`_query.Query` object's target mapper.
1271
+
1272
+ :param instance:
1273
+ An instance which has some :func:`_orm.relationship`.
1274
+
1275
+ :param property:
1276
+ Class bound attribute which indicates
1277
+ what relationship from the instance should be used to reconcile the
1278
+ parent/child relationship.
1279
+
1280
+ :param from_entity:
1281
+ Entity in which to consider as the left side. This defaults to the
1282
+ "zero" entity of the :class:`_query.Query` itself.
1283
+
1284
+ """
1285
+ relationships = util.preloaded.orm_relationships
1286
+
1287
+ if from_entity:
1288
+ entity_zero = inspect(from_entity)
1289
+ else:
1290
+ entity_zero = _legacy_filter_by_entity_zero(self)
1291
+ if property is None:
1292
+ # TODO: deprecate, property has to be supplied
1293
+ mapper = object_mapper(instance)
1294
+
1295
+ for prop in mapper.iterate_properties:
1296
+ if (
1297
+ isinstance(prop, relationships.RelationshipProperty)
1298
+ and prop.mapper is entity_zero.mapper # type: ignore
1299
+ ):
1300
+ property = prop # type: ignore # noqa: A001
1301
+ break
1302
+ else:
1303
+ raise sa_exc.InvalidRequestError(
1304
+ "Could not locate a property which relates instances "
1305
+ "of class '%s' to instances of class '%s'"
1306
+ % (
1307
+ entity_zero.mapper.class_.__name__, # type: ignore
1308
+ instance.__class__.__name__,
1309
+ )
1310
+ )
1311
+
1312
+ return self.filter(
1313
+ with_parent(
1314
+ instance,
1315
+ property, # type: ignore
1316
+ entity_zero.entity, # type: ignore
1317
+ )
1318
+ )
1319
+
1320
+ @_generative
1321
+ def add_entity(
1322
+ self,
1323
+ entity: _EntityType[Any],
1324
+ alias: Optional[Union[Alias, Subquery]] = None,
1325
+ ) -> Query[Any]:
1326
+ """add a mapped entity to the list of result columns
1327
+ to be returned.
1328
+
1329
+ .. seealso::
1330
+
1331
+ :meth:`_sql.Select.add_columns` - v2 comparable method.
1332
+ """
1333
+
1334
+ if alias is not None:
1335
+ # TODO: deprecate
1336
+ entity = AliasedClass(entity, alias)
1337
+
1338
+ self._raw_columns = list(self._raw_columns)
1339
+
1340
+ self._raw_columns.append(
1341
+ coercions.expect(
1342
+ roles.ColumnsClauseRole, entity, apply_propagate_attrs=self
1343
+ )
1344
+ )
1345
+ return self
1346
+
1347
+ @_generative
1348
+ def with_session(self, session: Session) -> Self:
1349
+ """Return a :class:`_query.Query` that will use the given
1350
+ :class:`.Session`.
1351
+
1352
+ While the :class:`_query.Query`
1353
+ object is normally instantiated using the
1354
+ :meth:`.Session.query` method, it is legal to build the
1355
+ :class:`_query.Query`
1356
+ directly without necessarily using a :class:`.Session`. Such a
1357
+ :class:`_query.Query` object, or any :class:`_query.Query`
1358
+ already associated
1359
+ with a different :class:`.Session`, can produce a new
1360
+ :class:`_query.Query`
1361
+ object associated with a target session using this method::
1362
+
1363
+ from sqlalchemy.orm import Query
1364
+
1365
+ query = Query([MyClass]).filter(MyClass.id == 5)
1366
+
1367
+ result = query.with_session(my_session).one()
1368
+
1369
+ """
1370
+
1371
+ self.session = session
1372
+ return self
1373
+
1374
+ def _legacy_from_self(
1375
+ self, *entities: _ColumnsClauseArgument[Any]
1376
+ ) -> Self:
1377
+ # used for query.count() as well as for the same
1378
+ # function in BakedQuery, as well as some old tests in test_baked.py.
1379
+
1380
+ fromclause = (
1381
+ self.set_label_style(LABEL_STYLE_TABLENAME_PLUS_COL)
1382
+ .correlate(None)
1383
+ .subquery()
1384
+ ._anonymous_fromclause()
1385
+ )
1386
+
1387
+ q = self._from_selectable(fromclause)
1388
+
1389
+ if entities:
1390
+ q._set_entities(entities)
1391
+ return q
1392
+
1393
+ @_generative
1394
+ def _set_enable_single_crit(self, val: bool) -> Self:
1395
+ self._compile_options += {"_enable_single_crit": val}
1396
+ return self
1397
+
1398
+ @_generative
1399
+ def _from_selectable(
1400
+ self, fromclause: FromClause, set_entity_from: bool = True
1401
+ ) -> Self:
1402
+ for attr in (
1403
+ "_where_criteria",
1404
+ "_order_by_clauses",
1405
+ "_group_by_clauses",
1406
+ "_limit_clause",
1407
+ "_offset_clause",
1408
+ "_last_joined_entity",
1409
+ "_setup_joins",
1410
+ "_memoized_select_entities",
1411
+ "_distinct",
1412
+ "_distinct_on",
1413
+ "_having_criteria",
1414
+ "_prefixes",
1415
+ "_suffixes",
1416
+ ):
1417
+ self.__dict__.pop(attr, None)
1418
+ self._set_select_from([fromclause], set_entity_from)
1419
+ self._compile_options += {
1420
+ "_enable_single_crit": False,
1421
+ }
1422
+
1423
+ return self
1424
+
1425
+ @util.deprecated(
1426
+ "1.4",
1427
+ ":meth:`_query.Query.values` "
1428
+ "is deprecated and will be removed in a "
1429
+ "future release. Please use :meth:`_query.Query.with_entities`",
1430
+ )
1431
+ def values(self, *columns: _ColumnsClauseArgument[Any]) -> Iterable[Any]:
1432
+ """Return an iterator yielding result tuples corresponding
1433
+ to the given list of columns
1434
+
1435
+ """
1436
+ return self._values_no_warn(*columns)
1437
+
1438
+ _values = values
1439
+
1440
+ def _values_no_warn(
1441
+ self, *columns: _ColumnsClauseArgument[Any]
1442
+ ) -> Iterable[Any]:
1443
+ if not columns:
1444
+ return iter(())
1445
+ q = self._clone().enable_eagerloads(False)
1446
+ q._set_entities(columns)
1447
+ if not q.load_options._yield_per:
1448
+ q.load_options += {"_yield_per": 10}
1449
+ return iter(q)
1450
+
1451
+ @util.deprecated(
1452
+ "1.4",
1453
+ ":meth:`_query.Query.value` "
1454
+ "is deprecated and will be removed in a "
1455
+ "future release. Please use :meth:`_query.Query.with_entities` "
1456
+ "in combination with :meth:`_query.Query.scalar`",
1457
+ )
1458
+ def value(self, column: _ColumnExpressionArgument[Any]) -> Any:
1459
+ """Return a scalar result corresponding to the given
1460
+ column expression.
1461
+
1462
+ """
1463
+ try:
1464
+ return next(self._values_no_warn(column))[0] # type: ignore
1465
+ except StopIteration:
1466
+ return None
1467
+
1468
+ @overload
1469
+ def with_entities(self, _entity: _EntityType[_O]) -> Query[_O]: ...
1470
+
1471
+ @overload
1472
+ def with_entities(
1473
+ self,
1474
+ _colexpr: roles.TypedColumnsClauseRole[_T],
1475
+ ) -> RowReturningQuery[Tuple[_T]]: ...
1476
+
1477
+ # START OVERLOADED FUNCTIONS self.with_entities RowReturningQuery 2-8
1478
+
1479
+ # code within this block is **programmatically,
1480
+ # statically generated** by tools/generate_tuple_map_overloads.py
1481
+
1482
+ @overload
1483
+ def with_entities(
1484
+ self, __ent0: _TCCA[_T0], __ent1: _TCCA[_T1]
1485
+ ) -> RowReturningQuery[Tuple[_T0, _T1]]: ...
1486
+
1487
+ @overload
1488
+ def with_entities(
1489
+ self, __ent0: _TCCA[_T0], __ent1: _TCCA[_T1], __ent2: _TCCA[_T2]
1490
+ ) -> RowReturningQuery[Tuple[_T0, _T1, _T2]]: ...
1491
+
1492
+ @overload
1493
+ def with_entities(
1494
+ self,
1495
+ __ent0: _TCCA[_T0],
1496
+ __ent1: _TCCA[_T1],
1497
+ __ent2: _TCCA[_T2],
1498
+ __ent3: _TCCA[_T3],
1499
+ ) -> RowReturningQuery[Tuple[_T0, _T1, _T2, _T3]]: ...
1500
+
1501
+ @overload
1502
+ def with_entities(
1503
+ self,
1504
+ __ent0: _TCCA[_T0],
1505
+ __ent1: _TCCA[_T1],
1506
+ __ent2: _TCCA[_T2],
1507
+ __ent3: _TCCA[_T3],
1508
+ __ent4: _TCCA[_T4],
1509
+ ) -> RowReturningQuery[Tuple[_T0, _T1, _T2, _T3, _T4]]: ...
1510
+
1511
+ @overload
1512
+ def with_entities(
1513
+ self,
1514
+ __ent0: _TCCA[_T0],
1515
+ __ent1: _TCCA[_T1],
1516
+ __ent2: _TCCA[_T2],
1517
+ __ent3: _TCCA[_T3],
1518
+ __ent4: _TCCA[_T4],
1519
+ __ent5: _TCCA[_T5],
1520
+ ) -> RowReturningQuery[Tuple[_T0, _T1, _T2, _T3, _T4, _T5]]: ...
1521
+
1522
+ @overload
1523
+ def with_entities(
1524
+ self,
1525
+ __ent0: _TCCA[_T0],
1526
+ __ent1: _TCCA[_T1],
1527
+ __ent2: _TCCA[_T2],
1528
+ __ent3: _TCCA[_T3],
1529
+ __ent4: _TCCA[_T4],
1530
+ __ent5: _TCCA[_T5],
1531
+ __ent6: _TCCA[_T6],
1532
+ ) -> RowReturningQuery[Tuple[_T0, _T1, _T2, _T3, _T4, _T5, _T6]]: ...
1533
+
1534
+ @overload
1535
+ def with_entities(
1536
+ self,
1537
+ __ent0: _TCCA[_T0],
1538
+ __ent1: _TCCA[_T1],
1539
+ __ent2: _TCCA[_T2],
1540
+ __ent3: _TCCA[_T3],
1541
+ __ent4: _TCCA[_T4],
1542
+ __ent5: _TCCA[_T5],
1543
+ __ent6: _TCCA[_T6],
1544
+ __ent7: _TCCA[_T7],
1545
+ ) -> RowReturningQuery[Tuple[_T0, _T1, _T2, _T3, _T4, _T5, _T6, _T7]]: ...
1546
+
1547
+ # END OVERLOADED FUNCTIONS self.with_entities
1548
+
1549
+ @overload
1550
+ def with_entities(
1551
+ self, *entities: _ColumnsClauseArgument[Any]
1552
+ ) -> Query[Any]: ...
1553
+
1554
+ @_generative
1555
+ def with_entities(
1556
+ self, *entities: _ColumnsClauseArgument[Any], **__kw: Any
1557
+ ) -> Query[Any]:
1558
+ r"""Return a new :class:`_query.Query`
1559
+ replacing the SELECT list with the
1560
+ given entities.
1561
+
1562
+ e.g.::
1563
+
1564
+ # Users, filtered on some arbitrary criterion
1565
+ # and then ordered by related email address
1566
+ q = session.query(User).\
1567
+ join(User.address).\
1568
+ filter(User.name.like('%ed%')).\
1569
+ order_by(Address.email)
1570
+
1571
+ # given *only* User.id==5, Address.email, and 'q', what
1572
+ # would the *next* User in the result be ?
1573
+ subq = q.with_entities(Address.email).\
1574
+ order_by(None).\
1575
+ filter(User.id==5).\
1576
+ subquery()
1577
+ q = q.join((subq, subq.c.email < Address.email)).\
1578
+ limit(1)
1579
+
1580
+ .. seealso::
1581
+
1582
+ :meth:`_sql.Select.with_only_columns` - v2 comparable method.
1583
+ """
1584
+ if __kw:
1585
+ raise _no_kw()
1586
+
1587
+ # Query has all the same fields as Select for this operation
1588
+ # this could in theory be based on a protocol but not sure if it's
1589
+ # worth it
1590
+ _MemoizedSelectEntities._generate_for_statement(self) # type: ignore
1591
+ self._set_entities(entities)
1592
+ return self
1593
+
1594
+ @_generative
1595
+ def add_columns(
1596
+ self, *column: _ColumnExpressionArgument[Any]
1597
+ ) -> Query[Any]:
1598
+ """Add one or more column expressions to the list
1599
+ of result columns to be returned.
1600
+
1601
+ .. seealso::
1602
+
1603
+ :meth:`_sql.Select.add_columns` - v2 comparable method.
1604
+ """
1605
+
1606
+ self._raw_columns = list(self._raw_columns)
1607
+
1608
+ self._raw_columns.extend(
1609
+ coercions.expect(
1610
+ roles.ColumnsClauseRole,
1611
+ c,
1612
+ apply_propagate_attrs=self,
1613
+ post_inspect=True,
1614
+ )
1615
+ for c in column
1616
+ )
1617
+ return self
1618
+
1619
+ @util.deprecated(
1620
+ "1.4",
1621
+ ":meth:`_query.Query.add_column` "
1622
+ "is deprecated and will be removed in a "
1623
+ "future release. Please use :meth:`_query.Query.add_columns`",
1624
+ )
1625
+ def add_column(self, column: _ColumnExpressionArgument[Any]) -> Query[Any]:
1626
+ """Add a column expression to the list of result columns to be
1627
+ returned.
1628
+
1629
+ """
1630
+ return self.add_columns(column)
1631
+
1632
+ @_generative
1633
+ def options(self, *args: ExecutableOption) -> Self:
1634
+ """Return a new :class:`_query.Query` object,
1635
+ applying the given list of
1636
+ mapper options.
1637
+
1638
+ Most supplied options regard changing how column- and
1639
+ relationship-mapped attributes are loaded.
1640
+
1641
+ .. seealso::
1642
+
1643
+ :ref:`loading_columns`
1644
+
1645
+ :ref:`relationship_loader_options`
1646
+
1647
+ """
1648
+
1649
+ opts = tuple(util.flatten_iterator(args))
1650
+ if self._compile_options._current_path:
1651
+ # opting for lower method overhead for the checks
1652
+ for opt in opts:
1653
+ if not opt._is_core and opt._is_legacy_option: # type: ignore
1654
+ opt.process_query_conditionally(self) # type: ignore
1655
+ else:
1656
+ for opt in opts:
1657
+ if not opt._is_core and opt._is_legacy_option: # type: ignore
1658
+ opt.process_query(self) # type: ignore
1659
+
1660
+ self._with_options += opts
1661
+ return self
1662
+
1663
+ def with_transformation(
1664
+ self, fn: Callable[[Query[Any]], Query[Any]]
1665
+ ) -> Query[Any]:
1666
+ """Return a new :class:`_query.Query` object transformed by
1667
+ the given function.
1668
+
1669
+ E.g.::
1670
+
1671
+ def filter_something(criterion):
1672
+ def transform(q):
1673
+ return q.filter(criterion)
1674
+ return transform
1675
+
1676
+ q = q.with_transformation(filter_something(x==5))
1677
+
1678
+ This allows ad-hoc recipes to be created for :class:`_query.Query`
1679
+ objects.
1680
+
1681
+ """
1682
+ return fn(self)
1683
+
1684
+ def get_execution_options(self) -> _ImmutableExecuteOptions:
1685
+ """Get the non-SQL options which will take effect during execution.
1686
+
1687
+ .. versionadded:: 1.3
1688
+
1689
+ .. seealso::
1690
+
1691
+ :meth:`_query.Query.execution_options`
1692
+
1693
+ :meth:`_sql.Select.get_execution_options` - v2 comparable method.
1694
+
1695
+ """
1696
+ return self._execution_options
1697
+
1698
+ @overload
1699
+ def execution_options(
1700
+ self,
1701
+ *,
1702
+ compiled_cache: Optional[CompiledCacheType] = ...,
1703
+ logging_token: str = ...,
1704
+ isolation_level: IsolationLevel = ...,
1705
+ no_parameters: bool = False,
1706
+ stream_results: bool = False,
1707
+ max_row_buffer: int = ...,
1708
+ yield_per: int = ...,
1709
+ insertmanyvalues_page_size: int = ...,
1710
+ schema_translate_map: Optional[SchemaTranslateMapType] = ...,
1711
+ populate_existing: bool = False,
1712
+ autoflush: bool = False,
1713
+ preserve_rowcount: bool = False,
1714
+ **opt: Any,
1715
+ ) -> Self: ...
1716
+
1717
+ @overload
1718
+ def execution_options(self, **opt: Any) -> Self: ...
1719
+
1720
+ @_generative
1721
+ def execution_options(self, **kwargs: Any) -> Self:
1722
+ """Set non-SQL options which take effect during execution.
1723
+
1724
+ Options allowed here include all of those accepted by
1725
+ :meth:`_engine.Connection.execution_options`, as well as a series
1726
+ of ORM specific options:
1727
+
1728
+ ``populate_existing=True`` - equivalent to using
1729
+ :meth:`_orm.Query.populate_existing`
1730
+
1731
+ ``autoflush=True|False`` - equivalent to using
1732
+ :meth:`_orm.Query.autoflush`
1733
+
1734
+ ``yield_per=<value>`` - equivalent to using
1735
+ :meth:`_orm.Query.yield_per`
1736
+
1737
+ Note that the ``stream_results`` execution option is enabled
1738
+ automatically if the :meth:`~sqlalchemy.orm.query.Query.yield_per()`
1739
+ method or execution option is used.
1740
+
1741
+ .. versionadded:: 1.4 - added ORM options to
1742
+ :meth:`_orm.Query.execution_options`
1743
+
1744
+ The execution options may also be specified on a per execution basis
1745
+ when using :term:`2.0 style` queries via the
1746
+ :paramref:`_orm.Session.execution_options` parameter.
1747
+
1748
+ .. warning:: The
1749
+ :paramref:`_engine.Connection.execution_options.stream_results`
1750
+ parameter should not be used at the level of individual ORM
1751
+ statement executions, as the :class:`_orm.Session` will not track
1752
+ objects from different schema translate maps within a single
1753
+ session. For multiple schema translate maps within the scope of a
1754
+ single :class:`_orm.Session`, see :ref:`examples_sharding`.
1755
+
1756
+
1757
+ .. seealso::
1758
+
1759
+ :ref:`engine_stream_results`
1760
+
1761
+ :meth:`_query.Query.get_execution_options`
1762
+
1763
+ :meth:`_sql.Select.execution_options` - v2 equivalent method.
1764
+
1765
+ """
1766
+ self._execution_options = self._execution_options.union(kwargs)
1767
+ return self
1768
+
1769
+ @_generative
1770
+ def with_for_update(
1771
+ self,
1772
+ *,
1773
+ nowait: bool = False,
1774
+ read: bool = False,
1775
+ of: Optional[_ForUpdateOfArgument] = None,
1776
+ skip_locked: bool = False,
1777
+ key_share: bool = False,
1778
+ ) -> Self:
1779
+ """return a new :class:`_query.Query`
1780
+ with the specified options for the
1781
+ ``FOR UPDATE`` clause.
1782
+
1783
+ The behavior of this method is identical to that of
1784
+ :meth:`_expression.GenerativeSelect.with_for_update`.
1785
+ When called with no arguments,
1786
+ the resulting ``SELECT`` statement will have a ``FOR UPDATE`` clause
1787
+ appended. When additional arguments are specified, backend-specific
1788
+ options such as ``FOR UPDATE NOWAIT`` or ``LOCK IN SHARE MODE``
1789
+ can take effect.
1790
+
1791
+ E.g.::
1792
+
1793
+ q = sess.query(User).populate_existing().with_for_update(nowait=True, of=User)
1794
+
1795
+ The above query on a PostgreSQL backend will render like::
1796
+
1797
+ SELECT users.id AS users_id FROM users FOR UPDATE OF users NOWAIT
1798
+
1799
+ .. warning::
1800
+
1801
+ Using ``with_for_update`` in the context of eager loading
1802
+ relationships is not officially supported or recommended by
1803
+ SQLAlchemy and may not work with certain queries on various
1804
+ database backends. When ``with_for_update`` is successfully used
1805
+ with a query that involves :func:`_orm.joinedload`, SQLAlchemy will
1806
+ attempt to emit SQL that locks all involved tables.
1807
+
1808
+ .. note:: It is generally a good idea to combine the use of the
1809
+ :meth:`_orm.Query.populate_existing` method when using the
1810
+ :meth:`_orm.Query.with_for_update` method. The purpose of
1811
+ :meth:`_orm.Query.populate_existing` is to force all the data read
1812
+ from the SELECT to be populated into the ORM objects returned,
1813
+ even if these objects are already in the :term:`identity map`.
1814
+
1815
+ .. seealso::
1816
+
1817
+ :meth:`_expression.GenerativeSelect.with_for_update`
1818
+ - Core level method with
1819
+ full argument and behavioral description.
1820
+
1821
+ :meth:`_orm.Query.populate_existing` - overwrites attributes of
1822
+ objects already loaded in the identity map.
1823
+
1824
+ """ # noqa: E501
1825
+
1826
+ self._for_update_arg = ForUpdateArg(
1827
+ read=read,
1828
+ nowait=nowait,
1829
+ of=of,
1830
+ skip_locked=skip_locked,
1831
+ key_share=key_share,
1832
+ )
1833
+ return self
1834
+
1835
+ @_generative
1836
+ def params(
1837
+ self, __params: Optional[Dict[str, Any]] = None, **kw: Any
1838
+ ) -> Self:
1839
+ r"""Add values for bind parameters which may have been
1840
+ specified in filter().
1841
+
1842
+ Parameters may be specified using \**kwargs, or optionally a single
1843
+ dictionary as the first positional argument. The reason for both is
1844
+ that \**kwargs is convenient, however some parameter dictionaries
1845
+ contain unicode keys in which case \**kwargs cannot be used.
1846
+
1847
+ """
1848
+ if __params:
1849
+ kw.update(__params)
1850
+ self._params = self._params.union(kw)
1851
+ return self
1852
+
1853
+ def where(self, *criterion: _ColumnExpressionArgument[bool]) -> Self:
1854
+ """A synonym for :meth:`.Query.filter`.
1855
+
1856
+ .. versionadded:: 1.4
1857
+
1858
+ .. seealso::
1859
+
1860
+ :meth:`_sql.Select.where` - v2 equivalent method.
1861
+
1862
+ """
1863
+ return self.filter(*criterion)
1864
+
1865
+ @_generative
1866
+ @_assertions(_no_statement_condition, _no_limit_offset)
1867
+ def filter(self, *criterion: _ColumnExpressionArgument[bool]) -> Self:
1868
+ r"""Apply the given filtering criterion to a copy
1869
+ of this :class:`_query.Query`, using SQL expressions.
1870
+
1871
+ e.g.::
1872
+
1873
+ session.query(MyClass).filter(MyClass.name == 'some name')
1874
+
1875
+ Multiple criteria may be specified as comma separated; the effect
1876
+ is that they will be joined together using the :func:`.and_`
1877
+ function::
1878
+
1879
+ session.query(MyClass).\
1880
+ filter(MyClass.name == 'some name', MyClass.id > 5)
1881
+
1882
+ The criterion is any SQL expression object applicable to the
1883
+ WHERE clause of a select. String expressions are coerced
1884
+ into SQL expression constructs via the :func:`_expression.text`
1885
+ construct.
1886
+
1887
+ .. seealso::
1888
+
1889
+ :meth:`_query.Query.filter_by` - filter on keyword expressions.
1890
+
1891
+ :meth:`_sql.Select.where` - v2 equivalent method.
1892
+
1893
+ """
1894
+ for crit in list(criterion):
1895
+ crit = coercions.expect(
1896
+ roles.WhereHavingRole, crit, apply_propagate_attrs=self
1897
+ )
1898
+
1899
+ self._where_criteria += (crit,)
1900
+ return self
1901
+
1902
+ @util.memoized_property
1903
+ def _last_joined_entity(
1904
+ self,
1905
+ ) -> Optional[Union[_InternalEntityType[Any], _JoinTargetElement]]:
1906
+ if self._setup_joins:
1907
+ return _determine_last_joined_entity(
1908
+ self._setup_joins,
1909
+ )
1910
+ else:
1911
+ return None
1912
+
1913
+ def _filter_by_zero(self) -> Any:
1914
+ """for the filter_by() method, return the target entity for which
1915
+ we will attempt to derive an expression from based on string name.
1916
+
1917
+ """
1918
+
1919
+ if self._setup_joins:
1920
+ _last_joined_entity = self._last_joined_entity
1921
+ if _last_joined_entity is not None:
1922
+ return _last_joined_entity
1923
+
1924
+ # discussion related to #7239
1925
+ # special check determines if we should try to derive attributes
1926
+ # for filter_by() from the "from object", i.e., if the user
1927
+ # called query.select_from(some selectable).filter_by(some_attr=value).
1928
+ # We don't want to do that in the case that methods like
1929
+ # from_self(), select_entity_from(), or a set op like union() were
1930
+ # called; while these methods also place a
1931
+ # selectable in the _from_obj collection, they also set up
1932
+ # the _set_base_alias boolean which turns on the whole "adapt the
1933
+ # entity to this selectable" thing, meaning the query still continues
1934
+ # to construct itself in terms of the lead entity that was passed
1935
+ # to query(), e.g. query(User).from_self() is still in terms of User,
1936
+ # and not the subquery that from_self() created. This feature of
1937
+ # "implicitly adapt all occurrences of entity X to some arbitrary
1938
+ # subquery" is the main thing I am trying to do away with in 2.0 as
1939
+ # users should now used aliased() for that, but I can't entirely get
1940
+ # rid of it due to query.union() and other set ops relying upon it.
1941
+ #
1942
+ # compare this to the base Select()._filter_by_zero() which can
1943
+ # just return self._from_obj[0] if present, because there is no
1944
+ # "_set_base_alias" feature.
1945
+ #
1946
+ # IOW, this conditional essentially detects if
1947
+ # "select_from(some_selectable)" has been called, as opposed to
1948
+ # "select_entity_from()", "from_self()"
1949
+ # or "union() / some_set_op()".
1950
+ if self._from_obj and not self._compile_options._set_base_alias:
1951
+ return self._from_obj[0]
1952
+
1953
+ return self._raw_columns[0]
1954
+
1955
+ def filter_by(self, **kwargs: Any) -> Self:
1956
+ r"""Apply the given filtering criterion to a copy
1957
+ of this :class:`_query.Query`, using keyword expressions.
1958
+
1959
+ e.g.::
1960
+
1961
+ session.query(MyClass).filter_by(name = 'some name')
1962
+
1963
+ Multiple criteria may be specified as comma separated; the effect
1964
+ is that they will be joined together using the :func:`.and_`
1965
+ function::
1966
+
1967
+ session.query(MyClass).\
1968
+ filter_by(name = 'some name', id = 5)
1969
+
1970
+ The keyword expressions are extracted from the primary
1971
+ entity of the query, or the last entity that was the
1972
+ target of a call to :meth:`_query.Query.join`.
1973
+
1974
+ .. seealso::
1975
+
1976
+ :meth:`_query.Query.filter` - filter on SQL expressions.
1977
+
1978
+ :meth:`_sql.Select.filter_by` - v2 comparable method.
1979
+
1980
+ """
1981
+ from_entity = self._filter_by_zero()
1982
+
1983
+ clauses = [
1984
+ _entity_namespace_key(from_entity, key) == value
1985
+ for key, value in kwargs.items()
1986
+ ]
1987
+ return self.filter(*clauses)
1988
+
1989
+ @_generative
1990
+ def order_by(
1991
+ self,
1992
+ __first: Union[
1993
+ Literal[None, False, _NoArg.NO_ARG],
1994
+ _ColumnExpressionOrStrLabelArgument[Any],
1995
+ ] = _NoArg.NO_ARG,
1996
+ *clauses: _ColumnExpressionOrStrLabelArgument[Any],
1997
+ ) -> Self:
1998
+ """Apply one or more ORDER BY criteria to the query and return
1999
+ the newly resulting :class:`_query.Query`.
2000
+
2001
+ e.g.::
2002
+
2003
+ q = session.query(Entity).order_by(Entity.id, Entity.name)
2004
+
2005
+ Calling this method multiple times is equivalent to calling it once
2006
+ with all the clauses concatenated. All existing ORDER BY criteria may
2007
+ be cancelled by passing ``None`` by itself. New ORDER BY criteria may
2008
+ then be added by invoking :meth:`_orm.Query.order_by` again, e.g.::
2009
+
2010
+ # will erase all ORDER BY and ORDER BY new_col alone
2011
+ q = q.order_by(None).order_by(new_col)
2012
+
2013
+ .. seealso::
2014
+
2015
+ These sections describe ORDER BY in terms of :term:`2.0 style`
2016
+ invocation but apply to :class:`_orm.Query` as well:
2017
+
2018
+ :ref:`tutorial_order_by` - in the :ref:`unified_tutorial`
2019
+
2020
+ :ref:`tutorial_order_by_label` - in the :ref:`unified_tutorial`
2021
+
2022
+ :meth:`_sql.Select.order_by` - v2 equivalent method.
2023
+
2024
+ """
2025
+
2026
+ for assertion in (self._no_statement_condition, self._no_limit_offset):
2027
+ assertion("order_by")
2028
+
2029
+ if not clauses and (__first is None or __first is False):
2030
+ self._order_by_clauses = ()
2031
+ elif __first is not _NoArg.NO_ARG:
2032
+ criterion = tuple(
2033
+ coercions.expect(roles.OrderByRole, clause)
2034
+ for clause in (__first,) + clauses
2035
+ )
2036
+ self._order_by_clauses += criterion
2037
+
2038
+ return self
2039
+
2040
+ @_generative
2041
+ def group_by(
2042
+ self,
2043
+ __first: Union[
2044
+ Literal[None, False, _NoArg.NO_ARG],
2045
+ _ColumnExpressionOrStrLabelArgument[Any],
2046
+ ] = _NoArg.NO_ARG,
2047
+ *clauses: _ColumnExpressionOrStrLabelArgument[Any],
2048
+ ) -> Self:
2049
+ """Apply one or more GROUP BY criterion to the query and return
2050
+ the newly resulting :class:`_query.Query`.
2051
+
2052
+ All existing GROUP BY settings can be suppressed by
2053
+ passing ``None`` - this will suppress any GROUP BY configured
2054
+ on mappers as well.
2055
+
2056
+ .. seealso::
2057
+
2058
+ These sections describe GROUP BY in terms of :term:`2.0 style`
2059
+ invocation but apply to :class:`_orm.Query` as well:
2060
+
2061
+ :ref:`tutorial_group_by_w_aggregates` - in the
2062
+ :ref:`unified_tutorial`
2063
+
2064
+ :ref:`tutorial_order_by_label` - in the :ref:`unified_tutorial`
2065
+
2066
+ :meth:`_sql.Select.group_by` - v2 equivalent method.
2067
+
2068
+ """
2069
+
2070
+ for assertion in (self._no_statement_condition, self._no_limit_offset):
2071
+ assertion("group_by")
2072
+
2073
+ if not clauses and (__first is None or __first is False):
2074
+ self._group_by_clauses = ()
2075
+ elif __first is not _NoArg.NO_ARG:
2076
+ criterion = tuple(
2077
+ coercions.expect(roles.GroupByRole, clause)
2078
+ for clause in (__first,) + clauses
2079
+ )
2080
+ self._group_by_clauses += criterion
2081
+ return self
2082
+
2083
+ @_generative
2084
+ @_assertions(_no_statement_condition, _no_limit_offset)
2085
+ def having(self, *having: _ColumnExpressionArgument[bool]) -> Self:
2086
+ r"""Apply a HAVING criterion to the query and return the
2087
+ newly resulting :class:`_query.Query`.
2088
+
2089
+ :meth:`_query.Query.having` is used in conjunction with
2090
+ :meth:`_query.Query.group_by`.
2091
+
2092
+ HAVING criterion makes it possible to use filters on aggregate
2093
+ functions like COUNT, SUM, AVG, MAX, and MIN, eg.::
2094
+
2095
+ q = session.query(User.id).\
2096
+ join(User.addresses).\
2097
+ group_by(User.id).\
2098
+ having(func.count(Address.id) > 2)
2099
+
2100
+ .. seealso::
2101
+
2102
+ :meth:`_sql.Select.having` - v2 equivalent method.
2103
+
2104
+ """
2105
+
2106
+ for criterion in having:
2107
+ having_criteria = coercions.expect(
2108
+ roles.WhereHavingRole, criterion
2109
+ )
2110
+ self._having_criteria += (having_criteria,)
2111
+ return self
2112
+
2113
+ def _set_op(self, expr_fn: Any, *q: Query[Any]) -> Self:
2114
+ list_of_queries = (self,) + q
2115
+ return self._from_selectable(expr_fn(*(list_of_queries)).subquery())
2116
+
2117
+ def union(self, *q: Query[Any]) -> Self:
2118
+ """Produce a UNION of this Query against one or more queries.
2119
+
2120
+ e.g.::
2121
+
2122
+ q1 = sess.query(SomeClass).filter(SomeClass.foo=='bar')
2123
+ q2 = sess.query(SomeClass).filter(SomeClass.bar=='foo')
2124
+
2125
+ q3 = q1.union(q2)
2126
+
2127
+ The method accepts multiple Query objects so as to control
2128
+ the level of nesting. A series of ``union()`` calls such as::
2129
+
2130
+ x.union(y).union(z).all()
2131
+
2132
+ will nest on each ``union()``, and produces::
2133
+
2134
+ SELECT * FROM (SELECT * FROM (SELECT * FROM X UNION
2135
+ SELECT * FROM y) UNION SELECT * FROM Z)
2136
+
2137
+ Whereas::
2138
+
2139
+ x.union(y, z).all()
2140
+
2141
+ produces::
2142
+
2143
+ SELECT * FROM (SELECT * FROM X UNION SELECT * FROM y UNION
2144
+ SELECT * FROM Z)
2145
+
2146
+ Note that many database backends do not allow ORDER BY to
2147
+ be rendered on a query called within UNION, EXCEPT, etc.
2148
+ To disable all ORDER BY clauses including those configured
2149
+ on mappers, issue ``query.order_by(None)`` - the resulting
2150
+ :class:`_query.Query` object will not render ORDER BY within
2151
+ its SELECT statement.
2152
+
2153
+ .. seealso::
2154
+
2155
+ :meth:`_sql.Select.union` - v2 equivalent method.
2156
+
2157
+ """
2158
+ return self._set_op(expression.union, *q)
2159
+
2160
+ def union_all(self, *q: Query[Any]) -> Self:
2161
+ """Produce a UNION ALL of this Query against one or more queries.
2162
+
2163
+ Works the same way as :meth:`~sqlalchemy.orm.query.Query.union`. See
2164
+ that method for usage examples.
2165
+
2166
+ .. seealso::
2167
+
2168
+ :meth:`_sql.Select.union_all` - v2 equivalent method.
2169
+
2170
+ """
2171
+ return self._set_op(expression.union_all, *q)
2172
+
2173
+ def intersect(self, *q: Query[Any]) -> Self:
2174
+ """Produce an INTERSECT of this Query against one or more queries.
2175
+
2176
+ Works the same way as :meth:`~sqlalchemy.orm.query.Query.union`. See
2177
+ that method for usage examples.
2178
+
2179
+ .. seealso::
2180
+
2181
+ :meth:`_sql.Select.intersect` - v2 equivalent method.
2182
+
2183
+ """
2184
+ return self._set_op(expression.intersect, *q)
2185
+
2186
+ def intersect_all(self, *q: Query[Any]) -> Self:
2187
+ """Produce an INTERSECT ALL of this Query against one or more queries.
2188
+
2189
+ Works the same way as :meth:`~sqlalchemy.orm.query.Query.union`. See
2190
+ that method for usage examples.
2191
+
2192
+ .. seealso::
2193
+
2194
+ :meth:`_sql.Select.intersect_all` - v2 equivalent method.
2195
+
2196
+ """
2197
+ return self._set_op(expression.intersect_all, *q)
2198
+
2199
+ def except_(self, *q: Query[Any]) -> Self:
2200
+ """Produce an EXCEPT of this Query against one or more queries.
2201
+
2202
+ Works the same way as :meth:`~sqlalchemy.orm.query.Query.union`. See
2203
+ that method for usage examples.
2204
+
2205
+ .. seealso::
2206
+
2207
+ :meth:`_sql.Select.except_` - v2 equivalent method.
2208
+
2209
+ """
2210
+ return self._set_op(expression.except_, *q)
2211
+
2212
+ def except_all(self, *q: Query[Any]) -> Self:
2213
+ """Produce an EXCEPT ALL of this Query against one or more queries.
2214
+
2215
+ Works the same way as :meth:`~sqlalchemy.orm.query.Query.union`. See
2216
+ that method for usage examples.
2217
+
2218
+ .. seealso::
2219
+
2220
+ :meth:`_sql.Select.except_all` - v2 equivalent method.
2221
+
2222
+ """
2223
+ return self._set_op(expression.except_all, *q)
2224
+
2225
+ @_generative
2226
+ @_assertions(_no_statement_condition, _no_limit_offset)
2227
+ def join(
2228
+ self,
2229
+ target: _JoinTargetArgument,
2230
+ onclause: Optional[_OnClauseArgument] = None,
2231
+ *,
2232
+ isouter: bool = False,
2233
+ full: bool = False,
2234
+ ) -> Self:
2235
+ r"""Create a SQL JOIN against this :class:`_query.Query`
2236
+ object's criterion
2237
+ and apply generatively, returning the newly resulting
2238
+ :class:`_query.Query`.
2239
+
2240
+ **Simple Relationship Joins**
2241
+
2242
+ Consider a mapping between two classes ``User`` and ``Address``,
2243
+ with a relationship ``User.addresses`` representing a collection
2244
+ of ``Address`` objects associated with each ``User``. The most
2245
+ common usage of :meth:`_query.Query.join`
2246
+ is to create a JOIN along this
2247
+ relationship, using the ``User.addresses`` attribute as an indicator
2248
+ for how this should occur::
2249
+
2250
+ q = session.query(User).join(User.addresses)
2251
+
2252
+ Where above, the call to :meth:`_query.Query.join` along
2253
+ ``User.addresses`` will result in SQL approximately equivalent to::
2254
+
2255
+ SELECT user.id, user.name
2256
+ FROM user JOIN address ON user.id = address.user_id
2257
+
2258
+ In the above example we refer to ``User.addresses`` as passed to
2259
+ :meth:`_query.Query.join` as the "on clause", that is, it indicates
2260
+ how the "ON" portion of the JOIN should be constructed.
2261
+
2262
+ To construct a chain of joins, multiple :meth:`_query.Query.join`
2263
+ calls may be used. The relationship-bound attribute implies both
2264
+ the left and right side of the join at once::
2265
+
2266
+ q = session.query(User).\
2267
+ join(User.orders).\
2268
+ join(Order.items).\
2269
+ join(Item.keywords)
2270
+
2271
+ .. note:: as seen in the above example, **the order in which each
2272
+ call to the join() method occurs is important**. Query would not,
2273
+ for example, know how to join correctly if we were to specify
2274
+ ``User``, then ``Item``, then ``Order``, in our chain of joins; in
2275
+ such a case, depending on the arguments passed, it may raise an
2276
+ error that it doesn't know how to join, or it may produce invalid
2277
+ SQL in which case the database will raise an error. In correct
2278
+ practice, the
2279
+ :meth:`_query.Query.join` method is invoked in such a way that lines
2280
+ up with how we would want the JOIN clauses in SQL to be
2281
+ rendered, and each call should represent a clear link from what
2282
+ precedes it.
2283
+
2284
+ **Joins to a Target Entity or Selectable**
2285
+
2286
+ A second form of :meth:`_query.Query.join` allows any mapped entity or
2287
+ core selectable construct as a target. In this usage,
2288
+ :meth:`_query.Query.join` will attempt to create a JOIN along the
2289
+ natural foreign key relationship between two entities::
2290
+
2291
+ q = session.query(User).join(Address)
2292
+
2293
+ In the above calling form, :meth:`_query.Query.join` is called upon to
2294
+ create the "on clause" automatically for us. This calling form will
2295
+ ultimately raise an error if either there are no foreign keys between
2296
+ the two entities, or if there are multiple foreign key linkages between
2297
+ the target entity and the entity or entities already present on the
2298
+ left side such that creating a join requires more information. Note
2299
+ that when indicating a join to a target without any ON clause, ORM
2300
+ configured relationships are not taken into account.
2301
+
2302
+ **Joins to a Target with an ON Clause**
2303
+
2304
+ The third calling form allows both the target entity as well
2305
+ as the ON clause to be passed explicitly. A example that includes
2306
+ a SQL expression as the ON clause is as follows::
2307
+
2308
+ q = session.query(User).join(Address, User.id==Address.user_id)
2309
+
2310
+ The above form may also use a relationship-bound attribute as the
2311
+ ON clause as well::
2312
+
2313
+ q = session.query(User).join(Address, User.addresses)
2314
+
2315
+ The above syntax can be useful for the case where we wish
2316
+ to join to an alias of a particular target entity. If we wanted
2317
+ to join to ``Address`` twice, it could be achieved using two
2318
+ aliases set up using the :func:`~sqlalchemy.orm.aliased` function::
2319
+
2320
+ a1 = aliased(Address)
2321
+ a2 = aliased(Address)
2322
+
2323
+ q = session.query(User).\
2324
+ join(a1, User.addresses).\
2325
+ join(a2, User.addresses).\
2326
+ filter(a1.email_address=='ed@foo.com').\
2327
+ filter(a2.email_address=='ed@bar.com')
2328
+
2329
+ The relationship-bound calling form can also specify a target entity
2330
+ using the :meth:`_orm.PropComparator.of_type` method; a query
2331
+ equivalent to the one above would be::
2332
+
2333
+ a1 = aliased(Address)
2334
+ a2 = aliased(Address)
2335
+
2336
+ q = session.query(User).\
2337
+ join(User.addresses.of_type(a1)).\
2338
+ join(User.addresses.of_type(a2)).\
2339
+ filter(a1.email_address == 'ed@foo.com').\
2340
+ filter(a2.email_address == 'ed@bar.com')
2341
+
2342
+ **Augmenting Built-in ON Clauses**
2343
+
2344
+ As a substitute for providing a full custom ON condition for an
2345
+ existing relationship, the :meth:`_orm.PropComparator.and_` function
2346
+ may be applied to a relationship attribute to augment additional
2347
+ criteria into the ON clause; the additional criteria will be combined
2348
+ with the default criteria using AND::
2349
+
2350
+ q = session.query(User).join(
2351
+ User.addresses.and_(Address.email_address != 'foo@bar.com')
2352
+ )
2353
+
2354
+ .. versionadded:: 1.4
2355
+
2356
+ **Joining to Tables and Subqueries**
2357
+
2358
+
2359
+ The target of a join may also be any table or SELECT statement,
2360
+ which may be related to a target entity or not. Use the
2361
+ appropriate ``.subquery()`` method in order to make a subquery
2362
+ out of a query::
2363
+
2364
+ subq = session.query(Address).\
2365
+ filter(Address.email_address == 'ed@foo.com').\
2366
+ subquery()
2367
+
2368
+
2369
+ q = session.query(User).join(
2370
+ subq, User.id == subq.c.user_id
2371
+ )
2372
+
2373
+ Joining to a subquery in terms of a specific relationship and/or
2374
+ target entity may be achieved by linking the subquery to the
2375
+ entity using :func:`_orm.aliased`::
2376
+
2377
+ subq = session.query(Address).\
2378
+ filter(Address.email_address == 'ed@foo.com').\
2379
+ subquery()
2380
+
2381
+ address_subq = aliased(Address, subq)
2382
+
2383
+ q = session.query(User).join(
2384
+ User.addresses.of_type(address_subq)
2385
+ )
2386
+
2387
+
2388
+ **Controlling what to Join From**
2389
+
2390
+ In cases where the left side of the current state of
2391
+ :class:`_query.Query` is not in line with what we want to join from,
2392
+ the :meth:`_query.Query.select_from` method may be used::
2393
+
2394
+ q = session.query(Address).select_from(User).\
2395
+ join(User.addresses).\
2396
+ filter(User.name == 'ed')
2397
+
2398
+ Which will produce SQL similar to::
2399
+
2400
+ SELECT address.* FROM user
2401
+ JOIN address ON user.id=address.user_id
2402
+ WHERE user.name = :name_1
2403
+
2404
+ .. seealso::
2405
+
2406
+ :meth:`_sql.Select.join` - v2 equivalent method.
2407
+
2408
+ :param \*props: Incoming arguments for :meth:`_query.Query.join`,
2409
+ the props collection in modern use should be considered to be a one
2410
+ or two argument form, either as a single "target" entity or ORM
2411
+ attribute-bound relationship, or as a target entity plus an "on
2412
+ clause" which may be a SQL expression or ORM attribute-bound
2413
+ relationship.
2414
+
2415
+ :param isouter=False: If True, the join used will be a left outer join,
2416
+ just as if the :meth:`_query.Query.outerjoin` method were called.
2417
+
2418
+ :param full=False: render FULL OUTER JOIN; implies ``isouter``.
2419
+
2420
+ """
2421
+
2422
+ join_target = coercions.expect(
2423
+ roles.JoinTargetRole,
2424
+ target,
2425
+ apply_propagate_attrs=self,
2426
+ legacy=True,
2427
+ )
2428
+ if onclause is not None:
2429
+ onclause_element = coercions.expect(
2430
+ roles.OnClauseRole, onclause, legacy=True
2431
+ )
2432
+ else:
2433
+ onclause_element = None
2434
+
2435
+ self._setup_joins += (
2436
+ (
2437
+ join_target,
2438
+ onclause_element,
2439
+ None,
2440
+ {
2441
+ "isouter": isouter,
2442
+ "full": full,
2443
+ },
2444
+ ),
2445
+ )
2446
+
2447
+ self.__dict__.pop("_last_joined_entity", None)
2448
+ return self
2449
+
2450
+ def outerjoin(
2451
+ self,
2452
+ target: _JoinTargetArgument,
2453
+ onclause: Optional[_OnClauseArgument] = None,
2454
+ *,
2455
+ full: bool = False,
2456
+ ) -> Self:
2457
+ """Create a left outer join against this ``Query`` object's criterion
2458
+ and apply generatively, returning the newly resulting ``Query``.
2459
+
2460
+ Usage is the same as the ``join()`` method.
2461
+
2462
+ .. seealso::
2463
+
2464
+ :meth:`_sql.Select.outerjoin` - v2 equivalent method.
2465
+
2466
+ """
2467
+ return self.join(target, onclause=onclause, isouter=True, full=full)
2468
+
2469
+ @_generative
2470
+ @_assertions(_no_statement_condition)
2471
+ def reset_joinpoint(self) -> Self:
2472
+ """Return a new :class:`.Query`, where the "join point" has
2473
+ been reset back to the base FROM entities of the query.
2474
+
2475
+ This method is usually used in conjunction with the
2476
+ ``aliased=True`` feature of the :meth:`~.Query.join`
2477
+ method. See the example in :meth:`~.Query.join` for how
2478
+ this is used.
2479
+
2480
+ """
2481
+ self._last_joined_entity = None
2482
+
2483
+ return self
2484
+
2485
+ @_generative
2486
+ @_assertions(_no_clauseelement_condition)
2487
+ def select_from(self, *from_obj: _FromClauseArgument) -> Self:
2488
+ r"""Set the FROM clause of this :class:`.Query` explicitly.
2489
+
2490
+ :meth:`.Query.select_from` is often used in conjunction with
2491
+ :meth:`.Query.join` in order to control which entity is selected
2492
+ from on the "left" side of the join.
2493
+
2494
+ The entity or selectable object here effectively replaces the
2495
+ "left edge" of any calls to :meth:`~.Query.join`, when no
2496
+ joinpoint is otherwise established - usually, the default "join
2497
+ point" is the leftmost entity in the :class:`~.Query` object's
2498
+ list of entities to be selected.
2499
+
2500
+ A typical example::
2501
+
2502
+ q = session.query(Address).select_from(User).\
2503
+ join(User.addresses).\
2504
+ filter(User.name == 'ed')
2505
+
2506
+ Which produces SQL equivalent to::
2507
+
2508
+ SELECT address.* FROM user
2509
+ JOIN address ON user.id=address.user_id
2510
+ WHERE user.name = :name_1
2511
+
2512
+ :param \*from_obj: collection of one or more entities to apply
2513
+ to the FROM clause. Entities can be mapped classes,
2514
+ :class:`.AliasedClass` objects, :class:`.Mapper` objects
2515
+ as well as core :class:`.FromClause` elements like subqueries.
2516
+
2517
+ .. seealso::
2518
+
2519
+ :meth:`~.Query.join`
2520
+
2521
+ :meth:`.Query.select_entity_from`
2522
+
2523
+ :meth:`_sql.Select.select_from` - v2 equivalent method.
2524
+
2525
+ """
2526
+
2527
+ self._set_select_from(from_obj, False)
2528
+ return self
2529
+
2530
+ def __getitem__(self, item: Any) -> Any:
2531
+ return orm_util._getitem(
2532
+ self,
2533
+ item,
2534
+ )
2535
+
2536
+ @_generative
2537
+ @_assertions(_no_statement_condition)
2538
+ def slice(
2539
+ self,
2540
+ start: int,
2541
+ stop: int,
2542
+ ) -> Self:
2543
+ """Computes the "slice" of the :class:`_query.Query` represented by
2544
+ the given indices and returns the resulting :class:`_query.Query`.
2545
+
2546
+ The start and stop indices behave like the argument to Python's
2547
+ built-in :func:`range` function. This method provides an
2548
+ alternative to using ``LIMIT``/``OFFSET`` to get a slice of the
2549
+ query.
2550
+
2551
+ For example, ::
2552
+
2553
+ session.query(User).order_by(User.id).slice(1, 3)
2554
+
2555
+ renders as
2556
+
2557
+ .. sourcecode:: sql
2558
+
2559
+ SELECT users.id AS users_id,
2560
+ users.name AS users_name
2561
+ FROM users ORDER BY users.id
2562
+ LIMIT ? OFFSET ?
2563
+ (2, 1)
2564
+
2565
+ .. seealso::
2566
+
2567
+ :meth:`_query.Query.limit`
2568
+
2569
+ :meth:`_query.Query.offset`
2570
+
2571
+ :meth:`_sql.Select.slice` - v2 equivalent method.
2572
+
2573
+ """
2574
+
2575
+ self._limit_clause, self._offset_clause = sql_util._make_slice(
2576
+ self._limit_clause, self._offset_clause, start, stop
2577
+ )
2578
+ return self
2579
+
2580
+ @_generative
2581
+ @_assertions(_no_statement_condition)
2582
+ def limit(self, limit: _LimitOffsetType) -> Self:
2583
+ """Apply a ``LIMIT`` to the query and return the newly resulting
2584
+ ``Query``.
2585
+
2586
+ .. seealso::
2587
+
2588
+ :meth:`_sql.Select.limit` - v2 equivalent method.
2589
+
2590
+ """
2591
+ self._limit_clause = sql_util._offset_or_limit_clause(limit)
2592
+ return self
2593
+
2594
+ @_generative
2595
+ @_assertions(_no_statement_condition)
2596
+ def offset(self, offset: _LimitOffsetType) -> Self:
2597
+ """Apply an ``OFFSET`` to the query and return the newly resulting
2598
+ ``Query``.
2599
+
2600
+ .. seealso::
2601
+
2602
+ :meth:`_sql.Select.offset` - v2 equivalent method.
2603
+ """
2604
+ self._offset_clause = sql_util._offset_or_limit_clause(offset)
2605
+ return self
2606
+
2607
+ @_generative
2608
+ @_assertions(_no_statement_condition)
2609
+ def distinct(self, *expr: _ColumnExpressionArgument[Any]) -> Self:
2610
+ r"""Apply a ``DISTINCT`` to the query and return the newly resulting
2611
+ ``Query``.
2612
+
2613
+
2614
+ .. note::
2615
+
2616
+ The ORM-level :meth:`.distinct` call includes logic that will
2617
+ automatically add columns from the ORDER BY of the query to the
2618
+ columns clause of the SELECT statement, to satisfy the common need
2619
+ of the database backend that ORDER BY columns be part of the SELECT
2620
+ list when DISTINCT is used. These columns *are not* added to the
2621
+ list of columns actually fetched by the :class:`_query.Query`,
2622
+ however,
2623
+ so would not affect results. The columns are passed through when
2624
+ using the :attr:`_query.Query.statement` accessor, however.
2625
+
2626
+ .. deprecated:: 2.0 This logic is deprecated and will be removed
2627
+ in SQLAlchemy 2.0. See :ref:`migration_20_query_distinct`
2628
+ for a description of this use case in 2.0.
2629
+
2630
+ .. seealso::
2631
+
2632
+ :meth:`_sql.Select.distinct` - v2 equivalent method.
2633
+
2634
+ :param \*expr: optional column expressions. When present,
2635
+ the PostgreSQL dialect will render a ``DISTINCT ON (<expressions>)``
2636
+ construct.
2637
+
2638
+ .. deprecated:: 1.4 Using \*expr in other dialects is deprecated
2639
+ and will raise :class:`_exc.CompileError` in a future version.
2640
+
2641
+ """
2642
+ if expr:
2643
+ self._distinct = True
2644
+ self._distinct_on = self._distinct_on + tuple(
2645
+ coercions.expect(roles.ByOfRole, e) for e in expr
2646
+ )
2647
+ else:
2648
+ self._distinct = True
2649
+ return self
2650
+
2651
+ def all(self) -> List[_T]:
2652
+ """Return the results represented by this :class:`_query.Query`
2653
+ as a list.
2654
+
2655
+ This results in an execution of the underlying SQL statement.
2656
+
2657
+ .. warning:: The :class:`_query.Query` object,
2658
+ when asked to return either
2659
+ a sequence or iterator that consists of full ORM-mapped entities,
2660
+ will **deduplicate entries based on primary key**. See the FAQ for
2661
+ more details.
2662
+
2663
+ .. seealso::
2664
+
2665
+ :ref:`faq_query_deduplicating`
2666
+
2667
+ .. seealso::
2668
+
2669
+ :meth:`_engine.Result.all` - v2 comparable method.
2670
+
2671
+ :meth:`_engine.Result.scalars` - v2 comparable method.
2672
+ """
2673
+ return self._iter().all() # type: ignore
2674
+
2675
+ @_generative
2676
+ @_assertions(_no_clauseelement_condition)
2677
+ def from_statement(self, statement: ExecutableReturnsRows) -> Self:
2678
+ """Execute the given SELECT statement and return results.
2679
+
2680
+ This method bypasses all internal statement compilation, and the
2681
+ statement is executed without modification.
2682
+
2683
+ The statement is typically either a :func:`_expression.text`
2684
+ or :func:`_expression.select` construct, and should return the set
2685
+ of columns
2686
+ appropriate to the entity class represented by this
2687
+ :class:`_query.Query`.
2688
+
2689
+ .. seealso::
2690
+
2691
+ :meth:`_sql.Select.from_statement` - v2 comparable method.
2692
+
2693
+ """
2694
+ statement = coercions.expect(
2695
+ roles.SelectStatementRole, statement, apply_propagate_attrs=self
2696
+ )
2697
+ self._statement = statement
2698
+ return self
2699
+
2700
+ def first(self) -> Optional[_T]:
2701
+ """Return the first result of this ``Query`` or
2702
+ None if the result doesn't contain any row.
2703
+
2704
+ first() applies a limit of one within the generated SQL, so that
2705
+ only one primary entity row is generated on the server side
2706
+ (note this may consist of multiple result rows if join-loaded
2707
+ collections are present).
2708
+
2709
+ Calling :meth:`_query.Query.first`
2710
+ results in an execution of the underlying
2711
+ query.
2712
+
2713
+ .. seealso::
2714
+
2715
+ :meth:`_query.Query.one`
2716
+
2717
+ :meth:`_query.Query.one_or_none`
2718
+
2719
+ :meth:`_engine.Result.first` - v2 comparable method.
2720
+
2721
+ :meth:`_engine.Result.scalars` - v2 comparable method.
2722
+
2723
+ """
2724
+ # replicates limit(1) behavior
2725
+ if self._statement is not None:
2726
+ return self._iter().first() # type: ignore
2727
+ else:
2728
+ return self.limit(1)._iter().first() # type: ignore
2729
+
2730
+ def one_or_none(self) -> Optional[_T]:
2731
+ """Return at most one result or raise an exception.
2732
+
2733
+ Returns ``None`` if the query selects
2734
+ no rows. Raises ``sqlalchemy.orm.exc.MultipleResultsFound``
2735
+ if multiple object identities are returned, or if multiple
2736
+ rows are returned for a query that returns only scalar values
2737
+ as opposed to full identity-mapped entities.
2738
+
2739
+ Calling :meth:`_query.Query.one_or_none`
2740
+ results in an execution of the
2741
+ underlying query.
2742
+
2743
+ .. seealso::
2744
+
2745
+ :meth:`_query.Query.first`
2746
+
2747
+ :meth:`_query.Query.one`
2748
+
2749
+ :meth:`_engine.Result.one_or_none` - v2 comparable method.
2750
+
2751
+ :meth:`_engine.Result.scalar_one_or_none` - v2 comparable method.
2752
+
2753
+ """
2754
+ return self._iter().one_or_none() # type: ignore
2755
+
2756
+ def one(self) -> _T:
2757
+ """Return exactly one result or raise an exception.
2758
+
2759
+ Raises ``sqlalchemy.orm.exc.NoResultFound`` if the query selects
2760
+ no rows. Raises ``sqlalchemy.orm.exc.MultipleResultsFound``
2761
+ if multiple object identities are returned, or if multiple
2762
+ rows are returned for a query that returns only scalar values
2763
+ as opposed to full identity-mapped entities.
2764
+
2765
+ Calling :meth:`.one` results in an execution of the underlying query.
2766
+
2767
+ .. seealso::
2768
+
2769
+ :meth:`_query.Query.first`
2770
+
2771
+ :meth:`_query.Query.one_or_none`
2772
+
2773
+ :meth:`_engine.Result.one` - v2 comparable method.
2774
+
2775
+ :meth:`_engine.Result.scalar_one` - v2 comparable method.
2776
+
2777
+ """
2778
+ return self._iter().one() # type: ignore
2779
+
2780
+ def scalar(self) -> Any:
2781
+ """Return the first element of the first result or None
2782
+ if no rows present. If multiple rows are returned,
2783
+ raises MultipleResultsFound.
2784
+
2785
+ >>> session.query(Item).scalar()
2786
+ <Item>
2787
+ >>> session.query(Item.id).scalar()
2788
+ 1
2789
+ >>> session.query(Item.id).filter(Item.id < 0).scalar()
2790
+ None
2791
+ >>> session.query(Item.id, Item.name).scalar()
2792
+ 1
2793
+ >>> session.query(func.count(Parent.id)).scalar()
2794
+ 20
2795
+
2796
+ This results in an execution of the underlying query.
2797
+
2798
+ .. seealso::
2799
+
2800
+ :meth:`_engine.Result.scalar` - v2 comparable method.
2801
+
2802
+ """
2803
+ # TODO: not sure why we can't use result.scalar() here
2804
+ try:
2805
+ ret = self.one()
2806
+ if not isinstance(ret, collections_abc.Sequence):
2807
+ return ret
2808
+ return ret[0]
2809
+ except sa_exc.NoResultFound:
2810
+ return None
2811
+
2812
+ def __iter__(self) -> Iterator[_T]:
2813
+ result = self._iter()
2814
+ try:
2815
+ yield from result # type: ignore
2816
+ except GeneratorExit:
2817
+ # issue #8710 - direct iteration is not re-usable after
2818
+ # an iterable block is broken, so close the result
2819
+ result._soft_close()
2820
+ raise
2821
+
2822
+ def _iter(self) -> Union[ScalarResult[_T], Result[_T]]:
2823
+ # new style execution.
2824
+ params = self._params
2825
+
2826
+ statement = self._statement_20()
2827
+ result: Union[ScalarResult[_T], Result[_T]] = self.session.execute(
2828
+ statement,
2829
+ params,
2830
+ execution_options={"_sa_orm_load_options": self.load_options},
2831
+ )
2832
+
2833
+ # legacy: automatically set scalars, unique
2834
+ if result._attributes.get("is_single_entity", False):
2835
+ result = cast("Result[_T]", result).scalars()
2836
+
2837
+ if (
2838
+ result._attributes.get("filtered", False)
2839
+ and not self.load_options._yield_per
2840
+ ):
2841
+ result = result.unique()
2842
+
2843
+ return result
2844
+
2845
+ def __str__(self) -> str:
2846
+ statement = self._statement_20()
2847
+
2848
+ try:
2849
+ bind = (
2850
+ self._get_bind_args(statement, self.session.get_bind)
2851
+ if self.session
2852
+ else None
2853
+ )
2854
+ except sa_exc.UnboundExecutionError:
2855
+ bind = None
2856
+
2857
+ return str(statement.compile(bind))
2858
+
2859
+ def _get_bind_args(self, statement: Any, fn: Any, **kw: Any) -> Any:
2860
+ return fn(clause=statement, **kw)
2861
+
2862
+ @property
2863
+ def column_descriptions(self) -> List[ORMColumnDescription]:
2864
+ """Return metadata about the columns which would be
2865
+ returned by this :class:`_query.Query`.
2866
+
2867
+ Format is a list of dictionaries::
2868
+
2869
+ user_alias = aliased(User, name='user2')
2870
+ q = sess.query(User, User.id, user_alias)
2871
+
2872
+ # this expression:
2873
+ q.column_descriptions
2874
+
2875
+ # would return:
2876
+ [
2877
+ {
2878
+ 'name':'User',
2879
+ 'type':User,
2880
+ 'aliased':False,
2881
+ 'expr':User,
2882
+ 'entity': User
2883
+ },
2884
+ {
2885
+ 'name':'id',
2886
+ 'type':Integer(),
2887
+ 'aliased':False,
2888
+ 'expr':User.id,
2889
+ 'entity': User
2890
+ },
2891
+ {
2892
+ 'name':'user2',
2893
+ 'type':User,
2894
+ 'aliased':True,
2895
+ 'expr':user_alias,
2896
+ 'entity': user_alias
2897
+ }
2898
+ ]
2899
+
2900
+ .. seealso::
2901
+
2902
+ This API is available using :term:`2.0 style` queries as well,
2903
+ documented at:
2904
+
2905
+ * :ref:`queryguide_inspection`
2906
+
2907
+ * :attr:`.Select.column_descriptions`
2908
+
2909
+ """
2910
+
2911
+ return _column_descriptions(self, legacy=True)
2912
+
2913
+ @util.deprecated(
2914
+ "2.0",
2915
+ "The :meth:`_orm.Query.instances` method is deprecated and will "
2916
+ "be removed in a future release. "
2917
+ "Use the Select.from_statement() method or aliased() construct in "
2918
+ "conjunction with Session.execute() instead.",
2919
+ )
2920
+ def instances(
2921
+ self,
2922
+ result_proxy: CursorResult[Any],
2923
+ context: Optional[QueryContext] = None,
2924
+ ) -> Any:
2925
+ """Return an ORM result given a :class:`_engine.CursorResult` and
2926
+ :class:`.QueryContext`.
2927
+
2928
+ """
2929
+ if context is None:
2930
+ util.warn_deprecated(
2931
+ "Using the Query.instances() method without a context "
2932
+ "is deprecated and will be disallowed in a future release. "
2933
+ "Please make use of :meth:`_query.Query.from_statement` "
2934
+ "for linking ORM results to arbitrary select constructs.",
2935
+ version="1.4",
2936
+ )
2937
+ compile_state = self._compile_state(for_statement=False)
2938
+
2939
+ context = QueryContext(
2940
+ compile_state,
2941
+ compile_state.statement,
2942
+ compile_state.statement,
2943
+ self._params,
2944
+ self.session,
2945
+ self.load_options,
2946
+ )
2947
+
2948
+ result = loading.instances(result_proxy, context)
2949
+
2950
+ # legacy: automatically set scalars, unique
2951
+ if result._attributes.get("is_single_entity", False):
2952
+ result = result.scalars() # type: ignore
2953
+
2954
+ if result._attributes.get("filtered", False):
2955
+ result = result.unique()
2956
+
2957
+ # TODO: isn't this supposed to be a list?
2958
+ return result
2959
+
2960
+ @util.became_legacy_20(
2961
+ ":meth:`_orm.Query.merge_result`",
2962
+ alternative="The method is superseded by the "
2963
+ ":func:`_orm.merge_frozen_result` function.",
2964
+ enable_warnings=False, # warnings occur via loading.merge_result
2965
+ )
2966
+ def merge_result(
2967
+ self,
2968
+ iterator: Union[
2969
+ FrozenResult[Any], Iterable[Sequence[Any]], Iterable[object]
2970
+ ],
2971
+ load: bool = True,
2972
+ ) -> Union[FrozenResult[Any], Iterable[Any]]:
2973
+ """Merge a result into this :class:`_query.Query` object's Session.
2974
+
2975
+ Given an iterator returned by a :class:`_query.Query`
2976
+ of the same structure
2977
+ as this one, return an identical iterator of results, with all mapped
2978
+ instances merged into the session using :meth:`.Session.merge`. This
2979
+ is an optimized method which will merge all mapped instances,
2980
+ preserving the structure of the result rows and unmapped columns with
2981
+ less method overhead than that of calling :meth:`.Session.merge`
2982
+ explicitly for each value.
2983
+
2984
+ The structure of the results is determined based on the column list of
2985
+ this :class:`_query.Query` - if these do not correspond,
2986
+ unchecked errors
2987
+ will occur.
2988
+
2989
+ The 'load' argument is the same as that of :meth:`.Session.merge`.
2990
+
2991
+ For an example of how :meth:`_query.Query.merge_result` is used, see
2992
+ the source code for the example :ref:`examples_caching`, where
2993
+ :meth:`_query.Query.merge_result` is used to efficiently restore state
2994
+ from a cache back into a target :class:`.Session`.
2995
+
2996
+ """
2997
+
2998
+ return loading.merge_result(self, iterator, load)
2999
+
3000
+ def exists(self) -> Exists:
3001
+ """A convenience method that turns a query into an EXISTS subquery
3002
+ of the form EXISTS (SELECT 1 FROM ... WHERE ...).
3003
+
3004
+ e.g.::
3005
+
3006
+ q = session.query(User).filter(User.name == 'fred')
3007
+ session.query(q.exists())
3008
+
3009
+ Producing SQL similar to::
3010
+
3011
+ SELECT EXISTS (
3012
+ SELECT 1 FROM users WHERE users.name = :name_1
3013
+ ) AS anon_1
3014
+
3015
+ The EXISTS construct is usually used in the WHERE clause::
3016
+
3017
+ session.query(User.id).filter(q.exists()).scalar()
3018
+
3019
+ Note that some databases such as SQL Server don't allow an
3020
+ EXISTS expression to be present in the columns clause of a
3021
+ SELECT. To select a simple boolean value based on the exists
3022
+ as a WHERE, use :func:`.literal`::
3023
+
3024
+ from sqlalchemy import literal
3025
+
3026
+ session.query(literal(True)).filter(q.exists()).scalar()
3027
+
3028
+ .. seealso::
3029
+
3030
+ :meth:`_sql.Select.exists` - v2 comparable method.
3031
+
3032
+ """
3033
+
3034
+ # .add_columns() for the case that we are a query().select_from(X),
3035
+ # so that ".statement" can be produced (#2995) but also without
3036
+ # omitting the FROM clause from a query(X) (#2818);
3037
+ # .with_only_columns() after we have a core select() so that
3038
+ # we get just "SELECT 1" without any entities.
3039
+
3040
+ inner = (
3041
+ self.enable_eagerloads(False)
3042
+ .add_columns(sql.literal_column("1"))
3043
+ .set_label_style(LABEL_STYLE_TABLENAME_PLUS_COL)
3044
+ ._get_select_statement_only()
3045
+ .with_only_columns(1)
3046
+ )
3047
+
3048
+ ezero = self._entity_from_pre_ent_zero()
3049
+ if ezero is not None:
3050
+ inner = inner.select_from(ezero)
3051
+
3052
+ return sql.exists(inner)
3053
+
3054
+ def count(self) -> int:
3055
+ r"""Return a count of rows this the SQL formed by this :class:`Query`
3056
+ would return.
3057
+
3058
+ This generates the SQL for this Query as follows::
3059
+
3060
+ SELECT count(1) AS count_1 FROM (
3061
+ SELECT <rest of query follows...>
3062
+ ) AS anon_1
3063
+
3064
+ The above SQL returns a single row, which is the aggregate value
3065
+ of the count function; the :meth:`_query.Query.count`
3066
+ method then returns
3067
+ that single integer value.
3068
+
3069
+ .. warning::
3070
+
3071
+ It is important to note that the value returned by
3072
+ count() is **not the same as the number of ORM objects that this
3073
+ Query would return from a method such as the .all() method**.
3074
+ The :class:`_query.Query` object,
3075
+ when asked to return full entities,
3076
+ will **deduplicate entries based on primary key**, meaning if the
3077
+ same primary key value would appear in the results more than once,
3078
+ only one object of that primary key would be present. This does
3079
+ not apply to a query that is against individual columns.
3080
+
3081
+ .. seealso::
3082
+
3083
+ :ref:`faq_query_deduplicating`
3084
+
3085
+ For fine grained control over specific columns to count, to skip the
3086
+ usage of a subquery or otherwise control of the FROM clause, or to use
3087
+ other aggregate functions, use :attr:`~sqlalchemy.sql.expression.func`
3088
+ expressions in conjunction with :meth:`~.Session.query`, i.e.::
3089
+
3090
+ from sqlalchemy import func
3091
+
3092
+ # count User records, without
3093
+ # using a subquery.
3094
+ session.query(func.count(User.id))
3095
+
3096
+ # return count of user "id" grouped
3097
+ # by "name"
3098
+ session.query(func.count(User.id)).\
3099
+ group_by(User.name)
3100
+
3101
+ from sqlalchemy import distinct
3102
+
3103
+ # count distinct "name" values
3104
+ session.query(func.count(distinct(User.name)))
3105
+
3106
+ .. seealso::
3107
+
3108
+ :ref:`migration_20_query_usage`
3109
+
3110
+ """
3111
+ col = sql.func.count(sql.literal_column("*"))
3112
+ return ( # type: ignore
3113
+ self._legacy_from_self(col).enable_eagerloads(False).scalar()
3114
+ )
3115
+
3116
+ def delete(
3117
+ self, synchronize_session: SynchronizeSessionArgument = "auto"
3118
+ ) -> int:
3119
+ r"""Perform a DELETE with an arbitrary WHERE clause.
3120
+
3121
+ Deletes rows matched by this query from the database.
3122
+
3123
+ E.g.::
3124
+
3125
+ sess.query(User).filter(User.age == 25).\
3126
+ delete(synchronize_session=False)
3127
+
3128
+ sess.query(User).filter(User.age == 25).\
3129
+ delete(synchronize_session='evaluate')
3130
+
3131
+ .. warning::
3132
+
3133
+ See the section :ref:`orm_expression_update_delete` for important
3134
+ caveats and warnings, including limitations when using bulk UPDATE
3135
+ and DELETE with mapper inheritance configurations.
3136
+
3137
+ :param synchronize_session: chooses the strategy to update the
3138
+ attributes on objects in the session. See the section
3139
+ :ref:`orm_expression_update_delete` for a discussion of these
3140
+ strategies.
3141
+
3142
+ :return: the count of rows matched as returned by the database's
3143
+ "row count" feature.
3144
+
3145
+ .. seealso::
3146
+
3147
+ :ref:`orm_expression_update_delete`
3148
+
3149
+ """
3150
+
3151
+ bulk_del = BulkDelete(self)
3152
+ if self.dispatch.before_compile_delete:
3153
+ for fn in self.dispatch.before_compile_delete:
3154
+ new_query = fn(bulk_del.query, bulk_del)
3155
+ if new_query is not None:
3156
+ bulk_del.query = new_query
3157
+
3158
+ self = bulk_del.query
3159
+
3160
+ delete_ = sql.delete(*self._raw_columns) # type: ignore
3161
+ delete_._where_criteria = self._where_criteria
3162
+ result: CursorResult[Any] = self.session.execute(
3163
+ delete_,
3164
+ self._params,
3165
+ execution_options=self._execution_options.union(
3166
+ {"synchronize_session": synchronize_session}
3167
+ ),
3168
+ )
3169
+ bulk_del.result = result # type: ignore
3170
+ self.session.dispatch.after_bulk_delete(bulk_del)
3171
+ result.close()
3172
+
3173
+ return result.rowcount
3174
+
3175
+ def update(
3176
+ self,
3177
+ values: Dict[_DMLColumnArgument, Any],
3178
+ synchronize_session: SynchronizeSessionArgument = "auto",
3179
+ update_args: Optional[Dict[Any, Any]] = None,
3180
+ ) -> int:
3181
+ r"""Perform an UPDATE with an arbitrary WHERE clause.
3182
+
3183
+ Updates rows matched by this query in the database.
3184
+
3185
+ E.g.::
3186
+
3187
+ sess.query(User).filter(User.age == 25).\
3188
+ update({User.age: User.age - 10}, synchronize_session=False)
3189
+
3190
+ sess.query(User).filter(User.age == 25).\
3191
+ update({"age": User.age - 10}, synchronize_session='evaluate')
3192
+
3193
+ .. warning::
3194
+
3195
+ See the section :ref:`orm_expression_update_delete` for important
3196
+ caveats and warnings, including limitations when using arbitrary
3197
+ UPDATE and DELETE with mapper inheritance configurations.
3198
+
3199
+ :param values: a dictionary with attributes names, or alternatively
3200
+ mapped attributes or SQL expressions, as keys, and literal
3201
+ values or sql expressions as values. If :ref:`parameter-ordered
3202
+ mode <tutorial_parameter_ordered_updates>` is desired, the values can
3203
+ be passed as a list of 2-tuples; this requires that the
3204
+ :paramref:`~sqlalchemy.sql.expression.update.preserve_parameter_order`
3205
+ flag is passed to the :paramref:`.Query.update.update_args` dictionary
3206
+ as well.
3207
+
3208
+ :param synchronize_session: chooses the strategy to update the
3209
+ attributes on objects in the session. See the section
3210
+ :ref:`orm_expression_update_delete` for a discussion of these
3211
+ strategies.
3212
+
3213
+ :param update_args: Optional dictionary, if present will be passed
3214
+ to the underlying :func:`_expression.update`
3215
+ construct as the ``**kw`` for
3216
+ the object. May be used to pass dialect-specific arguments such
3217
+ as ``mysql_limit``, as well as other special arguments such as
3218
+ :paramref:`~sqlalchemy.sql.expression.update.preserve_parameter_order`.
3219
+
3220
+ :return: the count of rows matched as returned by the database's
3221
+ "row count" feature.
3222
+
3223
+
3224
+ .. seealso::
3225
+
3226
+ :ref:`orm_expression_update_delete`
3227
+
3228
+ """
3229
+
3230
+ update_args = update_args or {}
3231
+
3232
+ bulk_ud = BulkUpdate(self, values, update_args)
3233
+
3234
+ if self.dispatch.before_compile_update:
3235
+ for fn in self.dispatch.before_compile_update:
3236
+ new_query = fn(bulk_ud.query, bulk_ud)
3237
+ if new_query is not None:
3238
+ bulk_ud.query = new_query
3239
+ self = bulk_ud.query
3240
+
3241
+ upd = sql.update(*self._raw_columns) # type: ignore
3242
+
3243
+ ppo = update_args.pop("preserve_parameter_order", False)
3244
+ if ppo:
3245
+ upd = upd.ordered_values(*values) # type: ignore
3246
+ else:
3247
+ upd = upd.values(values)
3248
+ if update_args:
3249
+ upd = upd.with_dialect_options(**update_args)
3250
+
3251
+ upd._where_criteria = self._where_criteria
3252
+ result: CursorResult[Any] = self.session.execute(
3253
+ upd,
3254
+ self._params,
3255
+ execution_options=self._execution_options.union(
3256
+ {"synchronize_session": synchronize_session}
3257
+ ),
3258
+ )
3259
+ bulk_ud.result = result # type: ignore
3260
+ self.session.dispatch.after_bulk_update(bulk_ud)
3261
+ result.close()
3262
+ return result.rowcount
3263
+
3264
+ def _compile_state(
3265
+ self, for_statement: bool = False, **kw: Any
3266
+ ) -> ORMCompileState:
3267
+ """Create an out-of-compiler ORMCompileState object.
3268
+
3269
+ The ORMCompileState object is normally created directly as a result
3270
+ of the SQLCompiler.process() method being handed a Select()
3271
+ or FromStatement() object that uses the "orm" plugin. This method
3272
+ provides a means of creating this ORMCompileState object directly
3273
+ without using the compiler.
3274
+
3275
+ This method is used only for deprecated cases, which include
3276
+ the .from_self() method for a Query that has multiple levels
3277
+ of .from_self() in use, as well as the instances() method. It is
3278
+ also used within the test suite to generate ORMCompileState objects
3279
+ for test purposes.
3280
+
3281
+ """
3282
+
3283
+ stmt = self._statement_20(for_statement=for_statement, **kw)
3284
+ assert for_statement == stmt._compile_options._for_statement
3285
+
3286
+ # this chooses between ORMFromStatementCompileState and
3287
+ # ORMSelectCompileState. We could also base this on
3288
+ # query._statement is not None as we have the ORM Query here
3289
+ # however this is the more general path.
3290
+ compile_state_cls = cast(
3291
+ ORMCompileState,
3292
+ ORMCompileState._get_plugin_class_for_plugin(stmt, "orm"),
3293
+ )
3294
+
3295
+ return compile_state_cls.create_for_statement(stmt, None)
3296
+
3297
+ def _compile_context(self, for_statement: bool = False) -> QueryContext:
3298
+ compile_state = self._compile_state(for_statement=for_statement)
3299
+ context = QueryContext(
3300
+ compile_state,
3301
+ compile_state.statement,
3302
+ compile_state.statement,
3303
+ self._params,
3304
+ self.session,
3305
+ self.load_options,
3306
+ )
3307
+
3308
+ return context
3309
+
3310
+
3311
+ class AliasOption(interfaces.LoaderOption):
3312
+ inherit_cache = False
3313
+
3314
+ @util.deprecated(
3315
+ "1.4",
3316
+ "The :class:`.AliasOption` object is not necessary "
3317
+ "for entities to be matched up to a query that is established "
3318
+ "via :meth:`.Query.from_statement` and now does nothing.",
3319
+ )
3320
+ def __init__(self, alias: Union[Alias, Subquery]):
3321
+ r"""Return a :class:`.MapperOption` that will indicate to the
3322
+ :class:`_query.Query`
3323
+ that the main table has been aliased.
3324
+
3325
+ """
3326
+
3327
+ def process_compile_state(self, compile_state: ORMCompileState) -> None:
3328
+ pass
3329
+
3330
+
3331
+ class BulkUD:
3332
+ """State used for the orm.Query version of update() / delete().
3333
+
3334
+ This object is now specific to Query only.
3335
+
3336
+ """
3337
+
3338
+ def __init__(self, query: Query[Any]):
3339
+ self.query = query.enable_eagerloads(False)
3340
+ self._validate_query_state()
3341
+ self.mapper = self.query._entity_from_pre_ent_zero()
3342
+
3343
+ def _validate_query_state(self) -> None:
3344
+ for attr, methname, notset, op in (
3345
+ ("_limit_clause", "limit()", None, operator.is_),
3346
+ ("_offset_clause", "offset()", None, operator.is_),
3347
+ ("_order_by_clauses", "order_by()", (), operator.eq),
3348
+ ("_group_by_clauses", "group_by()", (), operator.eq),
3349
+ ("_distinct", "distinct()", False, operator.is_),
3350
+ (
3351
+ "_from_obj",
3352
+ "join(), outerjoin(), select_from(), or from_self()",
3353
+ (),
3354
+ operator.eq,
3355
+ ),
3356
+ (
3357
+ "_setup_joins",
3358
+ "join(), outerjoin(), select_from(), or from_self()",
3359
+ (),
3360
+ operator.eq,
3361
+ ),
3362
+ ):
3363
+ if not op(getattr(self.query, attr), notset):
3364
+ raise sa_exc.InvalidRequestError(
3365
+ "Can't call Query.update() or Query.delete() "
3366
+ "when %s has been called" % (methname,)
3367
+ )
3368
+
3369
+ @property
3370
+ def session(self) -> Session:
3371
+ return self.query.session
3372
+
3373
+
3374
+ class BulkUpdate(BulkUD):
3375
+ """BulkUD which handles UPDATEs."""
3376
+
3377
+ def __init__(
3378
+ self,
3379
+ query: Query[Any],
3380
+ values: Dict[_DMLColumnArgument, Any],
3381
+ update_kwargs: Optional[Dict[Any, Any]],
3382
+ ):
3383
+ super().__init__(query)
3384
+ self.values = values
3385
+ self.update_kwargs = update_kwargs
3386
+
3387
+
3388
+ class BulkDelete(BulkUD):
3389
+ """BulkUD which handles DELETEs."""
3390
+
3391
+
3392
+ class RowReturningQuery(Query[Row[_TP]]):
3393
+ if TYPE_CHECKING:
3394
+
3395
+ def tuples(self) -> Query[_TP]: # type: ignore
3396
+ ...