SQLAlchemy 2.1.0b1__cp313-cp313-win_arm64.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (267) hide show
  1. sqlalchemy/__init__.py +295 -0
  2. sqlalchemy/connectors/__init__.py +18 -0
  3. sqlalchemy/connectors/aioodbc.py +161 -0
  4. sqlalchemy/connectors/asyncio.py +476 -0
  5. sqlalchemy/connectors/pyodbc.py +250 -0
  6. sqlalchemy/dialects/__init__.py +62 -0
  7. sqlalchemy/dialects/_typing.py +30 -0
  8. sqlalchemy/dialects/mssql/__init__.py +88 -0
  9. sqlalchemy/dialects/mssql/aioodbc.py +63 -0
  10. sqlalchemy/dialects/mssql/base.py +4110 -0
  11. sqlalchemy/dialects/mssql/information_schema.py +285 -0
  12. sqlalchemy/dialects/mssql/json.py +129 -0
  13. sqlalchemy/dialects/mssql/provision.py +185 -0
  14. sqlalchemy/dialects/mssql/pymssql.py +126 -0
  15. sqlalchemy/dialects/mssql/pyodbc.py +758 -0
  16. sqlalchemy/dialects/mysql/__init__.py +106 -0
  17. sqlalchemy/dialects/mysql/_mariadb_shim.py +312 -0
  18. sqlalchemy/dialects/mysql/aiomysql.py +226 -0
  19. sqlalchemy/dialects/mysql/asyncmy.py +214 -0
  20. sqlalchemy/dialects/mysql/base.py +3870 -0
  21. sqlalchemy/dialects/mysql/cymysql.py +106 -0
  22. sqlalchemy/dialects/mysql/dml.py +279 -0
  23. sqlalchemy/dialects/mysql/enumerated.py +277 -0
  24. sqlalchemy/dialects/mysql/expression.py +146 -0
  25. sqlalchemy/dialects/mysql/json.py +91 -0
  26. sqlalchemy/dialects/mysql/mariadb.py +67 -0
  27. sqlalchemy/dialects/mysql/mariadbconnector.py +330 -0
  28. sqlalchemy/dialects/mysql/mysqlconnector.py +296 -0
  29. sqlalchemy/dialects/mysql/mysqldb.py +312 -0
  30. sqlalchemy/dialects/mysql/provision.py +147 -0
  31. sqlalchemy/dialects/mysql/pymysql.py +157 -0
  32. sqlalchemy/dialects/mysql/pyodbc.py +156 -0
  33. sqlalchemy/dialects/mysql/reflection.py +724 -0
  34. sqlalchemy/dialects/mysql/reserved_words.py +570 -0
  35. sqlalchemy/dialects/mysql/types.py +845 -0
  36. sqlalchemy/dialects/oracle/__init__.py +83 -0
  37. sqlalchemy/dialects/oracle/base.py +3871 -0
  38. sqlalchemy/dialects/oracle/cx_oracle.py +1522 -0
  39. sqlalchemy/dialects/oracle/dictionary.py +507 -0
  40. sqlalchemy/dialects/oracle/oracledb.py +894 -0
  41. sqlalchemy/dialects/oracle/provision.py +288 -0
  42. sqlalchemy/dialects/oracle/types.py +350 -0
  43. sqlalchemy/dialects/oracle/vector.py +368 -0
  44. sqlalchemy/dialects/postgresql/__init__.py +171 -0
  45. sqlalchemy/dialects/postgresql/_psycopg_common.py +193 -0
  46. sqlalchemy/dialects/postgresql/array.py +534 -0
  47. sqlalchemy/dialects/postgresql/asyncpg.py +1331 -0
  48. sqlalchemy/dialects/postgresql/base.py +5729 -0
  49. sqlalchemy/dialects/postgresql/bitstring.py +327 -0
  50. sqlalchemy/dialects/postgresql/dml.py +360 -0
  51. sqlalchemy/dialects/postgresql/ext.py +593 -0
  52. sqlalchemy/dialects/postgresql/hstore.py +413 -0
  53. sqlalchemy/dialects/postgresql/json.py +407 -0
  54. sqlalchemy/dialects/postgresql/named_types.py +521 -0
  55. sqlalchemy/dialects/postgresql/operators.py +130 -0
  56. sqlalchemy/dialects/postgresql/pg8000.py +672 -0
  57. sqlalchemy/dialects/postgresql/pg_catalog.py +344 -0
  58. sqlalchemy/dialects/postgresql/provision.py +175 -0
  59. sqlalchemy/dialects/postgresql/psycopg.py +815 -0
  60. sqlalchemy/dialects/postgresql/psycopg2.py +887 -0
  61. sqlalchemy/dialects/postgresql/psycopg2cffi.py +61 -0
  62. sqlalchemy/dialects/postgresql/ranges.py +1002 -0
  63. sqlalchemy/dialects/postgresql/types.py +388 -0
  64. sqlalchemy/dialects/sqlite/__init__.py +57 -0
  65. sqlalchemy/dialects/sqlite/aiosqlite.py +321 -0
  66. sqlalchemy/dialects/sqlite/base.py +3050 -0
  67. sqlalchemy/dialects/sqlite/dml.py +279 -0
  68. sqlalchemy/dialects/sqlite/json.py +89 -0
  69. sqlalchemy/dialects/sqlite/provision.py +223 -0
  70. sqlalchemy/dialects/sqlite/pysqlcipher.py +157 -0
  71. sqlalchemy/dialects/sqlite/pysqlite.py +754 -0
  72. sqlalchemy/dialects/type_migration_guidelines.txt +145 -0
  73. sqlalchemy/engine/__init__.py +62 -0
  74. sqlalchemy/engine/_processors_cy.cp313-win_arm64.pyd +0 -0
  75. sqlalchemy/engine/_processors_cy.py +92 -0
  76. sqlalchemy/engine/_result_cy.cp313-win_arm64.pyd +0 -0
  77. sqlalchemy/engine/_result_cy.py +633 -0
  78. sqlalchemy/engine/_row_cy.cp313-win_arm64.pyd +0 -0
  79. sqlalchemy/engine/_row_cy.py +232 -0
  80. sqlalchemy/engine/_util_cy.cp313-win_arm64.pyd +0 -0
  81. sqlalchemy/engine/_util_cy.py +136 -0
  82. sqlalchemy/engine/base.py +3334 -0
  83. sqlalchemy/engine/characteristics.py +155 -0
  84. sqlalchemy/engine/create.py +869 -0
  85. sqlalchemy/engine/cursor.py +2416 -0
  86. sqlalchemy/engine/default.py +2393 -0
  87. sqlalchemy/engine/events.py +965 -0
  88. sqlalchemy/engine/interfaces.py +3465 -0
  89. sqlalchemy/engine/mock.py +134 -0
  90. sqlalchemy/engine/processors.py +82 -0
  91. sqlalchemy/engine/reflection.py +2100 -0
  92. sqlalchemy/engine/result.py +1932 -0
  93. sqlalchemy/engine/row.py +397 -0
  94. sqlalchemy/engine/strategies.py +16 -0
  95. sqlalchemy/engine/url.py +922 -0
  96. sqlalchemy/engine/util.py +156 -0
  97. sqlalchemy/event/__init__.py +26 -0
  98. sqlalchemy/event/api.py +220 -0
  99. sqlalchemy/event/attr.py +674 -0
  100. sqlalchemy/event/base.py +472 -0
  101. sqlalchemy/event/legacy.py +258 -0
  102. sqlalchemy/event/registry.py +390 -0
  103. sqlalchemy/events.py +17 -0
  104. sqlalchemy/exc.py +922 -0
  105. sqlalchemy/ext/__init__.py +11 -0
  106. sqlalchemy/ext/associationproxy.py +2072 -0
  107. sqlalchemy/ext/asyncio/__init__.py +29 -0
  108. sqlalchemy/ext/asyncio/base.py +281 -0
  109. sqlalchemy/ext/asyncio/engine.py +1475 -0
  110. sqlalchemy/ext/asyncio/exc.py +21 -0
  111. sqlalchemy/ext/asyncio/result.py +994 -0
  112. sqlalchemy/ext/asyncio/scoping.py +1667 -0
  113. sqlalchemy/ext/asyncio/session.py +1993 -0
  114. sqlalchemy/ext/automap.py +1701 -0
  115. sqlalchemy/ext/baked.py +559 -0
  116. sqlalchemy/ext/compiler.py +600 -0
  117. sqlalchemy/ext/declarative/__init__.py +65 -0
  118. sqlalchemy/ext/declarative/extensions.py +560 -0
  119. sqlalchemy/ext/horizontal_shard.py +481 -0
  120. sqlalchemy/ext/hybrid.py +1877 -0
  121. sqlalchemy/ext/indexable.py +364 -0
  122. sqlalchemy/ext/instrumentation.py +450 -0
  123. sqlalchemy/ext/mutable.py +1081 -0
  124. sqlalchemy/ext/orderinglist.py +439 -0
  125. sqlalchemy/ext/serializer.py +185 -0
  126. sqlalchemy/future/__init__.py +16 -0
  127. sqlalchemy/future/engine.py +15 -0
  128. sqlalchemy/inspection.py +174 -0
  129. sqlalchemy/log.py +283 -0
  130. sqlalchemy/orm/__init__.py +175 -0
  131. sqlalchemy/orm/_orm_constructors.py +2694 -0
  132. sqlalchemy/orm/_typing.py +179 -0
  133. sqlalchemy/orm/attributes.py +2868 -0
  134. sqlalchemy/orm/base.py +970 -0
  135. sqlalchemy/orm/bulk_persistence.py +2152 -0
  136. sqlalchemy/orm/clsregistry.py +582 -0
  137. sqlalchemy/orm/collections.py +1568 -0
  138. sqlalchemy/orm/context.py +3471 -0
  139. sqlalchemy/orm/decl_api.py +2257 -0
  140. sqlalchemy/orm/decl_base.py +2304 -0
  141. sqlalchemy/orm/dependency.py +1306 -0
  142. sqlalchemy/orm/descriptor_props.py +1183 -0
  143. sqlalchemy/orm/dynamic.py +300 -0
  144. sqlalchemy/orm/evaluator.py +379 -0
  145. sqlalchemy/orm/events.py +3386 -0
  146. sqlalchemy/orm/exc.py +237 -0
  147. sqlalchemy/orm/identity.py +302 -0
  148. sqlalchemy/orm/instrumentation.py +746 -0
  149. sqlalchemy/orm/interfaces.py +1589 -0
  150. sqlalchemy/orm/loading.py +1684 -0
  151. sqlalchemy/orm/mapped_collection.py +557 -0
  152. sqlalchemy/orm/mapper.py +4406 -0
  153. sqlalchemy/orm/path_registry.py +814 -0
  154. sqlalchemy/orm/persistence.py +1789 -0
  155. sqlalchemy/orm/properties.py +973 -0
  156. sqlalchemy/orm/query.py +3521 -0
  157. sqlalchemy/orm/relationships.py +3570 -0
  158. sqlalchemy/orm/scoping.py +2220 -0
  159. sqlalchemy/orm/session.py +5389 -0
  160. sqlalchemy/orm/state.py +1175 -0
  161. sqlalchemy/orm/state_changes.py +196 -0
  162. sqlalchemy/orm/strategies.py +3480 -0
  163. sqlalchemy/orm/strategy_options.py +2544 -0
  164. sqlalchemy/orm/sync.py +164 -0
  165. sqlalchemy/orm/unitofwork.py +798 -0
  166. sqlalchemy/orm/util.py +2435 -0
  167. sqlalchemy/orm/writeonly.py +694 -0
  168. sqlalchemy/pool/__init__.py +41 -0
  169. sqlalchemy/pool/base.py +1514 -0
  170. sqlalchemy/pool/events.py +372 -0
  171. sqlalchemy/pool/impl.py +582 -0
  172. sqlalchemy/py.typed +0 -0
  173. sqlalchemy/schema.py +72 -0
  174. sqlalchemy/sql/__init__.py +153 -0
  175. sqlalchemy/sql/_dml_constructors.py +132 -0
  176. sqlalchemy/sql/_elements_constructors.py +2147 -0
  177. sqlalchemy/sql/_orm_types.py +20 -0
  178. sqlalchemy/sql/_selectable_constructors.py +773 -0
  179. sqlalchemy/sql/_typing.py +486 -0
  180. sqlalchemy/sql/_util_cy.cp313-win_arm64.pyd +0 -0
  181. sqlalchemy/sql/_util_cy.py +127 -0
  182. sqlalchemy/sql/annotation.py +590 -0
  183. sqlalchemy/sql/base.py +2602 -0
  184. sqlalchemy/sql/cache_key.py +1066 -0
  185. sqlalchemy/sql/coercions.py +1373 -0
  186. sqlalchemy/sql/compiler.py +8259 -0
  187. sqlalchemy/sql/crud.py +1807 -0
  188. sqlalchemy/sql/ddl.py +1928 -0
  189. sqlalchemy/sql/default_comparator.py +654 -0
  190. sqlalchemy/sql/dml.py +1974 -0
  191. sqlalchemy/sql/elements.py +6016 -0
  192. sqlalchemy/sql/events.py +458 -0
  193. sqlalchemy/sql/expression.py +170 -0
  194. sqlalchemy/sql/functions.py +2257 -0
  195. sqlalchemy/sql/lambdas.py +1443 -0
  196. sqlalchemy/sql/naming.py +209 -0
  197. sqlalchemy/sql/operators.py +2897 -0
  198. sqlalchemy/sql/roles.py +332 -0
  199. sqlalchemy/sql/schema.py +6560 -0
  200. sqlalchemy/sql/selectable.py +7497 -0
  201. sqlalchemy/sql/sqltypes.py +4050 -0
  202. sqlalchemy/sql/traversals.py +1042 -0
  203. sqlalchemy/sql/type_api.py +2425 -0
  204. sqlalchemy/sql/util.py +1495 -0
  205. sqlalchemy/sql/visitors.py +1157 -0
  206. sqlalchemy/testing/__init__.py +96 -0
  207. sqlalchemy/testing/assertions.py +1007 -0
  208. sqlalchemy/testing/assertsql.py +519 -0
  209. sqlalchemy/testing/asyncio.py +128 -0
  210. sqlalchemy/testing/config.py +440 -0
  211. sqlalchemy/testing/engines.py +478 -0
  212. sqlalchemy/testing/entities.py +117 -0
  213. sqlalchemy/testing/exclusions.py +476 -0
  214. sqlalchemy/testing/fixtures/__init__.py +30 -0
  215. sqlalchemy/testing/fixtures/base.py +366 -0
  216. sqlalchemy/testing/fixtures/mypy.py +247 -0
  217. sqlalchemy/testing/fixtures/orm.py +227 -0
  218. sqlalchemy/testing/fixtures/sql.py +538 -0
  219. sqlalchemy/testing/pickleable.py +155 -0
  220. sqlalchemy/testing/plugin/__init__.py +6 -0
  221. sqlalchemy/testing/plugin/bootstrap.py +51 -0
  222. sqlalchemy/testing/plugin/plugin_base.py +828 -0
  223. sqlalchemy/testing/plugin/pytestplugin.py +892 -0
  224. sqlalchemy/testing/profiling.py +329 -0
  225. sqlalchemy/testing/provision.py +596 -0
  226. sqlalchemy/testing/requirements.py +1973 -0
  227. sqlalchemy/testing/schema.py +198 -0
  228. sqlalchemy/testing/suite/__init__.py +19 -0
  229. sqlalchemy/testing/suite/test_cte.py +237 -0
  230. sqlalchemy/testing/suite/test_ddl.py +420 -0
  231. sqlalchemy/testing/suite/test_dialect.py +776 -0
  232. sqlalchemy/testing/suite/test_insert.py +630 -0
  233. sqlalchemy/testing/suite/test_reflection.py +3557 -0
  234. sqlalchemy/testing/suite/test_results.py +660 -0
  235. sqlalchemy/testing/suite/test_rowcount.py +258 -0
  236. sqlalchemy/testing/suite/test_select.py +2112 -0
  237. sqlalchemy/testing/suite/test_sequence.py +317 -0
  238. sqlalchemy/testing/suite/test_table_via_select.py +686 -0
  239. sqlalchemy/testing/suite/test_types.py +2253 -0
  240. sqlalchemy/testing/suite/test_unicode_ddl.py +189 -0
  241. sqlalchemy/testing/suite/test_update_delete.py +139 -0
  242. sqlalchemy/testing/util.py +535 -0
  243. sqlalchemy/testing/warnings.py +52 -0
  244. sqlalchemy/types.py +76 -0
  245. sqlalchemy/util/__init__.py +157 -0
  246. sqlalchemy/util/_collections.py +693 -0
  247. sqlalchemy/util/_collections_cy.cp313-win_arm64.pyd +0 -0
  248. sqlalchemy/util/_collections_cy.pxd +8 -0
  249. sqlalchemy/util/_collections_cy.py +516 -0
  250. sqlalchemy/util/_has_cython.py +46 -0
  251. sqlalchemy/util/_immutabledict_cy.cp313-win_arm64.pyd +0 -0
  252. sqlalchemy/util/_immutabledict_cy.py +240 -0
  253. sqlalchemy/util/compat.py +287 -0
  254. sqlalchemy/util/concurrency.py +322 -0
  255. sqlalchemy/util/cython.py +79 -0
  256. sqlalchemy/util/deprecations.py +401 -0
  257. sqlalchemy/util/langhelpers.py +2256 -0
  258. sqlalchemy/util/preloaded.py +152 -0
  259. sqlalchemy/util/queue.py +304 -0
  260. sqlalchemy/util/tool_support.py +201 -0
  261. sqlalchemy/util/topological.py +120 -0
  262. sqlalchemy/util/typing.py +711 -0
  263. sqlalchemy-2.1.0b1.dist-info/METADATA +267 -0
  264. sqlalchemy-2.1.0b1.dist-info/RECORD +267 -0
  265. sqlalchemy-2.1.0b1.dist-info/WHEEL +5 -0
  266. sqlalchemy-2.1.0b1.dist-info/licenses/LICENSE +19 -0
  267. sqlalchemy-2.1.0b1.dist-info/top_level.txt +1 -0
