engine.py 47 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469
  1. # ext/asyncio/engine.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 asyncio
  9. import contextlib
  10. from typing import Any
  11. from typing import AsyncIterator
  12. from typing import Callable
  13. from typing import Dict
  14. from typing import Generator
  15. from typing import NoReturn
  16. from typing import Optional
  17. from typing import overload
  18. from typing import Tuple
  19. from typing import Type
  20. from typing import TYPE_CHECKING
  21. from typing import TypeVar
  22. from typing import Union
  23. from . import exc as async_exc
  24. from .base import asyncstartablecontext
  25. from .base import GeneratorStartableContext
  26. from .base import ProxyComparable
  27. from .base import StartableContext
  28. from .result import _ensure_sync_result
  29. from .result import AsyncResult
  30. from .result import AsyncScalarResult
  31. from ... import exc
  32. from ... import inspection
  33. from ... import util
  34. from ...engine import Connection
  35. from ...engine import create_engine as _create_engine
  36. from ...engine import create_pool_from_url as _create_pool_from_url
  37. from ...engine import Engine
  38. from ...engine.base import NestedTransaction
  39. from ...engine.base import Transaction
  40. from ...exc import ArgumentError
  41. from ...util.concurrency import greenlet_spawn
  42. from ...util.typing import Concatenate
  43. from ...util.typing import ParamSpec
  44. if TYPE_CHECKING:
  45. from ...engine.cursor import CursorResult
  46. from ...engine.interfaces import _CoreAnyExecuteParams
  47. from ...engine.interfaces import _CoreSingleExecuteParams
  48. from ...engine.interfaces import _DBAPIAnyExecuteParams
  49. from ...engine.interfaces import _ExecuteOptions
  50. from ...engine.interfaces import CompiledCacheType
  51. from ...engine.interfaces import CoreExecuteOptionsParameter
  52. from ...engine.interfaces import Dialect
  53. from ...engine.interfaces import IsolationLevel
  54. from ...engine.interfaces import SchemaTranslateMapType
  55. from ...engine.result import ScalarResult
  56. from ...engine.url import URL
  57. from ...pool import Pool
  58. from ...pool import PoolProxiedConnection
  59. from ...sql._typing import _InfoType
  60. from ...sql.base import Executable
  61. from ...sql.selectable import TypedReturnsRows
  62. _P = ParamSpec("_P")
  63. _T = TypeVar("_T", bound=Any)
  64. def create_async_engine(url: Union[str, URL], **kw: Any) -> AsyncEngine:
  65. """Create a new async engine instance.
  66. Arguments passed to :func:`_asyncio.create_async_engine` are mostly
  67. identical to those passed to the :func:`_sa.create_engine` function.
  68. The specified dialect must be an asyncio-compatible dialect
  69. such as :ref:`dialect-postgresql-asyncpg`.
  70. .. versionadded:: 1.4
  71. :param async_creator: an async callable which returns a driver-level
  72. asyncio connection. If given, the function should take no arguments,
  73. and return a new asyncio connection from the underlying asyncio
  74. database driver; the connection will be wrapped in the appropriate
  75. structures to be used with the :class:`.AsyncEngine`. Note that the
  76. parameters specified in the URL are not applied here, and the creator
  77. function should use its own connection parameters.
  78. This parameter is the asyncio equivalent of the
  79. :paramref:`_sa.create_engine.creator` parameter of the
  80. :func:`_sa.create_engine` function.
  81. .. versionadded:: 2.0.16
  82. """
  83. if kw.get("server_side_cursors", False):
  84. raise async_exc.AsyncMethodRequired(
  85. "Can't set server_side_cursors for async engine globally; "
  86. "use the connection.stream() method for an async "
  87. "streaming result set"
  88. )
  89. kw["_is_async"] = True
  90. async_creator = kw.pop("async_creator", None)
  91. if async_creator:
  92. if kw.get("creator", None):
  93. raise ArgumentError(
  94. "Can only specify one of 'async_creator' or 'creator', "
  95. "not both."
  96. )
  97. def creator() -> Any:
  98. # note that to send adapted arguments like
  99. # prepared_statement_cache_size, user would use
  100. # "creator" and emulate this form here
  101. return sync_engine.dialect.dbapi.connect( # type: ignore
  102. async_creator_fn=async_creator
  103. )
  104. kw["creator"] = creator
  105. sync_engine = _create_engine(url, **kw)
  106. return AsyncEngine(sync_engine)
  107. def async_engine_from_config(
  108. configuration: Dict[str, Any], prefix: str = "sqlalchemy.", **kwargs: Any
  109. ) -> AsyncEngine:
  110. """Create a new AsyncEngine instance using a configuration dictionary.
  111. This function is analogous to the :func:`_sa.engine_from_config` function
  112. in SQLAlchemy Core, except that the requested dialect must be an
  113. asyncio-compatible dialect such as :ref:`dialect-postgresql-asyncpg`.
  114. The argument signature of the function is identical to that
  115. of :func:`_sa.engine_from_config`.
  116. .. versionadded:: 1.4.29
  117. """
  118. options = {
  119. key[len(prefix) :]: value
  120. for key, value in configuration.items()
  121. if key.startswith(prefix)
  122. }
  123. options["_coerce_config"] = True
  124. options.update(kwargs)
  125. url = options.pop("url")
  126. return create_async_engine(url, **options)
  127. def create_async_pool_from_url(url: Union[str, URL], **kwargs: Any) -> Pool:
  128. """Create a new async engine instance.
  129. Arguments passed to :func:`_asyncio.create_async_pool_from_url` are mostly
  130. identical to those passed to the :func:`_sa.create_pool_from_url` function.
  131. The specified dialect must be an asyncio-compatible dialect
  132. such as :ref:`dialect-postgresql-asyncpg`.
  133. .. versionadded:: 2.0.10
  134. """
  135. kwargs["_is_async"] = True
  136. return _create_pool_from_url(url, **kwargs)
  137. class AsyncConnectable:
  138. __slots__ = "_slots_dispatch", "__weakref__"
  139. @classmethod
  140. def _no_async_engine_events(cls) -> NoReturn:
  141. raise NotImplementedError(
  142. "asynchronous events are not implemented at this time. Apply "
  143. "synchronous listeners to the AsyncEngine.sync_engine or "
  144. "AsyncConnection.sync_connection attributes."
  145. )
  146. @util.create_proxy_methods(
  147. Connection,
  148. ":class:`_engine.Connection`",
  149. ":class:`_asyncio.AsyncConnection`",
  150. classmethods=[],
  151. methods=[],
  152. attributes=[
  153. "closed",
  154. "invalidated",
  155. "dialect",
  156. "default_isolation_level",
  157. ],
  158. )
  159. class AsyncConnection(
  160. ProxyComparable[Connection],
  161. StartableContext["AsyncConnection"],
  162. AsyncConnectable,
  163. ):
  164. """An asyncio proxy for a :class:`_engine.Connection`.
  165. :class:`_asyncio.AsyncConnection` is acquired using the
  166. :meth:`_asyncio.AsyncEngine.connect`
  167. method of :class:`_asyncio.AsyncEngine`::
  168. from sqlalchemy.ext.asyncio import create_async_engine
  169. engine = create_async_engine("postgresql+asyncpg://user:pass@host/dbname")
  170. async with engine.connect() as conn:
  171. result = await conn.execute(select(table))
  172. .. versionadded:: 1.4
  173. """ # noqa
  174. # AsyncConnection is a thin proxy; no state should be added here
  175. # that is not retrievable from the "sync" engine / connection, e.g.
  176. # current transaction, info, etc. It should be possible to
  177. # create a new AsyncConnection that matches this one given only the
  178. # "sync" elements.
  179. __slots__ = (
  180. "engine",
  181. "sync_engine",
  182. "sync_connection",
  183. )
  184. def __init__(
  185. self,
  186. async_engine: AsyncEngine,
  187. sync_connection: Optional[Connection] = None,
  188. ):
  189. self.engine = async_engine
  190. self.sync_engine = async_engine.sync_engine
  191. self.sync_connection = self._assign_proxied(sync_connection)
  192. sync_connection: Optional[Connection]
  193. """Reference to the sync-style :class:`_engine.Connection` this
  194. :class:`_asyncio.AsyncConnection` proxies requests towards.
  195. This instance can be used as an event target.
  196. .. seealso::
  197. :ref:`asyncio_events`
  198. """
  199. sync_engine: Engine
  200. """Reference to the sync-style :class:`_engine.Engine` this
  201. :class:`_asyncio.AsyncConnection` is associated with via its underlying
  202. :class:`_engine.Connection`.
  203. This instance can be used as an event target.
  204. .. seealso::
  205. :ref:`asyncio_events`
  206. """
  207. @classmethod
  208. def _regenerate_proxy_for_target(
  209. cls, target: Connection, **additional_kw: Any # noqa: U100
  210. ) -> AsyncConnection:
  211. return AsyncConnection(
  212. AsyncEngine._retrieve_proxy_for_target(target.engine), target
  213. )
  214. async def start(
  215. self, is_ctxmanager: bool = False # noqa: U100
  216. ) -> AsyncConnection:
  217. """Start this :class:`_asyncio.AsyncConnection` object's context
  218. outside of using a Python ``with:`` block.
  219. """
  220. if self.sync_connection:
  221. raise exc.InvalidRequestError("connection is already started")
  222. self.sync_connection = self._assign_proxied(
  223. await greenlet_spawn(self.sync_engine.connect)
  224. )
  225. return self
  226. @property
  227. def connection(self) -> NoReturn:
  228. """Not implemented for async; call
  229. :meth:`_asyncio.AsyncConnection.get_raw_connection`.
  230. """
  231. raise exc.InvalidRequestError(
  232. "AsyncConnection.connection accessor is not implemented as the "
  233. "attribute may need to reconnect on an invalidated connection. "
  234. "Use the get_raw_connection() method."
  235. )
  236. async def get_raw_connection(self) -> PoolProxiedConnection:
  237. """Return the pooled DBAPI-level connection in use by this
  238. :class:`_asyncio.AsyncConnection`.
  239. This is a SQLAlchemy connection-pool proxied connection
  240. which then has the attribute
  241. :attr:`_pool._ConnectionFairy.driver_connection` that refers to the
  242. actual driver connection. Its
  243. :attr:`_pool._ConnectionFairy.dbapi_connection` refers instead
  244. to an :class:`_engine.AdaptedConnection` instance that
  245. adapts the driver connection to the DBAPI protocol.
  246. """
  247. return await greenlet_spawn(getattr, self._proxied, "connection")
  248. @util.ro_non_memoized_property
  249. def info(self) -> _InfoType:
  250. """Return the :attr:`_engine.Connection.info` dictionary of the
  251. underlying :class:`_engine.Connection`.
  252. This dictionary is freely writable for user-defined state to be
  253. associated with the database connection.
  254. This attribute is only available if the :class:`.AsyncConnection` is
  255. currently connected. If the :attr:`.AsyncConnection.closed` attribute
  256. is ``True``, then accessing this attribute will raise
  257. :class:`.ResourceClosedError`.
  258. .. versionadded:: 1.4.0b2
  259. """
  260. return self._proxied.info
  261. @util.ro_non_memoized_property
  262. def _proxied(self) -> Connection:
  263. if not self.sync_connection:
  264. self._raise_for_not_started()
  265. return self.sync_connection
  266. def begin(self) -> AsyncTransaction:
  267. """Begin a transaction prior to autobegin occurring."""
  268. assert self._proxied
  269. return AsyncTransaction(self)
  270. def begin_nested(self) -> AsyncTransaction:
  271. """Begin a nested transaction and return a transaction handle."""
  272. assert self._proxied
  273. return AsyncTransaction(self, nested=True)
  274. async def invalidate(
  275. self, exception: Optional[BaseException] = None
  276. ) -> None:
  277. """Invalidate the underlying DBAPI connection associated with
  278. this :class:`_engine.Connection`.
  279. See the method :meth:`_engine.Connection.invalidate` for full
  280. detail on this method.
  281. """
  282. return await greenlet_spawn(
  283. self._proxied.invalidate, exception=exception
  284. )
  285. async def get_isolation_level(self) -> IsolationLevel:
  286. return await greenlet_spawn(self._proxied.get_isolation_level)
  287. def in_transaction(self) -> bool:
  288. """Return True if a transaction is in progress."""
  289. return self._proxied.in_transaction()
  290. def in_nested_transaction(self) -> bool:
  291. """Return True if a transaction is in progress.
  292. .. versionadded:: 1.4.0b2
  293. """
  294. return self._proxied.in_nested_transaction()
  295. def get_transaction(self) -> Optional[AsyncTransaction]:
  296. """Return an :class:`.AsyncTransaction` representing the current
  297. transaction, if any.
  298. This makes use of the underlying synchronous connection's
  299. :meth:`_engine.Connection.get_transaction` method to get the current
  300. :class:`_engine.Transaction`, which is then proxied in a new
  301. :class:`.AsyncTransaction` object.
  302. .. versionadded:: 1.4.0b2
  303. """
  304. trans = self._proxied.get_transaction()
  305. if trans is not None:
  306. return AsyncTransaction._retrieve_proxy_for_target(trans)
  307. else:
  308. return None
  309. def get_nested_transaction(self) -> Optional[AsyncTransaction]:
  310. """Return an :class:`.AsyncTransaction` representing the current
  311. nested (savepoint) transaction, if any.
  312. This makes use of the underlying synchronous connection's
  313. :meth:`_engine.Connection.get_nested_transaction` method to get the
  314. current :class:`_engine.Transaction`, which is then proxied in a new
  315. :class:`.AsyncTransaction` object.
  316. .. versionadded:: 1.4.0b2
  317. """
  318. trans = self._proxied.get_nested_transaction()
  319. if trans is not None:
  320. return AsyncTransaction._retrieve_proxy_for_target(trans)
  321. else:
  322. return None
  323. @overload
  324. async def execution_options(
  325. self,
  326. *,
  327. compiled_cache: Optional[CompiledCacheType] = ...,
  328. logging_token: str = ...,
  329. isolation_level: IsolationLevel = ...,
  330. no_parameters: bool = False,
  331. stream_results: bool = False,
  332. max_row_buffer: int = ...,
  333. yield_per: int = ...,
  334. insertmanyvalues_page_size: int = ...,
  335. schema_translate_map: Optional[SchemaTranslateMapType] = ...,
  336. preserve_rowcount: bool = False,
  337. **opt: Any,
  338. ) -> AsyncConnection: ...
  339. @overload
  340. async def execution_options(self, **opt: Any) -> AsyncConnection: ...
  341. async def execution_options(self, **opt: Any) -> AsyncConnection:
  342. r"""Set non-SQL options for the connection which take effect
  343. during execution.
  344. This returns this :class:`_asyncio.AsyncConnection` object with
  345. the new options added.
  346. See :meth:`_engine.Connection.execution_options` for full details
  347. on this method.
  348. """
  349. conn = self._proxied
  350. c2 = await greenlet_spawn(conn.execution_options, **opt)
  351. assert c2 is conn
  352. return self
  353. async def commit(self) -> None:
  354. """Commit the transaction that is currently in progress.
  355. This method commits the current transaction if one has been started.
  356. If no transaction was started, the method has no effect, assuming
  357. the connection is in a non-invalidated state.
  358. A transaction is begun on a :class:`_engine.Connection` automatically
  359. whenever a statement is first executed, or when the
  360. :meth:`_engine.Connection.begin` method is called.
  361. """
  362. await greenlet_spawn(self._proxied.commit)
  363. async def rollback(self) -> None:
  364. """Roll back the transaction that is currently in progress.
  365. This method rolls back the current transaction if one has been started.
  366. If no transaction was started, the method has no effect. If a
  367. transaction was started and the connection is in an invalidated state,
  368. the transaction is cleared using this method.
  369. A transaction is begun on a :class:`_engine.Connection` automatically
  370. whenever a statement is first executed, or when the
  371. :meth:`_engine.Connection.begin` method is called.
  372. """
  373. await greenlet_spawn(self._proxied.rollback)
  374. async def close(self) -> None:
  375. """Close this :class:`_asyncio.AsyncConnection`.
  376. This has the effect of also rolling back the transaction if one
  377. is in place.
  378. """
  379. await greenlet_spawn(self._proxied.close)
  380. async def aclose(self) -> None:
  381. """A synonym for :meth:`_asyncio.AsyncConnection.close`.
  382. The :meth:`_asyncio.AsyncConnection.aclose` name is specifically
  383. to support the Python standard library ``@contextlib.aclosing``
  384. context manager function.
  385. .. versionadded:: 2.0.20
  386. """
  387. await self.close()
  388. async def exec_driver_sql(
  389. self,
  390. statement: str,
  391. parameters: Optional[_DBAPIAnyExecuteParams] = None,
  392. execution_options: Optional[CoreExecuteOptionsParameter] = None,
  393. ) -> CursorResult[Any]:
  394. r"""Executes a driver-level SQL string and return buffered
  395. :class:`_engine.Result`.
  396. """
  397. result = await greenlet_spawn(
  398. self._proxied.exec_driver_sql,
  399. statement,
  400. parameters,
  401. execution_options,
  402. _require_await=True,
  403. )
  404. return await _ensure_sync_result(result, self.exec_driver_sql)
  405. @overload
  406. def stream(
  407. self,
  408. statement: TypedReturnsRows[_T],
  409. parameters: Optional[_CoreAnyExecuteParams] = None,
  410. *,
  411. execution_options: Optional[CoreExecuteOptionsParameter] = None,
  412. ) -> GeneratorStartableContext[AsyncResult[_T]]: ...
  413. @overload
  414. def stream(
  415. self,
  416. statement: Executable,
  417. parameters: Optional[_CoreAnyExecuteParams] = None,
  418. *,
  419. execution_options: Optional[CoreExecuteOptionsParameter] = None,
  420. ) -> GeneratorStartableContext[AsyncResult[Any]]: ...
  421. @asyncstartablecontext
  422. async def stream(
  423. self,
  424. statement: Executable,
  425. parameters: Optional[_CoreAnyExecuteParams] = None,
  426. *,
  427. execution_options: Optional[CoreExecuteOptionsParameter] = None,
  428. ) -> AsyncIterator[AsyncResult[Any]]:
  429. """Execute a statement and return an awaitable yielding a
  430. :class:`_asyncio.AsyncResult` object.
  431. E.g.::
  432. result = await conn.stream(stmt)
  433. async for row in result:
  434. print(f"{row}")
  435. The :meth:`.AsyncConnection.stream`
  436. method supports optional context manager use against the
  437. :class:`.AsyncResult` object, as in::
  438. async with conn.stream(stmt) as result:
  439. async for row in result:
  440. print(f"{row}")
  441. In the above pattern, the :meth:`.AsyncResult.close` method is
  442. invoked unconditionally, even if the iterator is interrupted by an
  443. exception throw. Context manager use remains optional, however,
  444. and the function may be called in either an ``async with fn():`` or
  445. ``await fn()`` style.
  446. .. versionadded:: 2.0.0b3 added context manager support
  447. :return: an awaitable object that will yield an
  448. :class:`_asyncio.AsyncResult` object.
  449. .. seealso::
  450. :meth:`.AsyncConnection.stream_scalars`
  451. """
  452. if not self.dialect.supports_server_side_cursors:
  453. raise exc.InvalidRequestError(
  454. "Cant use `stream` or `stream_scalars` with the current "
  455. "dialect since it does not support server side cursors."
  456. )
  457. result = await greenlet_spawn(
  458. self._proxied.execute,
  459. statement,
  460. parameters,
  461. execution_options=util.EMPTY_DICT.merge_with(
  462. execution_options, {"stream_results": True}
  463. ),
  464. _require_await=True,
  465. )
  466. assert result.context._is_server_side
  467. ar = AsyncResult(result)
  468. try:
  469. yield ar
  470. except GeneratorExit:
  471. pass
  472. else:
  473. task = asyncio.create_task(ar.close())
  474. await asyncio.shield(task)
  475. @overload
  476. async def execute(
  477. self,
  478. statement: TypedReturnsRows[_T],
  479. parameters: Optional[_CoreAnyExecuteParams] = None,
  480. *,
  481. execution_options: Optional[CoreExecuteOptionsParameter] = None,
  482. ) -> CursorResult[_T]: ...
  483. @overload
  484. async def execute(
  485. self,
  486. statement: Executable,
  487. parameters: Optional[_CoreAnyExecuteParams] = None,
  488. *,
  489. execution_options: Optional[CoreExecuteOptionsParameter] = None,
  490. ) -> CursorResult[Any]: ...
  491. async def execute(
  492. self,
  493. statement: Executable,
  494. parameters: Optional[_CoreAnyExecuteParams] = None,
  495. *,
  496. execution_options: Optional[CoreExecuteOptionsParameter] = None,
  497. ) -> CursorResult[Any]:
  498. r"""Executes a SQL statement construct and return a buffered
  499. :class:`_engine.Result`.
  500. :param object: The statement to be executed. This is always
  501. an object that is in both the :class:`_expression.ClauseElement` and
  502. :class:`_expression.Executable` hierarchies, including:
  503. * :class:`_expression.Select`
  504. * :class:`_expression.Insert`, :class:`_expression.Update`,
  505. :class:`_expression.Delete`
  506. * :class:`_expression.TextClause` and
  507. :class:`_expression.TextualSelect`
  508. * :class:`_schema.DDL` and objects which inherit from
  509. :class:`_schema.ExecutableDDLElement`
  510. :param parameters: parameters which will be bound into the statement.
  511. This may be either a dictionary of parameter names to values,
  512. or a mutable sequence (e.g. a list) of dictionaries. When a
  513. list of dictionaries is passed, the underlying statement execution
  514. will make use of the DBAPI ``cursor.executemany()`` method.
  515. When a single dictionary is passed, the DBAPI ``cursor.execute()``
  516. method will be used.
  517. :param execution_options: optional dictionary of execution options,
  518. which will be associated with the statement execution. This
  519. dictionary can provide a subset of the options that are accepted
  520. by :meth:`_engine.Connection.execution_options`.
  521. :return: a :class:`_engine.Result` object.
  522. """
  523. result = await greenlet_spawn(
  524. self._proxied.execute,
  525. statement,
  526. parameters,
  527. execution_options=execution_options,
  528. _require_await=True,
  529. )
  530. return await _ensure_sync_result(result, self.execute)
  531. @overload
  532. async def scalar(
  533. self,
  534. statement: TypedReturnsRows[Tuple[_T]],
  535. parameters: Optional[_CoreSingleExecuteParams] = None,
  536. *,
  537. execution_options: Optional[CoreExecuteOptionsParameter] = None,
  538. ) -> Optional[_T]: ...
  539. @overload
  540. async def scalar(
  541. self,
  542. statement: Executable,
  543. parameters: Optional[_CoreSingleExecuteParams] = None,
  544. *,
  545. execution_options: Optional[CoreExecuteOptionsParameter] = None,
  546. ) -> Any: ...
  547. async def scalar(
  548. self,
  549. statement: Executable,
  550. parameters: Optional[_CoreSingleExecuteParams] = None,
  551. *,
  552. execution_options: Optional[CoreExecuteOptionsParameter] = None,
  553. ) -> Any:
  554. r"""Executes a SQL statement construct and returns a scalar object.
  555. This method is shorthand for invoking the
  556. :meth:`_engine.Result.scalar` method after invoking the
  557. :meth:`_engine.Connection.execute` method. Parameters are equivalent.
  558. :return: a scalar Python value representing the first column of the
  559. first row returned.
  560. """
  561. result = await self.execute(
  562. statement, parameters, execution_options=execution_options
  563. )
  564. return result.scalar()
  565. @overload
  566. async def scalars(
  567. self,
  568. statement: TypedReturnsRows[Tuple[_T]],
  569. parameters: Optional[_CoreAnyExecuteParams] = None,
  570. *,
  571. execution_options: Optional[CoreExecuteOptionsParameter] = None,
  572. ) -> ScalarResult[_T]: ...
  573. @overload
  574. async def scalars(
  575. self,
  576. statement: Executable,
  577. parameters: Optional[_CoreAnyExecuteParams] = None,
  578. *,
  579. execution_options: Optional[CoreExecuteOptionsParameter] = None,
  580. ) -> ScalarResult[Any]: ...
  581. async def scalars(
  582. self,
  583. statement: Executable,
  584. parameters: Optional[_CoreAnyExecuteParams] = None,
  585. *,
  586. execution_options: Optional[CoreExecuteOptionsParameter] = None,
  587. ) -> ScalarResult[Any]:
  588. r"""Executes a SQL statement construct and returns a scalar objects.
  589. This method is shorthand for invoking the
  590. :meth:`_engine.Result.scalars` method after invoking the
  591. :meth:`_engine.Connection.execute` method. Parameters are equivalent.
  592. :return: a :class:`_engine.ScalarResult` object.
  593. .. versionadded:: 1.4.24
  594. """
  595. result = await self.execute(
  596. statement, parameters, execution_options=execution_options
  597. )
  598. return result.scalars()
  599. @overload
  600. def stream_scalars(
  601. self,
  602. statement: TypedReturnsRows[Tuple[_T]],
  603. parameters: Optional[_CoreSingleExecuteParams] = None,
  604. *,
  605. execution_options: Optional[CoreExecuteOptionsParameter] = None,
  606. ) -> GeneratorStartableContext[AsyncScalarResult[_T]]: ...
  607. @overload
  608. def stream_scalars(
  609. self,
  610. statement: Executable,
  611. parameters: Optional[_CoreSingleExecuteParams] = None,
  612. *,
  613. execution_options: Optional[CoreExecuteOptionsParameter] = None,
  614. ) -> GeneratorStartableContext[AsyncScalarResult[Any]]: ...
  615. @asyncstartablecontext
  616. async def stream_scalars(
  617. self,
  618. statement: Executable,
  619. parameters: Optional[_CoreSingleExecuteParams] = None,
  620. *,
  621. execution_options: Optional[CoreExecuteOptionsParameter] = None,
  622. ) -> AsyncIterator[AsyncScalarResult[Any]]:
  623. r"""Execute a statement and return an awaitable yielding a
  624. :class:`_asyncio.AsyncScalarResult` object.
  625. E.g.::
  626. result = await conn.stream_scalars(stmt)
  627. async for scalar in result:
  628. print(f"{scalar}")
  629. This method is shorthand for invoking the
  630. :meth:`_engine.AsyncResult.scalars` method after invoking the
  631. :meth:`_engine.Connection.stream` method. Parameters are equivalent.
  632. The :meth:`.AsyncConnection.stream_scalars`
  633. method supports optional context manager use against the
  634. :class:`.AsyncScalarResult` object, as in::
  635. async with conn.stream_scalars(stmt) as result:
  636. async for scalar in result:
  637. print(f"{scalar}")
  638. In the above pattern, the :meth:`.AsyncScalarResult.close` method is
  639. invoked unconditionally, even if the iterator is interrupted by an
  640. exception throw. Context manager use remains optional, however,
  641. and the function may be called in either an ``async with fn():`` or
  642. ``await fn()`` style.
  643. .. versionadded:: 2.0.0b3 added context manager support
  644. :return: an awaitable object that will yield an
  645. :class:`_asyncio.AsyncScalarResult` object.
  646. .. versionadded:: 1.4.24
  647. .. seealso::
  648. :meth:`.AsyncConnection.stream`
  649. """
  650. async with self.stream(
  651. statement, parameters, execution_options=execution_options
  652. ) as result:
  653. yield result.scalars()
  654. async def run_sync(
  655. self,
  656. fn: Callable[Concatenate[Connection, _P], _T],
  657. *arg: _P.args,
  658. **kw: _P.kwargs,
  659. ) -> _T:
  660. '''Invoke the given synchronous (i.e. not async) callable,
  661. passing a synchronous-style :class:`_engine.Connection` as the first
  662. argument.
  663. This method allows traditional synchronous SQLAlchemy functions to
  664. run within the context of an asyncio application.
  665. E.g.::
  666. def do_something_with_core(conn: Connection, arg1: int, arg2: str) -> str:
  667. """A synchronous function that does not require awaiting
  668. :param conn: a Core SQLAlchemy Connection, used synchronously
  669. :return: an optional return value is supported
  670. """
  671. conn.execute(some_table.insert().values(int_col=arg1, str_col=arg2))
  672. return "success"
  673. async def do_something_async(async_engine: AsyncEngine) -> None:
  674. """an async function that uses awaiting"""
  675. async with async_engine.begin() as async_conn:
  676. # run do_something_with_core() with a sync-style
  677. # Connection, proxied into an awaitable
  678. return_code = await async_conn.run_sync(
  679. do_something_with_core, 5, "strval"
  680. )
  681. print(return_code)
  682. This method maintains the asyncio event loop all the way through
  683. to the database connection by running the given callable in a
  684. specially instrumented greenlet.
  685. The most rudimentary use of :meth:`.AsyncConnection.run_sync` is to
  686. invoke methods such as :meth:`_schema.MetaData.create_all`, given
  687. an :class:`.AsyncConnection` that needs to be provided to
  688. :meth:`_schema.MetaData.create_all` as a :class:`_engine.Connection`
  689. object::
  690. # run metadata.create_all(conn) with a sync-style Connection,
  691. # proxied into an awaitable
  692. with async_engine.begin() as conn:
  693. await conn.run_sync(metadata.create_all)
  694. .. note::
  695. The provided callable is invoked inline within the asyncio event
  696. loop, and will block on traditional IO calls. IO within this
  697. callable should only call into SQLAlchemy's asyncio database
  698. APIs which will be properly adapted to the greenlet context.
  699. .. seealso::
  700. :meth:`.AsyncSession.run_sync`
  701. :ref:`session_run_sync`
  702. ''' # noqa: E501
  703. return await greenlet_spawn(
  704. fn, self._proxied, *arg, _require_await=False, **kw
  705. )
  706. def __await__(self) -> Generator[Any, None, AsyncConnection]:
  707. return self.start().__await__()
  708. async def __aexit__(self, type_: Any, value: Any, traceback: Any) -> None:
  709. task = asyncio.create_task(self.close())
  710. await asyncio.shield(task)
  711. # START PROXY METHODS AsyncConnection
  712. # code within this block is **programmatically,
  713. # statically generated** by tools/generate_proxy_methods.py
  714. @property
  715. def closed(self) -> Any:
  716. r"""Return True if this connection is closed.
  717. .. container:: class_bases
  718. Proxied for the :class:`_engine.Connection` class
  719. on behalf of the :class:`_asyncio.AsyncConnection` class.
  720. """ # noqa: E501
  721. return self._proxied.closed
  722. @property
  723. def invalidated(self) -> Any:
  724. r"""Return True if this connection was invalidated.
  725. .. container:: class_bases
  726. Proxied for the :class:`_engine.Connection` class
  727. on behalf of the :class:`_asyncio.AsyncConnection` class.
  728. This does not indicate whether or not the connection was
  729. invalidated at the pool level, however
  730. """ # noqa: E501
  731. return self._proxied.invalidated
  732. @property
  733. def dialect(self) -> Dialect:
  734. r"""Proxy for the :attr:`_engine.Connection.dialect` attribute
  735. on behalf of the :class:`_asyncio.AsyncConnection` class.
  736. """ # noqa: E501
  737. return self._proxied.dialect
  738. @dialect.setter
  739. def dialect(self, attr: Dialect) -> None:
  740. self._proxied.dialect = attr
  741. @property
  742. def default_isolation_level(self) -> Any:
  743. r"""The initial-connection time isolation level associated with the
  744. :class:`_engine.Dialect` in use.
  745. .. container:: class_bases
  746. Proxied for the :class:`_engine.Connection` class
  747. on behalf of the :class:`_asyncio.AsyncConnection` class.
  748. This value is independent of the
  749. :paramref:`.Connection.execution_options.isolation_level` and
  750. :paramref:`.Engine.execution_options.isolation_level` execution
  751. options, and is determined by the :class:`_engine.Dialect` when the
  752. first connection is created, by performing a SQL query against the
  753. database for the current isolation level before any additional commands
  754. have been emitted.
  755. Calling this accessor does not invoke any new SQL queries.
  756. .. seealso::
  757. :meth:`_engine.Connection.get_isolation_level`
  758. - view current actual isolation level
  759. :paramref:`_sa.create_engine.isolation_level`
  760. - set per :class:`_engine.Engine` isolation level
  761. :paramref:`.Connection.execution_options.isolation_level`
  762. - set per :class:`_engine.Connection` isolation level
  763. """ # noqa: E501
  764. return self._proxied.default_isolation_level
  765. # END PROXY METHODS AsyncConnection
  766. @util.create_proxy_methods(
  767. Engine,
  768. ":class:`_engine.Engine`",
  769. ":class:`_asyncio.AsyncEngine`",
  770. classmethods=[],
  771. methods=[
  772. "clear_compiled_cache",
  773. "update_execution_options",
  774. "get_execution_options",
  775. ],
  776. attributes=["url", "pool", "dialect", "engine", "name", "driver", "echo"],
  777. )
  778. class AsyncEngine(ProxyComparable[Engine], AsyncConnectable):
  779. """An asyncio proxy for a :class:`_engine.Engine`.
  780. :class:`_asyncio.AsyncEngine` is acquired using the
  781. :func:`_asyncio.create_async_engine` function::
  782. from sqlalchemy.ext.asyncio import create_async_engine
  783. engine = create_async_engine("postgresql+asyncpg://user:pass@host/dbname")
  784. .. versionadded:: 1.4
  785. """ # noqa
  786. # AsyncEngine is a thin proxy; no state should be added here
  787. # that is not retrievable from the "sync" engine / connection, e.g.
  788. # current transaction, info, etc. It should be possible to
  789. # create a new AsyncEngine that matches this one given only the
  790. # "sync" elements.
  791. __slots__ = "sync_engine"
  792. _connection_cls: Type[AsyncConnection] = AsyncConnection
  793. sync_engine: Engine
  794. """Reference to the sync-style :class:`_engine.Engine` this
  795. :class:`_asyncio.AsyncEngine` proxies requests towards.
  796. This instance can be used as an event target.
  797. .. seealso::
  798. :ref:`asyncio_events`
  799. """
  800. def __init__(self, sync_engine: Engine):
  801. if not sync_engine.dialect.is_async:
  802. raise exc.InvalidRequestError(
  803. "The asyncio extension requires an async driver to be used. "
  804. f"The loaded {sync_engine.dialect.driver!r} is not async."
  805. )
  806. self.sync_engine = self._assign_proxied(sync_engine)
  807. @util.ro_non_memoized_property
  808. def _proxied(self) -> Engine:
  809. return self.sync_engine
  810. @classmethod
  811. def _regenerate_proxy_for_target(
  812. cls, target: Engine, **additional_kw: Any # noqa: U100
  813. ) -> AsyncEngine:
  814. return AsyncEngine(target)
  815. @contextlib.asynccontextmanager
  816. async def begin(self) -> AsyncIterator[AsyncConnection]:
  817. """Return a context manager which when entered will deliver an
  818. :class:`_asyncio.AsyncConnection` with an
  819. :class:`_asyncio.AsyncTransaction` established.
  820. E.g.::
  821. async with async_engine.begin() as conn:
  822. await conn.execute(
  823. text("insert into table (x, y, z) values (1, 2, 3)")
  824. )
  825. await conn.execute(text("my_special_procedure(5)"))
  826. """
  827. conn = self.connect()
  828. async with conn:
  829. async with conn.begin():
  830. yield conn
  831. def connect(self) -> AsyncConnection:
  832. """Return an :class:`_asyncio.AsyncConnection` object.
  833. The :class:`_asyncio.AsyncConnection` will procure a database
  834. connection from the underlying connection pool when it is entered
  835. as an async context manager::
  836. async with async_engine.connect() as conn:
  837. result = await conn.execute(select(user_table))
  838. The :class:`_asyncio.AsyncConnection` may also be started outside of a
  839. context manager by invoking its :meth:`_asyncio.AsyncConnection.start`
  840. method.
  841. """
  842. return self._connection_cls(self)
  843. async def raw_connection(self) -> PoolProxiedConnection:
  844. """Return a "raw" DBAPI connection from the connection pool.
  845. .. seealso::
  846. :ref:`dbapi_connections`
  847. """
  848. return await greenlet_spawn(self.sync_engine.raw_connection)
  849. @overload
  850. def execution_options(
  851. self,
  852. *,
  853. compiled_cache: Optional[CompiledCacheType] = ...,
  854. logging_token: str = ...,
  855. isolation_level: IsolationLevel = ...,
  856. insertmanyvalues_page_size: int = ...,
  857. schema_translate_map: Optional[SchemaTranslateMapType] = ...,
  858. **opt: Any,
  859. ) -> AsyncEngine: ...
  860. @overload
  861. def execution_options(self, **opt: Any) -> AsyncEngine: ...
  862. def execution_options(self, **opt: Any) -> AsyncEngine:
  863. """Return a new :class:`_asyncio.AsyncEngine` that will provide
  864. :class:`_asyncio.AsyncConnection` objects with the given execution
  865. options.
  866. Proxied from :meth:`_engine.Engine.execution_options`. See that
  867. method for details.
  868. """
  869. return AsyncEngine(self.sync_engine.execution_options(**opt))
  870. async def dispose(self, close: bool = True) -> None:
  871. """Dispose of the connection pool used by this
  872. :class:`_asyncio.AsyncEngine`.
  873. :param close: if left at its default of ``True``, has the
  874. effect of fully closing all **currently checked in**
  875. database connections. Connections that are still checked out
  876. will **not** be closed, however they will no longer be associated
  877. with this :class:`_engine.Engine`,
  878. so when they are closed individually, eventually the
  879. :class:`_pool.Pool` which they are associated with will
  880. be garbage collected and they will be closed out fully, if
  881. not already closed on checkin.
  882. If set to ``False``, the previous connection pool is de-referenced,
  883. and otherwise not touched in any way.
  884. .. seealso::
  885. :meth:`_engine.Engine.dispose`
  886. """
  887. await greenlet_spawn(self.sync_engine.dispose, close=close)
  888. # START PROXY METHODS AsyncEngine
  889. # code within this block is **programmatically,
  890. # statically generated** by tools/generate_proxy_methods.py
  891. def clear_compiled_cache(self) -> None:
  892. r"""Clear the compiled cache associated with the dialect.
  893. .. container:: class_bases
  894. Proxied for the :class:`_engine.Engine` class on
  895. behalf of the :class:`_asyncio.AsyncEngine` class.
  896. This applies **only** to the built-in cache that is established
  897. via the :paramref:`_engine.create_engine.query_cache_size` parameter.
  898. It will not impact any dictionary caches that were passed via the
  899. :paramref:`.Connection.execution_options.compiled_cache` parameter.
  900. .. versionadded:: 1.4
  901. """ # noqa: E501
  902. return self._proxied.clear_compiled_cache()
  903. def update_execution_options(self, **opt: Any) -> None:
  904. r"""Update the default execution_options dictionary
  905. of this :class:`_engine.Engine`.
  906. .. container:: class_bases
  907. Proxied for the :class:`_engine.Engine` class on
  908. behalf of the :class:`_asyncio.AsyncEngine` class.
  909. The given keys/values in \**opt are added to the
  910. default execution options that will be used for
  911. all connections. The initial contents of this dictionary
  912. can be sent via the ``execution_options`` parameter
  913. to :func:`_sa.create_engine`.
  914. .. seealso::
  915. :meth:`_engine.Connection.execution_options`
  916. :meth:`_engine.Engine.execution_options`
  917. """ # noqa: E501
  918. return self._proxied.update_execution_options(**opt)
  919. def get_execution_options(self) -> _ExecuteOptions:
  920. r"""Get the non-SQL options which will take effect during execution.
  921. .. container:: class_bases
  922. Proxied for the :class:`_engine.Engine` class on
  923. behalf of the :class:`_asyncio.AsyncEngine` class.
  924. .. versionadded: 1.3
  925. .. seealso::
  926. :meth:`_engine.Engine.execution_options`
  927. """ # noqa: E501
  928. return self._proxied.get_execution_options()
  929. @property
  930. def url(self) -> URL:
  931. r"""Proxy for the :attr:`_engine.Engine.url` attribute
  932. on behalf of the :class:`_asyncio.AsyncEngine` class.
  933. """ # noqa: E501
  934. return self._proxied.url
  935. @url.setter
  936. def url(self, attr: URL) -> None:
  937. self._proxied.url = attr
  938. @property
  939. def pool(self) -> Pool:
  940. r"""Proxy for the :attr:`_engine.Engine.pool` attribute
  941. on behalf of the :class:`_asyncio.AsyncEngine` class.
  942. """ # noqa: E501
  943. return self._proxied.pool
  944. @pool.setter
  945. def pool(self, attr: Pool) -> None:
  946. self._proxied.pool = attr
  947. @property
  948. def dialect(self) -> Dialect:
  949. r"""Proxy for the :attr:`_engine.Engine.dialect` attribute
  950. on behalf of the :class:`_asyncio.AsyncEngine` class.
  951. """ # noqa: E501
  952. return self._proxied.dialect
  953. @dialect.setter
  954. def dialect(self, attr: Dialect) -> None:
  955. self._proxied.dialect = attr
  956. @property
  957. def engine(self) -> Any:
  958. r"""Returns this :class:`.Engine`.
  959. .. container:: class_bases
  960. Proxied for the :class:`_engine.Engine` class
  961. on behalf of the :class:`_asyncio.AsyncEngine` class.
  962. Used for legacy schemes that accept :class:`.Connection` /
  963. :class:`.Engine` objects within the same variable.
  964. """ # noqa: E501
  965. return self._proxied.engine
  966. @property
  967. def name(self) -> Any:
  968. r"""String name of the :class:`~sqlalchemy.engine.interfaces.Dialect`
  969. in use by this :class:`Engine`.
  970. .. container:: class_bases
  971. Proxied for the :class:`_engine.Engine` class
  972. on behalf of the :class:`_asyncio.AsyncEngine` class.
  973. """ # noqa: E501
  974. return self._proxied.name
  975. @property
  976. def driver(self) -> Any:
  977. r"""Driver name of the :class:`~sqlalchemy.engine.interfaces.Dialect`
  978. in use by this :class:`Engine`.
  979. .. container:: class_bases
  980. Proxied for the :class:`_engine.Engine` class
  981. on behalf of the :class:`_asyncio.AsyncEngine` class.
  982. """ # noqa: E501
  983. return self._proxied.driver
  984. @property
  985. def echo(self) -> Any:
  986. r"""When ``True``, enable log output for this element.
  987. .. container:: class_bases
  988. Proxied for the :class:`_engine.Engine` class
  989. on behalf of the :class:`_asyncio.AsyncEngine` class.
  990. This has the effect of setting the Python logging level for the namespace
  991. of this element's class and object reference. A value of boolean ``True``
  992. indicates that the loglevel ``logging.INFO`` will be set for the logger,
  993. whereas the string value ``debug`` will set the loglevel to
  994. ``logging.DEBUG``.
  995. """ # noqa: E501
  996. return self._proxied.echo
  997. @echo.setter
  998. def echo(self, attr: Any) -> None:
  999. self._proxied.echo = attr
  1000. # END PROXY METHODS AsyncEngine
  1001. class AsyncTransaction(
  1002. ProxyComparable[Transaction], StartableContext["AsyncTransaction"]
  1003. ):
  1004. """An asyncio proxy for a :class:`_engine.Transaction`."""
  1005. __slots__ = ("connection", "sync_transaction", "nested")
  1006. sync_transaction: Optional[Transaction]
  1007. connection: AsyncConnection
  1008. nested: bool
  1009. def __init__(self, connection: AsyncConnection, nested: bool = False):
  1010. self.connection = connection
  1011. self.sync_transaction = None
  1012. self.nested = nested
  1013. @classmethod
  1014. def _regenerate_proxy_for_target(
  1015. cls, target: Transaction, **additional_kw: Any # noqa: U100
  1016. ) -> AsyncTransaction:
  1017. sync_connection = target.connection
  1018. sync_transaction = target
  1019. nested = isinstance(target, NestedTransaction)
  1020. async_connection = AsyncConnection._retrieve_proxy_for_target(
  1021. sync_connection
  1022. )
  1023. assert async_connection is not None
  1024. obj = cls.__new__(cls)
  1025. obj.connection = async_connection
  1026. obj.sync_transaction = obj._assign_proxied(sync_transaction)
  1027. obj.nested = nested
  1028. return obj
  1029. @util.ro_non_memoized_property
  1030. def _proxied(self) -> Transaction:
  1031. if not self.sync_transaction:
  1032. self._raise_for_not_started()
  1033. return self.sync_transaction
  1034. @property
  1035. def is_valid(self) -> bool:
  1036. return self._proxied.is_valid
  1037. @property
  1038. def is_active(self) -> bool:
  1039. return self._proxied.is_active
  1040. async def close(self) -> None:
  1041. """Close this :class:`.AsyncTransaction`.
  1042. If this transaction is the base transaction in a begin/commit
  1043. nesting, the transaction will rollback(). Otherwise, the
  1044. method returns.
  1045. This is used to cancel a Transaction without affecting the scope of
  1046. an enclosing transaction.
  1047. """
  1048. await greenlet_spawn(self._proxied.close)
  1049. async def rollback(self) -> None:
  1050. """Roll back this :class:`.AsyncTransaction`."""
  1051. await greenlet_spawn(self._proxied.rollback)
  1052. async def commit(self) -> None:
  1053. """Commit this :class:`.AsyncTransaction`."""
  1054. await greenlet_spawn(self._proxied.commit)
  1055. async def start(self, is_ctxmanager: bool = False) -> AsyncTransaction:
  1056. """Start this :class:`_asyncio.AsyncTransaction` object's context
  1057. outside of using a Python ``with:`` block.
  1058. """
  1059. self.sync_transaction = self._assign_proxied(
  1060. await greenlet_spawn(
  1061. self.connection._proxied.begin_nested
  1062. if self.nested
  1063. else self.connection._proxied.begin
  1064. )
  1065. )
  1066. if is_ctxmanager:
  1067. self.sync_transaction.__enter__()
  1068. return self
  1069. async def __aexit__(self, type_: Any, value: Any, traceback: Any) -> None:
  1070. await greenlet_spawn(self._proxied.__exit__, type_, value, traceback)
  1071. @overload
  1072. def _get_sync_engine_or_connection(async_engine: AsyncEngine) -> Engine: ...
  1073. @overload
  1074. def _get_sync_engine_or_connection(
  1075. async_engine: AsyncConnection,
  1076. ) -> Connection: ...
  1077. def _get_sync_engine_or_connection(
  1078. async_engine: Union[AsyncEngine, AsyncConnection],
  1079. ) -> Union[Engine, Connection]:
  1080. if isinstance(async_engine, AsyncConnection):
  1081. return async_engine._proxied
  1082. try:
  1083. return async_engine.sync_engine
  1084. except AttributeError as e:
  1085. raise exc.ArgumentError(
  1086. "AsyncEngine expected, got %r" % async_engine
  1087. ) from e
  1088. @inspection._inspects(AsyncConnection)
  1089. def _no_insp_for_async_conn_yet(
  1090. subject: AsyncConnection, # noqa: U100
  1091. ) -> NoReturn:
  1092. raise exc.NoInspectionAvailable(
  1093. "Inspection on an AsyncConnection is currently not supported. "
  1094. "Please use ``run_sync`` to pass a callable where it's possible "
  1095. "to call ``inspect`` on the passed connection.",
  1096. code="xd3s",
  1097. )
  1098. @inspection._inspects(AsyncEngine)
  1099. def _no_insp_for_async_engine_xyet(
  1100. subject: AsyncEngine, # noqa: U100
  1101. ) -> NoReturn:
  1102. raise exc.NoInspectionAvailable(
  1103. "Inspection on an AsyncEngine is currently not supported. "
  1104. "Please obtain a connection then use ``conn.run_sync`` to pass a "
  1105. "callable where it's possible to call ``inspect`` on the "
  1106. "passed connection.",
  1107. code="xd3s",
  1108. )