SQLAlchemy 2.0.36__cp313-cp313-win_amd64.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-win_amd64.pyd +0 -0
  13. sqlalchemy/cyextension/collections.pyx +409 -0
  14. sqlalchemy/cyextension/immutabledict.cp313-win_amd64.pyd +0 -0
  15. sqlalchemy/cyextension/immutabledict.pxd +8 -0
  16. sqlalchemy/cyextension/immutabledict.pyx +133 -0
  17. sqlalchemy/cyextension/processors.cp313-win_amd64.pyd +0 -0
  18. sqlalchemy/cyextension/processors.pyx +68 -0
  19. sqlalchemy/cyextension/resultproxy.cp313-win_amd64.pyd +0 -0
  20. sqlalchemy/cyextension/resultproxy.pyx +102 -0
  21. sqlalchemy/cyextension/util.cp313-win_amd64.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,2181 @@
1
+ # engine/cursor.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
+ # mypy: allow-untyped-defs, allow-untyped-calls
8
+
9
+ """Define cursor-specific result set constructs including
10
+ :class:`.CursorResult`."""
11
+
12
+
13
+ from __future__ import annotations
14
+
15
+ import collections
16
+ import functools
17
+ import operator
18
+ import typing
19
+ from typing import Any
20
+ from typing import cast
21
+ from typing import ClassVar
22
+ from typing import Dict
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 Sequence
29
+ from typing import Tuple
30
+ from typing import TYPE_CHECKING
31
+ from typing import TypeVar
32
+ from typing import Union
33
+
34
+ from .result import IteratorResult
35
+ from .result import MergedResult
36
+ from .result import Result
37
+ from .result import ResultMetaData
38
+ from .result import SimpleResultMetaData
39
+ from .result import tuplegetter
40
+ from .row import Row
41
+ from .. import exc
42
+ from .. import util
43
+ from ..sql import elements
44
+ from ..sql import sqltypes
45
+ from ..sql import util as sql_util
46
+ from ..sql.base import _generative
47
+ from ..sql.compiler import ResultColumnsEntry
48
+ from ..sql.compiler import RM_NAME
49
+ from ..sql.compiler import RM_OBJECTS
50
+ from ..sql.compiler import RM_RENDERED_NAME
51
+ from ..sql.compiler import RM_TYPE
52
+ from ..sql.type_api import TypeEngine
53
+ from ..util import compat
54
+ from ..util.typing import Literal
55
+ from ..util.typing import Self
56
+
57
+
58
+ if typing.TYPE_CHECKING:
59
+ from .base import Connection
60
+ from .default import DefaultExecutionContext
61
+ from .interfaces import _DBAPICursorDescription
62
+ from .interfaces import DBAPICursor
63
+ from .interfaces import Dialect
64
+ from .interfaces import ExecutionContext
65
+ from .result import _KeyIndexType
66
+ from .result import _KeyMapRecType
67
+ from .result import _KeyMapType
68
+ from .result import _KeyType
69
+ from .result import _ProcessorsType
70
+ from .result import _TupleGetterType
71
+ from ..sql.type_api import _ResultProcessorType
72
+
73
+
74
+ _T = TypeVar("_T", bound=Any)
75
+
76
+
77
+ # metadata entry tuple indexes.
78
+ # using raw tuple is faster than namedtuple.
79
+ # these match up to the positions in
80
+ # _CursorKeyMapRecType
81
+ MD_INDEX: Literal[0] = 0
82
+ """integer index in cursor.description
83
+
84
+ """
85
+
86
+ MD_RESULT_MAP_INDEX: Literal[1] = 1
87
+ """integer index in compiled._result_columns"""
88
+
89
+ MD_OBJECTS: Literal[2] = 2
90
+ """other string keys and ColumnElement obj that can match.
91
+
92
+ This comes from compiler.RM_OBJECTS / compiler.ResultColumnsEntry.objects
93
+
94
+ """
95
+
96
+ MD_LOOKUP_KEY: Literal[3] = 3
97
+ """string key we usually expect for key-based lookup
98
+
99
+ this comes from compiler.RM_NAME / compiler.ResultColumnsEntry.name
100
+ """
101
+
102
+
103
+ MD_RENDERED_NAME: Literal[4] = 4
104
+ """name that is usually in cursor.description
105
+
106
+ this comes from compiler.RENDERED_NAME / compiler.ResultColumnsEntry.keyname
107
+ """
108
+
109
+
110
+ MD_PROCESSOR: Literal[5] = 5
111
+ """callable to process a result value into a row"""
112
+
113
+ MD_UNTRANSLATED: Literal[6] = 6
114
+ """raw name from cursor.description"""
115
+
116
+
117
+ _CursorKeyMapRecType = Tuple[
118
+ Optional[int], # MD_INDEX, None means the record is ambiguously named
119
+ int, # MD_RESULT_MAP_INDEX
120
+ List[Any], # MD_OBJECTS
121
+ str, # MD_LOOKUP_KEY
122
+ str, # MD_RENDERED_NAME
123
+ Optional["_ResultProcessorType[Any]"], # MD_PROCESSOR
124
+ Optional[str], # MD_UNTRANSLATED
125
+ ]
126
+
127
+ _CursorKeyMapType = Mapping["_KeyType", _CursorKeyMapRecType]
128
+
129
+ # same as _CursorKeyMapRecType except the MD_INDEX value is definitely
130
+ # not None
131
+ _NonAmbigCursorKeyMapRecType = Tuple[
132
+ int,
133
+ int,
134
+ List[Any],
135
+ str,
136
+ str,
137
+ Optional["_ResultProcessorType[Any]"],
138
+ str,
139
+ ]
140
+
141
+
142
+ class CursorResultMetaData(ResultMetaData):
143
+ """Result metadata for DBAPI cursors."""
144
+
145
+ __slots__ = (
146
+ "_keymap",
147
+ "_processors",
148
+ "_keys",
149
+ "_keymap_by_result_column_idx",
150
+ "_tuplefilter",
151
+ "_translated_indexes",
152
+ "_safe_for_cache",
153
+ "_unpickled",
154
+ "_key_to_index",
155
+ # don't need _unique_filters support here for now. Can be added
156
+ # if a need arises.
157
+ )
158
+
159
+ _keymap: _CursorKeyMapType
160
+ _processors: _ProcessorsType
161
+ _keymap_by_result_column_idx: Optional[Dict[int, _KeyMapRecType]]
162
+ _unpickled: bool
163
+ _safe_for_cache: bool
164
+ _translated_indexes: Optional[List[int]]
165
+
166
+ returns_rows: ClassVar[bool] = True
167
+
168
+ def _has_key(self, key: Any) -> bool:
169
+ return key in self._keymap
170
+
171
+ def _for_freeze(self) -> ResultMetaData:
172
+ return SimpleResultMetaData(
173
+ self._keys,
174
+ extra=[self._keymap[key][MD_OBJECTS] for key in self._keys],
175
+ )
176
+
177
+ def _make_new_metadata(
178
+ self,
179
+ *,
180
+ unpickled: bool,
181
+ processors: _ProcessorsType,
182
+ keys: Sequence[str],
183
+ keymap: _KeyMapType,
184
+ tuplefilter: Optional[_TupleGetterType],
185
+ translated_indexes: Optional[List[int]],
186
+ safe_for_cache: bool,
187
+ keymap_by_result_column_idx: Any,
188
+ ) -> CursorResultMetaData:
189
+ new_obj = self.__class__.__new__(self.__class__)
190
+ new_obj._unpickled = unpickled
191
+ new_obj._processors = processors
192
+ new_obj._keys = keys
193
+ new_obj._keymap = keymap
194
+ new_obj._tuplefilter = tuplefilter
195
+ new_obj._translated_indexes = translated_indexes
196
+ new_obj._safe_for_cache = safe_for_cache
197
+ new_obj._keymap_by_result_column_idx = keymap_by_result_column_idx
198
+ new_obj._key_to_index = self._make_key_to_index(keymap, MD_INDEX)
199
+ return new_obj
200
+
201
+ def _remove_processors(self) -> CursorResultMetaData:
202
+ assert not self._tuplefilter
203
+ return self._make_new_metadata(
204
+ unpickled=self._unpickled,
205
+ processors=[None] * len(self._processors),
206
+ tuplefilter=None,
207
+ translated_indexes=None,
208
+ keymap={
209
+ key: value[0:5] + (None,) + value[6:]
210
+ for key, value in self._keymap.items()
211
+ },
212
+ keys=self._keys,
213
+ safe_for_cache=self._safe_for_cache,
214
+ keymap_by_result_column_idx=self._keymap_by_result_column_idx,
215
+ )
216
+
217
+ def _splice_horizontally(
218
+ self, other: CursorResultMetaData
219
+ ) -> CursorResultMetaData:
220
+ assert not self._tuplefilter
221
+
222
+ keymap = dict(self._keymap)
223
+ offset = len(self._keys)
224
+ keymap.update(
225
+ {
226
+ key: (
227
+ # int index should be None for ambiguous key
228
+ (
229
+ value[0] + offset
230
+ if value[0] is not None and key not in keymap
231
+ else None
232
+ ),
233
+ value[1] + offset,
234
+ *value[2:],
235
+ )
236
+ for key, value in other._keymap.items()
237
+ }
238
+ )
239
+ return self._make_new_metadata(
240
+ unpickled=self._unpickled,
241
+ processors=self._processors + other._processors, # type: ignore
242
+ tuplefilter=None,
243
+ translated_indexes=None,
244
+ keys=self._keys + other._keys, # type: ignore
245
+ keymap=keymap,
246
+ safe_for_cache=self._safe_for_cache,
247
+ keymap_by_result_column_idx={
248
+ metadata_entry[MD_RESULT_MAP_INDEX]: metadata_entry
249
+ for metadata_entry in keymap.values()
250
+ },
251
+ )
252
+
253
+ def _reduce(self, keys: Sequence[_KeyIndexType]) -> ResultMetaData:
254
+ recs = list(self._metadata_for_keys(keys))
255
+
256
+ indexes = [rec[MD_INDEX] for rec in recs]
257
+ new_keys: List[str] = [rec[MD_LOOKUP_KEY] for rec in recs]
258
+
259
+ if self._translated_indexes:
260
+ indexes = [self._translated_indexes[idx] for idx in indexes]
261
+ tup = tuplegetter(*indexes)
262
+ new_recs = [(index,) + rec[1:] for index, rec in enumerate(recs)]
263
+
264
+ keymap = {rec[MD_LOOKUP_KEY]: rec for rec in new_recs}
265
+ # TODO: need unit test for:
266
+ # result = connection.execute("raw sql, no columns").scalars()
267
+ # without the "or ()" it's failing because MD_OBJECTS is None
268
+ keymap.update(
269
+ (e, new_rec)
270
+ for new_rec in new_recs
271
+ for e in new_rec[MD_OBJECTS] or ()
272
+ )
273
+
274
+ return self._make_new_metadata(
275
+ unpickled=self._unpickled,
276
+ processors=self._processors,
277
+ keys=new_keys,
278
+ tuplefilter=tup,
279
+ translated_indexes=indexes,
280
+ keymap=keymap, # type: ignore[arg-type]
281
+ safe_for_cache=self._safe_for_cache,
282
+ keymap_by_result_column_idx=self._keymap_by_result_column_idx,
283
+ )
284
+
285
+ def _adapt_to_context(self, context: ExecutionContext) -> ResultMetaData:
286
+ """When using a cached Compiled construct that has a _result_map,
287
+ for a new statement that used the cached Compiled, we need to ensure
288
+ the keymap has the Column objects from our new statement as keys.
289
+ So here we rewrite keymap with new entries for the new columns
290
+ as matched to those of the cached statement.
291
+
292
+ """
293
+
294
+ if not context.compiled or not context.compiled._result_columns:
295
+ return self
296
+
297
+ compiled_statement = context.compiled.statement
298
+ invoked_statement = context.invoked_statement
299
+
300
+ if TYPE_CHECKING:
301
+ assert isinstance(invoked_statement, elements.ClauseElement)
302
+
303
+ if compiled_statement is invoked_statement:
304
+ return self
305
+
306
+ assert invoked_statement is not None
307
+
308
+ # this is the most common path for Core statements when
309
+ # caching is used. In ORM use, this codepath is not really used
310
+ # as the _result_disable_adapt_to_context execution option is
311
+ # set by the ORM.
312
+
313
+ # make a copy and add the columns from the invoked statement
314
+ # to the result map.
315
+
316
+ keymap_by_position = self._keymap_by_result_column_idx
317
+
318
+ if keymap_by_position is None:
319
+ # first retrival from cache, this map will not be set up yet,
320
+ # initialize lazily
321
+ keymap_by_position = self._keymap_by_result_column_idx = {
322
+ metadata_entry[MD_RESULT_MAP_INDEX]: metadata_entry
323
+ for metadata_entry in self._keymap.values()
324
+ }
325
+
326
+ assert not self._tuplefilter
327
+ return self._make_new_metadata(
328
+ keymap=compat.dict_union(
329
+ self._keymap,
330
+ {
331
+ new: keymap_by_position[idx]
332
+ for idx, new in enumerate(
333
+ invoked_statement._all_selected_columns
334
+ )
335
+ if idx in keymap_by_position
336
+ },
337
+ ),
338
+ unpickled=self._unpickled,
339
+ processors=self._processors,
340
+ tuplefilter=None,
341
+ translated_indexes=None,
342
+ keys=self._keys,
343
+ safe_for_cache=self._safe_for_cache,
344
+ keymap_by_result_column_idx=self._keymap_by_result_column_idx,
345
+ )
346
+
347
+ def __init__(
348
+ self,
349
+ parent: CursorResult[Any],
350
+ cursor_description: _DBAPICursorDescription,
351
+ ):
352
+ context = parent.context
353
+ self._tuplefilter = None
354
+ self._translated_indexes = None
355
+ self._safe_for_cache = self._unpickled = False
356
+
357
+ if context.result_column_struct:
358
+ (
359
+ result_columns,
360
+ cols_are_ordered,
361
+ textual_ordered,
362
+ ad_hoc_textual,
363
+ loose_column_name_matching,
364
+ ) = context.result_column_struct
365
+ num_ctx_cols = len(result_columns)
366
+ else:
367
+ result_columns = cols_are_ordered = ( # type: ignore
368
+ num_ctx_cols
369
+ ) = ad_hoc_textual = loose_column_name_matching = (
370
+ textual_ordered
371
+ ) = False
372
+
373
+ # merge cursor.description with the column info
374
+ # present in the compiled structure, if any
375
+ raw = self._merge_cursor_description(
376
+ context,
377
+ cursor_description,
378
+ result_columns,
379
+ num_ctx_cols,
380
+ cols_are_ordered,
381
+ textual_ordered,
382
+ ad_hoc_textual,
383
+ loose_column_name_matching,
384
+ )
385
+
386
+ # processors in key order which are used when building up
387
+ # a row
388
+ self._processors = [
389
+ metadata_entry[MD_PROCESSOR] for metadata_entry in raw
390
+ ]
391
+
392
+ # this is used when using this ResultMetaData in a Core-only cache
393
+ # retrieval context. it's initialized on first cache retrieval
394
+ # when the _result_disable_adapt_to_context execution option
395
+ # (which the ORM generally sets) is not set.
396
+ self._keymap_by_result_column_idx = None
397
+
398
+ # for compiled SQL constructs, copy additional lookup keys into
399
+ # the key lookup map, such as Column objects, labels,
400
+ # column keys and other names
401
+ if num_ctx_cols:
402
+ # keymap by primary string...
403
+ by_key = {
404
+ metadata_entry[MD_LOOKUP_KEY]: metadata_entry
405
+ for metadata_entry in raw
406
+ }
407
+
408
+ if len(by_key) != num_ctx_cols:
409
+ # if by-primary-string dictionary smaller than
410
+ # number of columns, assume we have dupes; (this check
411
+ # is also in place if string dictionary is bigger, as
412
+ # can occur when '*' was used as one of the compiled columns,
413
+ # which may or may not be suggestive of dupes), rewrite
414
+ # dupe records with "None" for index which results in
415
+ # ambiguous column exception when accessed.
416
+ #
417
+ # this is considered to be the less common case as it is not
418
+ # common to have dupe column keys in a SELECT statement.
419
+ #
420
+ # new in 1.4: get the complete set of all possible keys,
421
+ # strings, objects, whatever, that are dupes across two
422
+ # different records, first.
423
+ index_by_key: Dict[Any, Any] = {}
424
+ dupes = set()
425
+ for metadata_entry in raw:
426
+ for key in (metadata_entry[MD_RENDERED_NAME],) + (
427
+ metadata_entry[MD_OBJECTS] or ()
428
+ ):
429
+ idx = metadata_entry[MD_INDEX]
430
+ # if this key has been associated with more than one
431
+ # positional index, it's a dupe
432
+ if index_by_key.setdefault(key, idx) != idx:
433
+ dupes.add(key)
434
+
435
+ # then put everything we have into the keymap excluding only
436
+ # those keys that are dupes.
437
+ self._keymap = {
438
+ obj_elem: metadata_entry
439
+ for metadata_entry in raw
440
+ if metadata_entry[MD_OBJECTS]
441
+ for obj_elem in metadata_entry[MD_OBJECTS]
442
+ if obj_elem not in dupes
443
+ }
444
+
445
+ # then for the dupe keys, put the "ambiguous column"
446
+ # record into by_key.
447
+ by_key.update(
448
+ {
449
+ key: (None, None, [], key, key, None, None)
450
+ for key in dupes
451
+ }
452
+ )
453
+
454
+ else:
455
+ # no dupes - copy secondary elements from compiled
456
+ # columns into self._keymap. this is the most common
457
+ # codepath for Core / ORM statement executions before the
458
+ # result metadata is cached
459
+ self._keymap = {
460
+ obj_elem: metadata_entry
461
+ for metadata_entry in raw
462
+ if metadata_entry[MD_OBJECTS]
463
+ for obj_elem in metadata_entry[MD_OBJECTS]
464
+ }
465
+ # update keymap with primary string names taking
466
+ # precedence
467
+ self._keymap.update(by_key)
468
+ else:
469
+ # no compiled objects to map, just create keymap by primary string
470
+ self._keymap = {
471
+ metadata_entry[MD_LOOKUP_KEY]: metadata_entry
472
+ for metadata_entry in raw
473
+ }
474
+
475
+ # update keymap with "translated" names. In SQLAlchemy this is a
476
+ # sqlite only thing, and in fact impacting only extremely old SQLite
477
+ # versions unlikely to be present in modern Python versions.
478
+ # however, the pyhive third party dialect is
479
+ # also using this hook, which means others still might use it as well.
480
+ # I dislike having this awkward hook here but as long as we need
481
+ # to use names in cursor.description in some cases we need to have
482
+ # some hook to accomplish this.
483
+ if not num_ctx_cols and context._translate_colname:
484
+ self._keymap.update(
485
+ {
486
+ metadata_entry[MD_UNTRANSLATED]: self._keymap[
487
+ metadata_entry[MD_LOOKUP_KEY]
488
+ ]
489
+ for metadata_entry in raw
490
+ if metadata_entry[MD_UNTRANSLATED]
491
+ }
492
+ )
493
+
494
+ self._key_to_index = self._make_key_to_index(self._keymap, MD_INDEX)
495
+
496
+ def _merge_cursor_description(
497
+ self,
498
+ context,
499
+ cursor_description,
500
+ result_columns,
501
+ num_ctx_cols,
502
+ cols_are_ordered,
503
+ textual_ordered,
504
+ ad_hoc_textual,
505
+ loose_column_name_matching,
506
+ ):
507
+ """Merge a cursor.description with compiled result column information.
508
+
509
+ There are at least four separate strategies used here, selected
510
+ depending on the type of SQL construct used to start with.
511
+
512
+ The most common case is that of the compiled SQL expression construct,
513
+ which generated the column names present in the raw SQL string and
514
+ which has the identical number of columns as were reported by
515
+ cursor.description. In this case, we assume a 1-1 positional mapping
516
+ between the entries in cursor.description and the compiled object.
517
+ This is also the most performant case as we disregard extracting /
518
+ decoding the column names present in cursor.description since we
519
+ already have the desired name we generated in the compiled SQL
520
+ construct.
521
+
522
+ The next common case is that of the completely raw string SQL,
523
+ such as passed to connection.execute(). In this case we have no
524
+ compiled construct to work with, so we extract and decode the
525
+ names from cursor.description and index those as the primary
526
+ result row target keys.
527
+
528
+ The remaining fairly common case is that of the textual SQL
529
+ that includes at least partial column information; this is when
530
+ we use a :class:`_expression.TextualSelect` construct.
531
+ This construct may have
532
+ unordered or ordered column information. In the ordered case, we
533
+ merge the cursor.description and the compiled construct's information
534
+ positionally, and warn if there are additional description names
535
+ present, however we still decode the names in cursor.description
536
+ as we don't have a guarantee that the names in the columns match
537
+ on these. In the unordered case, we match names in cursor.description
538
+ to that of the compiled construct based on name matching.
539
+ In both of these cases, the cursor.description names and the column
540
+ expression objects and names are indexed as result row target keys.
541
+
542
+ The final case is much less common, where we have a compiled
543
+ non-textual SQL expression construct, but the number of columns
544
+ in cursor.description doesn't match what's in the compiled
545
+ construct. We make the guess here that there might be textual
546
+ column expressions in the compiled construct that themselves include
547
+ a comma in them causing them to split. We do the same name-matching
548
+ as with textual non-ordered columns.
549
+
550
+ The name-matched system of merging is the same as that used by
551
+ SQLAlchemy for all cases up through the 0.9 series. Positional
552
+ matching for compiled SQL expressions was introduced in 1.0 as a
553
+ major performance feature, and positional matching for textual
554
+ :class:`_expression.TextualSelect` objects in 1.1.
555
+ As name matching is no longer
556
+ a common case, it was acceptable to factor it into smaller generator-
557
+ oriented methods that are easier to understand, but incur slightly
558
+ more performance overhead.
559
+
560
+ """
561
+
562
+ if (
563
+ num_ctx_cols
564
+ and cols_are_ordered
565
+ and not textual_ordered
566
+ and num_ctx_cols == len(cursor_description)
567
+ ):
568
+ self._keys = [elem[0] for elem in result_columns]
569
+ # pure positional 1-1 case; doesn't need to read
570
+ # the names from cursor.description
571
+
572
+ # most common case for Core and ORM
573
+
574
+ # this metadata is safe to cache because we are guaranteed
575
+ # to have the columns in the same order for new executions
576
+ self._safe_for_cache = True
577
+ return [
578
+ (
579
+ idx,
580
+ idx,
581
+ rmap_entry[RM_OBJECTS],
582
+ rmap_entry[RM_NAME],
583
+ rmap_entry[RM_RENDERED_NAME],
584
+ context.get_result_processor(
585
+ rmap_entry[RM_TYPE],
586
+ rmap_entry[RM_RENDERED_NAME],
587
+ cursor_description[idx][1],
588
+ ),
589
+ None,
590
+ )
591
+ for idx, rmap_entry in enumerate(result_columns)
592
+ ]
593
+ else:
594
+ # name-based or text-positional cases, where we need
595
+ # to read cursor.description names
596
+
597
+ if textual_ordered or (
598
+ ad_hoc_textual and len(cursor_description) == num_ctx_cols
599
+ ):
600
+ self._safe_for_cache = True
601
+ # textual positional case
602
+ raw_iterator = self._merge_textual_cols_by_position(
603
+ context, cursor_description, result_columns
604
+ )
605
+ elif num_ctx_cols:
606
+ # compiled SQL with a mismatch of description cols
607
+ # vs. compiled cols, or textual w/ unordered columns
608
+ # the order of columns can change if the query is
609
+ # against a "select *", so not safe to cache
610
+ self._safe_for_cache = False
611
+ raw_iterator = self._merge_cols_by_name(
612
+ context,
613
+ cursor_description,
614
+ result_columns,
615
+ loose_column_name_matching,
616
+ )
617
+ else:
618
+ # no compiled SQL, just a raw string, order of columns
619
+ # can change for "select *"
620
+ self._safe_for_cache = False
621
+ raw_iterator = self._merge_cols_by_none(
622
+ context, cursor_description
623
+ )
624
+
625
+ return [
626
+ (
627
+ idx,
628
+ ridx,
629
+ obj,
630
+ cursor_colname,
631
+ cursor_colname,
632
+ context.get_result_processor(
633
+ mapped_type, cursor_colname, coltype
634
+ ),
635
+ untranslated,
636
+ )
637
+ for (
638
+ idx,
639
+ ridx,
640
+ cursor_colname,
641
+ mapped_type,
642
+ coltype,
643
+ obj,
644
+ untranslated,
645
+ ) in raw_iterator
646
+ ]
647
+
648
+ def _colnames_from_description(self, context, cursor_description):
649
+ """Extract column names and data types from a cursor.description.
650
+
651
+ Applies unicode decoding, column translation, "normalization",
652
+ and case sensitivity rules to the names based on the dialect.
653
+
654
+ """
655
+
656
+ dialect = context.dialect
657
+ translate_colname = context._translate_colname
658
+ normalize_name = (
659
+ dialect.normalize_name if dialect.requires_name_normalize else None
660
+ )
661
+ untranslated = None
662
+
663
+ self._keys = []
664
+
665
+ for idx, rec in enumerate(cursor_description):
666
+ colname = rec[0]
667
+ coltype = rec[1]
668
+
669
+ if translate_colname:
670
+ colname, untranslated = translate_colname(colname)
671
+
672
+ if normalize_name:
673
+ colname = normalize_name(colname)
674
+
675
+ self._keys.append(colname)
676
+
677
+ yield idx, colname, untranslated, coltype
678
+
679
+ def _merge_textual_cols_by_position(
680
+ self, context, cursor_description, result_columns
681
+ ):
682
+ num_ctx_cols = len(result_columns)
683
+
684
+ if num_ctx_cols > len(cursor_description):
685
+ util.warn(
686
+ "Number of columns in textual SQL (%d) is "
687
+ "smaller than number of columns requested (%d)"
688
+ % (num_ctx_cols, len(cursor_description))
689
+ )
690
+ seen = set()
691
+
692
+ for (
693
+ idx,
694
+ colname,
695
+ untranslated,
696
+ coltype,
697
+ ) in self._colnames_from_description(context, cursor_description):
698
+ if idx < num_ctx_cols:
699
+ ctx_rec = result_columns[idx]
700
+ obj = ctx_rec[RM_OBJECTS]
701
+ ridx = idx
702
+ mapped_type = ctx_rec[RM_TYPE]
703
+ if obj[0] in seen:
704
+ raise exc.InvalidRequestError(
705
+ "Duplicate column expression requested "
706
+ "in textual SQL: %r" % obj[0]
707
+ )
708
+ seen.add(obj[0])
709
+ else:
710
+ mapped_type = sqltypes.NULLTYPE
711
+ obj = None
712
+ ridx = None
713
+ yield idx, ridx, colname, mapped_type, coltype, obj, untranslated
714
+
715
+ def _merge_cols_by_name(
716
+ self,
717
+ context,
718
+ cursor_description,
719
+ result_columns,
720
+ loose_column_name_matching,
721
+ ):
722
+ match_map = self._create_description_match_map(
723
+ result_columns, loose_column_name_matching
724
+ )
725
+ mapped_type: TypeEngine[Any]
726
+
727
+ for (
728
+ idx,
729
+ colname,
730
+ untranslated,
731
+ coltype,
732
+ ) in self._colnames_from_description(context, cursor_description):
733
+ try:
734
+ ctx_rec = match_map[colname]
735
+ except KeyError:
736
+ mapped_type = sqltypes.NULLTYPE
737
+ obj = None
738
+ result_columns_idx = None
739
+ else:
740
+ obj = ctx_rec[1]
741
+ mapped_type = ctx_rec[2]
742
+ result_columns_idx = ctx_rec[3]
743
+ yield (
744
+ idx,
745
+ result_columns_idx,
746
+ colname,
747
+ mapped_type,
748
+ coltype,
749
+ obj,
750
+ untranslated,
751
+ )
752
+
753
+ @classmethod
754
+ def _create_description_match_map(
755
+ cls,
756
+ result_columns: List[ResultColumnsEntry],
757
+ loose_column_name_matching: bool = False,
758
+ ) -> Dict[
759
+ Union[str, object], Tuple[str, Tuple[Any, ...], TypeEngine[Any], int]
760
+ ]:
761
+ """when matching cursor.description to a set of names that are present
762
+ in a Compiled object, as is the case with TextualSelect, get all the
763
+ names we expect might match those in cursor.description.
764
+ """
765
+
766
+ d: Dict[
767
+ Union[str, object],
768
+ Tuple[str, Tuple[Any, ...], TypeEngine[Any], int],
769
+ ] = {}
770
+ for ridx, elem in enumerate(result_columns):
771
+ key = elem[RM_RENDERED_NAME]
772
+ if key in d:
773
+ # conflicting keyname - just add the column-linked objects
774
+ # to the existing record. if there is a duplicate column
775
+ # name in the cursor description, this will allow all of those
776
+ # objects to raise an ambiguous column error
777
+ e_name, e_obj, e_type, e_ridx = d[key]
778
+ d[key] = e_name, e_obj + elem[RM_OBJECTS], e_type, ridx
779
+ else:
780
+ d[key] = (elem[RM_NAME], elem[RM_OBJECTS], elem[RM_TYPE], ridx)
781
+
782
+ if loose_column_name_matching:
783
+ # when using a textual statement with an unordered set
784
+ # of columns that line up, we are expecting the user
785
+ # to be using label names in the SQL that match to the column
786
+ # expressions. Enable more liberal matching for this case;
787
+ # duplicate keys that are ambiguous will be fixed later.
788
+ for r_key in elem[RM_OBJECTS]:
789
+ d.setdefault(
790
+ r_key,
791
+ (elem[RM_NAME], elem[RM_OBJECTS], elem[RM_TYPE], ridx),
792
+ )
793
+ return d
794
+
795
+ def _merge_cols_by_none(self, context, cursor_description):
796
+ for (
797
+ idx,
798
+ colname,
799
+ untranslated,
800
+ coltype,
801
+ ) in self._colnames_from_description(context, cursor_description):
802
+ yield (
803
+ idx,
804
+ None,
805
+ colname,
806
+ sqltypes.NULLTYPE,
807
+ coltype,
808
+ None,
809
+ untranslated,
810
+ )
811
+
812
+ if not TYPE_CHECKING:
813
+
814
+ def _key_fallback(
815
+ self, key: Any, err: Optional[Exception], raiseerr: bool = True
816
+ ) -> Optional[NoReturn]:
817
+ if raiseerr:
818
+ if self._unpickled and isinstance(key, elements.ColumnElement):
819
+ raise exc.NoSuchColumnError(
820
+ "Row was unpickled; lookup by ColumnElement "
821
+ "is unsupported"
822
+ ) from err
823
+ else:
824
+ raise exc.NoSuchColumnError(
825
+ "Could not locate column in row for column '%s'"
826
+ % util.string_or_unprintable(key)
827
+ ) from err
828
+ else:
829
+ return None
830
+
831
+ def _raise_for_ambiguous_column_name(self, rec):
832
+ raise exc.InvalidRequestError(
833
+ "Ambiguous column name '%s' in "
834
+ "result set column descriptions" % rec[MD_LOOKUP_KEY]
835
+ )
836
+
837
+ def _index_for_key(self, key: Any, raiseerr: bool = True) -> Optional[int]:
838
+ # TODO: can consider pre-loading ints and negative ints
839
+ # into _keymap - also no coverage here
840
+ if isinstance(key, int):
841
+ key = self._keys[key]
842
+
843
+ try:
844
+ rec = self._keymap[key]
845
+ except KeyError as ke:
846
+ x = self._key_fallback(key, ke, raiseerr)
847
+ assert x is None
848
+ return None
849
+
850
+ index = rec[0]
851
+
852
+ if index is None:
853
+ self._raise_for_ambiguous_column_name(rec)
854
+ return index
855
+
856
+ def _indexes_for_keys(self, keys):
857
+ try:
858
+ return [self._keymap[key][0] for key in keys]
859
+ except KeyError as ke:
860
+ # ensure it raises
861
+ CursorResultMetaData._key_fallback(self, ke.args[0], ke)
862
+
863
+ def _metadata_for_keys(
864
+ self, keys: Sequence[Any]
865
+ ) -> Iterator[_NonAmbigCursorKeyMapRecType]:
866
+ for key in keys:
867
+ if int in key.__class__.__mro__:
868
+ key = self._keys[key]
869
+
870
+ try:
871
+ rec = self._keymap[key]
872
+ except KeyError as ke:
873
+ # ensure it raises
874
+ CursorResultMetaData._key_fallback(self, ke.args[0], ke)
875
+
876
+ index = rec[MD_INDEX]
877
+
878
+ if index is None:
879
+ self._raise_for_ambiguous_column_name(rec)
880
+
881
+ yield cast(_NonAmbigCursorKeyMapRecType, rec)
882
+
883
+ def __getstate__(self):
884
+ # TODO: consider serializing this as SimpleResultMetaData
885
+ return {
886
+ "_keymap": {
887
+ key: (
888
+ rec[MD_INDEX],
889
+ rec[MD_RESULT_MAP_INDEX],
890
+ [],
891
+ key,
892
+ rec[MD_RENDERED_NAME],
893
+ None,
894
+ None,
895
+ )
896
+ for key, rec in self._keymap.items()
897
+ if isinstance(key, (str, int))
898
+ },
899
+ "_keys": self._keys,
900
+ "_translated_indexes": self._translated_indexes,
901
+ }
902
+
903
+ def __setstate__(self, state):
904
+ self._processors = [None for _ in range(len(state["_keys"]))]
905
+ self._keymap = state["_keymap"]
906
+ self._keymap_by_result_column_idx = None
907
+ self._key_to_index = self._make_key_to_index(self._keymap, MD_INDEX)
908
+ self._keys = state["_keys"]
909
+ self._unpickled = True
910
+ if state["_translated_indexes"]:
911
+ self._translated_indexes = cast(
912
+ "List[int]", state["_translated_indexes"]
913
+ )
914
+ self._tuplefilter = tuplegetter(*self._translated_indexes)
915
+ else:
916
+ self._translated_indexes = self._tuplefilter = None
917
+
918
+
919
+ class ResultFetchStrategy:
920
+ """Define a fetching strategy for a result object.
921
+
922
+
923
+ .. versionadded:: 1.4
924
+
925
+ """
926
+
927
+ __slots__ = ()
928
+
929
+ alternate_cursor_description: Optional[_DBAPICursorDescription] = None
930
+
931
+ def soft_close(
932
+ self, result: CursorResult[Any], dbapi_cursor: Optional[DBAPICursor]
933
+ ) -> None:
934
+ raise NotImplementedError()
935
+
936
+ def hard_close(
937
+ self, result: CursorResult[Any], dbapi_cursor: Optional[DBAPICursor]
938
+ ) -> None:
939
+ raise NotImplementedError()
940
+
941
+ def yield_per(
942
+ self,
943
+ result: CursorResult[Any],
944
+ dbapi_cursor: Optional[DBAPICursor],
945
+ num: int,
946
+ ) -> None:
947
+ return
948
+
949
+ def fetchone(
950
+ self,
951
+ result: CursorResult[Any],
952
+ dbapi_cursor: DBAPICursor,
953
+ hard_close: bool = False,
954
+ ) -> Any:
955
+ raise NotImplementedError()
956
+
957
+ def fetchmany(
958
+ self,
959
+ result: CursorResult[Any],
960
+ dbapi_cursor: DBAPICursor,
961
+ size: Optional[int] = None,
962
+ ) -> Any:
963
+ raise NotImplementedError()
964
+
965
+ def fetchall(
966
+ self,
967
+ result: CursorResult[Any],
968
+ dbapi_cursor: DBAPICursor,
969
+ ) -> Any:
970
+ raise NotImplementedError()
971
+
972
+ def handle_exception(
973
+ self,
974
+ result: CursorResult[Any],
975
+ dbapi_cursor: Optional[DBAPICursor],
976
+ err: BaseException,
977
+ ) -> NoReturn:
978
+ raise err
979
+
980
+
981
+ class NoCursorFetchStrategy(ResultFetchStrategy):
982
+ """Cursor strategy for a result that has no open cursor.
983
+
984
+ There are two varieties of this strategy, one for DQL and one for
985
+ DML (and also DDL), each of which represent a result that had a cursor
986
+ but no longer has one.
987
+
988
+ """
989
+
990
+ __slots__ = ()
991
+
992
+ def soft_close(self, result, dbapi_cursor):
993
+ pass
994
+
995
+ def hard_close(self, result, dbapi_cursor):
996
+ pass
997
+
998
+ def fetchone(self, result, dbapi_cursor, hard_close=False):
999
+ return self._non_result(result, None)
1000
+
1001
+ def fetchmany(self, result, dbapi_cursor, size=None):
1002
+ return self._non_result(result, [])
1003
+
1004
+ def fetchall(self, result, dbapi_cursor):
1005
+ return self._non_result(result, [])
1006
+
1007
+ def _non_result(self, result, default, err=None):
1008
+ raise NotImplementedError()
1009
+
1010
+
1011
+ class NoCursorDQLFetchStrategy(NoCursorFetchStrategy):
1012
+ """Cursor strategy for a DQL result that has no open cursor.
1013
+
1014
+ This is a result set that can return rows, i.e. for a SELECT, or for an
1015
+ INSERT, UPDATE, DELETE that includes RETURNING. However it is in the state
1016
+ where the cursor is closed and no rows remain available. The owning result
1017
+ object may or may not be "hard closed", which determines if the fetch
1018
+ methods send empty results or raise for closed result.
1019
+
1020
+ """
1021
+
1022
+ __slots__ = ()
1023
+
1024
+ def _non_result(self, result, default, err=None):
1025
+ if result.closed:
1026
+ raise exc.ResourceClosedError(
1027
+ "This result object is closed."
1028
+ ) from err
1029
+ else:
1030
+ return default
1031
+
1032
+
1033
+ _NO_CURSOR_DQL = NoCursorDQLFetchStrategy()
1034
+
1035
+
1036
+ class NoCursorDMLFetchStrategy(NoCursorFetchStrategy):
1037
+ """Cursor strategy for a DML result that has no open cursor.
1038
+
1039
+ This is a result set that does not return rows, i.e. for an INSERT,
1040
+ UPDATE, DELETE that does not include RETURNING.
1041
+
1042
+ """
1043
+
1044
+ __slots__ = ()
1045
+
1046
+ def _non_result(self, result, default, err=None):
1047
+ # we only expect to have a _NoResultMetaData() here right now.
1048
+ assert not result._metadata.returns_rows
1049
+ result._metadata._we_dont_return_rows(err)
1050
+
1051
+
1052
+ _NO_CURSOR_DML = NoCursorDMLFetchStrategy()
1053
+
1054
+
1055
+ class CursorFetchStrategy(ResultFetchStrategy):
1056
+ """Call fetch methods from a DBAPI cursor.
1057
+
1058
+ Alternate versions of this class may instead buffer the rows from
1059
+ cursors or not use cursors at all.
1060
+
1061
+ """
1062
+
1063
+ __slots__ = ()
1064
+
1065
+ def soft_close(
1066
+ self, result: CursorResult[Any], dbapi_cursor: Optional[DBAPICursor]
1067
+ ) -> None:
1068
+ result.cursor_strategy = _NO_CURSOR_DQL
1069
+
1070
+ def hard_close(
1071
+ self, result: CursorResult[Any], dbapi_cursor: Optional[DBAPICursor]
1072
+ ) -> None:
1073
+ result.cursor_strategy = _NO_CURSOR_DQL
1074
+
1075
+ def handle_exception(
1076
+ self,
1077
+ result: CursorResult[Any],
1078
+ dbapi_cursor: Optional[DBAPICursor],
1079
+ err: BaseException,
1080
+ ) -> NoReturn:
1081
+ result.connection._handle_dbapi_exception(
1082
+ err, None, None, dbapi_cursor, result.context
1083
+ )
1084
+
1085
+ def yield_per(
1086
+ self,
1087
+ result: CursorResult[Any],
1088
+ dbapi_cursor: Optional[DBAPICursor],
1089
+ num: int,
1090
+ ) -> None:
1091
+ result.cursor_strategy = BufferedRowCursorFetchStrategy(
1092
+ dbapi_cursor,
1093
+ {"max_row_buffer": num},
1094
+ initial_buffer=collections.deque(),
1095
+ growth_factor=0,
1096
+ )
1097
+
1098
+ def fetchone(
1099
+ self,
1100
+ result: CursorResult[Any],
1101
+ dbapi_cursor: DBAPICursor,
1102
+ hard_close: bool = False,
1103
+ ) -> Any:
1104
+ try:
1105
+ row = dbapi_cursor.fetchone()
1106
+ if row is None:
1107
+ result._soft_close(hard=hard_close)
1108
+ return row
1109
+ except BaseException as e:
1110
+ self.handle_exception(result, dbapi_cursor, e)
1111
+
1112
+ def fetchmany(
1113
+ self,
1114
+ result: CursorResult[Any],
1115
+ dbapi_cursor: DBAPICursor,
1116
+ size: Optional[int] = None,
1117
+ ) -> Any:
1118
+ try:
1119
+ if size is None:
1120
+ l = dbapi_cursor.fetchmany()
1121
+ else:
1122
+ l = dbapi_cursor.fetchmany(size)
1123
+
1124
+ if not l:
1125
+ result._soft_close()
1126
+ return l
1127
+ except BaseException as e:
1128
+ self.handle_exception(result, dbapi_cursor, e)
1129
+
1130
+ def fetchall(
1131
+ self,
1132
+ result: CursorResult[Any],
1133
+ dbapi_cursor: DBAPICursor,
1134
+ ) -> Any:
1135
+ try:
1136
+ rows = dbapi_cursor.fetchall()
1137
+ result._soft_close()
1138
+ return rows
1139
+ except BaseException as e:
1140
+ self.handle_exception(result, dbapi_cursor, e)
1141
+
1142
+
1143
+ _DEFAULT_FETCH = CursorFetchStrategy()
1144
+
1145
+
1146
+ class BufferedRowCursorFetchStrategy(CursorFetchStrategy):
1147
+ """A cursor fetch strategy with row buffering behavior.
1148
+
1149
+ This strategy buffers the contents of a selection of rows
1150
+ before ``fetchone()`` is called. This is to allow the results of
1151
+ ``cursor.description`` to be available immediately, when
1152
+ interfacing with a DB-API that requires rows to be consumed before
1153
+ this information is available (currently psycopg2, when used with
1154
+ server-side cursors).
1155
+
1156
+ The pre-fetching behavior fetches only one row initially, and then
1157
+ grows its buffer size by a fixed amount with each successive need
1158
+ for additional rows up the ``max_row_buffer`` size, which defaults
1159
+ to 1000::
1160
+
1161
+ with psycopg2_engine.connect() as conn:
1162
+
1163
+ result = conn.execution_options(
1164
+ stream_results=True, max_row_buffer=50
1165
+ ).execute(text("select * from table"))
1166
+
1167
+ .. versionadded:: 1.4 ``max_row_buffer`` may now exceed 1000 rows.
1168
+
1169
+ .. seealso::
1170
+
1171
+ :ref:`psycopg2_execution_options`
1172
+ """
1173
+
1174
+ __slots__ = ("_max_row_buffer", "_rowbuffer", "_bufsize", "_growth_factor")
1175
+
1176
+ def __init__(
1177
+ self,
1178
+ dbapi_cursor,
1179
+ execution_options,
1180
+ growth_factor=5,
1181
+ initial_buffer=None,
1182
+ ):
1183
+ self._max_row_buffer = execution_options.get("max_row_buffer", 1000)
1184
+
1185
+ if initial_buffer is not None:
1186
+ self._rowbuffer = initial_buffer
1187
+ else:
1188
+ self._rowbuffer = collections.deque(dbapi_cursor.fetchmany(1))
1189
+ self._growth_factor = growth_factor
1190
+
1191
+ if growth_factor:
1192
+ self._bufsize = min(self._max_row_buffer, self._growth_factor)
1193
+ else:
1194
+ self._bufsize = self._max_row_buffer
1195
+
1196
+ @classmethod
1197
+ def create(cls, result):
1198
+ return BufferedRowCursorFetchStrategy(
1199
+ result.cursor,
1200
+ result.context.execution_options,
1201
+ )
1202
+
1203
+ def _buffer_rows(self, result, dbapi_cursor):
1204
+ """this is currently used only by fetchone()."""
1205
+
1206
+ size = self._bufsize
1207
+ try:
1208
+ if size < 1:
1209
+ new_rows = dbapi_cursor.fetchall()
1210
+ else:
1211
+ new_rows = dbapi_cursor.fetchmany(size)
1212
+ except BaseException as e:
1213
+ self.handle_exception(result, dbapi_cursor, e)
1214
+
1215
+ if not new_rows:
1216
+ return
1217
+ self._rowbuffer = collections.deque(new_rows)
1218
+ if self._growth_factor and size < self._max_row_buffer:
1219
+ self._bufsize = min(
1220
+ self._max_row_buffer, size * self._growth_factor
1221
+ )
1222
+
1223
+ def yield_per(self, result, dbapi_cursor, num):
1224
+ self._growth_factor = 0
1225
+ self._max_row_buffer = self._bufsize = num
1226
+
1227
+ def soft_close(self, result, dbapi_cursor):
1228
+ self._rowbuffer.clear()
1229
+ super().soft_close(result, dbapi_cursor)
1230
+
1231
+ def hard_close(self, result, dbapi_cursor):
1232
+ self._rowbuffer.clear()
1233
+ super().hard_close(result, dbapi_cursor)
1234
+
1235
+ def fetchone(self, result, dbapi_cursor, hard_close=False):
1236
+ if not self._rowbuffer:
1237
+ self._buffer_rows(result, dbapi_cursor)
1238
+ if not self._rowbuffer:
1239
+ try:
1240
+ result._soft_close(hard=hard_close)
1241
+ except BaseException as e:
1242
+ self.handle_exception(result, dbapi_cursor, e)
1243
+ return None
1244
+ return self._rowbuffer.popleft()
1245
+
1246
+ def fetchmany(self, result, dbapi_cursor, size=None):
1247
+ if size is None:
1248
+ return self.fetchall(result, dbapi_cursor)
1249
+
1250
+ rb = self._rowbuffer
1251
+ lb = len(rb)
1252
+ close = False
1253
+ if size > lb:
1254
+ try:
1255
+ new = dbapi_cursor.fetchmany(size - lb)
1256
+ except BaseException as e:
1257
+ self.handle_exception(result, dbapi_cursor, e)
1258
+ else:
1259
+ if not new:
1260
+ # defer closing since it may clear the row buffer
1261
+ close = True
1262
+ else:
1263
+ rb.extend(new)
1264
+
1265
+ res = [rb.popleft() for _ in range(min(size, len(rb)))]
1266
+ if close:
1267
+ result._soft_close()
1268
+ return res
1269
+
1270
+ def fetchall(self, result, dbapi_cursor):
1271
+ try:
1272
+ ret = list(self._rowbuffer) + list(dbapi_cursor.fetchall())
1273
+ self._rowbuffer.clear()
1274
+ result._soft_close()
1275
+ return ret
1276
+ except BaseException as e:
1277
+ self.handle_exception(result, dbapi_cursor, e)
1278
+
1279
+
1280
+ class FullyBufferedCursorFetchStrategy(CursorFetchStrategy):
1281
+ """A cursor strategy that buffers rows fully upon creation.
1282
+
1283
+ Used for operations where a result is to be delivered
1284
+ after the database conversation can not be continued,
1285
+ such as MSSQL INSERT...OUTPUT after an autocommit.
1286
+
1287
+ """
1288
+
1289
+ __slots__ = ("_rowbuffer", "alternate_cursor_description")
1290
+
1291
+ def __init__(
1292
+ self, dbapi_cursor, alternate_description=None, initial_buffer=None
1293
+ ):
1294
+ self.alternate_cursor_description = alternate_description
1295
+ if initial_buffer is not None:
1296
+ self._rowbuffer = collections.deque(initial_buffer)
1297
+ else:
1298
+ self._rowbuffer = collections.deque(dbapi_cursor.fetchall())
1299
+
1300
+ def yield_per(self, result, dbapi_cursor, num):
1301
+ pass
1302
+
1303
+ def soft_close(self, result, dbapi_cursor):
1304
+ self._rowbuffer.clear()
1305
+ super().soft_close(result, dbapi_cursor)
1306
+
1307
+ def hard_close(self, result, dbapi_cursor):
1308
+ self._rowbuffer.clear()
1309
+ super().hard_close(result, dbapi_cursor)
1310
+
1311
+ def fetchone(self, result, dbapi_cursor, hard_close=False):
1312
+ if self._rowbuffer:
1313
+ return self._rowbuffer.popleft()
1314
+ else:
1315
+ result._soft_close(hard=hard_close)
1316
+ return None
1317
+
1318
+ def fetchmany(self, result, dbapi_cursor, size=None):
1319
+ if size is None:
1320
+ return self.fetchall(result, dbapi_cursor)
1321
+
1322
+ rb = self._rowbuffer
1323
+ rows = [rb.popleft() for _ in range(min(size, len(rb)))]
1324
+ if not rows:
1325
+ result._soft_close()
1326
+ return rows
1327
+
1328
+ def fetchall(self, result, dbapi_cursor):
1329
+ ret = self._rowbuffer
1330
+ self._rowbuffer = collections.deque()
1331
+ result._soft_close()
1332
+ return ret
1333
+
1334
+
1335
+ class _NoResultMetaData(ResultMetaData):
1336
+ __slots__ = ()
1337
+
1338
+ returns_rows = False
1339
+
1340
+ def _we_dont_return_rows(self, err=None):
1341
+ raise exc.ResourceClosedError(
1342
+ "This result object does not return rows. "
1343
+ "It has been closed automatically."
1344
+ ) from err
1345
+
1346
+ def _index_for_key(self, keys, raiseerr):
1347
+ self._we_dont_return_rows()
1348
+
1349
+ def _metadata_for_keys(self, key):
1350
+ self._we_dont_return_rows()
1351
+
1352
+ def _reduce(self, keys):
1353
+ self._we_dont_return_rows()
1354
+
1355
+ @property
1356
+ def _keymap(self):
1357
+ self._we_dont_return_rows()
1358
+
1359
+ @property
1360
+ def _key_to_index(self):
1361
+ self._we_dont_return_rows()
1362
+
1363
+ @property
1364
+ def _processors(self):
1365
+ self._we_dont_return_rows()
1366
+
1367
+ @property
1368
+ def keys(self):
1369
+ self._we_dont_return_rows()
1370
+
1371
+
1372
+ _NO_RESULT_METADATA = _NoResultMetaData()
1373
+
1374
+
1375
+ def null_dml_result() -> IteratorResult[Any]:
1376
+ it: IteratorResult[Any] = IteratorResult(_NoResultMetaData(), iter([]))
1377
+ it._soft_close()
1378
+ return it
1379
+
1380
+
1381
+ class CursorResult(Result[_T]):
1382
+ """A Result that is representing state from a DBAPI cursor.
1383
+
1384
+ .. versionchanged:: 1.4 The :class:`.CursorResult``
1385
+ class replaces the previous :class:`.ResultProxy` interface.
1386
+ This classes are based on the :class:`.Result` calling API
1387
+ which provides an updated usage model and calling facade for
1388
+ SQLAlchemy Core and SQLAlchemy ORM.
1389
+
1390
+ Returns database rows via the :class:`.Row` class, which provides
1391
+ additional API features and behaviors on top of the raw data returned by
1392
+ the DBAPI. Through the use of filters such as the :meth:`.Result.scalars`
1393
+ method, other kinds of objects may also be returned.
1394
+
1395
+ .. seealso::
1396
+
1397
+ :ref:`tutorial_selecting_data` - introductory material for accessing
1398
+ :class:`_engine.CursorResult` and :class:`.Row` objects.
1399
+
1400
+ """
1401
+
1402
+ __slots__ = (
1403
+ "context",
1404
+ "dialect",
1405
+ "cursor",
1406
+ "cursor_strategy",
1407
+ "_echo",
1408
+ "connection",
1409
+ )
1410
+
1411
+ _metadata: Union[CursorResultMetaData, _NoResultMetaData]
1412
+ _no_result_metadata = _NO_RESULT_METADATA
1413
+ _soft_closed: bool = False
1414
+ closed: bool = False
1415
+ _is_cursor = True
1416
+
1417
+ context: DefaultExecutionContext
1418
+ dialect: Dialect
1419
+ cursor_strategy: ResultFetchStrategy
1420
+ connection: Connection
1421
+
1422
+ def __init__(
1423
+ self,
1424
+ context: DefaultExecutionContext,
1425
+ cursor_strategy: ResultFetchStrategy,
1426
+ cursor_description: Optional[_DBAPICursorDescription],
1427
+ ):
1428
+ self.context = context
1429
+ self.dialect = context.dialect
1430
+ self.cursor = context.cursor
1431
+ self.cursor_strategy = cursor_strategy
1432
+ self.connection = context.root_connection
1433
+ self._echo = echo = (
1434
+ self.connection._echo and context.engine._should_log_debug()
1435
+ )
1436
+
1437
+ if cursor_description is not None:
1438
+ # inline of Result._row_getter(), set up an initial row
1439
+ # getter assuming no transformations will be called as this
1440
+ # is the most common case
1441
+
1442
+ metadata = self._init_metadata(context, cursor_description)
1443
+
1444
+ _make_row: Any
1445
+ _make_row = functools.partial(
1446
+ Row,
1447
+ metadata,
1448
+ metadata._effective_processors,
1449
+ metadata._key_to_index,
1450
+ )
1451
+
1452
+ if context._num_sentinel_cols:
1453
+ sentinel_filter = operator.itemgetter(
1454
+ slice(-context._num_sentinel_cols)
1455
+ )
1456
+
1457
+ def _sliced_row(raw_data):
1458
+ return _make_row(sentinel_filter(raw_data))
1459
+
1460
+ sliced_row = _sliced_row
1461
+ else:
1462
+ sliced_row = _make_row
1463
+
1464
+ if echo:
1465
+ log = self.context.connection._log_debug
1466
+
1467
+ def _log_row(row):
1468
+ log("Row %r", sql_util._repr_row(row))
1469
+ return row
1470
+
1471
+ self._row_logging_fn = _log_row
1472
+
1473
+ def _make_row_2(row):
1474
+ return _log_row(sliced_row(row))
1475
+
1476
+ make_row = _make_row_2
1477
+ else:
1478
+ make_row = sliced_row
1479
+ self._set_memoized_attribute("_row_getter", make_row)
1480
+
1481
+ else:
1482
+ assert context._num_sentinel_cols == 0
1483
+ self._metadata = self._no_result_metadata
1484
+
1485
+ def _init_metadata(self, context, cursor_description):
1486
+ if context.compiled:
1487
+ compiled = context.compiled
1488
+
1489
+ if compiled._cached_metadata:
1490
+ metadata = compiled._cached_metadata
1491
+ else:
1492
+ metadata = CursorResultMetaData(self, cursor_description)
1493
+ if metadata._safe_for_cache:
1494
+ compiled._cached_metadata = metadata
1495
+
1496
+ # result rewrite/ adapt step. this is to suit the case
1497
+ # when we are invoked against a cached Compiled object, we want
1498
+ # to rewrite the ResultMetaData to reflect the Column objects
1499
+ # that are in our current SQL statement object, not the one
1500
+ # that is associated with the cached Compiled object.
1501
+ # the Compiled object may also tell us to not
1502
+ # actually do this step; this is to support the ORM where
1503
+ # it is to produce a new Result object in any case, and will
1504
+ # be using the cached Column objects against this database result
1505
+ # so we don't want to rewrite them.
1506
+ #
1507
+ # Basically this step suits the use case where the end user
1508
+ # is using Core SQL expressions and is accessing columns in the
1509
+ # result row using row._mapping[table.c.column].
1510
+ if (
1511
+ not context.execution_options.get(
1512
+ "_result_disable_adapt_to_context", False
1513
+ )
1514
+ and compiled._result_columns
1515
+ and context.cache_hit is context.dialect.CACHE_HIT
1516
+ and compiled.statement is not context.invoked_statement
1517
+ ):
1518
+ metadata = metadata._adapt_to_context(context)
1519
+
1520
+ self._metadata = metadata
1521
+
1522
+ else:
1523
+ self._metadata = metadata = CursorResultMetaData(
1524
+ self, cursor_description
1525
+ )
1526
+ if self._echo:
1527
+ context.connection._log_debug(
1528
+ "Col %r", tuple(x[0] for x in cursor_description)
1529
+ )
1530
+ return metadata
1531
+
1532
+ def _soft_close(self, hard=False):
1533
+ """Soft close this :class:`_engine.CursorResult`.
1534
+
1535
+ This releases all DBAPI cursor resources, but leaves the
1536
+ CursorResult "open" from a semantic perspective, meaning the
1537
+ fetchXXX() methods will continue to return empty results.
1538
+
1539
+ This method is called automatically when:
1540
+
1541
+ * all result rows are exhausted using the fetchXXX() methods.
1542
+ * cursor.description is None.
1543
+
1544
+ This method is **not public**, but is documented in order to clarify
1545
+ the "autoclose" process used.
1546
+
1547
+ .. seealso::
1548
+
1549
+ :meth:`_engine.CursorResult.close`
1550
+
1551
+
1552
+ """
1553
+
1554
+ if (not hard and self._soft_closed) or (hard and self.closed):
1555
+ return
1556
+
1557
+ if hard:
1558
+ self.closed = True
1559
+ self.cursor_strategy.hard_close(self, self.cursor)
1560
+ else:
1561
+ self.cursor_strategy.soft_close(self, self.cursor)
1562
+
1563
+ if not self._soft_closed:
1564
+ cursor = self.cursor
1565
+ self.cursor = None # type: ignore
1566
+ self.connection._safe_close_cursor(cursor)
1567
+ self._soft_closed = True
1568
+
1569
+ @property
1570
+ def inserted_primary_key_rows(self):
1571
+ """Return the value of
1572
+ :attr:`_engine.CursorResult.inserted_primary_key`
1573
+ as a row contained within a list; some dialects may support a
1574
+ multiple row form as well.
1575
+
1576
+ .. note:: As indicated below, in current SQLAlchemy versions this
1577
+ accessor is only useful beyond what's already supplied by
1578
+ :attr:`_engine.CursorResult.inserted_primary_key` when using the
1579
+ :ref:`postgresql_psycopg2` dialect. Future versions hope to
1580
+ generalize this feature to more dialects.
1581
+
1582
+ This accessor is added to support dialects that offer the feature
1583
+ that is currently implemented by the :ref:`psycopg2_executemany_mode`
1584
+ feature, currently **only the psycopg2 dialect**, which provides
1585
+ for many rows to be INSERTed at once while still retaining the
1586
+ behavior of being able to return server-generated primary key values.
1587
+
1588
+ * **When using the psycopg2 dialect, or other dialects that may support
1589
+ "fast executemany" style inserts in upcoming releases** : When
1590
+ invoking an INSERT statement while passing a list of rows as the
1591
+ second argument to :meth:`_engine.Connection.execute`, this accessor
1592
+ will then provide a list of rows, where each row contains the primary
1593
+ key value for each row that was INSERTed.
1594
+
1595
+ * **When using all other dialects / backends that don't yet support
1596
+ this feature**: This accessor is only useful for **single row INSERT
1597
+ statements**, and returns the same information as that of the
1598
+ :attr:`_engine.CursorResult.inserted_primary_key` within a
1599
+ single-element list. When an INSERT statement is executed in
1600
+ conjunction with a list of rows to be INSERTed, the list will contain
1601
+ one row per row inserted in the statement, however it will contain
1602
+ ``None`` for any server-generated values.
1603
+
1604
+ Future releases of SQLAlchemy will further generalize the
1605
+ "fast execution helper" feature of psycopg2 to suit other dialects,
1606
+ thus allowing this accessor to be of more general use.
1607
+
1608
+ .. versionadded:: 1.4
1609
+
1610
+ .. seealso::
1611
+
1612
+ :attr:`_engine.CursorResult.inserted_primary_key`
1613
+
1614
+ """
1615
+ if not self.context.compiled:
1616
+ raise exc.InvalidRequestError(
1617
+ "Statement is not a compiled expression construct."
1618
+ )
1619
+ elif not self.context.isinsert:
1620
+ raise exc.InvalidRequestError(
1621
+ "Statement is not an insert() expression construct."
1622
+ )
1623
+ elif self.context._is_explicit_returning:
1624
+ raise exc.InvalidRequestError(
1625
+ "Can't call inserted_primary_key "
1626
+ "when returning() "
1627
+ "is used."
1628
+ )
1629
+ return self.context.inserted_primary_key_rows
1630
+
1631
+ @property
1632
+ def inserted_primary_key(self):
1633
+ """Return the primary key for the row just inserted.
1634
+
1635
+ The return value is a :class:`_result.Row` object representing
1636
+ a named tuple of primary key values in the order in which the
1637
+ primary key columns are configured in the source
1638
+ :class:`_schema.Table`.
1639
+
1640
+ .. versionchanged:: 1.4.8 - the
1641
+ :attr:`_engine.CursorResult.inserted_primary_key`
1642
+ value is now a named tuple via the :class:`_result.Row` class,
1643
+ rather than a plain tuple.
1644
+
1645
+ This accessor only applies to single row :func:`_expression.insert`
1646
+ constructs which did not explicitly specify
1647
+ :meth:`_expression.Insert.returning`. Support for multirow inserts,
1648
+ while not yet available for most backends, would be accessed using
1649
+ the :attr:`_engine.CursorResult.inserted_primary_key_rows` accessor.
1650
+
1651
+ Note that primary key columns which specify a server_default clause, or
1652
+ otherwise do not qualify as "autoincrement" columns (see the notes at
1653
+ :class:`_schema.Column`), and were generated using the database-side
1654
+ default, will appear in this list as ``None`` unless the backend
1655
+ supports "returning" and the insert statement executed with the
1656
+ "implicit returning" enabled.
1657
+
1658
+ Raises :class:`~sqlalchemy.exc.InvalidRequestError` if the executed
1659
+ statement is not a compiled expression construct
1660
+ or is not an insert() construct.
1661
+
1662
+ """
1663
+
1664
+ if self.context.executemany:
1665
+ raise exc.InvalidRequestError(
1666
+ "This statement was an executemany call; if primary key "
1667
+ "returning is supported, please "
1668
+ "use .inserted_primary_key_rows."
1669
+ )
1670
+
1671
+ ikp = self.inserted_primary_key_rows
1672
+ if ikp:
1673
+ return ikp[0]
1674
+ else:
1675
+ return None
1676
+
1677
+ def last_updated_params(self):
1678
+ """Return the collection of updated parameters from this
1679
+ execution.
1680
+
1681
+ Raises :class:`~sqlalchemy.exc.InvalidRequestError` if the executed
1682
+ statement is not a compiled expression construct
1683
+ or is not an update() construct.
1684
+
1685
+ """
1686
+ if not self.context.compiled:
1687
+ raise exc.InvalidRequestError(
1688
+ "Statement is not a compiled expression construct."
1689
+ )
1690
+ elif not self.context.isupdate:
1691
+ raise exc.InvalidRequestError(
1692
+ "Statement is not an update() expression construct."
1693
+ )
1694
+ elif self.context.executemany:
1695
+ return self.context.compiled_parameters
1696
+ else:
1697
+ return self.context.compiled_parameters[0]
1698
+
1699
+ def last_inserted_params(self):
1700
+ """Return the collection of inserted parameters from this
1701
+ execution.
1702
+
1703
+ Raises :class:`~sqlalchemy.exc.InvalidRequestError` if the executed
1704
+ statement is not a compiled expression construct
1705
+ or is not an insert() construct.
1706
+
1707
+ """
1708
+ if not self.context.compiled:
1709
+ raise exc.InvalidRequestError(
1710
+ "Statement is not a compiled expression construct."
1711
+ )
1712
+ elif not self.context.isinsert:
1713
+ raise exc.InvalidRequestError(
1714
+ "Statement is not an insert() expression construct."
1715
+ )
1716
+ elif self.context.executemany:
1717
+ return self.context.compiled_parameters
1718
+ else:
1719
+ return self.context.compiled_parameters[0]
1720
+
1721
+ @property
1722
+ def returned_defaults_rows(self):
1723
+ """Return a list of rows each containing the values of default
1724
+ columns that were fetched using
1725
+ the :meth:`.ValuesBase.return_defaults` feature.
1726
+
1727
+ The return value is a list of :class:`.Row` objects.
1728
+
1729
+ .. versionadded:: 1.4
1730
+
1731
+ """
1732
+ return self.context.returned_default_rows
1733
+
1734
+ def splice_horizontally(self, other):
1735
+ """Return a new :class:`.CursorResult` that "horizontally splices"
1736
+ together the rows of this :class:`.CursorResult` with that of another
1737
+ :class:`.CursorResult`.
1738
+
1739
+ .. tip:: This method is for the benefit of the SQLAlchemy ORM and is
1740
+ not intended for general use.
1741
+
1742
+ "horizontally splices" means that for each row in the first and second
1743
+ result sets, a new row that concatenates the two rows together is
1744
+ produced, which then becomes the new row. The incoming
1745
+ :class:`.CursorResult` must have the identical number of rows. It is
1746
+ typically expected that the two result sets come from the same sort
1747
+ order as well, as the result rows are spliced together based on their
1748
+ position in the result.
1749
+
1750
+ The expected use case here is so that multiple INSERT..RETURNING
1751
+ statements (which definitely need to be sorted) against different
1752
+ tables can produce a single result that looks like a JOIN of those two
1753
+ tables.
1754
+
1755
+ E.g.::
1756
+
1757
+ r1 = connection.execute(
1758
+ users.insert().returning(
1759
+ users.c.user_name,
1760
+ users.c.user_id,
1761
+ sort_by_parameter_order=True
1762
+ ),
1763
+ user_values
1764
+ )
1765
+
1766
+ r2 = connection.execute(
1767
+ addresses.insert().returning(
1768
+ addresses.c.address_id,
1769
+ addresses.c.address,
1770
+ addresses.c.user_id,
1771
+ sort_by_parameter_order=True
1772
+ ),
1773
+ address_values
1774
+ )
1775
+
1776
+ rows = r1.splice_horizontally(r2).all()
1777
+ assert (
1778
+ rows ==
1779
+ [
1780
+ ("john", 1, 1, "foo@bar.com", 1),
1781
+ ("jack", 2, 2, "bar@bat.com", 2),
1782
+ ]
1783
+ )
1784
+
1785
+ .. versionadded:: 2.0
1786
+
1787
+ .. seealso::
1788
+
1789
+ :meth:`.CursorResult.splice_vertically`
1790
+
1791
+
1792
+ """
1793
+
1794
+ clone = self._generate()
1795
+ total_rows = [
1796
+ tuple(r1) + tuple(r2)
1797
+ for r1, r2 in zip(
1798
+ list(self._raw_row_iterator()),
1799
+ list(other._raw_row_iterator()),
1800
+ )
1801
+ ]
1802
+
1803
+ clone._metadata = clone._metadata._splice_horizontally(other._metadata)
1804
+
1805
+ clone.cursor_strategy = FullyBufferedCursorFetchStrategy(
1806
+ None,
1807
+ initial_buffer=total_rows,
1808
+ )
1809
+ clone._reset_memoizations()
1810
+ return clone
1811
+
1812
+ def splice_vertically(self, other):
1813
+ """Return a new :class:`.CursorResult` that "vertically splices",
1814
+ i.e. "extends", the rows of this :class:`.CursorResult` with that of
1815
+ another :class:`.CursorResult`.
1816
+
1817
+ .. tip:: This method is for the benefit of the SQLAlchemy ORM and is
1818
+ not intended for general use.
1819
+
1820
+ "vertically splices" means the rows of the given result are appended to
1821
+ the rows of this cursor result. The incoming :class:`.CursorResult`
1822
+ must have rows that represent the identical list of columns in the
1823
+ identical order as they are in this :class:`.CursorResult`.
1824
+
1825
+ .. versionadded:: 2.0
1826
+
1827
+ .. seealso::
1828
+
1829
+ :meth:`.CursorResult.splice_horizontally`
1830
+
1831
+ """
1832
+ clone = self._generate()
1833
+ total_rows = list(self._raw_row_iterator()) + list(
1834
+ other._raw_row_iterator()
1835
+ )
1836
+
1837
+ clone.cursor_strategy = FullyBufferedCursorFetchStrategy(
1838
+ None,
1839
+ initial_buffer=total_rows,
1840
+ )
1841
+ clone._reset_memoizations()
1842
+ return clone
1843
+
1844
+ def _rewind(self, rows):
1845
+ """rewind this result back to the given rowset.
1846
+
1847
+ this is used internally for the case where an :class:`.Insert`
1848
+ construct combines the use of
1849
+ :meth:`.Insert.return_defaults` along with the
1850
+ "supplemental columns" feature.
1851
+
1852
+ """
1853
+
1854
+ if self._echo:
1855
+ self.context.connection._log_debug(
1856
+ "CursorResult rewound %d row(s)", len(rows)
1857
+ )
1858
+
1859
+ # the rows given are expected to be Row objects, so we
1860
+ # have to clear out processors which have already run on these
1861
+ # rows
1862
+ self._metadata = cast(
1863
+ CursorResultMetaData, self._metadata
1864
+ )._remove_processors()
1865
+
1866
+ self.cursor_strategy = FullyBufferedCursorFetchStrategy(
1867
+ None,
1868
+ # TODO: if these are Row objects, can we save on not having to
1869
+ # re-make new Row objects out of them a second time? is that
1870
+ # what's actually happening right now? maybe look into this
1871
+ initial_buffer=rows,
1872
+ )
1873
+ self._reset_memoizations()
1874
+ return self
1875
+
1876
+ @property
1877
+ def returned_defaults(self):
1878
+ """Return the values of default columns that were fetched using
1879
+ the :meth:`.ValuesBase.return_defaults` feature.
1880
+
1881
+ The value is an instance of :class:`.Row`, or ``None``
1882
+ if :meth:`.ValuesBase.return_defaults` was not used or if the
1883
+ backend does not support RETURNING.
1884
+
1885
+ .. seealso::
1886
+
1887
+ :meth:`.ValuesBase.return_defaults`
1888
+
1889
+ """
1890
+
1891
+ if self.context.executemany:
1892
+ raise exc.InvalidRequestError(
1893
+ "This statement was an executemany call; if return defaults "
1894
+ "is supported, please use .returned_defaults_rows."
1895
+ )
1896
+
1897
+ rows = self.context.returned_default_rows
1898
+ if rows:
1899
+ return rows[0]
1900
+ else:
1901
+ return None
1902
+
1903
+ def lastrow_has_defaults(self):
1904
+ """Return ``lastrow_has_defaults()`` from the underlying
1905
+ :class:`.ExecutionContext`.
1906
+
1907
+ See :class:`.ExecutionContext` for details.
1908
+
1909
+ """
1910
+
1911
+ return self.context.lastrow_has_defaults()
1912
+
1913
+ def postfetch_cols(self):
1914
+ """Return ``postfetch_cols()`` from the underlying
1915
+ :class:`.ExecutionContext`.
1916
+
1917
+ See :class:`.ExecutionContext` for details.
1918
+
1919
+ Raises :class:`~sqlalchemy.exc.InvalidRequestError` if the executed
1920
+ statement is not a compiled expression construct
1921
+ or is not an insert() or update() construct.
1922
+
1923
+ """
1924
+
1925
+ if not self.context.compiled:
1926
+ raise exc.InvalidRequestError(
1927
+ "Statement is not a compiled expression construct."
1928
+ )
1929
+ elif not self.context.isinsert and not self.context.isupdate:
1930
+ raise exc.InvalidRequestError(
1931
+ "Statement is not an insert() or update() "
1932
+ "expression construct."
1933
+ )
1934
+ return self.context.postfetch_cols
1935
+
1936
+ def prefetch_cols(self):
1937
+ """Return ``prefetch_cols()`` from the underlying
1938
+ :class:`.ExecutionContext`.
1939
+
1940
+ See :class:`.ExecutionContext` for details.
1941
+
1942
+ Raises :class:`~sqlalchemy.exc.InvalidRequestError` if the executed
1943
+ statement is not a compiled expression construct
1944
+ or is not an insert() or update() construct.
1945
+
1946
+ """
1947
+
1948
+ if not self.context.compiled:
1949
+ raise exc.InvalidRequestError(
1950
+ "Statement is not a compiled expression construct."
1951
+ )
1952
+ elif not self.context.isinsert and not self.context.isupdate:
1953
+ raise exc.InvalidRequestError(
1954
+ "Statement is not an insert() or update() "
1955
+ "expression construct."
1956
+ )
1957
+ return self.context.prefetch_cols
1958
+
1959
+ def supports_sane_rowcount(self):
1960
+ """Return ``supports_sane_rowcount`` from the dialect.
1961
+
1962
+ See :attr:`_engine.CursorResult.rowcount` for background.
1963
+
1964
+ """
1965
+
1966
+ return self.dialect.supports_sane_rowcount
1967
+
1968
+ def supports_sane_multi_rowcount(self):
1969
+ """Return ``supports_sane_multi_rowcount`` from the dialect.
1970
+
1971
+ See :attr:`_engine.CursorResult.rowcount` for background.
1972
+
1973
+ """
1974
+
1975
+ return self.dialect.supports_sane_multi_rowcount
1976
+
1977
+ @util.memoized_property
1978
+ def rowcount(self) -> int:
1979
+ """Return the 'rowcount' for this result.
1980
+
1981
+ The primary purpose of 'rowcount' is to report the number of rows
1982
+ matched by the WHERE criterion of an UPDATE or DELETE statement
1983
+ executed once (i.e. for a single parameter set), which may then be
1984
+ compared to the number of rows expected to be updated or deleted as a
1985
+ means of asserting data integrity.
1986
+
1987
+ This attribute is transferred from the ``cursor.rowcount`` attribute
1988
+ of the DBAPI before the cursor is closed, to support DBAPIs that
1989
+ don't make this value available after cursor close. Some DBAPIs may
1990
+ offer meaningful values for other kinds of statements, such as INSERT
1991
+ and SELECT statements as well. In order to retrieve ``cursor.rowcount``
1992
+ for these statements, set the
1993
+ :paramref:`.Connection.execution_options.preserve_rowcount`
1994
+ execution option to True, which will cause the ``cursor.rowcount``
1995
+ value to be unconditionally memoized before any results are returned
1996
+ or the cursor is closed, regardless of statement type.
1997
+
1998
+ For cases where the DBAPI does not support rowcount for a particular
1999
+ kind of statement and/or execution, the returned value will be ``-1``,
2000
+ which is delivered directly from the DBAPI and is part of :pep:`249`.
2001
+ All DBAPIs should support rowcount for single-parameter-set
2002
+ UPDATE and DELETE statements, however.
2003
+
2004
+ .. note::
2005
+
2006
+ Notes regarding :attr:`_engine.CursorResult.rowcount`:
2007
+
2008
+
2009
+ * This attribute returns the number of rows *matched*,
2010
+ which is not necessarily the same as the number of rows
2011
+ that were actually *modified*. For example, an UPDATE statement
2012
+ may have no net change on a given row if the SET values
2013
+ given are the same as those present in the row already.
2014
+ Such a row would be matched but not modified.
2015
+ On backends that feature both styles, such as MySQL,
2016
+ rowcount is configured to return the match
2017
+ count in all cases.
2018
+
2019
+ * :attr:`_engine.CursorResult.rowcount` in the default case is
2020
+ *only* useful in conjunction with an UPDATE or DELETE statement,
2021
+ and only with a single set of parameters. For other kinds of
2022
+ statements, SQLAlchemy will not attempt to pre-memoize the value
2023
+ unless the
2024
+ :paramref:`.Connection.execution_options.preserve_rowcount`
2025
+ execution option is used. Note that contrary to :pep:`249`, many
2026
+ DBAPIs do not support rowcount values for statements that are not
2027
+ UPDATE or DELETE, particularly when rows are being returned which
2028
+ are not fully pre-buffered. DBAPIs that dont support rowcount
2029
+ for a particular kind of statement should return the value ``-1``
2030
+ for such statements.
2031
+
2032
+ * :attr:`_engine.CursorResult.rowcount` may not be meaningful
2033
+ when executing a single statement with multiple parameter sets
2034
+ (i.e. an :term:`executemany`). Most DBAPIs do not sum "rowcount"
2035
+ values across multiple parameter sets and will return ``-1``
2036
+ when accessed.
2037
+
2038
+ * SQLAlchemy's :ref:`engine_insertmanyvalues` feature does support
2039
+ a correct population of :attr:`_engine.CursorResult.rowcount`
2040
+ when the :paramref:`.Connection.execution_options.preserve_rowcount`
2041
+ execution option is set to True.
2042
+
2043
+ * Statements that use RETURNING may not support rowcount, returning
2044
+ a ``-1`` value instead.
2045
+
2046
+ .. seealso::
2047
+
2048
+ :ref:`tutorial_update_delete_rowcount` - in the :ref:`unified_tutorial`
2049
+
2050
+ :paramref:`.Connection.execution_options.preserve_rowcount`
2051
+
2052
+ """ # noqa: E501
2053
+ try:
2054
+ return self.context.rowcount
2055
+ except BaseException as e:
2056
+ self.cursor_strategy.handle_exception(self, self.cursor, e)
2057
+ raise # not called
2058
+
2059
+ @property
2060
+ def lastrowid(self):
2061
+ """Return the 'lastrowid' accessor on the DBAPI cursor.
2062
+
2063
+ This is a DBAPI specific method and is only functional
2064
+ for those backends which support it, for statements
2065
+ where it is appropriate. It's behavior is not
2066
+ consistent across backends.
2067
+
2068
+ Usage of this method is normally unnecessary when
2069
+ using insert() expression constructs; the
2070
+ :attr:`~CursorResult.inserted_primary_key` attribute provides a
2071
+ tuple of primary key values for a newly inserted row,
2072
+ regardless of database backend.
2073
+
2074
+ """
2075
+ try:
2076
+ return self.context.get_lastrowid()
2077
+ except BaseException as e:
2078
+ self.cursor_strategy.handle_exception(self, self.cursor, e)
2079
+
2080
+ @property
2081
+ def returns_rows(self):
2082
+ """True if this :class:`_engine.CursorResult` returns zero or more
2083
+ rows.
2084
+
2085
+ I.e. if it is legal to call the methods
2086
+ :meth:`_engine.CursorResult.fetchone`,
2087
+ :meth:`_engine.CursorResult.fetchmany`
2088
+ :meth:`_engine.CursorResult.fetchall`.
2089
+
2090
+ Overall, the value of :attr:`_engine.CursorResult.returns_rows` should
2091
+ always be synonymous with whether or not the DBAPI cursor had a
2092
+ ``.description`` attribute, indicating the presence of result columns,
2093
+ noting that a cursor that returns zero rows still has a
2094
+ ``.description`` if a row-returning statement was emitted.
2095
+
2096
+ This attribute should be True for all results that are against
2097
+ SELECT statements, as well as for DML statements INSERT/UPDATE/DELETE
2098
+ that use RETURNING. For INSERT/UPDATE/DELETE statements that were
2099
+ not using RETURNING, the value will usually be False, however
2100
+ there are some dialect-specific exceptions to this, such as when
2101
+ using the MSSQL / pyodbc dialect a SELECT is emitted inline in
2102
+ order to retrieve an inserted primary key value.
2103
+
2104
+
2105
+ """
2106
+ return self._metadata.returns_rows
2107
+
2108
+ @property
2109
+ def is_insert(self):
2110
+ """True if this :class:`_engine.CursorResult` is the result
2111
+ of a executing an expression language compiled
2112
+ :func:`_expression.insert` construct.
2113
+
2114
+ When True, this implies that the
2115
+ :attr:`inserted_primary_key` attribute is accessible,
2116
+ assuming the statement did not include
2117
+ a user defined "returning" construct.
2118
+
2119
+ """
2120
+ return self.context.isinsert
2121
+
2122
+ def _fetchiter_impl(self):
2123
+ fetchone = self.cursor_strategy.fetchone
2124
+
2125
+ while True:
2126
+ row = fetchone(self, self.cursor)
2127
+ if row is None:
2128
+ break
2129
+ yield row
2130
+
2131
+ def _fetchone_impl(self, hard_close=False):
2132
+ return self.cursor_strategy.fetchone(self, self.cursor, hard_close)
2133
+
2134
+ def _fetchall_impl(self):
2135
+ return self.cursor_strategy.fetchall(self, self.cursor)
2136
+
2137
+ def _fetchmany_impl(self, size=None):
2138
+ return self.cursor_strategy.fetchmany(self, self.cursor, size)
2139
+
2140
+ def _raw_row_iterator(self):
2141
+ return self._fetchiter_impl()
2142
+
2143
+ def merge(self, *others: Result[Any]) -> MergedResult[Any]:
2144
+ merged_result = super().merge(*others)
2145
+ if self.context._has_rowcount:
2146
+ merged_result.rowcount = sum(
2147
+ cast("CursorResult[Any]", result).rowcount
2148
+ for result in (self,) + others
2149
+ )
2150
+ return merged_result
2151
+
2152
+ def close(self) -> Any:
2153
+ """Close this :class:`_engine.CursorResult`.
2154
+
2155
+ This closes out the underlying DBAPI cursor corresponding to the
2156
+ statement execution, if one is still present. Note that the DBAPI
2157
+ cursor is automatically released when the :class:`_engine.CursorResult`
2158
+ exhausts all available rows. :meth:`_engine.CursorResult.close` is
2159
+ generally an optional method except in the case when discarding a
2160
+ :class:`_engine.CursorResult` that still has additional rows pending
2161
+ for fetch.
2162
+
2163
+ After this method is called, it is no longer valid to call upon
2164
+ the fetch methods, which will raise a :class:`.ResourceClosedError`
2165
+ on subsequent use.
2166
+
2167
+ .. seealso::
2168
+
2169
+ :ref:`connections_toplevel`
2170
+
2171
+ """
2172
+ self._soft_close(hard=True)
2173
+
2174
+ @_generative
2175
+ def yield_per(self, num: int) -> Self:
2176
+ self._yield_per = num
2177
+ self.cursor_strategy.yield_per(self, self.cursor, num)
2178
+ return self
2179
+
2180
+
2181
+ ResultProxy = CursorResult