result.py 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962
  1. # ext/asyncio/result.py
  2. # Copyright (C) 2020-2025 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. from __future__ import annotations
  8. import operator
  9. from typing import Any
  10. from typing import AsyncIterator
  11. from typing import Optional
  12. from typing import overload
  13. from typing import Sequence
  14. from typing import Tuple
  15. from typing import TYPE_CHECKING
  16. from typing import TypeVar
  17. from . import exc as async_exc
  18. from ... import util
  19. from ...engine import Result
  20. from ...engine.result import _NO_ROW
  21. from ...engine.result import _R
  22. from ...engine.result import _WithKeys
  23. from ...engine.result import FilterResult
  24. from ...engine.result import FrozenResult
  25. from ...engine.result import ResultMetaData
  26. from ...engine.row import Row
  27. from ...engine.row import RowMapping
  28. from ...sql.base import _generative
  29. from ...util.concurrency import greenlet_spawn
  30. from ...util.typing import Literal
  31. from ...util.typing import Self
  32. if TYPE_CHECKING:
  33. from ...engine import CursorResult
  34. from ...engine.result import _KeyIndexType
  35. from ...engine.result import _UniqueFilterType
  36. _T = TypeVar("_T", bound=Any)
  37. _TP = TypeVar("_TP", bound=Tuple[Any, ...])
  38. class AsyncCommon(FilterResult[_R]):
  39. __slots__ = ()
  40. _real_result: Result[Any]
  41. _metadata: ResultMetaData
  42. async def close(self) -> None: # type: ignore[override]
  43. """Close this result."""
  44. await greenlet_spawn(self._real_result.close)
  45. @property
  46. def closed(self) -> bool:
  47. """proxies the .closed attribute of the underlying result object,
  48. if any, else raises ``AttributeError``.
  49. .. versionadded:: 2.0.0b3
  50. """
  51. return self._real_result.closed
  52. class AsyncResult(_WithKeys, AsyncCommon[Row[_TP]]):
  53. """An asyncio wrapper around a :class:`_result.Result` object.
  54. The :class:`_asyncio.AsyncResult` only applies to statement executions that
  55. use a server-side cursor. It is returned only from the
  56. :meth:`_asyncio.AsyncConnection.stream` and
  57. :meth:`_asyncio.AsyncSession.stream` methods.
  58. .. note:: As is the case with :class:`_engine.Result`, this object is
  59. used for ORM results returned by :meth:`_asyncio.AsyncSession.execute`,
  60. which can yield instances of ORM mapped objects either individually or
  61. within tuple-like rows. Note that these result objects do not
  62. deduplicate instances or rows automatically as is the case with the
  63. legacy :class:`_orm.Query` object. For in-Python de-duplication of
  64. instances or rows, use the :meth:`_asyncio.AsyncResult.unique` modifier
  65. method.
  66. .. versionadded:: 1.4
  67. """
  68. __slots__ = ()
  69. _real_result: Result[_TP]
  70. def __init__(self, real_result: Result[_TP]):
  71. self._real_result = real_result
  72. self._metadata = real_result._metadata
  73. self._unique_filter_state = real_result._unique_filter_state
  74. self._source_supports_scalars = real_result._source_supports_scalars
  75. self._post_creational_filter = None
  76. # BaseCursorResult pre-generates the "_row_getter". Use that
  77. # if available rather than building a second one
  78. if "_row_getter" in real_result.__dict__:
  79. self._set_memoized_attribute(
  80. "_row_getter", real_result.__dict__["_row_getter"]
  81. )
  82. @property
  83. def t(self) -> AsyncTupleResult[_TP]:
  84. """Apply a "typed tuple" typing filter to returned rows.
  85. The :attr:`_asyncio.AsyncResult.t` attribute is a synonym for
  86. calling the :meth:`_asyncio.AsyncResult.tuples` method.
  87. .. versionadded:: 2.0
  88. """
  89. return self # type: ignore
  90. def tuples(self) -> AsyncTupleResult[_TP]:
  91. """Apply a "typed tuple" typing filter to returned rows.
  92. This method returns the same :class:`_asyncio.AsyncResult` object
  93. at runtime,
  94. however annotates as returning a :class:`_asyncio.AsyncTupleResult`
  95. object that will indicate to :pep:`484` typing tools that plain typed
  96. ``Tuple`` instances are returned rather than rows. This allows
  97. tuple unpacking and ``__getitem__`` access of :class:`_engine.Row`
  98. objects to by typed, for those cases where the statement invoked
  99. itself included typing information.
  100. .. versionadded:: 2.0
  101. :return: the :class:`_result.AsyncTupleResult` type at typing time.
  102. .. seealso::
  103. :attr:`_asyncio.AsyncResult.t` - shorter synonym
  104. :attr:`_engine.Row.t` - :class:`_engine.Row` version
  105. """
  106. return self # type: ignore
  107. @_generative
  108. def unique(self, strategy: Optional[_UniqueFilterType] = None) -> Self:
  109. """Apply unique filtering to the objects returned by this
  110. :class:`_asyncio.AsyncResult`.
  111. Refer to :meth:`_engine.Result.unique` in the synchronous
  112. SQLAlchemy API for a complete behavioral description.
  113. """
  114. self._unique_filter_state = (set(), strategy)
  115. return self
  116. def columns(self, *col_expressions: _KeyIndexType) -> Self:
  117. r"""Establish the columns that should be returned in each row.
  118. Refer to :meth:`_engine.Result.columns` in the synchronous
  119. SQLAlchemy API for a complete behavioral description.
  120. """
  121. return self._column_slices(col_expressions)
  122. async def partitions(
  123. self, size: Optional[int] = None
  124. ) -> AsyncIterator[Sequence[Row[_TP]]]:
  125. """Iterate through sub-lists of rows of the size given.
  126. An async iterator is returned::
  127. async def scroll_results(connection):
  128. result = await connection.stream(select(users_table))
  129. async for partition in result.partitions(100):
  130. print("list of rows: %s" % partition)
  131. Refer to :meth:`_engine.Result.partitions` in the synchronous
  132. SQLAlchemy API for a complete behavioral description.
  133. """
  134. getter = self._manyrow_getter
  135. while True:
  136. partition = await greenlet_spawn(getter, self, size)
  137. if partition:
  138. yield partition
  139. else:
  140. break
  141. async def fetchall(self) -> Sequence[Row[_TP]]:
  142. """A synonym for the :meth:`_asyncio.AsyncResult.all` method.
  143. .. versionadded:: 2.0
  144. """
  145. return await greenlet_spawn(self._allrows)
  146. async def fetchone(self) -> Optional[Row[_TP]]:
  147. """Fetch one row.
  148. When all rows are exhausted, returns None.
  149. This method is provided for backwards compatibility with
  150. SQLAlchemy 1.x.x.
  151. To fetch the first row of a result only, use the
  152. :meth:`_asyncio.AsyncResult.first` method. To iterate through all
  153. rows, iterate the :class:`_asyncio.AsyncResult` object directly.
  154. :return: a :class:`_engine.Row` object if no filters are applied,
  155. or ``None`` if no rows remain.
  156. """
  157. row = await greenlet_spawn(self._onerow_getter, self)
  158. if row is _NO_ROW:
  159. return None
  160. else:
  161. return row
  162. async def fetchmany(
  163. self, size: Optional[int] = None
  164. ) -> Sequence[Row[_TP]]:
  165. """Fetch many rows.
  166. When all rows are exhausted, returns an empty list.
  167. This method is provided for backwards compatibility with
  168. SQLAlchemy 1.x.x.
  169. To fetch rows in groups, use the
  170. :meth:`._asyncio.AsyncResult.partitions` method.
  171. :return: a list of :class:`_engine.Row` objects.
  172. .. seealso::
  173. :meth:`_asyncio.AsyncResult.partitions`
  174. """
  175. return await greenlet_spawn(self._manyrow_getter, self, size)
  176. async def all(self) -> Sequence[Row[_TP]]:
  177. """Return all rows in a list.
  178. Closes the result set after invocation. Subsequent invocations
  179. will return an empty list.
  180. :return: a list of :class:`_engine.Row` objects.
  181. """
  182. return await greenlet_spawn(self._allrows)
  183. def __aiter__(self) -> AsyncResult[_TP]:
  184. return self
  185. async def __anext__(self) -> Row[_TP]:
  186. row = await greenlet_spawn(self._onerow_getter, self)
  187. if row is _NO_ROW:
  188. raise StopAsyncIteration()
  189. else:
  190. return row
  191. async def first(self) -> Optional[Row[_TP]]:
  192. """Fetch the first row or ``None`` if no row is present.
  193. Closes the result set and discards remaining rows.
  194. .. note:: This method returns one **row**, e.g. tuple, by default.
  195. To return exactly one single scalar value, that is, the first
  196. column of the first row, use the
  197. :meth:`_asyncio.AsyncResult.scalar` method,
  198. or combine :meth:`_asyncio.AsyncResult.scalars` and
  199. :meth:`_asyncio.AsyncResult.first`.
  200. Additionally, in contrast to the behavior of the legacy ORM
  201. :meth:`_orm.Query.first` method, **no limit is applied** to the
  202. SQL query which was invoked to produce this
  203. :class:`_asyncio.AsyncResult`;
  204. for a DBAPI driver that buffers results in memory before yielding
  205. rows, all rows will be sent to the Python process and all but
  206. the first row will be discarded.
  207. .. seealso::
  208. :ref:`migration_20_unify_select`
  209. :return: a :class:`_engine.Row` object, or None
  210. if no rows remain.
  211. .. seealso::
  212. :meth:`_asyncio.AsyncResult.scalar`
  213. :meth:`_asyncio.AsyncResult.one`
  214. """
  215. return await greenlet_spawn(self._only_one_row, False, False, False)
  216. async def one_or_none(self) -> Optional[Row[_TP]]:
  217. """Return at most one result or raise an exception.
  218. Returns ``None`` if the result has no rows.
  219. Raises :class:`.MultipleResultsFound`
  220. if multiple rows are returned.
  221. .. versionadded:: 1.4
  222. :return: The first :class:`_engine.Row` or ``None`` if no row
  223. is available.
  224. :raises: :class:`.MultipleResultsFound`
  225. .. seealso::
  226. :meth:`_asyncio.AsyncResult.first`
  227. :meth:`_asyncio.AsyncResult.one`
  228. """
  229. return await greenlet_spawn(self._only_one_row, True, False, False)
  230. @overload
  231. async def scalar_one(self: AsyncResult[Tuple[_T]]) -> _T: ...
  232. @overload
  233. async def scalar_one(self) -> Any: ...
  234. async def scalar_one(self) -> Any:
  235. """Return exactly one scalar result or raise an exception.
  236. This is equivalent to calling :meth:`_asyncio.AsyncResult.scalars` and
  237. then :meth:`_asyncio.AsyncScalarResult.one`.
  238. .. seealso::
  239. :meth:`_asyncio.AsyncScalarResult.one`
  240. :meth:`_asyncio.AsyncResult.scalars`
  241. """
  242. return await greenlet_spawn(self._only_one_row, True, True, True)
  243. @overload
  244. async def scalar_one_or_none(
  245. self: AsyncResult[Tuple[_T]],
  246. ) -> Optional[_T]: ...
  247. @overload
  248. async def scalar_one_or_none(self) -> Optional[Any]: ...
  249. async def scalar_one_or_none(self) -> Optional[Any]:
  250. """Return exactly one scalar result or ``None``.
  251. This is equivalent to calling :meth:`_asyncio.AsyncResult.scalars` and
  252. then :meth:`_asyncio.AsyncScalarResult.one_or_none`.
  253. .. seealso::
  254. :meth:`_asyncio.AsyncScalarResult.one_or_none`
  255. :meth:`_asyncio.AsyncResult.scalars`
  256. """
  257. return await greenlet_spawn(self._only_one_row, True, False, True)
  258. async def one(self) -> Row[_TP]:
  259. """Return exactly one row or raise an exception.
  260. Raises :class:`.NoResultFound` if the result returns no
  261. rows, or :class:`.MultipleResultsFound` if multiple rows
  262. would be returned.
  263. .. note:: This method returns one **row**, e.g. tuple, by default.
  264. To return exactly one single scalar value, that is, the first
  265. column of the first row, use the
  266. :meth:`_asyncio.AsyncResult.scalar_one` method, or combine
  267. :meth:`_asyncio.AsyncResult.scalars` and
  268. :meth:`_asyncio.AsyncResult.one`.
  269. .. versionadded:: 1.4
  270. :return: The first :class:`_engine.Row`.
  271. :raises: :class:`.MultipleResultsFound`, :class:`.NoResultFound`
  272. .. seealso::
  273. :meth:`_asyncio.AsyncResult.first`
  274. :meth:`_asyncio.AsyncResult.one_or_none`
  275. :meth:`_asyncio.AsyncResult.scalar_one`
  276. """
  277. return await greenlet_spawn(self._only_one_row, True, True, False)
  278. @overload
  279. async def scalar(self: AsyncResult[Tuple[_T]]) -> Optional[_T]: ...
  280. @overload
  281. async def scalar(self) -> Any: ...
  282. async def scalar(self) -> Any:
  283. """Fetch the first column of the first row, and close the result set.
  284. Returns ``None`` if there are no rows to fetch.
  285. No validation is performed to test if additional rows remain.
  286. After calling this method, the object is fully closed,
  287. e.g. the :meth:`_engine.CursorResult.close`
  288. method will have been called.
  289. :return: a Python scalar value, or ``None`` if no rows remain.
  290. """
  291. return await greenlet_spawn(self._only_one_row, False, False, True)
  292. async def freeze(self) -> FrozenResult[_TP]:
  293. """Return a callable object that will produce copies of this
  294. :class:`_asyncio.AsyncResult` when invoked.
  295. The callable object returned is an instance of
  296. :class:`_engine.FrozenResult`.
  297. This is used for result set caching. The method must be called
  298. on the result when it has been unconsumed, and calling the method
  299. will consume the result fully. When the :class:`_engine.FrozenResult`
  300. is retrieved from a cache, it can be called any number of times where
  301. it will produce a new :class:`_engine.Result` object each time
  302. against its stored set of rows.
  303. .. seealso::
  304. :ref:`do_orm_execute_re_executing` - example usage within the
  305. ORM to implement a result-set cache.
  306. """
  307. return await greenlet_spawn(FrozenResult, self)
  308. @overload
  309. def scalars(
  310. self: AsyncResult[Tuple[_T]], index: Literal[0]
  311. ) -> AsyncScalarResult[_T]: ...
  312. @overload
  313. def scalars(self: AsyncResult[Tuple[_T]]) -> AsyncScalarResult[_T]: ...
  314. @overload
  315. def scalars(self, index: _KeyIndexType = 0) -> AsyncScalarResult[Any]: ...
  316. def scalars(self, index: _KeyIndexType = 0) -> AsyncScalarResult[Any]:
  317. """Return an :class:`_asyncio.AsyncScalarResult` filtering object which
  318. will return single elements rather than :class:`_row.Row` objects.
  319. Refer to :meth:`_result.Result.scalars` in the synchronous
  320. SQLAlchemy API for a complete behavioral description.
  321. :param index: integer or row key indicating the column to be fetched
  322. from each row, defaults to ``0`` indicating the first column.
  323. :return: a new :class:`_asyncio.AsyncScalarResult` filtering object
  324. referring to this :class:`_asyncio.AsyncResult` object.
  325. """
  326. return AsyncScalarResult(self._real_result, index)
  327. def mappings(self) -> AsyncMappingResult:
  328. """Apply a mappings filter to returned rows, returning an instance of
  329. :class:`_asyncio.AsyncMappingResult`.
  330. When this filter is applied, fetching rows will return
  331. :class:`_engine.RowMapping` objects instead of :class:`_engine.Row`
  332. objects.
  333. :return: a new :class:`_asyncio.AsyncMappingResult` filtering object
  334. referring to the underlying :class:`_result.Result` object.
  335. """
  336. return AsyncMappingResult(self._real_result)
  337. class AsyncScalarResult(AsyncCommon[_R]):
  338. """A wrapper for a :class:`_asyncio.AsyncResult` that returns scalar values
  339. rather than :class:`_row.Row` values.
  340. The :class:`_asyncio.AsyncScalarResult` object is acquired by calling the
  341. :meth:`_asyncio.AsyncResult.scalars` method.
  342. Refer to the :class:`_result.ScalarResult` object in the synchronous
  343. SQLAlchemy API for a complete behavioral description.
  344. .. versionadded:: 1.4
  345. """
  346. __slots__ = ()
  347. _generate_rows = False
  348. def __init__(self, real_result: Result[Any], index: _KeyIndexType):
  349. self._real_result = real_result
  350. if real_result._source_supports_scalars:
  351. self._metadata = real_result._metadata
  352. self._post_creational_filter = None
  353. else:
  354. self._metadata = real_result._metadata._reduce([index])
  355. self._post_creational_filter = operator.itemgetter(0)
  356. self._unique_filter_state = real_result._unique_filter_state
  357. def unique(
  358. self,
  359. strategy: Optional[_UniqueFilterType] = None,
  360. ) -> Self:
  361. """Apply unique filtering to the objects returned by this
  362. :class:`_asyncio.AsyncScalarResult`.
  363. See :meth:`_asyncio.AsyncResult.unique` for usage details.
  364. """
  365. self._unique_filter_state = (set(), strategy)
  366. return self
  367. async def partitions(
  368. self, size: Optional[int] = None
  369. ) -> AsyncIterator[Sequence[_R]]:
  370. """Iterate through sub-lists of elements of the size given.
  371. Equivalent to :meth:`_asyncio.AsyncResult.partitions` except that
  372. scalar values, rather than :class:`_engine.Row` objects,
  373. are returned.
  374. """
  375. getter = self._manyrow_getter
  376. while True:
  377. partition = await greenlet_spawn(getter, self, size)
  378. if partition:
  379. yield partition
  380. else:
  381. break
  382. async def fetchall(self) -> Sequence[_R]:
  383. """A synonym for the :meth:`_asyncio.AsyncScalarResult.all` method."""
  384. return await greenlet_spawn(self._allrows)
  385. async def fetchmany(self, size: Optional[int] = None) -> Sequence[_R]:
  386. """Fetch many objects.
  387. Equivalent to :meth:`_asyncio.AsyncResult.fetchmany` except that
  388. scalar values, rather than :class:`_engine.Row` objects,
  389. are returned.
  390. """
  391. return await greenlet_spawn(self._manyrow_getter, self, size)
  392. async def all(self) -> Sequence[_R]:
  393. """Return all scalar values in a list.
  394. Equivalent to :meth:`_asyncio.AsyncResult.all` except that
  395. scalar values, rather than :class:`_engine.Row` objects,
  396. are returned.
  397. """
  398. return await greenlet_spawn(self._allrows)
  399. def __aiter__(self) -> AsyncScalarResult[_R]:
  400. return self
  401. async def __anext__(self) -> _R:
  402. row = await greenlet_spawn(self._onerow_getter, self)
  403. if row is _NO_ROW:
  404. raise StopAsyncIteration()
  405. else:
  406. return row
  407. async def first(self) -> Optional[_R]:
  408. """Fetch the first object or ``None`` if no object is present.
  409. Equivalent to :meth:`_asyncio.AsyncResult.first` except that
  410. scalar values, rather than :class:`_engine.Row` objects,
  411. are returned.
  412. """
  413. return await greenlet_spawn(self._only_one_row, False, False, False)
  414. async def one_or_none(self) -> Optional[_R]:
  415. """Return at most one object or raise an exception.
  416. Equivalent to :meth:`_asyncio.AsyncResult.one_or_none` except that
  417. scalar values, rather than :class:`_engine.Row` objects,
  418. are returned.
  419. """
  420. return await greenlet_spawn(self._only_one_row, True, False, False)
  421. async def one(self) -> _R:
  422. """Return exactly one object or raise an exception.
  423. Equivalent to :meth:`_asyncio.AsyncResult.one` except that
  424. scalar values, rather than :class:`_engine.Row` objects,
  425. are returned.
  426. """
  427. return await greenlet_spawn(self._only_one_row, True, True, False)
  428. class AsyncMappingResult(_WithKeys, AsyncCommon[RowMapping]):
  429. """A wrapper for a :class:`_asyncio.AsyncResult` that returns dictionary
  430. values rather than :class:`_engine.Row` values.
  431. The :class:`_asyncio.AsyncMappingResult` object is acquired by calling the
  432. :meth:`_asyncio.AsyncResult.mappings` method.
  433. Refer to the :class:`_result.MappingResult` object in the synchronous
  434. SQLAlchemy API for a complete behavioral description.
  435. .. versionadded:: 1.4
  436. """
  437. __slots__ = ()
  438. _generate_rows = True
  439. _post_creational_filter = operator.attrgetter("_mapping")
  440. def __init__(self, result: Result[Any]):
  441. self._real_result = result
  442. self._unique_filter_state = result._unique_filter_state
  443. self._metadata = result._metadata
  444. if result._source_supports_scalars:
  445. self._metadata = self._metadata._reduce([0])
  446. def unique(
  447. self,
  448. strategy: Optional[_UniqueFilterType] = None,
  449. ) -> Self:
  450. """Apply unique filtering to the objects returned by this
  451. :class:`_asyncio.AsyncMappingResult`.
  452. See :meth:`_asyncio.AsyncResult.unique` for usage details.
  453. """
  454. self._unique_filter_state = (set(), strategy)
  455. return self
  456. def columns(self, *col_expressions: _KeyIndexType) -> Self:
  457. r"""Establish the columns that should be returned in each row."""
  458. return self._column_slices(col_expressions)
  459. async def partitions(
  460. self, size: Optional[int] = None
  461. ) -> AsyncIterator[Sequence[RowMapping]]:
  462. """Iterate through sub-lists of elements of the size given.
  463. Equivalent to :meth:`_asyncio.AsyncResult.partitions` except that
  464. :class:`_engine.RowMapping` values, rather than :class:`_engine.Row`
  465. objects, are returned.
  466. """
  467. getter = self._manyrow_getter
  468. while True:
  469. partition = await greenlet_spawn(getter, self, size)
  470. if partition:
  471. yield partition
  472. else:
  473. break
  474. async def fetchall(self) -> Sequence[RowMapping]:
  475. """A synonym for the :meth:`_asyncio.AsyncMappingResult.all` method."""
  476. return await greenlet_spawn(self._allrows)
  477. async def fetchone(self) -> Optional[RowMapping]:
  478. """Fetch one object.
  479. Equivalent to :meth:`_asyncio.AsyncResult.fetchone` except that
  480. :class:`_engine.RowMapping` values, rather than :class:`_engine.Row`
  481. objects, are returned.
  482. """
  483. row = await greenlet_spawn(self._onerow_getter, self)
  484. if row is _NO_ROW:
  485. return None
  486. else:
  487. return row
  488. async def fetchmany(
  489. self, size: Optional[int] = None
  490. ) -> Sequence[RowMapping]:
  491. """Fetch many rows.
  492. Equivalent to :meth:`_asyncio.AsyncResult.fetchmany` except that
  493. :class:`_engine.RowMapping` values, rather than :class:`_engine.Row`
  494. objects, are returned.
  495. """
  496. return await greenlet_spawn(self._manyrow_getter, self, size)
  497. async def all(self) -> Sequence[RowMapping]:
  498. """Return all rows in a list.
  499. Equivalent to :meth:`_asyncio.AsyncResult.all` except that
  500. :class:`_engine.RowMapping` values, rather than :class:`_engine.Row`
  501. objects, are returned.
  502. """
  503. return await greenlet_spawn(self._allrows)
  504. def __aiter__(self) -> AsyncMappingResult:
  505. return self
  506. async def __anext__(self) -> RowMapping:
  507. row = await greenlet_spawn(self._onerow_getter, self)
  508. if row is _NO_ROW:
  509. raise StopAsyncIteration()
  510. else:
  511. return row
  512. async def first(self) -> Optional[RowMapping]:
  513. """Fetch the first object or ``None`` if no object is present.
  514. Equivalent to :meth:`_asyncio.AsyncResult.first` except that
  515. :class:`_engine.RowMapping` values, rather than :class:`_engine.Row`
  516. objects, are returned.
  517. """
  518. return await greenlet_spawn(self._only_one_row, False, False, False)
  519. async def one_or_none(self) -> Optional[RowMapping]:
  520. """Return at most one object or raise an exception.
  521. Equivalent to :meth:`_asyncio.AsyncResult.one_or_none` except that
  522. :class:`_engine.RowMapping` values, rather than :class:`_engine.Row`
  523. objects, are returned.
  524. """
  525. return await greenlet_spawn(self._only_one_row, True, False, False)
  526. async def one(self) -> RowMapping:
  527. """Return exactly one object or raise an exception.
  528. Equivalent to :meth:`_asyncio.AsyncResult.one` except that
  529. :class:`_engine.RowMapping` values, rather than :class:`_engine.Row`
  530. objects, are returned.
  531. """
  532. return await greenlet_spawn(self._only_one_row, True, True, False)
  533. class AsyncTupleResult(AsyncCommon[_R], util.TypingOnly):
  534. """A :class:`_asyncio.AsyncResult` that's typed as returning plain
  535. Python tuples instead of rows.
  536. Since :class:`_engine.Row` acts like a tuple in every way already,
  537. this class is a typing only class, regular :class:`_asyncio.AsyncResult` is
  538. still used at runtime.
  539. """
  540. __slots__ = ()
  541. if TYPE_CHECKING:
  542. async def partitions(
  543. self, size: Optional[int] = None
  544. ) -> AsyncIterator[Sequence[_R]]:
  545. """Iterate through sub-lists of elements of the size given.
  546. Equivalent to :meth:`_result.Result.partitions` except that
  547. tuple values, rather than :class:`_engine.Row` objects,
  548. are returned.
  549. """
  550. ...
  551. async def fetchone(self) -> Optional[_R]:
  552. """Fetch one tuple.
  553. Equivalent to :meth:`_result.Result.fetchone` except that
  554. tuple values, rather than :class:`_engine.Row`
  555. objects, are returned.
  556. """
  557. ...
  558. async def fetchall(self) -> Sequence[_R]:
  559. """A synonym for the :meth:`_engine.ScalarResult.all` method."""
  560. ...
  561. async def fetchmany(self, size: Optional[int] = None) -> Sequence[_R]:
  562. """Fetch many objects.
  563. Equivalent to :meth:`_result.Result.fetchmany` except that
  564. tuple values, rather than :class:`_engine.Row` objects,
  565. are returned.
  566. """
  567. ...
  568. async def all(self) -> Sequence[_R]: # noqa: A001
  569. """Return all scalar values in a list.
  570. Equivalent to :meth:`_result.Result.all` except that
  571. tuple values, rather than :class:`_engine.Row` objects,
  572. are returned.
  573. """
  574. ...
  575. def __aiter__(self) -> AsyncIterator[_R]: ...
  576. async def __anext__(self) -> _R: ...
  577. async def first(self) -> Optional[_R]:
  578. """Fetch the first object or ``None`` if no object is present.
  579. Equivalent to :meth:`_result.Result.first` except that
  580. tuple values, rather than :class:`_engine.Row` objects,
  581. are returned.
  582. """
  583. ...
  584. async def one_or_none(self) -> Optional[_R]:
  585. """Return at most one object or raise an exception.
  586. Equivalent to :meth:`_result.Result.one_or_none` except that
  587. tuple values, rather than :class:`_engine.Row` objects,
  588. are returned.
  589. """
  590. ...
  591. async def one(self) -> _R:
  592. """Return exactly one object or raise an exception.
  593. Equivalent to :meth:`_result.Result.one` except that
  594. tuple values, rather than :class:`_engine.Row` objects,
  595. are returned.
  596. """
  597. ...
  598. @overload
  599. async def scalar_one(self: AsyncTupleResult[Tuple[_T]]) -> _T: ...
  600. @overload
  601. async def scalar_one(self) -> Any: ...
  602. async def scalar_one(self) -> Any:
  603. """Return exactly one scalar result or raise an exception.
  604. This is equivalent to calling :meth:`_engine.Result.scalars`
  605. and then :meth:`_engine.AsyncScalarResult.one`.
  606. .. seealso::
  607. :meth:`_engine.AsyncScalarResult.one`
  608. :meth:`_engine.Result.scalars`
  609. """
  610. ...
  611. @overload
  612. async def scalar_one_or_none(
  613. self: AsyncTupleResult[Tuple[_T]],
  614. ) -> Optional[_T]: ...
  615. @overload
  616. async def scalar_one_or_none(self) -> Optional[Any]: ...
  617. async def scalar_one_or_none(self) -> Optional[Any]:
  618. """Return exactly one or no scalar result.
  619. This is equivalent to calling :meth:`_engine.Result.scalars`
  620. and then :meth:`_engine.AsyncScalarResult.one_or_none`.
  621. .. seealso::
  622. :meth:`_engine.AsyncScalarResult.one_or_none`
  623. :meth:`_engine.Result.scalars`
  624. """
  625. ...
  626. @overload
  627. async def scalar(
  628. self: AsyncTupleResult[Tuple[_T]],
  629. ) -> Optional[_T]: ...
  630. @overload
  631. async def scalar(self) -> Any: ...
  632. async def scalar(self) -> Any:
  633. """Fetch the first column of the first row, and close the result
  634. set.
  635. Returns ``None`` if there are no rows to fetch.
  636. No validation is performed to test if additional rows remain.
  637. After calling this method, the object is fully closed,
  638. e.g. the :meth:`_engine.CursorResult.close`
  639. method will have been called.
  640. :return: a Python scalar value , or ``None`` if no rows remain.
  641. """
  642. ...
  643. _RT = TypeVar("_RT", bound="Result[Any]")
  644. async def _ensure_sync_result(result: _RT, calling_method: Any) -> _RT:
  645. cursor_result: CursorResult[Any]
  646. try:
  647. is_cursor = result._is_cursor
  648. except AttributeError:
  649. # legacy execute(DefaultGenerator) case
  650. return result
  651. if not is_cursor:
  652. cursor_result = getattr(result, "raw", None) # type: ignore
  653. else:
  654. cursor_result = result # type: ignore
  655. if cursor_result and cursor_result.context._is_server_side:
  656. await greenlet_spawn(cursor_result.close)
  657. raise async_exc.AsyncMethodRequired(
  658. "Can't use the %s.%s() method with a "
  659. "server-side cursor. "
  660. "Use the %s.stream() method for an async "
  661. "streaming result set."
  662. % (
  663. calling_method.__self__.__class__.__name__,
  664. calling_method.__name__,
  665. calling_method.__self__.__class__.__name__,
  666. )
  667. )
  668. return result