SQLAlchemy 2.0.36__cp313-cp313-win32.whl

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