result.py 76 KB

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