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,2382 @@
1
+ # engine/result.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
+ """Define generic result set constructs."""
9
+
10
+ from __future__ import annotations
11
+
12
+ from enum import Enum
13
+ import functools
14
+ import itertools
15
+ import operator
16
+ import typing
17
+ from typing import Any
18
+ from typing import Callable
19
+ from typing import cast
20
+ from typing import Dict
21
+ from typing import Generic
22
+ from typing import Iterable
23
+ from typing import Iterator
24
+ from typing import List
25
+ from typing import Mapping
26
+ from typing import NoReturn
27
+ from typing import Optional
28
+ from typing import overload
29
+ from typing import Sequence
30
+ from typing import Set
31
+ from typing import Tuple
32
+ from typing import TYPE_CHECKING
33
+ from typing import TypeVar
34
+ from typing import Union
35
+
36
+ from .row import Row
37
+ from .row import RowMapping
38
+ from .. import exc
39
+ from .. import util
40
+ from ..sql.base import _generative
41
+ from ..sql.base import HasMemoized
42
+ from ..sql.base import InPlaceGenerative
43
+ from ..util import HasMemoized_ro_memoized_attribute
44
+ from ..util import NONE_SET
45
+ from ..util._has_cy import HAS_CYEXTENSION
46
+ from ..util.typing import Literal
47
+ from ..util.typing import Self
48
+
49
+ if typing.TYPE_CHECKING or not HAS_CYEXTENSION:
50
+ from ._py_row import tuplegetter as tuplegetter
51
+ else:
52
+ from sqlalchemy.cyextension.resultproxy import tuplegetter as tuplegetter
53
+
54
+ if typing.TYPE_CHECKING:
55
+ from ..sql.schema import Column
56
+ from ..sql.type_api import _ResultProcessorType
57
+
58
+ _KeyType = Union[str, "Column[Any]"]
59
+ _KeyIndexType = Union[str, "Column[Any]", int]
60
+
61
+ # is overridden in cursor using _CursorKeyMapRecType
62
+ _KeyMapRecType = Any
63
+
64
+ _KeyMapType = Mapping[_KeyType, _KeyMapRecType]
65
+
66
+
67
+ _RowData = Union[Row[Any], RowMapping, Any]
68
+ """A generic form of "row" that accommodates for the different kinds of
69
+ "rows" that different result objects return, including row, row mapping, and
70
+ scalar values"""
71
+
72
+ _RawRowType = Tuple[Any, ...]
73
+ """represents the kind of row we get from a DBAPI cursor"""
74
+
75
+ _R = TypeVar("_R", bound=_RowData)
76
+ _T = TypeVar("_T", bound=Any)
77
+ _TP = TypeVar("_TP", bound=Tuple[Any, ...])
78
+
79
+ _InterimRowType = Union[_R, _RawRowType]
80
+ """a catchall "anything" kind of return type that can be applied
81
+ across all the result types
82
+
83
+ """
84
+
85
+ _InterimSupportsScalarsRowType = Union[Row[Any], Any]
86
+
87
+ _ProcessorsType = Sequence[Optional["_ResultProcessorType[Any]"]]
88
+ _TupleGetterType = Callable[[Sequence[Any]], Sequence[Any]]
89
+ _UniqueFilterType = Callable[[Any], Any]
90
+ _UniqueFilterStateType = Tuple[Set[Any], Optional[_UniqueFilterType]]
91
+
92
+
93
+ class ResultMetaData:
94
+ """Base for metadata about result rows."""
95
+
96
+ __slots__ = ()
97
+
98
+ _tuplefilter: Optional[_TupleGetterType] = None
99
+ _translated_indexes: Optional[Sequence[int]] = None
100
+ _unique_filters: Optional[Sequence[Callable[[Any], Any]]] = None
101
+ _keymap: _KeyMapType
102
+ _keys: Sequence[str]
103
+ _processors: Optional[_ProcessorsType]
104
+ _key_to_index: Mapping[_KeyType, int]
105
+
106
+ @property
107
+ def keys(self) -> RMKeyView:
108
+ return RMKeyView(self)
109
+
110
+ def _has_key(self, key: object) -> bool:
111
+ raise NotImplementedError()
112
+
113
+ def _for_freeze(self) -> ResultMetaData:
114
+ raise NotImplementedError()
115
+
116
+ @overload
117
+ def _key_fallback(
118
+ self, key: Any, err: Optional[Exception], raiseerr: Literal[True] = ...
119
+ ) -> NoReturn: ...
120
+
121
+ @overload
122
+ def _key_fallback(
123
+ self,
124
+ key: Any,
125
+ err: Optional[Exception],
126
+ raiseerr: Literal[False] = ...,
127
+ ) -> None: ...
128
+
129
+ @overload
130
+ def _key_fallback(
131
+ self, key: Any, err: Optional[Exception], raiseerr: bool = ...
132
+ ) -> Optional[NoReturn]: ...
133
+
134
+ def _key_fallback(
135
+ self, key: Any, err: Optional[Exception], raiseerr: bool = True
136
+ ) -> Optional[NoReturn]:
137
+ assert raiseerr
138
+ raise KeyError(key) from err
139
+
140
+ def _raise_for_ambiguous_column_name(
141
+ self, rec: _KeyMapRecType
142
+ ) -> NoReturn:
143
+ raise NotImplementedError(
144
+ "ambiguous column name logic is implemented for "
145
+ "CursorResultMetaData"
146
+ )
147
+
148
+ def _index_for_key(
149
+ self, key: _KeyIndexType, raiseerr: bool
150
+ ) -> Optional[int]:
151
+ raise NotImplementedError()
152
+
153
+ def _indexes_for_keys(
154
+ self, keys: Sequence[_KeyIndexType]
155
+ ) -> Sequence[int]:
156
+ raise NotImplementedError()
157
+
158
+ def _metadata_for_keys(
159
+ self, keys: Sequence[_KeyIndexType]
160
+ ) -> Iterator[_KeyMapRecType]:
161
+ raise NotImplementedError()
162
+
163
+ def _reduce(self, keys: Sequence[_KeyIndexType]) -> ResultMetaData:
164
+ raise NotImplementedError()
165
+
166
+ def _getter(
167
+ self, key: Any, raiseerr: bool = True
168
+ ) -> Optional[Callable[[Row[Any]], Any]]:
169
+ index = self._index_for_key(key, raiseerr)
170
+
171
+ if index is not None:
172
+ return operator.itemgetter(index)
173
+ else:
174
+ return None
175
+
176
+ def _row_as_tuple_getter(
177
+ self, keys: Sequence[_KeyIndexType]
178
+ ) -> _TupleGetterType:
179
+ indexes = self._indexes_for_keys(keys)
180
+ return tuplegetter(*indexes)
181
+
182
+ def _make_key_to_index(
183
+ self, keymap: Mapping[_KeyType, Sequence[Any]], index: int
184
+ ) -> Mapping[_KeyType, int]:
185
+ return {
186
+ key: rec[index]
187
+ for key, rec in keymap.items()
188
+ if rec[index] is not None
189
+ }
190
+
191
+ def _key_not_found(self, key: Any, attr_error: bool) -> NoReturn:
192
+ if key in self._keymap:
193
+ # the index must be none in this case
194
+ self._raise_for_ambiguous_column_name(self._keymap[key])
195
+ else:
196
+ # unknown key
197
+ if attr_error:
198
+ try:
199
+ self._key_fallback(key, None)
200
+ except KeyError as ke:
201
+ raise AttributeError(ke.args[0]) from ke
202
+ else:
203
+ self._key_fallback(key, None)
204
+
205
+ @property
206
+ def _effective_processors(self) -> Optional[_ProcessorsType]:
207
+ if not self._processors or NONE_SET.issuperset(self._processors):
208
+ return None
209
+ else:
210
+ return self._processors
211
+
212
+
213
+ class RMKeyView(typing.KeysView[Any]):
214
+ __slots__ = ("_parent", "_keys")
215
+
216
+ _parent: ResultMetaData
217
+ _keys: Sequence[str]
218
+
219
+ def __init__(self, parent: ResultMetaData):
220
+ self._parent = parent
221
+ self._keys = [k for k in parent._keys if k is not None]
222
+
223
+ def __len__(self) -> int:
224
+ return len(self._keys)
225
+
226
+ def __repr__(self) -> str:
227
+ return "{0.__class__.__name__}({0._keys!r})".format(self)
228
+
229
+ def __iter__(self) -> Iterator[str]:
230
+ return iter(self._keys)
231
+
232
+ def __contains__(self, item: Any) -> bool:
233
+ if isinstance(item, int):
234
+ return False
235
+
236
+ # note this also includes special key fallback behaviors
237
+ # which also don't seem to be tested in test_resultset right now
238
+ return self._parent._has_key(item)
239
+
240
+ def __eq__(self, other: Any) -> bool:
241
+ return list(other) == list(self)
242
+
243
+ def __ne__(self, other: Any) -> bool:
244
+ return list(other) != list(self)
245
+
246
+
247
+ class SimpleResultMetaData(ResultMetaData):
248
+ """result metadata for in-memory collections."""
249
+
250
+ __slots__ = (
251
+ "_keys",
252
+ "_keymap",
253
+ "_processors",
254
+ "_tuplefilter",
255
+ "_translated_indexes",
256
+ "_unique_filters",
257
+ "_key_to_index",
258
+ )
259
+
260
+ _keys: Sequence[str]
261
+
262
+ def __init__(
263
+ self,
264
+ keys: Sequence[str],
265
+ extra: Optional[Sequence[Any]] = None,
266
+ _processors: Optional[_ProcessorsType] = None,
267
+ _tuplefilter: Optional[_TupleGetterType] = None,
268
+ _translated_indexes: Optional[Sequence[int]] = None,
269
+ _unique_filters: Optional[Sequence[Callable[[Any], Any]]] = None,
270
+ ):
271
+ self._keys = list(keys)
272
+ self._tuplefilter = _tuplefilter
273
+ self._translated_indexes = _translated_indexes
274
+ self._unique_filters = _unique_filters
275
+ if extra:
276
+ recs_names = [
277
+ (
278
+ (name,) + (extras if extras else ()),
279
+ (index, name, extras),
280
+ )
281
+ for index, (name, extras) in enumerate(zip(self._keys, extra))
282
+ ]
283
+ else:
284
+ recs_names = [
285
+ ((name,), (index, name, ()))
286
+ for index, name in enumerate(self._keys)
287
+ ]
288
+
289
+ self._keymap = {key: rec for keys, rec in recs_names for key in keys}
290
+
291
+ self._processors = _processors
292
+
293
+ self._key_to_index = self._make_key_to_index(self._keymap, 0)
294
+
295
+ def _has_key(self, key: object) -> bool:
296
+ return key in self._keymap
297
+
298
+ def _for_freeze(self) -> ResultMetaData:
299
+ unique_filters = self._unique_filters
300
+ if unique_filters and self._tuplefilter:
301
+ unique_filters = self._tuplefilter(unique_filters)
302
+
303
+ # TODO: are we freezing the result with or without uniqueness
304
+ # applied?
305
+ return SimpleResultMetaData(
306
+ self._keys,
307
+ extra=[self._keymap[key][2] for key in self._keys],
308
+ _unique_filters=unique_filters,
309
+ )
310
+
311
+ def __getstate__(self) -> Dict[str, Any]:
312
+ return {
313
+ "_keys": self._keys,
314
+ "_translated_indexes": self._translated_indexes,
315
+ }
316
+
317
+ def __setstate__(self, state: Dict[str, Any]) -> None:
318
+ if state["_translated_indexes"]:
319
+ _translated_indexes = state["_translated_indexes"]
320
+ _tuplefilter = tuplegetter(*_translated_indexes)
321
+ else:
322
+ _translated_indexes = _tuplefilter = None
323
+ self.__init__( # type: ignore
324
+ state["_keys"],
325
+ _translated_indexes=_translated_indexes,
326
+ _tuplefilter=_tuplefilter,
327
+ )
328
+
329
+ def _index_for_key(self, key: Any, raiseerr: bool = True) -> int:
330
+ if int in key.__class__.__mro__:
331
+ key = self._keys[key]
332
+ try:
333
+ rec = self._keymap[key]
334
+ except KeyError as ke:
335
+ rec = self._key_fallback(key, ke, raiseerr)
336
+
337
+ return rec[0] # type: ignore[no-any-return]
338
+
339
+ def _indexes_for_keys(self, keys: Sequence[Any]) -> Sequence[int]:
340
+ return [self._keymap[key][0] for key in keys]
341
+
342
+ def _metadata_for_keys(
343
+ self, keys: Sequence[Any]
344
+ ) -> Iterator[_KeyMapRecType]:
345
+ for key in keys:
346
+ if int in key.__class__.__mro__:
347
+ key = self._keys[key]
348
+
349
+ try:
350
+ rec = self._keymap[key]
351
+ except KeyError as ke:
352
+ rec = self._key_fallback(key, ke, True)
353
+
354
+ yield rec
355
+
356
+ def _reduce(self, keys: Sequence[Any]) -> ResultMetaData:
357
+ try:
358
+ metadata_for_keys = [
359
+ self._keymap[
360
+ self._keys[key] if int in key.__class__.__mro__ else key
361
+ ]
362
+ for key in keys
363
+ ]
364
+ except KeyError as ke:
365
+ self._key_fallback(ke.args[0], ke, True)
366
+
367
+ indexes: Sequence[int]
368
+ new_keys: Sequence[str]
369
+ extra: Sequence[Any]
370
+ indexes, new_keys, extra = zip(*metadata_for_keys)
371
+
372
+ if self._translated_indexes:
373
+ indexes = [self._translated_indexes[idx] for idx in indexes]
374
+
375
+ tup = tuplegetter(*indexes)
376
+
377
+ new_metadata = SimpleResultMetaData(
378
+ new_keys,
379
+ extra=extra,
380
+ _tuplefilter=tup,
381
+ _translated_indexes=indexes,
382
+ _processors=self._processors,
383
+ _unique_filters=self._unique_filters,
384
+ )
385
+
386
+ return new_metadata
387
+
388
+
389
+ def result_tuple(
390
+ fields: Sequence[str], extra: Optional[Any] = None
391
+ ) -> Callable[[Iterable[Any]], Row[Any]]:
392
+ parent = SimpleResultMetaData(fields, extra)
393
+ return functools.partial(
394
+ Row, parent, parent._effective_processors, parent._key_to_index
395
+ )
396
+
397
+
398
+ # a symbol that indicates to internal Result methods that
399
+ # "no row is returned". We can't use None for those cases where a scalar
400
+ # filter is applied to rows.
401
+ class _NoRow(Enum):
402
+ _NO_ROW = 0
403
+
404
+
405
+ _NO_ROW = _NoRow._NO_ROW
406
+
407
+
408
+ class ResultInternal(InPlaceGenerative, Generic[_R]):
409
+ __slots__ = ()
410
+
411
+ _real_result: Optional[Result[Any]] = None
412
+ _generate_rows: bool = True
413
+ _row_logging_fn: Optional[Callable[[Any], Any]]
414
+
415
+ _unique_filter_state: Optional[_UniqueFilterStateType] = None
416
+ _post_creational_filter: Optional[Callable[[Any], Any]] = None
417
+ _is_cursor = False
418
+
419
+ _metadata: ResultMetaData
420
+
421
+ _source_supports_scalars: bool
422
+
423
+ def _fetchiter_impl(self) -> Iterator[_InterimRowType[Row[Any]]]:
424
+ raise NotImplementedError()
425
+
426
+ def _fetchone_impl(
427
+ self, hard_close: bool = False
428
+ ) -> Optional[_InterimRowType[Row[Any]]]:
429
+ raise NotImplementedError()
430
+
431
+ def _fetchmany_impl(
432
+ self, size: Optional[int] = None
433
+ ) -> List[_InterimRowType[Row[Any]]]:
434
+ raise NotImplementedError()
435
+
436
+ def _fetchall_impl(self) -> List[_InterimRowType[Row[Any]]]:
437
+ raise NotImplementedError()
438
+
439
+ def _soft_close(self, hard: bool = False) -> None:
440
+ raise NotImplementedError()
441
+
442
+ @HasMemoized_ro_memoized_attribute
443
+ def _row_getter(self) -> Optional[Callable[..., _R]]:
444
+ real_result: Result[Any] = (
445
+ self._real_result
446
+ if self._real_result
447
+ else cast("Result[Any]", self)
448
+ )
449
+
450
+ if real_result._source_supports_scalars:
451
+ if not self._generate_rows:
452
+ return None
453
+ else:
454
+ _proc = Row
455
+
456
+ def process_row(
457
+ metadata: ResultMetaData,
458
+ processors: Optional[_ProcessorsType],
459
+ key_to_index: Mapping[_KeyType, int],
460
+ scalar_obj: Any,
461
+ ) -> Row[Any]:
462
+ return _proc(
463
+ metadata, processors, key_to_index, (scalar_obj,)
464
+ )
465
+
466
+ else:
467
+ process_row = Row # type: ignore
468
+
469
+ metadata = self._metadata
470
+
471
+ key_to_index = metadata._key_to_index
472
+ processors = metadata._effective_processors
473
+ tf = metadata._tuplefilter
474
+
475
+ if tf and not real_result._source_supports_scalars:
476
+ if processors:
477
+ processors = tf(processors)
478
+
479
+ _make_row_orig: Callable[..., _R] = functools.partial( # type: ignore # noqa E501
480
+ process_row, metadata, processors, key_to_index
481
+ )
482
+
483
+ fixed_tf = tf
484
+
485
+ def make_row(row: _InterimRowType[Row[Any]]) -> _R:
486
+ return _make_row_orig(fixed_tf(row))
487
+
488
+ else:
489
+ make_row = functools.partial( # type: ignore
490
+ process_row, metadata, processors, key_to_index
491
+ )
492
+
493
+ if real_result._row_logging_fn:
494
+ _log_row = real_result._row_logging_fn
495
+ _make_row = make_row
496
+
497
+ def make_row(row: _InterimRowType[Row[Any]]) -> _R:
498
+ return _log_row(_make_row(row)) # type: ignore
499
+
500
+ return make_row
501
+
502
+ @HasMemoized_ro_memoized_attribute
503
+ def _iterator_getter(self) -> Callable[..., Iterator[_R]]:
504
+ make_row = self._row_getter
505
+
506
+ post_creational_filter = self._post_creational_filter
507
+
508
+ if self._unique_filter_state:
509
+ uniques, strategy = self._unique_strategy
510
+
511
+ def iterrows(self: Result[Any]) -> Iterator[_R]:
512
+ for raw_row in self._fetchiter_impl():
513
+ obj: _InterimRowType[Any] = (
514
+ make_row(raw_row) if make_row else raw_row
515
+ )
516
+ hashed = strategy(obj) if strategy else obj
517
+ if hashed in uniques:
518
+ continue
519
+ uniques.add(hashed)
520
+ if post_creational_filter:
521
+ obj = post_creational_filter(obj)
522
+ yield obj # type: ignore
523
+
524
+ else:
525
+
526
+ def iterrows(self: Result[Any]) -> Iterator[_R]:
527
+ for raw_row in self._fetchiter_impl():
528
+ row: _InterimRowType[Any] = (
529
+ make_row(raw_row) if make_row else raw_row
530
+ )
531
+ if post_creational_filter:
532
+ row = post_creational_filter(row)
533
+ yield row # type: ignore
534
+
535
+ return iterrows
536
+
537
+ def _raw_all_rows(self) -> List[_R]:
538
+ make_row = self._row_getter
539
+ assert make_row is not None
540
+ rows = self._fetchall_impl()
541
+ return [make_row(row) for row in rows]
542
+
543
+ def _allrows(self) -> List[_R]:
544
+ post_creational_filter = self._post_creational_filter
545
+
546
+ make_row = self._row_getter
547
+
548
+ rows = self._fetchall_impl()
549
+ made_rows: List[_InterimRowType[_R]]
550
+ if make_row:
551
+ made_rows = [make_row(row) for row in rows]
552
+ else:
553
+ made_rows = rows # type: ignore
554
+
555
+ interim_rows: List[_R]
556
+
557
+ if self._unique_filter_state:
558
+ uniques, strategy = self._unique_strategy
559
+
560
+ interim_rows = [
561
+ made_row # type: ignore
562
+ for made_row, sig_row in [
563
+ (
564
+ made_row,
565
+ strategy(made_row) if strategy else made_row,
566
+ )
567
+ for made_row in made_rows
568
+ ]
569
+ if sig_row not in uniques and not uniques.add(sig_row) # type: ignore # noqa: E501
570
+ ]
571
+ else:
572
+ interim_rows = made_rows # type: ignore
573
+
574
+ if post_creational_filter:
575
+ interim_rows = [
576
+ post_creational_filter(row) for row in interim_rows
577
+ ]
578
+ return interim_rows
579
+
580
+ @HasMemoized_ro_memoized_attribute
581
+ def _onerow_getter(
582
+ self,
583
+ ) -> Callable[..., Union[Literal[_NoRow._NO_ROW], _R]]:
584
+ make_row = self._row_getter
585
+
586
+ post_creational_filter = self._post_creational_filter
587
+
588
+ if self._unique_filter_state:
589
+ uniques, strategy = self._unique_strategy
590
+
591
+ def onerow(self: Result[Any]) -> Union[_NoRow, _R]:
592
+ _onerow = self._fetchone_impl
593
+ while True:
594
+ row = _onerow()
595
+ if row is None:
596
+ return _NO_ROW
597
+ else:
598
+ obj: _InterimRowType[Any] = (
599
+ make_row(row) if make_row else row
600
+ )
601
+ hashed = strategy(obj) if strategy else obj
602
+ if hashed in uniques:
603
+ continue
604
+ else:
605
+ uniques.add(hashed)
606
+ if post_creational_filter:
607
+ obj = post_creational_filter(obj)
608
+ return obj # type: ignore
609
+
610
+ else:
611
+
612
+ def onerow(self: Result[Any]) -> Union[_NoRow, _R]:
613
+ row = self._fetchone_impl()
614
+ if row is None:
615
+ return _NO_ROW
616
+ else:
617
+ interim_row: _InterimRowType[Any] = (
618
+ make_row(row) if make_row else row
619
+ )
620
+ if post_creational_filter:
621
+ interim_row = post_creational_filter(interim_row)
622
+ return interim_row # type: ignore
623
+
624
+ return onerow
625
+
626
+ @HasMemoized_ro_memoized_attribute
627
+ def _manyrow_getter(self) -> Callable[..., List[_R]]:
628
+ make_row = self._row_getter
629
+
630
+ post_creational_filter = self._post_creational_filter
631
+
632
+ if self._unique_filter_state:
633
+ uniques, strategy = self._unique_strategy
634
+
635
+ def filterrows(
636
+ make_row: Optional[Callable[..., _R]],
637
+ rows: List[Any],
638
+ strategy: Optional[Callable[[List[Any]], Any]],
639
+ uniques: Set[Any],
640
+ ) -> List[_R]:
641
+ if make_row:
642
+ rows = [make_row(row) for row in rows]
643
+
644
+ if strategy:
645
+ made_rows = (
646
+ (made_row, strategy(made_row)) for made_row in rows
647
+ )
648
+ else:
649
+ made_rows = ((made_row, made_row) for made_row in rows)
650
+ return [
651
+ made_row
652
+ for made_row, sig_row in made_rows
653
+ if sig_row not in uniques and not uniques.add(sig_row) # type: ignore # noqa: E501
654
+ ]
655
+
656
+ def manyrows(
657
+ self: ResultInternal[_R], num: Optional[int]
658
+ ) -> List[_R]:
659
+ collect: List[_R] = []
660
+
661
+ _manyrows = self._fetchmany_impl
662
+
663
+ if num is None:
664
+ # if None is passed, we don't know the default
665
+ # manyrows number, DBAPI has this as cursor.arraysize
666
+ # different DBAPIs / fetch strategies may be different.
667
+ # do a fetch to find what the number is. if there are
668
+ # only fewer rows left, then it doesn't matter.
669
+ real_result = (
670
+ self._real_result
671
+ if self._real_result
672
+ else cast("Result[Any]", self)
673
+ )
674
+ if real_result._yield_per:
675
+ num_required = num = real_result._yield_per
676
+ else:
677
+ rows = _manyrows(num)
678
+ num = len(rows)
679
+ assert make_row is not None
680
+ collect.extend(
681
+ filterrows(make_row, rows, strategy, uniques)
682
+ )
683
+ num_required = num - len(collect)
684
+ else:
685
+ num_required = num
686
+
687
+ assert num is not None
688
+
689
+ while num_required:
690
+ rows = _manyrows(num_required)
691
+ if not rows:
692
+ break
693
+
694
+ collect.extend(
695
+ filterrows(make_row, rows, strategy, uniques)
696
+ )
697
+ num_required = num - len(collect)
698
+
699
+ if post_creational_filter:
700
+ collect = [post_creational_filter(row) for row in collect]
701
+ return collect
702
+
703
+ else:
704
+
705
+ def manyrows(
706
+ self: ResultInternal[_R], num: Optional[int]
707
+ ) -> List[_R]:
708
+ if num is None:
709
+ real_result = (
710
+ self._real_result
711
+ if self._real_result
712
+ else cast("Result[Any]", self)
713
+ )
714
+ num = real_result._yield_per
715
+
716
+ rows: List[_InterimRowType[Any]] = self._fetchmany_impl(num)
717
+ if make_row:
718
+ rows = [make_row(row) for row in rows]
719
+ if post_creational_filter:
720
+ rows = [post_creational_filter(row) for row in rows]
721
+ return rows # type: ignore
722
+
723
+ return manyrows
724
+
725
+ @overload
726
+ def _only_one_row(
727
+ self,
728
+ raise_for_second_row: bool,
729
+ raise_for_none: Literal[True],
730
+ scalar: bool,
731
+ ) -> _R: ...
732
+
733
+ @overload
734
+ def _only_one_row(
735
+ self,
736
+ raise_for_second_row: bool,
737
+ raise_for_none: bool,
738
+ scalar: bool,
739
+ ) -> Optional[_R]: ...
740
+
741
+ def _only_one_row(
742
+ self,
743
+ raise_for_second_row: bool,
744
+ raise_for_none: bool,
745
+ scalar: bool,
746
+ ) -> Optional[_R]:
747
+ onerow = self._fetchone_impl
748
+
749
+ row: Optional[_InterimRowType[Any]] = onerow(hard_close=True)
750
+ if row is None:
751
+ if raise_for_none:
752
+ raise exc.NoResultFound(
753
+ "No row was found when one was required"
754
+ )
755
+ else:
756
+ return None
757
+
758
+ if scalar and self._source_supports_scalars:
759
+ self._generate_rows = False
760
+ make_row = None
761
+ else:
762
+ make_row = self._row_getter
763
+
764
+ try:
765
+ row = make_row(row) if make_row else row
766
+ except:
767
+ self._soft_close(hard=True)
768
+ raise
769
+
770
+ if raise_for_second_row:
771
+ if self._unique_filter_state:
772
+ # for no second row but uniqueness, need to essentially
773
+ # consume the entire result :(
774
+ uniques, strategy = self._unique_strategy
775
+
776
+ existing_row_hash = strategy(row) if strategy else row
777
+
778
+ while True:
779
+ next_row: Any = onerow(hard_close=True)
780
+ if next_row is None:
781
+ next_row = _NO_ROW
782
+ break
783
+
784
+ try:
785
+ next_row = make_row(next_row) if make_row else next_row
786
+
787
+ if strategy:
788
+ assert next_row is not _NO_ROW
789
+ if existing_row_hash == strategy(next_row):
790
+ continue
791
+ elif row == next_row:
792
+ continue
793
+ # here, we have a row and it's different
794
+ break
795
+ except:
796
+ self._soft_close(hard=True)
797
+ raise
798
+ else:
799
+ next_row = onerow(hard_close=True)
800
+ if next_row is None:
801
+ next_row = _NO_ROW
802
+
803
+ if next_row is not _NO_ROW:
804
+ self._soft_close(hard=True)
805
+ raise exc.MultipleResultsFound(
806
+ "Multiple rows were found when exactly one was required"
807
+ if raise_for_none
808
+ else "Multiple rows were found when one or none "
809
+ "was required"
810
+ )
811
+ else:
812
+ next_row = _NO_ROW
813
+ # if we checked for second row then that would have
814
+ # closed us :)
815
+ self._soft_close(hard=True)
816
+
817
+ if not scalar:
818
+ post_creational_filter = self._post_creational_filter
819
+ if post_creational_filter:
820
+ row = post_creational_filter(row)
821
+
822
+ if scalar and make_row:
823
+ return row[0] # type: ignore
824
+ else:
825
+ return row # type: ignore
826
+
827
+ def _iter_impl(self) -> Iterator[_R]:
828
+ return self._iterator_getter(self)
829
+
830
+ def _next_impl(self) -> _R:
831
+ row = self._onerow_getter(self)
832
+ if row is _NO_ROW:
833
+ raise StopIteration()
834
+ else:
835
+ return row
836
+
837
+ @_generative
838
+ def _column_slices(self, indexes: Sequence[_KeyIndexType]) -> Self:
839
+ real_result = (
840
+ self._real_result
841
+ if self._real_result
842
+ else cast("Result[Any]", self)
843
+ )
844
+
845
+ if not real_result._source_supports_scalars or len(indexes) != 1:
846
+ self._metadata = self._metadata._reduce(indexes)
847
+
848
+ assert self._generate_rows
849
+
850
+ return self
851
+
852
+ @HasMemoized.memoized_attribute
853
+ def _unique_strategy(self) -> _UniqueFilterStateType:
854
+ assert self._unique_filter_state is not None
855
+ uniques, strategy = self._unique_filter_state
856
+
857
+ real_result = (
858
+ self._real_result
859
+ if self._real_result is not None
860
+ else cast("Result[Any]", self)
861
+ )
862
+
863
+ if not strategy and self._metadata._unique_filters:
864
+ if (
865
+ real_result._source_supports_scalars
866
+ and not self._generate_rows
867
+ ):
868
+ strategy = self._metadata._unique_filters[0]
869
+ else:
870
+ filters = self._metadata._unique_filters
871
+ if self._metadata._tuplefilter:
872
+ filters = self._metadata._tuplefilter(filters)
873
+
874
+ strategy = operator.methodcaller("_filter_on_values", filters)
875
+ return uniques, strategy
876
+
877
+
878
+ class _WithKeys:
879
+ __slots__ = ()
880
+
881
+ _metadata: ResultMetaData
882
+
883
+ # used mainly to share documentation on the keys method.
884
+ def keys(self) -> RMKeyView:
885
+ """Return an iterable view which yields the string keys that would
886
+ be represented by each :class:`_engine.Row`.
887
+
888
+ The keys can represent the labels of the columns returned by a core
889
+ statement or the names of the orm classes returned by an orm
890
+ execution.
891
+
892
+ The view also can be tested for key containment using the Python
893
+ ``in`` operator, which will test both for the string keys represented
894
+ in the view, as well as for alternate keys such as column objects.
895
+
896
+ .. versionchanged:: 1.4 a key view object is returned rather than a
897
+ plain list.
898
+
899
+
900
+ """
901
+ return self._metadata.keys
902
+
903
+
904
+ class Result(_WithKeys, ResultInternal[Row[_TP]]):
905
+ """Represent a set of database results.
906
+
907
+ .. versionadded:: 1.4 The :class:`_engine.Result` object provides a
908
+ completely updated usage model and calling facade for SQLAlchemy
909
+ Core and SQLAlchemy ORM. In Core, it forms the basis of the
910
+ :class:`_engine.CursorResult` object which replaces the previous
911
+ :class:`_engine.ResultProxy` interface. When using the ORM, a
912
+ higher level object called :class:`_engine.ChunkedIteratorResult`
913
+ is normally used.
914
+
915
+ .. note:: In SQLAlchemy 1.4 and above, this object is
916
+ used for ORM results returned by :meth:`_orm.Session.execute`, which can
917
+ yield instances of ORM mapped objects either individually or within
918
+ tuple-like rows. Note that the :class:`_engine.Result` object does not
919
+ deduplicate instances or rows automatically as is the case with the
920
+ legacy :class:`_orm.Query` object. For in-Python de-duplication of
921
+ instances or rows, use the :meth:`_engine.Result.unique` modifier
922
+ method.
923
+
924
+ .. seealso::
925
+
926
+ :ref:`tutorial_fetching_rows` - in the :doc:`/tutorial/index`
927
+
928
+ """
929
+
930
+ __slots__ = ("_metadata", "__dict__")
931
+
932
+ _row_logging_fn: Optional[Callable[[Row[Any]], Row[Any]]] = None
933
+
934
+ _source_supports_scalars: bool = False
935
+
936
+ _yield_per: Optional[int] = None
937
+
938
+ _attributes: util.immutabledict[Any, Any] = util.immutabledict()
939
+
940
+ def __init__(self, cursor_metadata: ResultMetaData):
941
+ self._metadata = cursor_metadata
942
+
943
+ def __enter__(self) -> Self:
944
+ return self
945
+
946
+ def __exit__(self, type_: Any, value: Any, traceback: Any) -> None:
947
+ self.close()
948
+
949
+ def close(self) -> None:
950
+ """close this :class:`_engine.Result`.
951
+
952
+ The behavior of this method is implementation specific, and is
953
+ not implemented by default. The method should generally end
954
+ the resources in use by the result object and also cause any
955
+ subsequent iteration or row fetching to raise
956
+ :class:`.ResourceClosedError`.
957
+
958
+ .. versionadded:: 1.4.27 - ``.close()`` was previously not generally
959
+ available for all :class:`_engine.Result` classes, instead only
960
+ being available on the :class:`_engine.CursorResult` returned for
961
+ Core statement executions. As most other result objects, namely the
962
+ ones used by the ORM, are proxying a :class:`_engine.CursorResult`
963
+ in any case, this allows the underlying cursor result to be closed
964
+ from the outside facade for the case when the ORM query is using
965
+ the ``yield_per`` execution option where it does not immediately
966
+ exhaust and autoclose the database cursor.
967
+
968
+ """
969
+ self._soft_close(hard=True)
970
+
971
+ @property
972
+ def _soft_closed(self) -> bool:
973
+ raise NotImplementedError()
974
+
975
+ @property
976
+ def closed(self) -> bool:
977
+ """return ``True`` if this :class:`_engine.Result` reports .closed
978
+
979
+ .. versionadded:: 1.4.43
980
+
981
+ """
982
+ raise NotImplementedError()
983
+
984
+ @_generative
985
+ def yield_per(self, num: int) -> Self:
986
+ """Configure the row-fetching strategy to fetch ``num`` rows at a time.
987
+
988
+ This impacts the underlying behavior of the result when iterating over
989
+ the result object, or otherwise making use of methods such as
990
+ :meth:`_engine.Result.fetchone` that return one row at a time. Data
991
+ from the underlying cursor or other data source will be buffered up to
992
+ this many rows in memory, and the buffered collection will then be
993
+ yielded out one row at a time or as many rows are requested. Each time
994
+ the buffer clears, it will be refreshed to this many rows or as many
995
+ rows remain if fewer remain.
996
+
997
+ The :meth:`_engine.Result.yield_per` method is generally used in
998
+ conjunction with the
999
+ :paramref:`_engine.Connection.execution_options.stream_results`
1000
+ execution option, which will allow the database dialect in use to make
1001
+ use of a server side cursor, if the DBAPI supports a specific "server
1002
+ side cursor" mode separate from its default mode of operation.
1003
+
1004
+ .. tip::
1005
+
1006
+ Consider using the
1007
+ :paramref:`_engine.Connection.execution_options.yield_per`
1008
+ execution option, which will simultaneously set
1009
+ :paramref:`_engine.Connection.execution_options.stream_results`
1010
+ to ensure the use of server side cursors, as well as automatically
1011
+ invoke the :meth:`_engine.Result.yield_per` method to establish
1012
+ a fixed row buffer size at once.
1013
+
1014
+ The :paramref:`_engine.Connection.execution_options.yield_per`
1015
+ execution option is available for ORM operations, with
1016
+ :class:`_orm.Session`-oriented use described at
1017
+ :ref:`orm_queryguide_yield_per`. The Core-only version which works
1018
+ with :class:`_engine.Connection` is new as of SQLAlchemy 1.4.40.
1019
+
1020
+ .. versionadded:: 1.4
1021
+
1022
+ :param num: number of rows to fetch each time the buffer is refilled.
1023
+ If set to a value below 1, fetches all rows for the next buffer.
1024
+
1025
+ .. seealso::
1026
+
1027
+ :ref:`engine_stream_results` - describes Core behavior for
1028
+ :meth:`_engine.Result.yield_per`
1029
+
1030
+ :ref:`orm_queryguide_yield_per` - in the :ref:`queryguide_toplevel`
1031
+
1032
+ """
1033
+ self._yield_per = num
1034
+ return self
1035
+
1036
+ @_generative
1037
+ def unique(self, strategy: Optional[_UniqueFilterType] = None) -> Self:
1038
+ """Apply unique filtering to the objects returned by this
1039
+ :class:`_engine.Result`.
1040
+
1041
+ When this filter is applied with no arguments, the rows or objects
1042
+ returned will filtered such that each row is returned uniquely. The
1043
+ algorithm used to determine this uniqueness is by default the Python
1044
+ hashing identity of the whole tuple. In some cases a specialized
1045
+ per-entity hashing scheme may be used, such as when using the ORM, a
1046
+ scheme is applied which works against the primary key identity of
1047
+ returned objects.
1048
+
1049
+ The unique filter is applied **after all other filters**, which means
1050
+ if the columns returned have been refined using a method such as the
1051
+ :meth:`_engine.Result.columns` or :meth:`_engine.Result.scalars`
1052
+ method, the uniquing is applied to **only the column or columns
1053
+ returned**. This occurs regardless of the order in which these
1054
+ methods have been called upon the :class:`_engine.Result` object.
1055
+
1056
+ The unique filter also changes the calculus used for methods like
1057
+ :meth:`_engine.Result.fetchmany` and :meth:`_engine.Result.partitions`.
1058
+ When using :meth:`_engine.Result.unique`, these methods will continue
1059
+ to yield the number of rows or objects requested, after uniquing
1060
+ has been applied. However, this necessarily impacts the buffering
1061
+ behavior of the underlying cursor or datasource, such that multiple
1062
+ underlying calls to ``cursor.fetchmany()`` may be necessary in order
1063
+ to accumulate enough objects in order to provide a unique collection
1064
+ of the requested size.
1065
+
1066
+ :param strategy: a callable that will be applied to rows or objects
1067
+ being iterated, which should return an object that represents the
1068
+ unique value of the row. A Python ``set()`` is used to store
1069
+ these identities. If not passed, a default uniqueness strategy
1070
+ is used which may have been assembled by the source of this
1071
+ :class:`_engine.Result` object.
1072
+
1073
+ """
1074
+ self._unique_filter_state = (set(), strategy)
1075
+ return self
1076
+
1077
+ def columns(self, *col_expressions: _KeyIndexType) -> Self:
1078
+ r"""Establish the columns that should be returned in each row.
1079
+
1080
+ This method may be used to limit the columns returned as well
1081
+ as to reorder them. The given list of expressions are normally
1082
+ a series of integers or string key names. They may also be
1083
+ appropriate :class:`.ColumnElement` objects which correspond to
1084
+ a given statement construct.
1085
+
1086
+ .. versionchanged:: 2.0 Due to a bug in 1.4, the
1087
+ :meth:`_engine.Result.columns` method had an incorrect behavior
1088
+ where calling upon the method with just one index would cause the
1089
+ :class:`_engine.Result` object to yield scalar values rather than
1090
+ :class:`_engine.Row` objects. In version 2.0, this behavior
1091
+ has been corrected such that calling upon
1092
+ :meth:`_engine.Result.columns` with a single index will
1093
+ produce a :class:`_engine.Result` object that continues
1094
+ to yield :class:`_engine.Row` objects, which include
1095
+ only a single column.
1096
+
1097
+ E.g.::
1098
+
1099
+ statement = select(table.c.x, table.c.y, table.c.z)
1100
+ result = connection.execute(statement)
1101
+
1102
+ for z, y in result.columns('z', 'y'):
1103
+ # ...
1104
+
1105
+
1106
+ Example of using the column objects from the statement itself::
1107
+
1108
+ for z, y in result.columns(
1109
+ statement.selected_columns.c.z,
1110
+ statement.selected_columns.c.y
1111
+ ):
1112
+ # ...
1113
+
1114
+ .. versionadded:: 1.4
1115
+
1116
+ :param \*col_expressions: indicates columns to be returned. Elements
1117
+ may be integer row indexes, string column names, or appropriate
1118
+ :class:`.ColumnElement` objects corresponding to a select construct.
1119
+
1120
+ :return: this :class:`_engine.Result` object with the modifications
1121
+ given.
1122
+
1123
+ """
1124
+ return self._column_slices(col_expressions)
1125
+
1126
+ @overload
1127
+ def scalars(self: Result[Tuple[_T]]) -> ScalarResult[_T]: ...
1128
+
1129
+ @overload
1130
+ def scalars(
1131
+ self: Result[Tuple[_T]], index: Literal[0]
1132
+ ) -> ScalarResult[_T]: ...
1133
+
1134
+ @overload
1135
+ def scalars(self, index: _KeyIndexType = 0) -> ScalarResult[Any]: ...
1136
+
1137
+ def scalars(self, index: _KeyIndexType = 0) -> ScalarResult[Any]:
1138
+ """Return a :class:`_engine.ScalarResult` filtering object which
1139
+ will return single elements rather than :class:`_row.Row` objects.
1140
+
1141
+ E.g.::
1142
+
1143
+ >>> result = conn.execute(text("select int_id from table"))
1144
+ >>> result.scalars().all()
1145
+ [1, 2, 3]
1146
+
1147
+ When results are fetched from the :class:`_engine.ScalarResult`
1148
+ filtering object, the single column-row that would be returned by the
1149
+ :class:`_engine.Result` is instead returned as the column's value.
1150
+
1151
+ .. versionadded:: 1.4
1152
+
1153
+ :param index: integer or row key indicating the column to be fetched
1154
+ from each row, defaults to ``0`` indicating the first column.
1155
+
1156
+ :return: a new :class:`_engine.ScalarResult` filtering object referring
1157
+ to this :class:`_engine.Result` object.
1158
+
1159
+ """
1160
+ return ScalarResult(self, index)
1161
+
1162
+ def _getter(
1163
+ self, key: _KeyIndexType, raiseerr: bool = True
1164
+ ) -> Optional[Callable[[Row[Any]], Any]]:
1165
+ """return a callable that will retrieve the given key from a
1166
+ :class:`_engine.Row`.
1167
+
1168
+ """
1169
+ if self._source_supports_scalars:
1170
+ raise NotImplementedError(
1171
+ "can't use this function in 'only scalars' mode"
1172
+ )
1173
+ return self._metadata._getter(key, raiseerr)
1174
+
1175
+ def _tuple_getter(self, keys: Sequence[_KeyIndexType]) -> _TupleGetterType:
1176
+ """return a callable that will retrieve the given keys from a
1177
+ :class:`_engine.Row`.
1178
+
1179
+ """
1180
+ if self._source_supports_scalars:
1181
+ raise NotImplementedError(
1182
+ "can't use this function in 'only scalars' mode"
1183
+ )
1184
+ return self._metadata._row_as_tuple_getter(keys)
1185
+
1186
+ def mappings(self) -> MappingResult:
1187
+ """Apply a mappings filter to returned rows, returning an instance of
1188
+ :class:`_engine.MappingResult`.
1189
+
1190
+ When this filter is applied, fetching rows will return
1191
+ :class:`_engine.RowMapping` objects instead of :class:`_engine.Row`
1192
+ objects.
1193
+
1194
+ .. versionadded:: 1.4
1195
+
1196
+ :return: a new :class:`_engine.MappingResult` filtering object
1197
+ referring to this :class:`_engine.Result` object.
1198
+
1199
+ """
1200
+
1201
+ return MappingResult(self)
1202
+
1203
+ @property
1204
+ def t(self) -> TupleResult[_TP]:
1205
+ """Apply a "typed tuple" typing filter to returned rows.
1206
+
1207
+ The :attr:`_engine.Result.t` attribute is a synonym for
1208
+ calling the :meth:`_engine.Result.tuples` method.
1209
+
1210
+ .. versionadded:: 2.0
1211
+
1212
+ """
1213
+ return self # type: ignore
1214
+
1215
+ def tuples(self) -> TupleResult[_TP]:
1216
+ """Apply a "typed tuple" typing filter to returned rows.
1217
+
1218
+ This method returns the same :class:`_engine.Result` object
1219
+ at runtime,
1220
+ however annotates as returning a :class:`_engine.TupleResult` object
1221
+ that will indicate to :pep:`484` typing tools that plain typed
1222
+ ``Tuple`` instances are returned rather than rows. This allows
1223
+ tuple unpacking and ``__getitem__`` access of :class:`_engine.Row`
1224
+ objects to by typed, for those cases where the statement invoked
1225
+ itself included typing information.
1226
+
1227
+ .. versionadded:: 2.0
1228
+
1229
+ :return: the :class:`_engine.TupleResult` type at typing time.
1230
+
1231
+ .. seealso::
1232
+
1233
+ :attr:`_engine.Result.t` - shorter synonym
1234
+
1235
+ :attr:`_engine.Row._t` - :class:`_engine.Row` version
1236
+
1237
+ """
1238
+
1239
+ return self # type: ignore
1240
+
1241
+ def _raw_row_iterator(self) -> Iterator[_RowData]:
1242
+ """Return a safe iterator that yields raw row data.
1243
+
1244
+ This is used by the :meth:`_engine.Result.merge` method
1245
+ to merge multiple compatible results together.
1246
+
1247
+ """
1248
+ raise NotImplementedError()
1249
+
1250
+ def __iter__(self) -> Iterator[Row[_TP]]:
1251
+ return self._iter_impl()
1252
+
1253
+ def __next__(self) -> Row[_TP]:
1254
+ return self._next_impl()
1255
+
1256
+ def partitions(
1257
+ self, size: Optional[int] = None
1258
+ ) -> Iterator[Sequence[Row[_TP]]]:
1259
+ """Iterate through sub-lists of rows of the size given.
1260
+
1261
+ Each list will be of the size given, excluding the last list to
1262
+ be yielded, which may have a small number of rows. No empty
1263
+ lists will be yielded.
1264
+
1265
+ The result object is automatically closed when the iterator
1266
+ is fully consumed.
1267
+
1268
+ Note that the backend driver will usually buffer the entire result
1269
+ ahead of time unless the
1270
+ :paramref:`.Connection.execution_options.stream_results` execution
1271
+ option is used indicating that the driver should not pre-buffer
1272
+ results, if possible. Not all drivers support this option and
1273
+ the option is silently ignored for those who do not.
1274
+
1275
+ When using the ORM, the :meth:`_engine.Result.partitions` method
1276
+ is typically more effective from a memory perspective when it is
1277
+ combined with use of the
1278
+ :ref:`yield_per execution option <orm_queryguide_yield_per>`,
1279
+ which instructs both the DBAPI driver to use server side cursors,
1280
+ if available, as well as instructs the ORM loading internals to only
1281
+ build a certain amount of ORM objects from a result at a time before
1282
+ yielding them out.
1283
+
1284
+ .. versionadded:: 1.4
1285
+
1286
+ :param size: indicate the maximum number of rows to be present
1287
+ in each list yielded. If None, makes use of the value set by
1288
+ the :meth:`_engine.Result.yield_per`, method, if it were called,
1289
+ or the :paramref:`_engine.Connection.execution_options.yield_per`
1290
+ execution option, which is equivalent in this regard. If
1291
+ yield_per weren't set, it makes use of the
1292
+ :meth:`_engine.Result.fetchmany` default, which may be backend
1293
+ specific and not well defined.
1294
+
1295
+ :return: iterator of lists
1296
+
1297
+ .. seealso::
1298
+
1299
+ :ref:`engine_stream_results`
1300
+
1301
+ :ref:`orm_queryguide_yield_per` - in the :ref:`queryguide_toplevel`
1302
+
1303
+ """
1304
+
1305
+ getter = self._manyrow_getter
1306
+
1307
+ while True:
1308
+ partition = getter(self, size)
1309
+ if partition:
1310
+ yield partition
1311
+ else:
1312
+ break
1313
+
1314
+ def fetchall(self) -> Sequence[Row[_TP]]:
1315
+ """A synonym for the :meth:`_engine.Result.all` method."""
1316
+
1317
+ return self._allrows()
1318
+
1319
+ def fetchone(self) -> Optional[Row[_TP]]:
1320
+ """Fetch one row.
1321
+
1322
+ When all rows are exhausted, returns None.
1323
+
1324
+ This method is provided for backwards compatibility with
1325
+ SQLAlchemy 1.x.x.
1326
+
1327
+ To fetch the first row of a result only, use the
1328
+ :meth:`_engine.Result.first` method. To iterate through all
1329
+ rows, iterate the :class:`_engine.Result` object directly.
1330
+
1331
+ :return: a :class:`_engine.Row` object if no filters are applied,
1332
+ or ``None`` if no rows remain.
1333
+
1334
+ """
1335
+ row = self._onerow_getter(self)
1336
+ if row is _NO_ROW:
1337
+ return None
1338
+ else:
1339
+ return row
1340
+
1341
+ def fetchmany(self, size: Optional[int] = None) -> Sequence[Row[_TP]]:
1342
+ """Fetch many rows.
1343
+
1344
+ When all rows are exhausted, returns an empty sequence.
1345
+
1346
+ This method is provided for backwards compatibility with
1347
+ SQLAlchemy 1.x.x.
1348
+
1349
+ To fetch rows in groups, use the :meth:`_engine.Result.partitions`
1350
+ method.
1351
+
1352
+ :return: a sequence of :class:`_engine.Row` objects.
1353
+
1354
+ .. seealso::
1355
+
1356
+ :meth:`_engine.Result.partitions`
1357
+
1358
+ """
1359
+
1360
+ return self._manyrow_getter(self, size)
1361
+
1362
+ def all(self) -> Sequence[Row[_TP]]:
1363
+ """Return all rows in a sequence.
1364
+
1365
+ Closes the result set after invocation. Subsequent invocations
1366
+ will return an empty sequence.
1367
+
1368
+ .. versionadded:: 1.4
1369
+
1370
+ :return: a sequence of :class:`_engine.Row` objects.
1371
+
1372
+ .. seealso::
1373
+
1374
+ :ref:`engine_stream_results` - How to stream a large result set
1375
+ without loading it completely in python.
1376
+
1377
+ """
1378
+
1379
+ return self._allrows()
1380
+
1381
+ def first(self) -> Optional[Row[_TP]]:
1382
+ """Fetch the first row or ``None`` if no row is present.
1383
+
1384
+ Closes the result set and discards remaining rows.
1385
+
1386
+ .. note:: This method returns one **row**, e.g. tuple, by default.
1387
+ To return exactly one single scalar value, that is, the first
1388
+ column of the first row, use the
1389
+ :meth:`_engine.Result.scalar` method,
1390
+ or combine :meth:`_engine.Result.scalars` and
1391
+ :meth:`_engine.Result.first`.
1392
+
1393
+ Additionally, in contrast to the behavior of the legacy ORM
1394
+ :meth:`_orm.Query.first` method, **no limit is applied** to the
1395
+ SQL query which was invoked to produce this
1396
+ :class:`_engine.Result`;
1397
+ for a DBAPI driver that buffers results in memory before yielding
1398
+ rows, all rows will be sent to the Python process and all but
1399
+ the first row will be discarded.
1400
+
1401
+ .. seealso::
1402
+
1403
+ :ref:`migration_20_unify_select`
1404
+
1405
+ :return: a :class:`_engine.Row` object, or None
1406
+ if no rows remain.
1407
+
1408
+ .. seealso::
1409
+
1410
+ :meth:`_engine.Result.scalar`
1411
+
1412
+ :meth:`_engine.Result.one`
1413
+
1414
+ """
1415
+
1416
+ return self._only_one_row(
1417
+ raise_for_second_row=False, raise_for_none=False, scalar=False
1418
+ )
1419
+
1420
+ def one_or_none(self) -> Optional[Row[_TP]]:
1421
+ """Return at most one result or raise an exception.
1422
+
1423
+ Returns ``None`` if the result has no rows.
1424
+ Raises :class:`.MultipleResultsFound`
1425
+ if multiple rows are returned.
1426
+
1427
+ .. versionadded:: 1.4
1428
+
1429
+ :return: The first :class:`_engine.Row` or ``None`` if no row
1430
+ is available.
1431
+
1432
+ :raises: :class:`.MultipleResultsFound`
1433
+
1434
+ .. seealso::
1435
+
1436
+ :meth:`_engine.Result.first`
1437
+
1438
+ :meth:`_engine.Result.one`
1439
+
1440
+ """
1441
+ return self._only_one_row(
1442
+ raise_for_second_row=True, raise_for_none=False, scalar=False
1443
+ )
1444
+
1445
+ @overload
1446
+ def scalar_one(self: Result[Tuple[_T]]) -> _T: ...
1447
+
1448
+ @overload
1449
+ def scalar_one(self) -> Any: ...
1450
+
1451
+ def scalar_one(self) -> Any:
1452
+ """Return exactly one scalar result or raise an exception.
1453
+
1454
+ This is equivalent to calling :meth:`_engine.Result.scalars` and
1455
+ then :meth:`_engine.ScalarResult.one`.
1456
+
1457
+ .. seealso::
1458
+
1459
+ :meth:`_engine.ScalarResult.one`
1460
+
1461
+ :meth:`_engine.Result.scalars`
1462
+
1463
+ """
1464
+ return self._only_one_row(
1465
+ raise_for_second_row=True, raise_for_none=True, scalar=True
1466
+ )
1467
+
1468
+ @overload
1469
+ def scalar_one_or_none(self: Result[Tuple[_T]]) -> Optional[_T]: ...
1470
+
1471
+ @overload
1472
+ def scalar_one_or_none(self) -> Optional[Any]: ...
1473
+
1474
+ def scalar_one_or_none(self) -> Optional[Any]:
1475
+ """Return exactly one scalar result or ``None``.
1476
+
1477
+ This is equivalent to calling :meth:`_engine.Result.scalars` and
1478
+ then :meth:`_engine.ScalarResult.one_or_none`.
1479
+
1480
+ .. seealso::
1481
+
1482
+ :meth:`_engine.ScalarResult.one_or_none`
1483
+
1484
+ :meth:`_engine.Result.scalars`
1485
+
1486
+ """
1487
+ return self._only_one_row(
1488
+ raise_for_second_row=True, raise_for_none=False, scalar=True
1489
+ )
1490
+
1491
+ def one(self) -> Row[_TP]:
1492
+ """Return exactly one row or raise an exception.
1493
+
1494
+ Raises :class:`.NoResultFound` if the result returns no
1495
+ rows, or :class:`.MultipleResultsFound` if multiple rows
1496
+ would be returned.
1497
+
1498
+ .. note:: This method returns one **row**, e.g. tuple, by default.
1499
+ To return exactly one single scalar value, that is, the first
1500
+ column of the first row, use the
1501
+ :meth:`_engine.Result.scalar_one` method, or combine
1502
+ :meth:`_engine.Result.scalars` and
1503
+ :meth:`_engine.Result.one`.
1504
+
1505
+ .. versionadded:: 1.4
1506
+
1507
+ :return: The first :class:`_engine.Row`.
1508
+
1509
+ :raises: :class:`.MultipleResultsFound`, :class:`.NoResultFound`
1510
+
1511
+ .. seealso::
1512
+
1513
+ :meth:`_engine.Result.first`
1514
+
1515
+ :meth:`_engine.Result.one_or_none`
1516
+
1517
+ :meth:`_engine.Result.scalar_one`
1518
+
1519
+ """
1520
+ return self._only_one_row(
1521
+ raise_for_second_row=True, raise_for_none=True, scalar=False
1522
+ )
1523
+
1524
+ @overload
1525
+ def scalar(self: Result[Tuple[_T]]) -> Optional[_T]: ...
1526
+
1527
+ @overload
1528
+ def scalar(self) -> Any: ...
1529
+
1530
+ def scalar(self) -> Any:
1531
+ """Fetch the first column of the first row, and close the result set.
1532
+
1533
+ Returns ``None`` if there are no rows to fetch.
1534
+
1535
+ No validation is performed to test if additional rows remain.
1536
+
1537
+ After calling this method, the object is fully closed,
1538
+ e.g. the :meth:`_engine.CursorResult.close`
1539
+ method will have been called.
1540
+
1541
+ :return: a Python scalar value, or ``None`` if no rows remain.
1542
+
1543
+ """
1544
+ return self._only_one_row(
1545
+ raise_for_second_row=False, raise_for_none=False, scalar=True
1546
+ )
1547
+
1548
+ def freeze(self) -> FrozenResult[_TP]:
1549
+ """Return a callable object that will produce copies of this
1550
+ :class:`_engine.Result` when invoked.
1551
+
1552
+ The callable object returned is an instance of
1553
+ :class:`_engine.FrozenResult`.
1554
+
1555
+ This is used for result set caching. The method must be called
1556
+ on the result when it has been unconsumed, and calling the method
1557
+ will consume the result fully. When the :class:`_engine.FrozenResult`
1558
+ is retrieved from a cache, it can be called any number of times where
1559
+ it will produce a new :class:`_engine.Result` object each time
1560
+ against its stored set of rows.
1561
+
1562
+ .. seealso::
1563
+
1564
+ :ref:`do_orm_execute_re_executing` - example usage within the
1565
+ ORM to implement a result-set cache.
1566
+
1567
+ """
1568
+
1569
+ return FrozenResult(self)
1570
+
1571
+ def merge(self, *others: Result[Any]) -> MergedResult[_TP]:
1572
+ """Merge this :class:`_engine.Result` with other compatible result
1573
+ objects.
1574
+
1575
+ The object returned is an instance of :class:`_engine.MergedResult`,
1576
+ which will be composed of iterators from the given result
1577
+ objects.
1578
+
1579
+ The new result will use the metadata from this result object.
1580
+ The subsequent result objects must be against an identical
1581
+ set of result / cursor metadata, otherwise the behavior is
1582
+ undefined.
1583
+
1584
+ """
1585
+ return MergedResult(self._metadata, (self,) + others)
1586
+
1587
+
1588
+ class FilterResult(ResultInternal[_R]):
1589
+ """A wrapper for a :class:`_engine.Result` that returns objects other than
1590
+ :class:`_engine.Row` objects, such as dictionaries or scalar objects.
1591
+
1592
+ :class:`_engine.FilterResult` is the common base for additional result
1593
+ APIs including :class:`_engine.MappingResult`,
1594
+ :class:`_engine.ScalarResult` and :class:`_engine.AsyncResult`.
1595
+
1596
+ """
1597
+
1598
+ __slots__ = (
1599
+ "_real_result",
1600
+ "_post_creational_filter",
1601
+ "_metadata",
1602
+ "_unique_filter_state",
1603
+ "__dict__",
1604
+ )
1605
+
1606
+ _post_creational_filter: Optional[Callable[[Any], Any]]
1607
+
1608
+ _real_result: Result[Any]
1609
+
1610
+ def __enter__(self) -> Self:
1611
+ return self
1612
+
1613
+ def __exit__(self, type_: Any, value: Any, traceback: Any) -> None:
1614
+ self._real_result.__exit__(type_, value, traceback)
1615
+
1616
+ @_generative
1617
+ def yield_per(self, num: int) -> Self:
1618
+ """Configure the row-fetching strategy to fetch ``num`` rows at a time.
1619
+
1620
+ The :meth:`_engine.FilterResult.yield_per` method is a pass through
1621
+ to the :meth:`_engine.Result.yield_per` method. See that method's
1622
+ documentation for usage notes.
1623
+
1624
+ .. versionadded:: 1.4.40 - added :meth:`_engine.FilterResult.yield_per`
1625
+ so that the method is available on all result set implementations
1626
+
1627
+ .. seealso::
1628
+
1629
+ :ref:`engine_stream_results` - describes Core behavior for
1630
+ :meth:`_engine.Result.yield_per`
1631
+
1632
+ :ref:`orm_queryguide_yield_per` - in the :ref:`queryguide_toplevel`
1633
+
1634
+ """
1635
+ self._real_result = self._real_result.yield_per(num)
1636
+ return self
1637
+
1638
+ def _soft_close(self, hard: bool = False) -> None:
1639
+ self._real_result._soft_close(hard=hard)
1640
+
1641
+ @property
1642
+ def _soft_closed(self) -> bool:
1643
+ return self._real_result._soft_closed
1644
+
1645
+ @property
1646
+ def closed(self) -> bool:
1647
+ """Return ``True`` if the underlying :class:`_engine.Result` reports
1648
+ closed
1649
+
1650
+ .. versionadded:: 1.4.43
1651
+
1652
+ """
1653
+ return self._real_result.closed
1654
+
1655
+ def close(self) -> None:
1656
+ """Close this :class:`_engine.FilterResult`.
1657
+
1658
+ .. versionadded:: 1.4.43
1659
+
1660
+ """
1661
+ self._real_result.close()
1662
+
1663
+ @property
1664
+ def _attributes(self) -> Dict[Any, Any]:
1665
+ return self._real_result._attributes
1666
+
1667
+ def _fetchiter_impl(self) -> Iterator[_InterimRowType[Row[Any]]]:
1668
+ return self._real_result._fetchiter_impl()
1669
+
1670
+ def _fetchone_impl(
1671
+ self, hard_close: bool = False
1672
+ ) -> Optional[_InterimRowType[Row[Any]]]:
1673
+ return self._real_result._fetchone_impl(hard_close=hard_close)
1674
+
1675
+ def _fetchall_impl(self) -> List[_InterimRowType[Row[Any]]]:
1676
+ return self._real_result._fetchall_impl()
1677
+
1678
+ def _fetchmany_impl(
1679
+ self, size: Optional[int] = None
1680
+ ) -> List[_InterimRowType[Row[Any]]]:
1681
+ return self._real_result._fetchmany_impl(size=size)
1682
+
1683
+
1684
+ class ScalarResult(FilterResult[_R]):
1685
+ """A wrapper for a :class:`_engine.Result` that returns scalar values
1686
+ rather than :class:`_row.Row` values.
1687
+
1688
+ The :class:`_engine.ScalarResult` object is acquired by calling the
1689
+ :meth:`_engine.Result.scalars` method.
1690
+
1691
+ A special limitation of :class:`_engine.ScalarResult` is that it has
1692
+ no ``fetchone()`` method; since the semantics of ``fetchone()`` are that
1693
+ the ``None`` value indicates no more results, this is not compatible
1694
+ with :class:`_engine.ScalarResult` since there is no way to distinguish
1695
+ between ``None`` as a row value versus ``None`` as an indicator. Use
1696
+ ``next(result)`` to receive values individually.
1697
+
1698
+ """
1699
+
1700
+ __slots__ = ()
1701
+
1702
+ _generate_rows = False
1703
+
1704
+ _post_creational_filter: Optional[Callable[[Any], Any]]
1705
+
1706
+ def __init__(self, real_result: Result[Any], index: _KeyIndexType):
1707
+ self._real_result = real_result
1708
+
1709
+ if real_result._source_supports_scalars:
1710
+ self._metadata = real_result._metadata
1711
+ self._post_creational_filter = None
1712
+ else:
1713
+ self._metadata = real_result._metadata._reduce([index])
1714
+ self._post_creational_filter = operator.itemgetter(0)
1715
+
1716
+ self._unique_filter_state = real_result._unique_filter_state
1717
+
1718
+ def unique(self, strategy: Optional[_UniqueFilterType] = None) -> Self:
1719
+ """Apply unique filtering to the objects returned by this
1720
+ :class:`_engine.ScalarResult`.
1721
+
1722
+ See :meth:`_engine.Result.unique` for usage details.
1723
+
1724
+ """
1725
+ self._unique_filter_state = (set(), strategy)
1726
+ return self
1727
+
1728
+ def partitions(self, size: Optional[int] = None) -> Iterator[Sequence[_R]]:
1729
+ """Iterate through sub-lists of elements of the size given.
1730
+
1731
+ Equivalent to :meth:`_engine.Result.partitions` except that
1732
+ scalar values, rather than :class:`_engine.Row` objects,
1733
+ are returned.
1734
+
1735
+ """
1736
+
1737
+ getter = self._manyrow_getter
1738
+
1739
+ while True:
1740
+ partition = getter(self, size)
1741
+ if partition:
1742
+ yield partition
1743
+ else:
1744
+ break
1745
+
1746
+ def fetchall(self) -> Sequence[_R]:
1747
+ """A synonym for the :meth:`_engine.ScalarResult.all` method."""
1748
+
1749
+ return self._allrows()
1750
+
1751
+ def fetchmany(self, size: Optional[int] = None) -> Sequence[_R]:
1752
+ """Fetch many objects.
1753
+
1754
+ Equivalent to :meth:`_engine.Result.fetchmany` except that
1755
+ scalar values, rather than :class:`_engine.Row` objects,
1756
+ are returned.
1757
+
1758
+ """
1759
+ return self._manyrow_getter(self, size)
1760
+
1761
+ def all(self) -> Sequence[_R]:
1762
+ """Return all scalar values in a sequence.
1763
+
1764
+ Equivalent to :meth:`_engine.Result.all` except that
1765
+ scalar values, rather than :class:`_engine.Row` objects,
1766
+ are returned.
1767
+
1768
+ """
1769
+ return self._allrows()
1770
+
1771
+ def __iter__(self) -> Iterator[_R]:
1772
+ return self._iter_impl()
1773
+
1774
+ def __next__(self) -> _R:
1775
+ return self._next_impl()
1776
+
1777
+ def first(self) -> Optional[_R]:
1778
+ """Fetch the first object or ``None`` if no object is present.
1779
+
1780
+ Equivalent to :meth:`_engine.Result.first` except that
1781
+ scalar values, rather than :class:`_engine.Row` objects,
1782
+ are returned.
1783
+
1784
+
1785
+ """
1786
+ return self._only_one_row(
1787
+ raise_for_second_row=False, raise_for_none=False, scalar=False
1788
+ )
1789
+
1790
+ def one_or_none(self) -> Optional[_R]:
1791
+ """Return at most one object or raise an exception.
1792
+
1793
+ Equivalent to :meth:`_engine.Result.one_or_none` except that
1794
+ scalar values, rather than :class:`_engine.Row` objects,
1795
+ are returned.
1796
+
1797
+ """
1798
+ return self._only_one_row(
1799
+ raise_for_second_row=True, raise_for_none=False, scalar=False
1800
+ )
1801
+
1802
+ def one(self) -> _R:
1803
+ """Return exactly one object or raise an exception.
1804
+
1805
+ Equivalent to :meth:`_engine.Result.one` except that
1806
+ scalar values, rather than :class:`_engine.Row` objects,
1807
+ are returned.
1808
+
1809
+ """
1810
+ return self._only_one_row(
1811
+ raise_for_second_row=True, raise_for_none=True, scalar=False
1812
+ )
1813
+
1814
+
1815
+ class TupleResult(FilterResult[_R], util.TypingOnly):
1816
+ """A :class:`_engine.Result` that's typed as returning plain
1817
+ Python tuples instead of rows.
1818
+
1819
+ Since :class:`_engine.Row` acts like a tuple in every way already,
1820
+ this class is a typing only class, regular :class:`_engine.Result` is
1821
+ still used at runtime.
1822
+
1823
+ """
1824
+
1825
+ __slots__ = ()
1826
+
1827
+ if TYPE_CHECKING:
1828
+
1829
+ def partitions(
1830
+ self, size: Optional[int] = None
1831
+ ) -> Iterator[Sequence[_R]]:
1832
+ """Iterate through sub-lists of elements of the size given.
1833
+
1834
+ Equivalent to :meth:`_engine.Result.partitions` except that
1835
+ tuple values, rather than :class:`_engine.Row` objects,
1836
+ are returned.
1837
+
1838
+ """
1839
+ ...
1840
+
1841
+ def fetchone(self) -> Optional[_R]:
1842
+ """Fetch one tuple.
1843
+
1844
+ Equivalent to :meth:`_engine.Result.fetchone` except that
1845
+ tuple values, rather than :class:`_engine.Row`
1846
+ objects, are returned.
1847
+
1848
+ """
1849
+ ...
1850
+
1851
+ def fetchall(self) -> Sequence[_R]:
1852
+ """A synonym for the :meth:`_engine.ScalarResult.all` method."""
1853
+ ...
1854
+
1855
+ def fetchmany(self, size: Optional[int] = None) -> Sequence[_R]:
1856
+ """Fetch many objects.
1857
+
1858
+ Equivalent to :meth:`_engine.Result.fetchmany` except that
1859
+ tuple values, rather than :class:`_engine.Row` objects,
1860
+ are returned.
1861
+
1862
+ """
1863
+ ...
1864
+
1865
+ def all(self) -> Sequence[_R]: # noqa: A001
1866
+ """Return all scalar values in a sequence.
1867
+
1868
+ Equivalent to :meth:`_engine.Result.all` except that
1869
+ tuple values, rather than :class:`_engine.Row` objects,
1870
+ are returned.
1871
+
1872
+ """
1873
+ ...
1874
+
1875
+ def __iter__(self) -> Iterator[_R]: ...
1876
+
1877
+ def __next__(self) -> _R: ...
1878
+
1879
+ def first(self) -> Optional[_R]:
1880
+ """Fetch the first object or ``None`` if no object is present.
1881
+
1882
+ Equivalent to :meth:`_engine.Result.first` except that
1883
+ tuple values, rather than :class:`_engine.Row` objects,
1884
+ are returned.
1885
+
1886
+
1887
+ """
1888
+ ...
1889
+
1890
+ def one_or_none(self) -> Optional[_R]:
1891
+ """Return at most one object or raise an exception.
1892
+
1893
+ Equivalent to :meth:`_engine.Result.one_or_none` except that
1894
+ tuple values, rather than :class:`_engine.Row` objects,
1895
+ are returned.
1896
+
1897
+ """
1898
+ ...
1899
+
1900
+ def one(self) -> _R:
1901
+ """Return exactly one object or raise an exception.
1902
+
1903
+ Equivalent to :meth:`_engine.Result.one` except that
1904
+ tuple values, rather than :class:`_engine.Row` objects,
1905
+ are returned.
1906
+
1907
+ """
1908
+ ...
1909
+
1910
+ @overload
1911
+ def scalar_one(self: TupleResult[Tuple[_T]]) -> _T: ...
1912
+
1913
+ @overload
1914
+ def scalar_one(self) -> Any: ...
1915
+
1916
+ def scalar_one(self) -> Any:
1917
+ """Return exactly one scalar result or raise an exception.
1918
+
1919
+ This is equivalent to calling :meth:`_engine.Result.scalars`
1920
+ and then :meth:`_engine.ScalarResult.one`.
1921
+
1922
+ .. seealso::
1923
+
1924
+ :meth:`_engine.ScalarResult.one`
1925
+
1926
+ :meth:`_engine.Result.scalars`
1927
+
1928
+ """
1929
+ ...
1930
+
1931
+ @overload
1932
+ def scalar_one_or_none(
1933
+ self: TupleResult[Tuple[_T]],
1934
+ ) -> Optional[_T]: ...
1935
+
1936
+ @overload
1937
+ def scalar_one_or_none(self) -> Optional[Any]: ...
1938
+
1939
+ def scalar_one_or_none(self) -> Optional[Any]:
1940
+ """Return exactly one or no scalar result.
1941
+
1942
+ This is equivalent to calling :meth:`_engine.Result.scalars`
1943
+ and then :meth:`_engine.ScalarResult.one_or_none`.
1944
+
1945
+ .. seealso::
1946
+
1947
+ :meth:`_engine.ScalarResult.one_or_none`
1948
+
1949
+ :meth:`_engine.Result.scalars`
1950
+
1951
+ """
1952
+ ...
1953
+
1954
+ @overload
1955
+ def scalar(self: TupleResult[Tuple[_T]]) -> Optional[_T]: ...
1956
+
1957
+ @overload
1958
+ def scalar(self) -> Any: ...
1959
+
1960
+ def scalar(self) -> Any:
1961
+ """Fetch the first column of the first row, and close the result
1962
+ set.
1963
+
1964
+ Returns ``None`` if there are no rows to fetch.
1965
+
1966
+ No validation is performed to test if additional rows remain.
1967
+
1968
+ After calling this method, the object is fully closed,
1969
+ e.g. the :meth:`_engine.CursorResult.close`
1970
+ method will have been called.
1971
+
1972
+ :return: a Python scalar value , or ``None`` if no rows remain.
1973
+
1974
+ """
1975
+ ...
1976
+
1977
+
1978
+ class MappingResult(_WithKeys, FilterResult[RowMapping]):
1979
+ """A wrapper for a :class:`_engine.Result` that returns dictionary values
1980
+ rather than :class:`_engine.Row` values.
1981
+
1982
+ The :class:`_engine.MappingResult` object is acquired by calling the
1983
+ :meth:`_engine.Result.mappings` method.
1984
+
1985
+ """
1986
+
1987
+ __slots__ = ()
1988
+
1989
+ _generate_rows = True
1990
+
1991
+ _post_creational_filter = operator.attrgetter("_mapping")
1992
+
1993
+ def __init__(self, result: Result[Any]):
1994
+ self._real_result = result
1995
+ self._unique_filter_state = result._unique_filter_state
1996
+ self._metadata = result._metadata
1997
+ if result._source_supports_scalars:
1998
+ self._metadata = self._metadata._reduce([0])
1999
+
2000
+ def unique(self, strategy: Optional[_UniqueFilterType] = None) -> Self:
2001
+ """Apply unique filtering to the objects returned by this
2002
+ :class:`_engine.MappingResult`.
2003
+
2004
+ See :meth:`_engine.Result.unique` for usage details.
2005
+
2006
+ """
2007
+ self._unique_filter_state = (set(), strategy)
2008
+ return self
2009
+
2010
+ def columns(self, *col_expressions: _KeyIndexType) -> Self:
2011
+ r"""Establish the columns that should be returned in each row."""
2012
+ return self._column_slices(col_expressions)
2013
+
2014
+ def partitions(
2015
+ self, size: Optional[int] = None
2016
+ ) -> Iterator[Sequence[RowMapping]]:
2017
+ """Iterate through sub-lists of elements of the size given.
2018
+
2019
+ Equivalent to :meth:`_engine.Result.partitions` except that
2020
+ :class:`_engine.RowMapping` values, rather than :class:`_engine.Row`
2021
+ objects, are returned.
2022
+
2023
+ """
2024
+
2025
+ getter = self._manyrow_getter
2026
+
2027
+ while True:
2028
+ partition = getter(self, size)
2029
+ if partition:
2030
+ yield partition
2031
+ else:
2032
+ break
2033
+
2034
+ def fetchall(self) -> Sequence[RowMapping]:
2035
+ """A synonym for the :meth:`_engine.MappingResult.all` method."""
2036
+
2037
+ return self._allrows()
2038
+
2039
+ def fetchone(self) -> Optional[RowMapping]:
2040
+ """Fetch one object.
2041
+
2042
+ Equivalent to :meth:`_engine.Result.fetchone` except that
2043
+ :class:`_engine.RowMapping` values, rather than :class:`_engine.Row`
2044
+ objects, are returned.
2045
+
2046
+ """
2047
+
2048
+ row = self._onerow_getter(self)
2049
+ if row is _NO_ROW:
2050
+ return None
2051
+ else:
2052
+ return row
2053
+
2054
+ def fetchmany(self, size: Optional[int] = None) -> Sequence[RowMapping]:
2055
+ """Fetch many objects.
2056
+
2057
+ Equivalent to :meth:`_engine.Result.fetchmany` except that
2058
+ :class:`_engine.RowMapping` values, rather than :class:`_engine.Row`
2059
+ objects, are returned.
2060
+
2061
+ """
2062
+
2063
+ return self._manyrow_getter(self, size)
2064
+
2065
+ def all(self) -> Sequence[RowMapping]:
2066
+ """Return all scalar values in a sequence.
2067
+
2068
+ Equivalent to :meth:`_engine.Result.all` except that
2069
+ :class:`_engine.RowMapping` values, rather than :class:`_engine.Row`
2070
+ objects, are returned.
2071
+
2072
+ """
2073
+
2074
+ return self._allrows()
2075
+
2076
+ def __iter__(self) -> Iterator[RowMapping]:
2077
+ return self._iter_impl()
2078
+
2079
+ def __next__(self) -> RowMapping:
2080
+ return self._next_impl()
2081
+
2082
+ def first(self) -> Optional[RowMapping]:
2083
+ """Fetch the first object or ``None`` if no object is present.
2084
+
2085
+ Equivalent to :meth:`_engine.Result.first` except that
2086
+ :class:`_engine.RowMapping` values, rather than :class:`_engine.Row`
2087
+ objects, are returned.
2088
+
2089
+
2090
+ """
2091
+ return self._only_one_row(
2092
+ raise_for_second_row=False, raise_for_none=False, scalar=False
2093
+ )
2094
+
2095
+ def one_or_none(self) -> Optional[RowMapping]:
2096
+ """Return at most one object or raise an exception.
2097
+
2098
+ Equivalent to :meth:`_engine.Result.one_or_none` except that
2099
+ :class:`_engine.RowMapping` values, rather than :class:`_engine.Row`
2100
+ objects, are returned.
2101
+
2102
+ """
2103
+ return self._only_one_row(
2104
+ raise_for_second_row=True, raise_for_none=False, scalar=False
2105
+ )
2106
+
2107
+ def one(self) -> RowMapping:
2108
+ """Return exactly one object or raise an exception.
2109
+
2110
+ Equivalent to :meth:`_engine.Result.one` except that
2111
+ :class:`_engine.RowMapping` values, rather than :class:`_engine.Row`
2112
+ objects, are returned.
2113
+
2114
+ """
2115
+ return self._only_one_row(
2116
+ raise_for_second_row=True, raise_for_none=True, scalar=False
2117
+ )
2118
+
2119
+
2120
+ class FrozenResult(Generic[_TP]):
2121
+ """Represents a :class:`_engine.Result` object in a "frozen" state suitable
2122
+ for caching.
2123
+
2124
+ The :class:`_engine.FrozenResult` object is returned from the
2125
+ :meth:`_engine.Result.freeze` method of any :class:`_engine.Result`
2126
+ object.
2127
+
2128
+ A new iterable :class:`_engine.Result` object is generated from a fixed
2129
+ set of data each time the :class:`_engine.FrozenResult` is invoked as
2130
+ a callable::
2131
+
2132
+
2133
+ result = connection.execute(query)
2134
+
2135
+ frozen = result.freeze()
2136
+
2137
+ unfrozen_result_one = frozen()
2138
+
2139
+ for row in unfrozen_result_one:
2140
+ print(row)
2141
+
2142
+ unfrozen_result_two = frozen()
2143
+ rows = unfrozen_result_two.all()
2144
+
2145
+ # ... etc
2146
+
2147
+ .. versionadded:: 1.4
2148
+
2149
+ .. seealso::
2150
+
2151
+ :ref:`do_orm_execute_re_executing` - example usage within the
2152
+ ORM to implement a result-set cache.
2153
+
2154
+ :func:`_orm.loading.merge_frozen_result` - ORM function to merge
2155
+ a frozen result back into a :class:`_orm.Session`.
2156
+
2157
+ """
2158
+
2159
+ data: Sequence[Any]
2160
+
2161
+ def __init__(self, result: Result[_TP]):
2162
+ self.metadata = result._metadata._for_freeze()
2163
+ self._source_supports_scalars = result._source_supports_scalars
2164
+ self._attributes = result._attributes
2165
+
2166
+ if self._source_supports_scalars:
2167
+ self.data = list(result._raw_row_iterator())
2168
+ else:
2169
+ self.data = result.fetchall()
2170
+
2171
+ def rewrite_rows(self) -> Sequence[Sequence[Any]]:
2172
+ if self._source_supports_scalars:
2173
+ return [[elem] for elem in self.data]
2174
+ else:
2175
+ return [list(row) for row in self.data]
2176
+
2177
+ def with_new_rows(
2178
+ self, tuple_data: Sequence[Row[_TP]]
2179
+ ) -> FrozenResult[_TP]:
2180
+ fr = FrozenResult.__new__(FrozenResult)
2181
+ fr.metadata = self.metadata
2182
+ fr._attributes = self._attributes
2183
+ fr._source_supports_scalars = self._source_supports_scalars
2184
+
2185
+ if self._source_supports_scalars:
2186
+ fr.data = [d[0] for d in tuple_data]
2187
+ else:
2188
+ fr.data = tuple_data
2189
+ return fr
2190
+
2191
+ def __call__(self) -> Result[_TP]:
2192
+ result: IteratorResult[_TP] = IteratorResult(
2193
+ self.metadata, iter(self.data)
2194
+ )
2195
+ result._attributes = self._attributes
2196
+ result._source_supports_scalars = self._source_supports_scalars
2197
+ return result
2198
+
2199
+
2200
+ class IteratorResult(Result[_TP]):
2201
+ """A :class:`_engine.Result` that gets data from a Python iterator of
2202
+ :class:`_engine.Row` objects or similar row-like data.
2203
+
2204
+ .. versionadded:: 1.4
2205
+
2206
+ """
2207
+
2208
+ _hard_closed = False
2209
+ _soft_closed = False
2210
+
2211
+ def __init__(
2212
+ self,
2213
+ cursor_metadata: ResultMetaData,
2214
+ iterator: Iterator[_InterimSupportsScalarsRowType],
2215
+ raw: Optional[Result[Any]] = None,
2216
+ _source_supports_scalars: bool = False,
2217
+ ):
2218
+ self._metadata = cursor_metadata
2219
+ self.iterator = iterator
2220
+ self.raw = raw
2221
+ self._source_supports_scalars = _source_supports_scalars
2222
+
2223
+ @property
2224
+ def closed(self) -> bool:
2225
+ """Return ``True`` if this :class:`_engine.IteratorResult` has
2226
+ been closed
2227
+
2228
+ .. versionadded:: 1.4.43
2229
+
2230
+ """
2231
+ return self._hard_closed
2232
+
2233
+ def _soft_close(self, hard: bool = False, **kw: Any) -> None:
2234
+ if hard:
2235
+ self._hard_closed = True
2236
+ if self.raw is not None:
2237
+ self.raw._soft_close(hard=hard, **kw)
2238
+ self.iterator = iter([])
2239
+ self._reset_memoizations()
2240
+ self._soft_closed = True
2241
+
2242
+ def _raise_hard_closed(self) -> NoReturn:
2243
+ raise exc.ResourceClosedError("This result object is closed.")
2244
+
2245
+ def _raw_row_iterator(self) -> Iterator[_RowData]:
2246
+ return self.iterator
2247
+
2248
+ def _fetchiter_impl(self) -> Iterator[_InterimSupportsScalarsRowType]:
2249
+ if self._hard_closed:
2250
+ self._raise_hard_closed()
2251
+ return self.iterator
2252
+
2253
+ def _fetchone_impl(
2254
+ self, hard_close: bool = False
2255
+ ) -> Optional[_InterimRowType[Row[Any]]]:
2256
+ if self._hard_closed:
2257
+ self._raise_hard_closed()
2258
+
2259
+ row = next(self.iterator, _NO_ROW)
2260
+ if row is _NO_ROW:
2261
+ self._soft_close(hard=hard_close)
2262
+ return None
2263
+ else:
2264
+ return row
2265
+
2266
+ def _fetchall_impl(self) -> List[_InterimRowType[Row[Any]]]:
2267
+ if self._hard_closed:
2268
+ self._raise_hard_closed()
2269
+ try:
2270
+ return list(self.iterator)
2271
+ finally:
2272
+ self._soft_close()
2273
+
2274
+ def _fetchmany_impl(
2275
+ self, size: Optional[int] = None
2276
+ ) -> List[_InterimRowType[Row[Any]]]:
2277
+ if self._hard_closed:
2278
+ self._raise_hard_closed()
2279
+
2280
+ return list(itertools.islice(self.iterator, 0, size))
2281
+
2282
+
2283
+ def null_result() -> IteratorResult[Any]:
2284
+ return IteratorResult(SimpleResultMetaData([]), iter([]))
2285
+
2286
+
2287
+ class ChunkedIteratorResult(IteratorResult[_TP]):
2288
+ """An :class:`_engine.IteratorResult` that works from an
2289
+ iterator-producing callable.
2290
+
2291
+ The given ``chunks`` argument is a function that is given a number of rows
2292
+ to return in each chunk, or ``None`` for all rows. The function should
2293
+ then return an un-consumed iterator of lists, each list of the requested
2294
+ size.
2295
+
2296
+ The function can be called at any time again, in which case it should
2297
+ continue from the same result set but adjust the chunk size as given.
2298
+
2299
+ .. versionadded:: 1.4
2300
+
2301
+ """
2302
+
2303
+ def __init__(
2304
+ self,
2305
+ cursor_metadata: ResultMetaData,
2306
+ chunks: Callable[
2307
+ [Optional[int]], Iterator[Sequence[_InterimRowType[_R]]]
2308
+ ],
2309
+ source_supports_scalars: bool = False,
2310
+ raw: Optional[Result[Any]] = None,
2311
+ dynamic_yield_per: bool = False,
2312
+ ):
2313
+ self._metadata = cursor_metadata
2314
+ self.chunks = chunks
2315
+ self._source_supports_scalars = source_supports_scalars
2316
+ self.raw = raw
2317
+ self.iterator = itertools.chain.from_iterable(self.chunks(None))
2318
+ self.dynamic_yield_per = dynamic_yield_per
2319
+
2320
+ @_generative
2321
+ def yield_per(self, num: int) -> Self:
2322
+ # TODO: this throws away the iterator which may be holding
2323
+ # onto a chunk. the yield_per cannot be changed once any
2324
+ # rows have been fetched. either find a way to enforce this,
2325
+ # or we can't use itertools.chain and will instead have to
2326
+ # keep track.
2327
+
2328
+ self._yield_per = num
2329
+ self.iterator = itertools.chain.from_iterable(self.chunks(num))
2330
+ return self
2331
+
2332
+ def _soft_close(self, hard: bool = False, **kw: Any) -> None:
2333
+ super()._soft_close(hard=hard, **kw)
2334
+ self.chunks = lambda size: [] # type: ignore
2335
+
2336
+ def _fetchmany_impl(
2337
+ self, size: Optional[int] = None
2338
+ ) -> List[_InterimRowType[Row[Any]]]:
2339
+ if self.dynamic_yield_per:
2340
+ self.iterator = itertools.chain.from_iterable(self.chunks(size))
2341
+ return super()._fetchmany_impl(size=size)
2342
+
2343
+
2344
+ class MergedResult(IteratorResult[_TP]):
2345
+ """A :class:`_engine.Result` that is merged from any number of
2346
+ :class:`_engine.Result` objects.
2347
+
2348
+ Returned by the :meth:`_engine.Result.merge` method.
2349
+
2350
+ .. versionadded:: 1.4
2351
+
2352
+ """
2353
+
2354
+ closed = False
2355
+ rowcount: Optional[int]
2356
+
2357
+ def __init__(
2358
+ self, cursor_metadata: ResultMetaData, results: Sequence[Result[_TP]]
2359
+ ):
2360
+ self._results = results
2361
+ super().__init__(
2362
+ cursor_metadata,
2363
+ itertools.chain.from_iterable(
2364
+ r._raw_row_iterator() for r in results
2365
+ ),
2366
+ )
2367
+
2368
+ self._unique_filter_state = results[0]._unique_filter_state
2369
+ self._yield_per = results[0]._yield_per
2370
+
2371
+ # going to try something w/ this in next rev
2372
+ self._source_supports_scalars = results[0]._source_supports_scalars
2373
+
2374
+ self._attributes = self._attributes.merge_with(
2375
+ *[r._attributes for r in results]
2376
+ )
2377
+
2378
+ def _soft_close(self, hard: bool = False, **kw: Any) -> None:
2379
+ for r in self._results:
2380
+ r._soft_close(hard=hard, **kw)
2381
+ if hard:
2382
+ self.closed = True