@@ -0,0 +1,1475 @@
1
+ # ext/asyncio/engine.py
2
+ # Copyright (C) 2020-2026 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
+
9
+ import asyncio
10
+ import contextlib
11
+ from typing import Any
12
+ from typing import AsyncIterator
13
+ from typing import Callable
14
+ from typing import Concatenate
15
+ from typing import Dict
16
+ from typing import Generator
17
+ from typing import NoReturn
18
+ from typing import Optional
19
+ from typing import overload
20
+ from typing import ParamSpec
21
+ from typing import Type
22
+ from typing import TYPE_CHECKING
23
+ from typing import TypeVar
24
+ from typing import Union
25
+
26
+ from . import exc as async_exc
27
+ from .base import asyncstartablecontext
28
+ from .base import GeneratorStartableContext
29
+ from .base import ProxyComparable
30
+ from .base import StartableContext
31
+ from .result import _ensure_sync_result
32
+ from .result import AsyncResult
33
+ from .result import AsyncScalarResult
34
+ from ... import exc
35
+ from ... import inspection
36
+ from ... import util
37
+ from ...engine import Connection
38
+ from ...engine import create_engine as _create_engine
39
+ from ...engine import create_pool_from_url as _create_pool_from_url
40
+ from ...engine import Engine
41
+ from ...engine.base import NestedTransaction
42
+ from ...engine.base import Transaction
43
+ from ...exc import ArgumentError
44
+ from ...util import immutabledict
45
+ from ...util.concurrency import greenlet_spawn
46
+ from ...util.typing import TupleAny
47
+ from ...util.typing import TypeVarTuple
48
+ from ...util.typing import Unpack
49
+
50
+ if TYPE_CHECKING:
51
+ from ...engine.cursor import CursorResult
52
+ from ...engine.interfaces import _CoreAnyExecuteParams
53
+ from ...engine.interfaces import _CoreSingleExecuteParams
54
+ from ...engine.interfaces import _DBAPIAnyExecuteParams
55
+ from ...engine.interfaces import _ExecuteOptions
56
+ from ...engine.interfaces import CompiledCacheType
57
+ from ...engine.interfaces import CoreExecuteOptionsParameter
58
+ from ...engine.interfaces import Dialect
59
+ from ...engine.interfaces import IsolationLevel
60
+ from ...engine.interfaces import SchemaTranslateMapType
61
+ from ...engine.result import ScalarResult
62
+ from ...engine.url import URL
63
+ from ...pool import Pool
64
+ from ...pool import PoolProxiedConnection
65
+ from ...sql._typing import _InfoType
66
+ from ...sql.base import Executable
67
+ from ...sql.selectable import TypedReturnsRows
68
+
69
+ _P = ParamSpec("_P")
70
+ _T = TypeVar("_T", bound=Any)
71
+ _Ts = TypeVarTuple("_Ts")
72
+ _stream_results = immutabledict(stream_results=True)
73
+
74
+
75
+ def create_async_engine(url: Union[str, URL], **kw: Any) -> AsyncEngine:
76
+ """Create a new async engine instance.
77
+
78
+ Arguments passed to :func:`_asyncio.create_async_engine` are mostly
79
+ identical to those passed to the :func:`_sa.create_engine` function.
80
+ The specified dialect must be an asyncio-compatible dialect
81
+ such as :ref:`dialect-postgresql-asyncpg`.
82
+
83
+ .. versionadded:: 1.4
84
+
85
+ :param async_creator: an async callable which returns a driver-level
86
+ asyncio connection. If given, the function should take no arguments,
87
+ and return a new asyncio connection from the underlying asyncio
88
+ database driver; the connection will be wrapped in the appropriate
89
+ structures to be used with the :class:`.AsyncEngine`. Note that the
90
+ parameters specified in the URL are not applied here, and the creator
91
+ function should use its own connection parameters.
92
+
93
+ This parameter is the asyncio equivalent of the
94
+ :paramref:`_sa.create_engine.creator` parameter of the
95
+ :func:`_sa.create_engine` function.
96
+
97
+ .. versionadded:: 2.0.16
98
+
99
+ """
100
+
101
+ if kw.get("server_side_cursors", False):
102
+ raise async_exc.AsyncMethodRequired(
103
+ "Can't set server_side_cursors for async engine globally; "
104
+ "use the connection.stream() method for an async "
105
+ "streaming result set"
106
+ )
107
+ kw["_is_async"] = True
108
+ async_creator = kw.pop("async_creator", None)
109
+ if async_creator:
110
+ if kw.get("creator", None):
111
+ raise ArgumentError(
112
+ "Can only specify one of 'async_creator' or 'creator', "
113
+ "not both."
114
+ )
115
+
116
+ def creator() -> Any:
117
+ # note that to send adapted arguments like
118
+ # prepared_statement_cache_size, user would use
119
+ # "creator" and emulate this form here
120
+ return sync_engine.dialect.dbapi.connect( # type: ignore
121
+ async_creator_fn=async_creator
122
+ )
123
+
124
+ kw["creator"] = creator
125
+ sync_engine = _create_engine(url, **kw)
126
+ return AsyncEngine(sync_engine)
127
+
128
+
129
+ def async_engine_from_config(
130
+ configuration: Dict[str, Any], prefix: str = "sqlalchemy.", **kwargs: Any
131
+ ) -> AsyncEngine:
132
+ """Create a new AsyncEngine instance using a configuration dictionary.
133
+
134
+ This function is analogous to the :func:`_sa.engine_from_config` function
135
+ in SQLAlchemy Core, except that the requested dialect must be an
136
+ asyncio-compatible dialect such as :ref:`dialect-postgresql-asyncpg`.
137
+ The argument signature of the function is identical to that
138
+ of :func:`_sa.engine_from_config`.
139
+
140
+ .. versionadded:: 1.4.29
141
+
142
+ """
143
+ options = {
144
+ key[len(prefix) :]: value
145
+ for key, value in configuration.items()
146
+ if key.startswith(prefix)
147
+ }
148
+ options["_coerce_config"] = True
149
+ options.update(kwargs)
150
+ url = options.pop("url")
151
+ return create_async_engine(url, **options)
152
+
153
+
154
+ def create_async_pool_from_url(url: Union[str, URL], **kwargs: Any) -> Pool:
155
+ """Create a new async engine instance.
156
+
157
+ Arguments passed to :func:`_asyncio.create_async_pool_from_url` are mostly
158
+ identical to those passed to the :func:`_sa.create_pool_from_url` function.
159
+ The specified dialect must be an asyncio-compatible dialect
160
+ such as :ref:`dialect-postgresql-asyncpg`.
161
+
162
+ .. versionadded:: 2.0.10
163
+
164
+ """
165
+ kwargs["_is_async"] = True
166
+ return _create_pool_from_url(url, **kwargs)
167
+
168
+
169
+ class AsyncConnectable:
170
+ __slots__ = "_slots_dispatch", "__weakref__"
171
+
172
+ @classmethod
173
+ def _no_async_engine_events(cls) -> NoReturn:
174
+ raise NotImplementedError(
175
+ "asynchronous events are not implemented at this time. Apply "
176
+ "synchronous listeners to the AsyncEngine.sync_engine or "
177
+ "AsyncConnection.sync_connection attributes."
178
+ )
179
+
180
+
181
+ @util.create_proxy_methods(
182
+ Connection,
183
+ ":class:`_engine.Connection`",
184
+ ":class:`_asyncio.AsyncConnection`",
185
+ classmethods=[],
186
+ methods=[],
187
+ attributes=[
188
+ "closed",
189
+ "invalidated",
190
+ "dialect",
191
+ "default_isolation_level",
192
+ ],
193
+ )
194
+ # "Class has incompatible disjoint bases" - no idea
195
+ class AsyncConnection( # type:ignore[misc]
196
+ ProxyComparable[Connection],
197
+ StartableContext["AsyncConnection"],
198
+ AsyncConnectable,
199
+ ):
200
+ """An asyncio proxy for a :class:`_engine.Connection`.
201
+
202
+ :class:`_asyncio.AsyncConnection` is acquired using the
203
+ :meth:`_asyncio.AsyncEngine.connect`
204
+ method of :class:`_asyncio.AsyncEngine`::
205
+
206
+ from sqlalchemy.ext.asyncio import create_async_engine
207
+
208
+ engine = create_async_engine("postgresql+asyncpg://user:pass@host/dbname")
209
+
210
+ async with engine.connect() as conn:
211
+ result = await conn.execute(select(table))
212
+
213
+ .. versionadded:: 1.4
214
+
215
+ """ # noqa
216
+
217
+ # AsyncConnection is a thin proxy; no state should be added here
218
+ # that is not retrievable from the "sync" engine / connection, e.g.
219
+ # current transaction, info, etc. It should be possible to
220
+ # create a new AsyncConnection that matches this one given only the
221
+ # "sync" elements.
222
+ __slots__ = (
223
+ "engine",
224
+ "sync_engine",
225
+ "sync_connection",
226
+ )
227
+
228
+ def __init__(
229
+ self,
230
+ async_engine: AsyncEngine,
231
+ sync_connection: Optional[Connection] = None,
232
+ ):
233
+ self.engine = async_engine
234
+ self.sync_engine = async_engine.sync_engine
235
+ self.sync_connection = self._assign_proxied(sync_connection)
236
+
237
+ sync_connection: Optional[Connection]
238
+ """Reference to the sync-style :class:`_engine.Connection` this
239
+ :class:`_asyncio.AsyncConnection` proxies requests towards.
240
+
241
+ This instance can be used as an event target.
242
+
243
+ .. seealso::
244
+
245
+ :ref:`asyncio_events`
246
+
247
+ """
248
+
249
+ sync_engine: Engine
250
+ """Reference to the sync-style :class:`_engine.Engine` this
251
+ :class:`_asyncio.AsyncConnection` is associated with via its underlying
252
+ :class:`_engine.Connection`.
253
+
254
+ This instance can be used as an event target.
255
+
256
+ .. seealso::
257
+
258
+ :ref:`asyncio_events`
259
+
260
+ """
261
+
262
+ @classmethod
263
+ def _regenerate_proxy_for_target(
264
+ cls, target: Connection, **additional_kw: Any # noqa: U100
265
+ ) -> AsyncConnection:
266
+ return AsyncConnection(
267
+ AsyncEngine._retrieve_proxy_for_target(target.engine), target
268
+ )
269
+
270
+ async def start(
271
+ self, is_ctxmanager: bool = False # noqa: U100
272
+ ) -> AsyncConnection:
273
+ """Start this :class:`_asyncio.AsyncConnection` object's context
274
+ outside of using a Python ``with:`` block.
275
+
276
+ """
277
+ if self.sync_connection:
278
+ raise exc.InvalidRequestError("connection is already started")
279
+ self.sync_connection = self._assign_proxied(
280
+ await greenlet_spawn(self.sync_engine.connect)
281
+ )
282
+ return self
283
+
284
+ @property
285
+ def connection(self) -> NoReturn:
286
+ """Not implemented for async; call
287
+ :meth:`_asyncio.AsyncConnection.get_raw_connection`.
288
+ """
289
+ raise exc.InvalidRequestError(
290
+ "AsyncConnection.connection accessor is not implemented as the "
291
+ "attribute may need to reconnect on an invalidated connection. "
292
+ "Use the get_raw_connection() method."
293
+ )
294
+
295
+ async def get_raw_connection(self) -> PoolProxiedConnection:
296
+ """Return the pooled DBAPI-level connection in use by this
297
+ :class:`_asyncio.AsyncConnection`.
298
+
299
+ This is a SQLAlchemy connection-pool proxied connection
300
+ which then has the attribute
301
+ :attr:`_pool._ConnectionFairy.driver_connection` that refers to the
302
+ actual driver connection. Its
303
+ :attr:`_pool._ConnectionFairy.dbapi_connection` refers instead
304
+ to an :class:`_engine.AdaptedConnection` instance that
305
+ adapts the driver connection to the DBAPI protocol.
306
+
307
+ """
308
+
309
+ return await greenlet_spawn(getattr, self._proxied, "connection")
310
+
311
+ @util.ro_non_memoized_property
312
+ def info(self) -> _InfoType:
313
+ """Return the :attr:`_engine.Connection.info` dictionary of the
314
+ underlying :class:`_engine.Connection`.
315
+
316
+ This dictionary is freely writable for user-defined state to be
317
+ associated with the database connection.
318
+
319
+ This attribute is only available if the :class:`.AsyncConnection` is
320
+ currently connected. If the :attr:`.AsyncConnection.closed` attribute
321
+ is ``True``, then accessing this attribute will raise
322
+ :class:`.ResourceClosedError`.
323
+
324
+ .. versionadded:: 1.4.0b2
325
+
326
+ """
327
+ return self._proxied.info
328
+
329
+ @util.ro_non_memoized_property
330
+ def _proxied(self) -> Connection:
331
+ if not self.sync_connection:
332
+ self._raise_for_not_started()
333
+ return self.sync_connection
334
+
335
+ def begin(self) -> AsyncTransaction:
336
+ """Begin a transaction prior to autobegin occurring."""
337
+ assert self._proxied
338
+ return AsyncTransaction(self)
339
+
340
+ def begin_nested(self) -> AsyncTransaction:
341
+ """Begin a nested transaction and return a transaction handle."""
342
+ assert self._proxied
343
+ return AsyncTransaction(self, nested=True)
344
+
345
+ async def invalidate(
346
+ self, exception: Optional[BaseException] = None
347
+ ) -> None:
348
+ """Invalidate the underlying DBAPI connection associated with
349
+ this :class:`_engine.Connection`.
350
+
351
+ See the method :meth:`_engine.Connection.invalidate` for full
352
+ detail on this method.
353
+
354
+ """
355
+
356
+ return await greenlet_spawn(
357
+ self._proxied.invalidate, exception=exception
358
+ )
359
+
360
+ async def get_isolation_level(self) -> IsolationLevel:
361
+ return await greenlet_spawn(self._proxied.get_isolation_level)
362
+
363
+ def in_transaction(self) -> bool:
364
+ """Return True if a transaction is in progress."""
365
+
366
+ return self._proxied.in_transaction()
367
+
368
+ def in_nested_transaction(self) -> bool:
369
+ """Return True if a transaction is in progress.
370
+
371
+ .. versionadded:: 1.4.0b2
372
+
373
+ """
374
+ return self._proxied.in_nested_transaction()
375
+
376
+ def get_transaction(self) -> Optional[AsyncTransaction]:
377
+ """Return an :class:`.AsyncTransaction` representing the current
378
+ transaction, if any.
379
+
380
+ This makes use of the underlying synchronous connection's
381
+ :meth:`_engine.Connection.get_transaction` method to get the current
382
+ :class:`_engine.Transaction`, which is then proxied in a new
383
+ :class:`.AsyncTransaction` object.
384
+
385
+ .. versionadded:: 1.4.0b2
386
+
387
+ """
388
+
389
+ trans = self._proxied.get_transaction()
390
+ if trans is not None:
391
+ return AsyncTransaction._retrieve_proxy_for_target(trans)
392
+ else:
393
+ return None
394
+
395
+ def get_nested_transaction(self) -> Optional[AsyncTransaction]:
396
+ """Return an :class:`.AsyncTransaction` representing the current
397
+ nested (savepoint) transaction, if any.
398
+
399
+ This makes use of the underlying synchronous connection's
400
+ :meth:`_engine.Connection.get_nested_transaction` method to get the
401
+ current :class:`_engine.Transaction`, which is then proxied in a new
402
+ :class:`.AsyncTransaction` object.
403
+
404
+ .. versionadded:: 1.4.0b2
405
+
406
+ """
407
+
408
+ trans = self._proxied.get_nested_transaction()
409
+ if trans is not None:
410
+ return AsyncTransaction._retrieve_proxy_for_target(trans)
411
+ else:
412
+ return None
413
+
414
+ @overload
415
+ async def execution_options(
416
+ self,
417
+ *,
418
+ compiled_cache: Optional[CompiledCacheType] = ...,
419
+ logging_token: str = ...,
420
+ isolation_level: IsolationLevel = ...,
421
+ no_parameters: bool = False,
422
+ stream_results: bool = False,
423
+ max_row_buffer: int = ...,
424
+ yield_per: int = ...,
425
+ insertmanyvalues_page_size: int = ...,
426
+ schema_translate_map: Optional[SchemaTranslateMapType] = ...,
427
+ preserve_rowcount: bool = False,
428
+ driver_column_names: bool = False,
429
+ **opt: Any,
430
+ ) -> AsyncConnection: ...
431
+
432
+ @overload
433
+ async def execution_options(self, **opt: Any) -> AsyncConnection: ...
434
+
435
+ async def execution_options(self, **opt: Any) -> AsyncConnection:
436
+ r"""Set non-SQL options for the connection which take effect
437
+ during execution.
438
+
439
+ This returns this :class:`_asyncio.AsyncConnection` object with
440
+ the new options added.
441
+
442
+ See :meth:`_engine.Connection.execution_options` for full details
443
+ on this method.
444
+
445
+ """
446
+
447
+ conn = self._proxied
448
+ c2 = await greenlet_spawn(conn.execution_options, **opt)
449
+ assert c2 is conn
450
+ return self
451
+
452
+ async def commit(self) -> None:
453
+ """Commit the transaction that is currently in progress.
454
+
455
+ This method commits the current transaction if one has been started.
456
+ If no transaction was started, the method has no effect, assuming
457
+ the connection is in a non-invalidated state.
458
+
459
+ A transaction is begun on a :class:`_engine.Connection` automatically
460
+ whenever a statement is first executed, or when the
461
+ :meth:`_engine.Connection.begin` method is called.
462
+
463
+ """
464
+ await greenlet_spawn(self._proxied.commit)
465
+
466
+ async def rollback(self) -> None:
467
+ """Roll back the transaction that is currently in progress.
468
+
469
+ This method rolls back the current transaction if one has been started.
470
+ If no transaction was started, the method has no effect. If a
471
+ transaction was started and the connection is in an invalidated state,
472
+ the transaction is cleared using this method.
473
+
474
+ A transaction is begun on a :class:`_engine.Connection` automatically
475
+ whenever a statement is first executed, or when the
476
+ :meth:`_engine.Connection.begin` method is called.
477
+
478
+
479
+ """
480
+ await greenlet_spawn(self._proxied.rollback)
481
+
482
+ async def close(self) -> None:
483
+ """Close this :class:`_asyncio.AsyncConnection`.
484
+
485
+ This has the effect of also rolling back the transaction if one
486
+ is in place.
487
+
488
+ """
489
+ await greenlet_spawn(self._proxied.close)
490
+
491
+ async def aclose(self) -> None:
492
+ """A synonym for :meth:`_asyncio.AsyncConnection.close`.
493
+
494
+ The :meth:`_asyncio.AsyncConnection.aclose` name is specifically
495
+ to support the Python standard library ``@contextlib.aclosing``
496
+ context manager function.
497
+
498
+ .. versionadded:: 2.0.20
499
+
500
+ """
501
+ await self.close()
502
+
503
+ async def exec_driver_sql(
504
+ self,
505
+ statement: str,
506
+ parameters: Optional[_DBAPIAnyExecuteParams] = None,
507
+ execution_options: Optional[CoreExecuteOptionsParameter] = None,
508
+ ) -> CursorResult[Any]:
509
+ r"""Executes a driver-level SQL string and return buffered
510
+ :class:`_engine.Result`.
511
+
512
+ """
513
+
514
+ result = await greenlet_spawn(
515
+ self._proxied.exec_driver_sql,
516
+ statement,
517
+ parameters,
518
+ execution_options,
519
+ _require_await=True,
520
+ )
521
+
522
+ return await _ensure_sync_result(result, self.exec_driver_sql)
523
+
524
+ @overload
525
+ def stream(
526
+ self,
527
+ statement: TypedReturnsRows[Unpack[_Ts]],
528
+ parameters: Optional[_CoreAnyExecuteParams] = None,
529
+ *,
530
+ execution_options: Optional[CoreExecuteOptionsParameter] = None,
531
+ ) -> GeneratorStartableContext[AsyncResult[Unpack[_Ts]]]: ...
532
+
533
+ @overload
534
+ def stream(
535
+ self,
536
+ statement: Executable,
537
+ parameters: Optional[_CoreAnyExecuteParams] = None,
538
+ *,
539
+ execution_options: Optional[CoreExecuteOptionsParameter] = None,
540
+ ) -> GeneratorStartableContext[AsyncResult[Unpack[TupleAny]]]: ...
541
+
542
+ @asyncstartablecontext
543
+ async def stream(
544
+ self,
545
+ statement: Executable,
546
+ parameters: Optional[_CoreAnyExecuteParams] = None,
547
+ *,
548
+ execution_options: Optional[CoreExecuteOptionsParameter] = None,
549
+ ) -> AsyncIterator[AsyncResult[Unpack[TupleAny]]]:
550
+ """Execute a statement and return an awaitable yielding a
551
+ :class:`_asyncio.AsyncResult` object.
552
+
553
+ E.g.::
554
+
555
+ result = await conn.stream(stmt)
556
+ async for row in result:
557
+ print(f"{row}")
558
+
559
+ The :meth:`.AsyncConnection.stream`
560
+ method supports optional context manager use against the
561
+ :class:`.AsyncResult` object, as in::
562
+
563
+ async with conn.stream(stmt) as result:
564
+ async for row in result:
565
+ print(f"{row}")
566
+
567
+ In the above pattern, the :meth:`.AsyncResult.close` method is
568
+ invoked unconditionally, even if the iterator is interrupted by an
569
+ exception throw. Context manager use remains optional, however,
570
+ and the function may be called in either an ``async with fn():`` or
571
+ ``await fn()`` style.
572
+
573
+ .. versionadded:: 2.0.0b3 added context manager support
574
+
575
+
576
+ :return: an awaitable object that will yield an
577
+ :class:`_asyncio.AsyncResult` object.
578
+
579
+ .. seealso::
580
+
581
+ :meth:`.AsyncConnection.stream_scalars`
582
+
583
+ """
584
+ if not self.dialect.supports_server_side_cursors:
585
+ raise exc.InvalidRequestError(
586
+ "Can't use `stream` or `stream_scalars` with the current "
587
+ "dialect since it does not support server side cursors."
588
+ )
589
+
590
+ result = await greenlet_spawn(
591
+ self._proxied.execute,
592
+ statement,
593
+ parameters,
594
+ execution_options=util.EMPTY_DICT.merge_with(
595
+ execution_options, _stream_results
596
+ ),
597
+ _require_await=True,
598
+ )
599
+ assert result.context._is_server_side
600
+ ar = AsyncResult(result)
601
+ try:
602
+ yield ar
603
+ except GeneratorExit:
604
+ pass
605
+ else:
606
+ task = asyncio.create_task(ar.close())
607
+ await asyncio.shield(task)
608
+
609
+ @overload
610
+ async def execute(
611
+ self,
612
+ statement: TypedReturnsRows[Unpack[_Ts]],
613
+ parameters: Optional[_CoreAnyExecuteParams] = None,
614
+ *,
615
+ execution_options: Optional[CoreExecuteOptionsParameter] = None,
616
+ ) -> CursorResult[Unpack[_Ts]]: ...
617
+
618
+ @overload
619
+ async def execute(
620
+ self,
621
+ statement: Executable,
622
+ parameters: Optional[_CoreAnyExecuteParams] = None,
623
+ *,
624
+ execution_options: Optional[CoreExecuteOptionsParameter] = None,
625
+ ) -> CursorResult[Unpack[TupleAny]]: ...
626
+
627
+ async def execute(
628
+ self,
629
+ statement: Executable,
630
+ parameters: Optional[_CoreAnyExecuteParams] = None,
631
+ *,
632
+ execution_options: Optional[CoreExecuteOptionsParameter] = None,
633
+ ) -> CursorResult[Unpack[TupleAny]]:
634
+ r"""Executes a SQL statement construct and return a buffered
635
+ :class:`_engine.Result`.
636
+
637
+ :param object: The statement to be executed. This is always
638
+ an object that is in both the :class:`_expression.ClauseElement` and
639
+ :class:`_expression.Executable` hierarchies, including:
640
+
641
+ * :class:`_expression.Select`
642
+ * :class:`_expression.Insert`, :class:`_expression.Update`,
643
+ :class:`_expression.Delete`
644
+ * :class:`_expression.TextClause` and
645
+ :class:`_expression.TextualSelect`
646
+ * :class:`_schema.DDL` and objects which inherit from
647
+ :class:`_schema.ExecutableDDLElement`
648
+
649
+ :param parameters: parameters which will be bound into the statement.
650
+ This may be either a dictionary of parameter names to values,
651
+ or a mutable sequence (e.g. a list) of dictionaries. When a
652
+ list of dictionaries is passed, the underlying statement execution
653
+ will make use of the DBAPI ``cursor.executemany()`` method.
654
+ When a single dictionary is passed, the DBAPI ``cursor.execute()``
655
+ method will be used.
656
+
657
+ :param execution_options: optional dictionary of execution options,
658
+ which will be associated with the statement execution. This
659
+ dictionary can provide a subset of the options that are accepted
660
+ by :meth:`_engine.Connection.execution_options`.
661
+
662
+ :return: a :class:`_engine.Result` object.
663
+
664
+ """
665
+ result = await greenlet_spawn(
666
+ self._proxied.execute,
667
+ statement,
668
+ parameters,
669
+ execution_options=execution_options,
670
+ _require_await=True,
671
+ )
672
+ return await _ensure_sync_result(result, self.execute)
673
+
674
+ @overload
675
+ async def scalar(
676
+ self,
677
+ statement: TypedReturnsRows[_T],
678
+ parameters: Optional[_CoreSingleExecuteParams] = None,
679
+ *,
680
+ execution_options: Optional[CoreExecuteOptionsParameter] = None,
681
+ ) -> Optional[_T]: ...
682
+
683
+ @overload
684
+ async def scalar(
685
+ self,
686
+ statement: Executable,
687
+ parameters: Optional[_CoreSingleExecuteParams] = None,
688
+ *,
689
+ execution_options: Optional[CoreExecuteOptionsParameter] = None,
690
+ ) -> Any: ...
691
+
692
+ async def scalar(
693
+ self,
694
+ statement: Executable,
695
+ parameters: Optional[_CoreSingleExecuteParams] = None,
696
+ *,
697
+ execution_options: Optional[CoreExecuteOptionsParameter] = None,
698
+ ) -> Any:
699
+ r"""Executes a SQL statement construct and returns a scalar object.
700
+
701
+ This method is shorthand for invoking the
702
+ :meth:`_engine.Result.scalar` method after invoking the
703
+ :meth:`_engine.Connection.execute` method. Parameters are equivalent.
704
+
705
+ :return: a scalar Python value representing the first column of the
706
+ first row returned.
707
+
708
+ """
709
+ result = await self.execute(
710
+ statement, parameters, execution_options=execution_options
711
+ )
712
+ return result.scalar()
713
+
714
+ @overload
715
+ async def scalars(
716
+ self,
717
+ statement: TypedReturnsRows[_T],
718
+ parameters: Optional[_CoreAnyExecuteParams] = None,
719
+ *,
720
+ execution_options: Optional[CoreExecuteOptionsParameter] = None,
721
+ ) -> ScalarResult[_T]: ...
722
+
723
+ @overload
724
+ async def scalars(
725
+ self,
726
+ statement: Executable,
727
+ parameters: Optional[_CoreAnyExecuteParams] = None,
728
+ *,
729
+ execution_options: Optional[CoreExecuteOptionsParameter] = None,
730
+ ) -> ScalarResult[Any]: ...
731
+
732
+ async def scalars(
733
+ self,
734
+ statement: Executable,
735
+ parameters: Optional[_CoreAnyExecuteParams] = None,
736
+ *,
737
+ execution_options: Optional[CoreExecuteOptionsParameter] = None,
738
+ ) -> ScalarResult[Any]:
739
+ r"""Executes a SQL statement construct and returns a scalar objects.
740
+
741
+ This method is shorthand for invoking the
742
+ :meth:`_engine.Result.scalars` method after invoking the
743
+ :meth:`_engine.Connection.execute` method. Parameters are equivalent.
744
+
745
+ :return: a :class:`_engine.ScalarResult` object.
746
+
747
+ .. versionadded:: 1.4.24
748
+
749
+ """
750
+ result = await self.execute(
751
+ statement, parameters, execution_options=execution_options
752
+ )
753
+ return result.scalars()
754
+
755
+ @overload
756
+ def stream_scalars(
757
+ self,
758
+ statement: TypedReturnsRows[_T],
759
+ parameters: Optional[_CoreSingleExecuteParams] = None,
760
+ *,
761
+ execution_options: Optional[CoreExecuteOptionsParameter] = None,
762
+ ) -> GeneratorStartableContext[AsyncScalarResult[_T]]: ...
763
+
764
+ @overload
765
+ def stream_scalars(
766
+ self,
767
+ statement: Executable,
768
+ parameters: Optional[_CoreSingleExecuteParams] = None,
769
+ *,
770
+ execution_options: Optional[CoreExecuteOptionsParameter] = None,
771
+ ) -> GeneratorStartableContext[AsyncScalarResult[Any]]: ...
772
+
773
+ @asyncstartablecontext
774
+ async def stream_scalars(
775
+ self,
776
+ statement: Executable,
777
+ parameters: Optional[_CoreSingleExecuteParams] = None,
778
+ *,
779
+ execution_options: Optional[CoreExecuteOptionsParameter] = None,
780
+ ) -> AsyncIterator[AsyncScalarResult[Any]]:
781
+ r"""Execute a statement and return an awaitable yielding a
782
+ :class:`_asyncio.AsyncScalarResult` object.
783
+
784
+ E.g.::
785
+
786
+ result = await conn.stream_scalars(stmt)
787
+ async for scalar in result:
788
+ print(f"{scalar}")
789
+
790
+ This method is shorthand for invoking the
791
+ :meth:`_engine.AsyncResult.scalars` method after invoking the
792
+ :meth:`_engine.Connection.stream` method. Parameters are equivalent.
793
+
794
+ The :meth:`.AsyncConnection.stream_scalars`
795
+ method supports optional context manager use against the
796
+ :class:`.AsyncScalarResult` object, as in::
797
+
798
+ async with conn.stream_scalars(stmt) as result:
799
+ async for scalar in result:
800
+ print(f"{scalar}")
801
+
802
+ In the above pattern, the :meth:`.AsyncScalarResult.close` method is
803
+ invoked unconditionally, even if the iterator is interrupted by an
804
+ exception throw. Context manager use remains optional, however,
805
+ and the function may be called in either an ``async with fn():`` or
806
+ ``await fn()`` style.
807
+
808
+ .. versionadded:: 2.0.0b3 added context manager support
809
+
810
+ :return: an awaitable object that will yield an
811
+ :class:`_asyncio.AsyncScalarResult` object.
812
+
813
+ .. versionadded:: 1.4.24
814
+
815
+ .. seealso::
816
+
817
+ :meth:`.AsyncConnection.stream`
818
+
819
+ """
820
+
821
+ async with self.stream(
822
+ statement, parameters, execution_options=execution_options
823
+ ) as result:
824
+ yield result.scalars()
825
+
826
+ async def run_sync(
827
+ self,
828
+ fn: Callable[Concatenate[Connection, _P], _T],
829
+ *arg: _P.args,
830
+ **kw: _P.kwargs,
831
+ ) -> _T:
832
+ '''Invoke the given synchronous (i.e. not async) callable,
833
+ passing a synchronous-style :class:`_engine.Connection` as the first
834
+ argument.
835
+
836
+ This method allows traditional synchronous SQLAlchemy functions to
837
+ run within the context of an asyncio application.
838
+
839
+ E.g.::
840
+
841
+ def do_something_with_core(conn: Connection, arg1: int, arg2: str) -> str:
842
+ """A synchronous function that does not require awaiting
843
+
844
+ :param conn: a Core SQLAlchemy Connection, used synchronously
845
+
846
+ :return: an optional return value is supported
847
+
848
+ """
849
+ conn.execute(some_table.insert().values(int_col=arg1, str_col=arg2))
850
+ return "success"
851
+
852
+
853
+ async def do_something_async(async_engine: AsyncEngine) -> None:
854
+ """an async function that uses awaiting"""
855
+
856
+ async with async_engine.begin() as async_conn:
857
+ # run do_something_with_core() with a sync-style
858
+ # Connection, proxied into an awaitable
859
+ return_code = await async_conn.run_sync(
860
+ do_something_with_core, 5, "strval"
861
+ )
862
+ print(return_code)
863
+
864
+ This method maintains the asyncio event loop all the way through
865
+ to the database connection by running the given callable in a
866
+ specially instrumented greenlet.
867
+
868
+ The most rudimentary use of :meth:`.AsyncConnection.run_sync` is to
869
+ invoke methods such as :meth:`_schema.MetaData.create_all`, given
870
+ an :class:`.AsyncConnection` that needs to be provided to
871
+ :meth:`_schema.MetaData.create_all` as a :class:`_engine.Connection`
872
+ object::
873
+
874
+ # run metadata.create_all(conn) with a sync-style Connection,
875
+ # proxied into an awaitable
876
+ with async_engine.begin() as conn:
877
+ await conn.run_sync(metadata.create_all)
878
+
879
+ .. note::
880
+
881
+ The provided callable is invoked inline within the asyncio event
882
+ loop, and will block on traditional IO calls. IO within this
883
+ callable should only call into SQLAlchemy's asyncio database
884
+ APIs which will be properly adapted to the greenlet context.
885
+
886
+ .. seealso::
887
+
888
+ :meth:`.AsyncSession.run_sync`
889
+
890
+ :ref:`session_run_sync`
891
+
892
+ ''' # noqa: E501
893
+
894
+ return await greenlet_spawn(
895
+ fn, self._proxied, *arg, _require_await=False, **kw
896
+ )
897
+
898
+ def __await__(self) -> Generator[Any, None, AsyncConnection]:
899
+ return self.start().__await__()
900
+
901
+ async def __aexit__(self, type_: Any, value: Any, traceback: Any) -> None:
902
+ task = asyncio.create_task(self.close())
903
+ await asyncio.shield(task)
904
+
905
+ # START PROXY METHODS AsyncConnection
906
+
907
+ # code within this block is **programmatically,
908
+ # statically generated** by tools/generate_proxy_methods.py
909
+
910
+ @property
911
+ def closed(self) -> Any:
912
+ r"""Return True if this connection is closed.
913
+
914
+ .. container:: class_bases
915
+
916
+ Proxied for the :class:`_engine.Connection` class
917
+ on behalf of the :class:`_asyncio.AsyncConnection` class.
918
+
919
+ """ # noqa: E501
920
+
921
+ return self._proxied.closed
922
+
923
+ @property
924
+ def invalidated(self) -> Any:
925
+ r"""Return True if this connection was invalidated.
926
+
927
+ .. container:: class_bases
928
+
929
+ Proxied for the :class:`_engine.Connection` class
930
+ on behalf of the :class:`_asyncio.AsyncConnection` class.
931
+
932
+ This does not indicate whether or not the connection was
933
+ invalidated at the pool level, however
934
+
935
+
936
+ """ # noqa: E501
937
+
938
+ return self._proxied.invalidated
939
+
940
+ @property
941
+ def dialect(self) -> Dialect:
942
+ r"""Proxy for the :attr:`_engine.Connection.dialect` attribute
943
+ on behalf of the :class:`_asyncio.AsyncConnection` class.
944
+
945
+ """ # noqa: E501
946
+
947
+ return self._proxied.dialect
948
+
949
+ @dialect.setter
950
+ def dialect(self, attr: Dialect) -> None:
951
+ self._proxied.dialect = attr
952
+
953
+ @property
954
+ def default_isolation_level(self) -> Any:
955
+ r"""The initial-connection time isolation level associated with the
956
+ :class:`_engine.Dialect` in use.
957
+
958
+ .. container:: class_bases
959
+
960
+ Proxied for the :class:`_engine.Connection` class
961
+ on behalf of the :class:`_asyncio.AsyncConnection` class.
962
+
963
+ This value is independent of the
964
+ :paramref:`.Connection.execution_options.isolation_level` and
965
+ :paramref:`.Engine.execution_options.isolation_level` execution
966
+ options, and is determined by the :class:`_engine.Dialect` when the
967
+ first connection is created, by performing a SQL query against the
968
+ database for the current isolation level before any additional commands
969
+ have been emitted.
970
+
971
+ Calling this accessor does not invoke any new SQL queries.
972
+
973
+ .. seealso::
974
+
975
+ :meth:`_engine.Connection.get_isolation_level`
976
+ - view current actual isolation level
977
+
978
+ :paramref:`_sa.create_engine.isolation_level`
979
+ - set per :class:`_engine.Engine` isolation level
980
+
981
+ :paramref:`.Connection.execution_options.isolation_level`
982
+ - set per :class:`_engine.Connection` isolation level
983
+
984
+
985
+ """ # noqa: E501
986
+
987
+ return self._proxied.default_isolation_level
988
+
989
+ # END PROXY METHODS AsyncConnection
990
+
991
+
992
+ @util.create_proxy_methods(
993
+ Engine,
994
+ ":class:`_engine.Engine`",
995
+ ":class:`_asyncio.AsyncEngine`",
996
+ classmethods=[],
997
+ methods=[
998
+ "clear_compiled_cache",
999
+ "update_execution_options",
1000
+ "get_execution_options",
1001
+ ],
1002
+ attributes=["url", "pool", "dialect", "engine", "name", "driver", "echo"],
1003
+ )
1004
+ # "Class has incompatible disjoint bases" - no idea
1005
+ class AsyncEngine(ProxyComparable[Engine], AsyncConnectable): # type: ignore[misc] # noqa:E501
1006
+ """An asyncio proxy for a :class:`_engine.Engine`.
1007
+
1008
+ :class:`_asyncio.AsyncEngine` is acquired using the
1009
+ :func:`_asyncio.create_async_engine` function::
1010
+
1011
+ from sqlalchemy.ext.asyncio import create_async_engine
1012
+
1013
+ engine = create_async_engine("postgresql+asyncpg://user:pass@host/dbname")
1014
+
1015
+ .. versionadded:: 1.4
1016
+
1017
+ """ # noqa
1018
+
1019
+ # AsyncEngine is a thin proxy; no state should be added here
1020
+ # that is not retrievable from the "sync" engine / connection, e.g.
1021
+ # current transaction, info, etc. It should be possible to
1022
+ # create a new AsyncEngine that matches this one given only the
1023
+ # "sync" elements.
1024
+ __slots__ = "sync_engine"
1025
+
1026
+ _connection_cls: Type[AsyncConnection] = AsyncConnection
1027
+
1028
+ sync_engine: Engine
1029
+ """Reference to the sync-style :class:`_engine.Engine` this
1030
+ :class:`_asyncio.AsyncEngine` proxies requests towards.
1031
+
1032
+ This instance can be used as an event target.
1033
+
1034
+ .. seealso::
1035
+
1036
+ :ref:`asyncio_events`
1037
+ """
1038
+
1039
+ def __init__(self, sync_engine: Engine):
1040
+ if not sync_engine.dialect.is_async:
1041
+ raise exc.InvalidRequestError(
1042
+ "The asyncio extension requires an async driver to be used. "
1043
+ f"The loaded {sync_engine.dialect.driver!r} is not async."
1044
+ )
1045
+ self.sync_engine = self._assign_proxied(sync_engine)
1046
+
1047
+ @util.ro_non_memoized_property
1048
+ def _proxied(self) -> Engine:
1049
+ return self.sync_engine
1050
+
1051
+ @classmethod
1052
+ def _regenerate_proxy_for_target(
1053
+ cls, target: Engine, **additional_kw: Any # noqa: U100
1054
+ ) -> AsyncEngine:
1055
+ return AsyncEngine(target)
1056
+
1057
+ @contextlib.asynccontextmanager
1058
+ async def begin(self) -> AsyncIterator[AsyncConnection]:
1059
+ """Return a context manager which when entered will deliver an
1060
+ :class:`_asyncio.AsyncConnection` with an
1061
+ :class:`_asyncio.AsyncTransaction` established.
1062
+
1063
+ E.g.::
1064
+
1065
+ async with async_engine.begin() as conn:
1066
+ await conn.execute(
1067
+ text("insert into table (x, y, z) values (1, 2, 3)")
1068
+ )
1069
+ await conn.execute(text("my_special_procedure(5)"))
1070
+
1071
+ """
1072
+ conn = self.connect()
1073
+
1074
+ async with conn:
1075
+ async with conn.begin():
1076
+ yield conn
1077
+
1078
+ def connect(self) -> AsyncConnection:
1079
+ """Return an :class:`_asyncio.AsyncConnection` object.
1080
+
1081
+ The :class:`_asyncio.AsyncConnection` will procure a database
1082
+ connection from the underlying connection pool when it is entered
1083
+ as an async context manager::
1084
+
1085
+ async with async_engine.connect() as conn:
1086
+ result = await conn.execute(select(user_table))
1087
+
1088
+ The :class:`_asyncio.AsyncConnection` may also be started outside of a
1089
+ context manager by invoking its :meth:`_asyncio.AsyncConnection.start`
1090
+ method.
1091
+
1092
+ """
1093
+
1094
+ return self._connection_cls(self)
1095
+
1096
+ async def raw_connection(self) -> PoolProxiedConnection:
1097
+ """Return a "raw" DBAPI connection from the connection pool.
1098
+
1099
+ .. seealso::
1100
+
1101
+ :ref:`dbapi_connections`
1102
+
1103
+ """
1104
+ return await greenlet_spawn(self.sync_engine.raw_connection)
1105
+
1106
+ @overload
1107
+ def execution_options(
1108
+ self,
1109
+ *,
1110
+ compiled_cache: Optional[CompiledCacheType] = ...,
1111
+ logging_token: str = ...,
1112
+ isolation_level: IsolationLevel = ...,
1113
+ insertmanyvalues_page_size: int = ...,
1114
+ schema_translate_map: Optional[SchemaTranslateMapType] = ...,
1115
+ **opt: Any,
1116
+ ) -> AsyncEngine: ...
1117
+
1118
+ @overload
1119
+ def execution_options(self, **opt: Any) -> AsyncEngine: ...
1120
+
1121
+ def execution_options(self, **opt: Any) -> AsyncEngine:
1122
+ """Return a new :class:`_asyncio.AsyncEngine` that will provide
1123
+ :class:`_asyncio.AsyncConnection` objects with the given execution
1124
+ options.
1125
+
1126
+ Proxied from :meth:`_engine.Engine.execution_options`. See that
1127
+ method for details.
1128
+
1129
+ """
1130
+
1131
+ return AsyncEngine(self.sync_engine.execution_options(**opt))
1132
+
1133
+ async def dispose(self, close: bool = True) -> None:
1134
+ """Dispose of the connection pool used by this
1135
+ :class:`_asyncio.AsyncEngine`.
1136
+
1137
+ :param close: if left at its default of ``True``, has the
1138
+ effect of fully closing all **currently checked in**
1139
+ database connections. Connections that are still checked out
1140
+ will **not** be closed, however they will no longer be associated
1141
+ with this :class:`_engine.Engine`,
1142
+ so when they are closed individually, eventually the
1143
+ :class:`_pool.Pool` which they are associated with will
1144
+ be garbage collected and they will be closed out fully, if
1145
+ not already closed on checkin.
1146
+
1147
+ If set to ``False``, the previous connection pool is de-referenced,
1148
+ and otherwise not touched in any way.
1149
+
1150
+ .. seealso::
1151
+
1152
+ :meth:`_engine.Engine.dispose`
1153
+
1154
+ """
1155
+
1156
+ await greenlet_spawn(self.sync_engine.dispose, close=close)
1157
+
1158
+ # START PROXY METHODS AsyncEngine
1159
+
1160
+ # code within this block is **programmatically,
1161
+ # statically generated** by tools/generate_proxy_methods.py
1162
+
1163
+ def clear_compiled_cache(self) -> None:
1164
+ r"""Clear the compiled cache associated with the dialect.
1165
+
1166
+ .. container:: class_bases
1167
+
1168
+ Proxied for the :class:`_engine.Engine` class on
1169
+ behalf of the :class:`_asyncio.AsyncEngine` class.
1170
+
1171
+ This applies **only** to the built-in cache that is established
1172
+ via the :paramref:`_engine.create_engine.query_cache_size` parameter.
1173
+ It will not impact any dictionary caches that were passed via the
1174
+ :paramref:`.Connection.execution_options.compiled_cache` parameter.
1175
+
1176
+ .. versionadded:: 1.4
1177
+
1178
+
1179
+ """ # noqa: E501
1180
+
1181
+ return self._proxied.clear_compiled_cache()
1182
+
1183
+ def update_execution_options(self, **opt: Any) -> None:
1184
+ r"""Update the default execution_options dictionary
1185
+ of this :class:`_engine.Engine`.
1186
+
1187
+ .. container:: class_bases
1188
+
1189
+ Proxied for the :class:`_engine.Engine` class on
1190
+ behalf of the :class:`_asyncio.AsyncEngine` class.
1191
+
1192
+ The given keys/values in \**opt are added to the
1193
+ default execution options that will be used for
1194
+ all connections. The initial contents of this dictionary
1195
+ can be sent via the ``execution_options`` parameter
1196
+ to :func:`_sa.create_engine`.
1197
+
1198
+ .. seealso::
1199
+
1200
+ :meth:`_engine.Connection.execution_options`
1201
+
1202
+ :meth:`_engine.Engine.execution_options`
1203
+
1204
+
1205
+ """ # noqa: E501
1206
+
1207
+ return self._proxied.update_execution_options(**opt)
1208
+
1209
+ def get_execution_options(self) -> _ExecuteOptions:
1210
+ r"""Get the non-SQL options which will take effect during execution.
1211
+
1212
+ .. container:: class_bases
1213
+
1214
+ Proxied for the :class:`_engine.Engine` class on
1215
+ behalf of the :class:`_asyncio.AsyncEngine` class.
1216
+
1217
+ .. seealso::
1218
+
1219
+ :meth:`_engine.Engine.execution_options`
1220
+
1221
+ """ # noqa: E501
1222
+
1223
+ return self._proxied.get_execution_options()
1224
+
1225
+ @property
1226
+ def url(self) -> URL:
1227
+ r"""Proxy for the :attr:`_engine.Engine.url` attribute
1228
+ on behalf of the :class:`_asyncio.AsyncEngine` class.
1229
+
1230
+ """ # noqa: E501
1231
+
1232
+ return self._proxied.url
1233
+
1234
+ @url.setter
1235
+ def url(self, attr: URL) -> None:
1236
+ self._proxied.url = attr
1237
+
1238
+ @property
1239
+ def pool(self) -> Pool:
1240
+ r"""Proxy for the :attr:`_engine.Engine.pool` attribute
1241
+ on behalf of the :class:`_asyncio.AsyncEngine` class.
1242
+
1243
+ """ # noqa: E501
1244
+
1245
+ return self._proxied.pool
1246
+
1247
+ @pool.setter
1248
+ def pool(self, attr: Pool) -> None:
1249
+ self._proxied.pool = attr
1250
+
1251
+ @property
1252
+ def dialect(self) -> Dialect:
1253
+ r"""Proxy for the :attr:`_engine.Engine.dialect` attribute
1254
+ on behalf of the :class:`_asyncio.AsyncEngine` class.
1255
+
1256
+ """ # noqa: E501
1257
+
1258
+ return self._proxied.dialect
1259
+
1260
+ @dialect.setter
1261
+ def dialect(self, attr: Dialect) -> None:
1262
+ self._proxied.dialect = attr
1263
+
1264
+ @property
1265
+ def engine(self) -> Any:
1266
+ r"""Returns this :class:`.Engine`.
1267
+
1268
+ .. container:: class_bases
1269
+
1270
+ Proxied for the :class:`_engine.Engine` class
1271
+ on behalf of the :class:`_asyncio.AsyncEngine` class.
1272
+
1273
+ Used for legacy schemes that accept :class:`.Connection` /
1274
+ :class:`.Engine` objects within the same variable.
1275
+
1276
+
1277
+ """ # noqa: E501
1278
+
1279
+ return self._proxied.engine
1280
+
1281
+ @property
1282
+ def name(self) -> Any:
1283
+ r"""String name of the :class:`~sqlalchemy.engine.interfaces.Dialect`
1284
+ in use by this :class:`Engine`.
1285
+
1286
+ .. container:: class_bases
1287
+
1288
+ Proxied for the :class:`_engine.Engine` class
1289
+ on behalf of the :class:`_asyncio.AsyncEngine` class.
1290
+
1291
+
1292
+ """ # noqa: E501
1293
+
1294
+ return self._proxied.name
1295
+
1296
+ @property
1297
+ def driver(self) -> Any:
1298
+ r"""Driver name of the :class:`~sqlalchemy.engine.interfaces.Dialect`
1299
+ in use by this :class:`Engine`.
1300
+
1301
+ .. container:: class_bases
1302
+
1303
+ Proxied for the :class:`_engine.Engine` class
1304
+ on behalf of the :class:`_asyncio.AsyncEngine` class.
1305
+
1306
+
1307
+ """ # noqa: E501
1308
+
1309
+ return self._proxied.driver
1310
+
1311
+ @property
1312
+ def echo(self) -> Any:
1313
+ r"""When ``True``, enable log output for this element.
1314
+
1315
+ .. container:: class_bases
1316
+
1317
+ Proxied for the :class:`_engine.Engine` class
1318
+ on behalf of the :class:`_asyncio.AsyncEngine` class.
1319
+
1320
+ This has the effect of setting the Python logging level for the namespace
1321
+ of this element's class and object reference. A value of boolean ``True``
1322
+ indicates that the loglevel ``logging.INFO`` will be set for the logger,
1323
+ whereas the string value ``debug`` will set the loglevel to
1324
+ ``logging.DEBUG``.
1325
+
1326
+ """ # noqa: E501
1327
+
1328
+ return self._proxied.echo
1329
+
1330
+ @echo.setter
1331
+ def echo(self, attr: Any) -> None:
1332
+ self._proxied.echo = attr
1333
+
1334
+ # END PROXY METHODS AsyncEngine
1335
+
1336
+
1337
+ class AsyncTransaction(
1338
+ ProxyComparable[Transaction], StartableContext["AsyncTransaction"]
1339
+ ):
1340
+ """An asyncio proxy for a :class:`_engine.Transaction`."""
1341
+
1342
+ __slots__ = ("connection", "sync_transaction", "nested")
1343
+
1344
+ sync_transaction: Optional[Transaction]
1345
+ connection: AsyncConnection
1346
+ nested: bool
1347
+
1348
+ def __init__(self, connection: AsyncConnection, nested: bool = False):
1349
+ self.connection = connection
1350
+ self.sync_transaction = None
1351
+ self.nested = nested
1352
+
1353
+ @classmethod
1354
+ def _regenerate_proxy_for_target(
1355
+ cls, target: Transaction, **additional_kw: Any # noqa: U100
1356
+ ) -> AsyncTransaction:
1357
+ sync_connection = target.connection
1358
+ sync_transaction = target
1359
+ nested = isinstance(target, NestedTransaction)
1360
+
1361
+ async_connection = AsyncConnection._retrieve_proxy_for_target(
1362
+ sync_connection
1363
+ )
1364
+ assert async_connection is not None
1365
+
1366
+ obj = cls.__new__(cls)
1367
+ obj.connection = async_connection
1368
+ obj.sync_transaction = obj._assign_proxied(sync_transaction)
1369
+ obj.nested = nested
1370
+ return obj
1371
+
1372
+ @util.ro_non_memoized_property
1373
+ def _proxied(self) -> Transaction:
1374
+ if not self.sync_transaction:
1375
+ self._raise_for_not_started()
1376
+ return self.sync_transaction
1377
+
1378
+ @property
1379
+ def is_valid(self) -> bool:
1380
+ return self._proxied.is_valid
1381
+
1382
+ @property
1383
+ def is_active(self) -> bool:
1384
+ return self._proxied.is_active
1385
+
1386
+ async def close(self) -> None:
1387
+ """Close this :class:`.AsyncTransaction`.
1388
+
1389
+ If this transaction is the base transaction in a begin/commit
1390
+ nesting, the transaction will rollback(). Otherwise, the
1391
+ method returns.
1392
+
1393
+ This is used to cancel a Transaction without affecting the scope of
1394
+ an enclosing transaction.
1395
+
1396
+ """
1397
+ await greenlet_spawn(self._proxied.close)
1398
+
1399
+ async def rollback(self) -> None:
1400
+ """Roll back this :class:`.AsyncTransaction`."""
1401
+ await greenlet_spawn(self._proxied.rollback)
1402
+
1403
+ async def commit(self) -> None:
1404
+ """Commit this :class:`.AsyncTransaction`."""
1405
+
1406
+ await greenlet_spawn(self._proxied.commit)
1407
+
1408
+ async def start(self, is_ctxmanager: bool = False) -> AsyncTransaction:
1409
+ """Start this :class:`_asyncio.AsyncTransaction` object's context
1410
+ outside of using a Python ``with:`` block.
1411
+
1412
+ """
1413
+
1414
+ self.sync_transaction = self._assign_proxied(
1415
+ await greenlet_spawn(
1416
+ self.connection._proxied.begin_nested
1417
+ if self.nested
1418
+ else self.connection._proxied.begin
1419
+ )
1420
+ )
1421
+ if is_ctxmanager:
1422
+ self.sync_transaction.__enter__()
1423
+ return self
1424
+
1425
+ async def __aexit__(self, type_: Any, value: Any, traceback: Any) -> None:
1426
+ await greenlet_spawn(self._proxied.__exit__, type_, value, traceback)
1427
+
1428
+
1429
+ @overload
1430
+ def _get_sync_engine_or_connection(async_engine: AsyncEngine) -> Engine: ...
1431
+
1432
+
1433
+ @overload
1434
+ def _get_sync_engine_or_connection(
1435
+ async_engine: AsyncConnection,
1436
+ ) -> Connection: ...
1437
+
1438
+
1439
+ def _get_sync_engine_or_connection(
1440
+ async_engine: Union[AsyncEngine, AsyncConnection],
1441
+ ) -> Union[Engine, Connection]:
1442
+ if isinstance(async_engine, AsyncConnection):
1443
+ return async_engine._proxied
1444
+
1445
+ try:
1446
+ return async_engine.sync_engine
1447
+ except AttributeError as e:
1448
+ raise exc.ArgumentError(
1449
+ "AsyncEngine expected, got %r" % async_engine
1450
+ ) from e
1451
+
1452
+
1453
+ @inspection._inspects(AsyncConnection)
1454
+ def _no_insp_for_async_conn_yet(
1455
+ subject: AsyncConnection, # noqa: U100
1456
+ ) -> NoReturn:
1457
+ raise exc.NoInspectionAvailable(
1458
+ "Inspection on an AsyncConnection is currently not supported. "
1459
+ "Please use ``run_sync`` to pass a callable where it's possible "
1460
+ "to call ``inspect`` on the passed connection.",
1461
+ code="xd3s",
1462
+ )
1463
+
1464
+
1465
+ @inspection._inspects(AsyncEngine)
1466
+ def _no_insp_for_async_engine_xyet(
1467
+ subject: AsyncEngine, # noqa: U100
1468
+ ) -> NoReturn:
1469
+ raise exc.NoInspectionAvailable(
1470
+ "Inspection on an AsyncEngine is currently not supported. "
1471
+ "Please obtain a connection then use ``conn.run_sync`` to pass a "
1472
+ "callable where it's possible to call ``inspect`` on the "
1473
+ "passed connection.",
1474
+ code="xd3s",
1475
+ )