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,1993 @@
1
+ # ext/asyncio/session.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
+ from typing import Any
11
+ from typing import Awaitable
12
+ from typing import Callable
13
+ from typing import cast
14
+ from typing import Concatenate
15
+ from typing import Dict
16
+ from typing import Generic
17
+ from typing import Iterable
18
+ from typing import Iterator
19
+ from typing import NoReturn
20
+ from typing import Optional
21
+ from typing import overload
22
+ from typing import ParamSpec
23
+ from typing import Sequence
24
+ from typing import Tuple
25
+ from typing import Type
26
+ from typing import TYPE_CHECKING
27
+ from typing import TypeVar
28
+ from typing import Union
29
+
30
+ from . import engine
31
+ from .base import ReversibleProxy
32
+ from .base import StartableContext
33
+ from .result import _ensure_sync_result
34
+ from .result import AsyncResult
35
+ from .result import AsyncScalarResult
36
+ from ... import util
37
+ from ...orm import close_all_sessions as _sync_close_all_sessions
38
+ from ...orm import object_session
39
+ from ...orm import Session
40
+ from ...orm import SessionTransaction
41
+ from ...orm import state as _instance_state
42
+ from ...util.concurrency import greenlet_spawn
43
+ from ...util.typing import TupleAny
44
+ from ...util.typing import TypeVarTuple
45
+ from ...util.typing import Unpack
46
+
47
+
48
+ if TYPE_CHECKING:
49
+ from .engine import AsyncConnection
50
+ from .engine import AsyncEngine
51
+ from ...engine import Connection
52
+ from ...engine import Engine
53
+ from ...engine import Result
54
+ from ...engine import Row
55
+ from ...engine import RowMapping
56
+ from ...engine import ScalarResult
57
+ from ...engine.interfaces import _CoreAnyExecuteParams
58
+ from ...engine.interfaces import _ExecuteOptions
59
+ from ...engine.interfaces import CoreExecuteOptionsParameter
60
+ from ...event import dispatcher
61
+ from ...orm._typing import _IdentityKeyType
62
+ from ...orm._typing import _O
63
+ from ...orm._typing import OrmExecuteOptionsParameter
64
+ from ...orm.identity import IdentityMap
65
+ from ...orm.interfaces import ORMOption
66
+ from ...orm.session import _BindArguments
67
+ from ...orm.session import _EntityBindKey
68
+ from ...orm.session import _PKIdentityArgument
69
+ from ...orm.session import _SessionBind
70
+ from ...orm.session import _SessionBindKey
71
+ from ...sql._typing import _InfoType
72
+ from ...sql.base import Executable
73
+ from ...sql.elements import ClauseElement
74
+ from ...sql.selectable import ForUpdateParameter
75
+ from ...sql.selectable import TypedReturnsRows
76
+
77
+ _AsyncSessionBind = Union["AsyncEngine", "AsyncConnection"]
78
+
79
+ _P = ParamSpec("_P")
80
+ _T = TypeVar("_T", bound=Any)
81
+ _Ts = TypeVarTuple("_Ts")
82
+
83
+ _EXECUTE_OPTIONS = util.immutabledict({"prebuffer_rows": True})
84
+ _STREAM_OPTIONS = util.immutabledict({"stream_results": True})
85
+
86
+
87
+ class AsyncAttrs:
88
+ """Mixin class which provides an awaitable accessor for all attributes.
89
+
90
+ E.g.::
91
+
92
+ from __future__ import annotations
93
+
94
+ from typing import List
95
+
96
+ from sqlalchemy import ForeignKey
97
+ from sqlalchemy import func
98
+ from sqlalchemy.ext.asyncio import AsyncAttrs
99
+ from sqlalchemy.orm import DeclarativeBase
100
+ from sqlalchemy.orm import Mapped
101
+ from sqlalchemy.orm import mapped_column
102
+ from sqlalchemy.orm import relationship
103
+
104
+
105
+ class Base(AsyncAttrs, DeclarativeBase):
106
+ pass
107
+
108
+
109
+ class A(Base):
110
+ __tablename__ = "a"
111
+
112
+ id: Mapped[int] = mapped_column(primary_key=True)
113
+ data: Mapped[str]
114
+ bs: Mapped[List[B]] = relationship()
115
+
116
+
117
+ class B(Base):
118
+ __tablename__ = "b"
119
+ id: Mapped[int] = mapped_column(primary_key=True)
120
+ a_id: Mapped[int] = mapped_column(ForeignKey("a.id"))
121
+ data: Mapped[str]
122
+
123
+ In the above example, the :class:`_asyncio.AsyncAttrs` mixin is applied to
124
+ the declarative ``Base`` class where it takes effect for all subclasses.
125
+ This mixin adds a single new attribute
126
+ :attr:`_asyncio.AsyncAttrs.awaitable_attrs` to all classes, which will
127
+ yield the value of any attribute as an awaitable. This allows attributes
128
+ which may be subject to lazy loading or deferred / unexpiry loading to be
129
+ accessed such that IO can still be emitted::
130
+
131
+ a1 = (await async_session.scalars(select(A).where(A.id == 5))).one()
132
+
133
+ # use the lazy loader on ``a1.bs`` via the ``.awaitable_attrs``
134
+ # interface, so that it may be awaited
135
+ for b1 in await a1.awaitable_attrs.bs:
136
+ print(b1)
137
+
138
+ The :attr:`_asyncio.AsyncAttrs.awaitable_attrs` performs a call against the
139
+ attribute that is approximately equivalent to using the
140
+ :meth:`_asyncio.AsyncSession.run_sync` method, e.g.::
141
+
142
+ for b1 in await async_session.run_sync(lambda sess: a1.bs):
143
+ print(b1)
144
+
145
+ .. versionadded:: 2.0.13
146
+
147
+ .. seealso::
148
+
149
+ :ref:`asyncio_orm_avoid_lazyloads`
150
+
151
+ """
152
+
153
+ class _AsyncAttrGetitem:
154
+ __slots__ = "_instance"
155
+
156
+ def __init__(self, _instance: Any):
157
+ self._instance = _instance
158
+
159
+ def __getattr__(self, name: str) -> Awaitable[Any]:
160
+ return greenlet_spawn(getattr, self._instance, name)
161
+
162
+ @property
163
+ def awaitable_attrs(self) -> AsyncAttrs._AsyncAttrGetitem:
164
+ """provide a namespace of all attributes on this object wrapped
165
+ as awaitables.
166
+
167
+ e.g.::
168
+
169
+
170
+ a1 = (await async_session.scalars(select(A).where(A.id == 5))).one()
171
+
172
+ some_attribute = await a1.awaitable_attrs.some_deferred_attribute
173
+ some_collection = await a1.awaitable_attrs.some_collection
174
+
175
+ """ # noqa: E501
176
+
177
+ return AsyncAttrs._AsyncAttrGetitem(self)
178
+
179
+
180
+ @util.create_proxy_methods(
181
+ Session,
182
+ ":class:`_orm.Session`",
183
+ ":class:`_asyncio.AsyncSession`",
184
+ classmethods=["object_session", "identity_key"],
185
+ methods=[
186
+ "__contains__",
187
+ "__iter__",
188
+ "add",
189
+ "add_all",
190
+ "expire",
191
+ "expire_all",
192
+ "expunge",
193
+ "expunge_all",
194
+ "is_modified",
195
+ "in_transaction",
196
+ "in_nested_transaction",
197
+ ],
198
+ attributes=[
199
+ "dirty",
200
+ "deleted",
201
+ "new",
202
+ "identity_map",
203
+ "is_active",
204
+ "autoflush",
205
+ "no_autoflush",
206
+ "info",
207
+ "execution_options",
208
+ ],
209
+ )
210
+ class AsyncSession(ReversibleProxy[Session]):
211
+ """Asyncio version of :class:`_orm.Session`.
212
+
213
+ The :class:`_asyncio.AsyncSession` is a proxy for a traditional
214
+ :class:`_orm.Session` instance.
215
+
216
+ The :class:`_asyncio.AsyncSession` is **not safe for use in concurrent
217
+ tasks.**. See :ref:`session_faq_threadsafe` for background.
218
+
219
+ .. versionadded:: 1.4
220
+
221
+ To use an :class:`_asyncio.AsyncSession` with custom :class:`_orm.Session`
222
+ implementations, see the
223
+ :paramref:`_asyncio.AsyncSession.sync_session_class` parameter.
224
+
225
+
226
+ """
227
+
228
+ _is_asyncio = True
229
+
230
+ dispatch: dispatcher[Session]
231
+
232
+ def __init__(
233
+ self,
234
+ bind: Optional[_AsyncSessionBind] = None,
235
+ *,
236
+ binds: Optional[Dict[_SessionBindKey, _AsyncSessionBind]] = None,
237
+ sync_session_class: Optional[Type[Session]] = None,
238
+ **kw: Any,
239
+ ):
240
+ r"""Construct a new :class:`_asyncio.AsyncSession`.
241
+
242
+ All parameters other than ``sync_session_class`` are passed to the
243
+ ``sync_session_class`` callable directly to instantiate a new
244
+ :class:`_orm.Session`. Refer to :meth:`_orm.Session.__init__` for
245
+ parameter documentation.
246
+
247
+ :param sync_session_class:
248
+ A :class:`_orm.Session` subclass or other callable which will be used
249
+ to construct the :class:`_orm.Session` which will be proxied. This
250
+ parameter may be used to provide custom :class:`_orm.Session`
251
+ subclasses. Defaults to the
252
+ :attr:`_asyncio.AsyncSession.sync_session_class` class-level
253
+ attribute.
254
+
255
+ .. versionadded:: 1.4.24
256
+
257
+ """
258
+ sync_bind = sync_binds = None
259
+
260
+ if bind:
261
+ self.bind = bind
262
+ sync_bind = engine._get_sync_engine_or_connection(bind)
263
+
264
+ if binds:
265
+ self.binds = binds
266
+ sync_binds = {
267
+ key: engine._get_sync_engine_or_connection(b)
268
+ for key, b in binds.items()
269
+ }
270
+
271
+ if sync_session_class:
272
+ self.sync_session_class = sync_session_class
273
+
274
+ self.sync_session = self._proxied = self._assign_proxied(
275
+ self.sync_session_class(bind=sync_bind, binds=sync_binds, **kw)
276
+ )
277
+
278
+ sync_session_class: Type[Session] = Session
279
+ """The class or callable that provides the
280
+ underlying :class:`_orm.Session` instance for a particular
281
+ :class:`_asyncio.AsyncSession`.
282
+
283
+ At the class level, this attribute is the default value for the
284
+ :paramref:`_asyncio.AsyncSession.sync_session_class` parameter. Custom
285
+ subclasses of :class:`_asyncio.AsyncSession` can override this.
286
+
287
+ At the instance level, this attribute indicates the current class or
288
+ callable that was used to provide the :class:`_orm.Session` instance for
289
+ this :class:`_asyncio.AsyncSession` instance.
290
+
291
+ .. versionadded:: 1.4.24
292
+
293
+ """
294
+
295
+ sync_session: Session
296
+ """Reference to the underlying :class:`_orm.Session` this
297
+ :class:`_asyncio.AsyncSession` proxies requests towards.
298
+
299
+ This instance can be used as an event target.
300
+
301
+ .. seealso::
302
+
303
+ :ref:`asyncio_events`
304
+
305
+ """
306
+
307
+ @classmethod
308
+ def _no_async_engine_events(cls) -> NoReturn:
309
+ raise NotImplementedError(
310
+ "asynchronous events are not implemented at this time. Apply "
311
+ "synchronous listeners to the AsyncSession.sync_session."
312
+ )
313
+
314
+ async def refresh(
315
+ self,
316
+ instance: object,
317
+ attribute_names: Optional[Iterable[str]] = None,
318
+ with_for_update: ForUpdateParameter = None,
319
+ ) -> None:
320
+ """Expire and refresh the attributes on the given instance.
321
+
322
+ A query will be issued to the database and all attributes will be
323
+ refreshed with their current database value.
324
+
325
+ This is the async version of the :meth:`_orm.Session.refresh` method.
326
+ See that method for a complete description of all options.
327
+
328
+ .. seealso::
329
+
330
+ :meth:`_orm.Session.refresh` - main documentation for refresh
331
+
332
+ """
333
+
334
+ await greenlet_spawn(
335
+ self.sync_session.refresh,
336
+ instance,
337
+ attribute_names=attribute_names,
338
+ with_for_update=with_for_update,
339
+ )
340
+
341
+ async def run_sync(
342
+ self,
343
+ fn: Callable[Concatenate[Session, _P], _T],
344
+ *arg: _P.args,
345
+ **kw: _P.kwargs,
346
+ ) -> _T:
347
+ '''Invoke the given synchronous (i.e. not async) callable,
348
+ passing a synchronous-style :class:`_orm.Session` as the first
349
+ argument.
350
+
351
+ This method allows traditional synchronous SQLAlchemy functions to
352
+ run within the context of an asyncio application.
353
+
354
+ E.g.::
355
+
356
+ def some_business_method(session: Session, param: str) -> str:
357
+ """A synchronous function that does not require awaiting
358
+
359
+ :param session: a SQLAlchemy Session, used synchronously
360
+
361
+ :return: an optional return value is supported
362
+
363
+ """
364
+ session.add(MyObject(param=param))
365
+ session.flush()
366
+ return "success"
367
+
368
+
369
+ async def do_something_async(async_engine: AsyncEngine) -> None:
370
+ """an async function that uses awaiting"""
371
+
372
+ with AsyncSession(async_engine) as async_session:
373
+ # run some_business_method() with a sync-style
374
+ # Session, proxied into an awaitable
375
+ return_code = await async_session.run_sync(
376
+ some_business_method, param="param1"
377
+ )
378
+ print(return_code)
379
+
380
+ This method maintains the asyncio event loop all the way through
381
+ to the database connection by running the given callable in a
382
+ specially instrumented greenlet.
383
+
384
+ .. tip::
385
+
386
+ The provided callable is invoked inline within the asyncio event
387
+ loop, and will block on traditional IO calls. IO within this
388
+ callable should only call into SQLAlchemy's asyncio database
389
+ APIs which will be properly adapted to the greenlet context.
390
+
391
+ .. seealso::
392
+
393
+ :class:`.AsyncAttrs` - a mixin for ORM mapped classes that provides
394
+ a similar feature more succinctly on a per-attribute basis
395
+
396
+ :meth:`.AsyncConnection.run_sync`
397
+
398
+ :ref:`session_run_sync`
399
+ ''' # noqa: E501
400
+
401
+ return await greenlet_spawn(
402
+ fn, self.sync_session, *arg, _require_await=False, **kw
403
+ )
404
+
405
+ @overload
406
+ async def execute(
407
+ self,
408
+ statement: TypedReturnsRows[Unpack[_Ts]],
409
+ params: Optional[_CoreAnyExecuteParams] = None,
410
+ *,
411
+ execution_options: OrmExecuteOptionsParameter = util.EMPTY_DICT,
412
+ bind_arguments: Optional[_BindArguments] = None,
413
+ _parent_execute_state: Optional[Any] = None,
414
+ _add_event: Optional[Any] = None,
415
+ ) -> Result[Unpack[_Ts]]: ...
416
+
417
+ @overload
418
+ async def execute(
419
+ self,
420
+ statement: Executable,
421
+ params: Optional[_CoreAnyExecuteParams] = None,
422
+ *,
423
+ execution_options: OrmExecuteOptionsParameter = util.EMPTY_DICT,
424
+ bind_arguments: Optional[_BindArguments] = None,
425
+ _parent_execute_state: Optional[Any] = None,
426
+ _add_event: Optional[Any] = None,
427
+ ) -> Result[Unpack[TupleAny]]: ...
428
+
429
+ async def execute(
430
+ self,
431
+ statement: Executable,
432
+ params: Optional[_CoreAnyExecuteParams] = None,
433
+ *,
434
+ execution_options: OrmExecuteOptionsParameter = util.EMPTY_DICT,
435
+ bind_arguments: Optional[_BindArguments] = None,
436
+ **kw: Any,
437
+ ) -> Result[Unpack[TupleAny]]:
438
+ """Execute a statement and return a buffered
439
+ :class:`_engine.Result` object.
440
+
441
+ .. seealso::
442
+
443
+ :meth:`_orm.Session.execute` - main documentation for execute
444
+
445
+ """
446
+
447
+ if execution_options:
448
+ execution_options = util.immutabledict(execution_options).union(
449
+ _EXECUTE_OPTIONS
450
+ )
451
+ else:
452
+ execution_options = _EXECUTE_OPTIONS
453
+
454
+ result = await greenlet_spawn(
455
+ self.sync_session.execute,
456
+ statement,
457
+ params=params,
458
+ execution_options=execution_options,
459
+ bind_arguments=bind_arguments,
460
+ **kw,
461
+ )
462
+ return await _ensure_sync_result(result, self.execute)
463
+
464
+ @overload
465
+ async def scalar(
466
+ self,
467
+ statement: TypedReturnsRows[_T],
468
+ params: Optional[_CoreAnyExecuteParams] = None,
469
+ *,
470
+ execution_options: OrmExecuteOptionsParameter = util.EMPTY_DICT,
471
+ bind_arguments: Optional[_BindArguments] = None,
472
+ **kw: Any,
473
+ ) -> Optional[_T]: ...
474
+
475
+ @overload
476
+ async def scalar(
477
+ self,
478
+ statement: Executable,
479
+ params: Optional[_CoreAnyExecuteParams] = None,
480
+ *,
481
+ execution_options: OrmExecuteOptionsParameter = util.EMPTY_DICT,
482
+ bind_arguments: Optional[_BindArguments] = None,
483
+ **kw: Any,
484
+ ) -> Any: ...
485
+
486
+ async def scalar(
487
+ self,
488
+ statement: Executable,
489
+ params: Optional[_CoreAnyExecuteParams] = None,
490
+ *,
491
+ execution_options: OrmExecuteOptionsParameter = util.EMPTY_DICT,
492
+ bind_arguments: Optional[_BindArguments] = None,
493
+ **kw: Any,
494
+ ) -> Any:
495
+ """Execute a statement and return a scalar result.
496
+
497
+ .. seealso::
498
+
499
+ :meth:`_orm.Session.scalar` - main documentation for scalar
500
+
501
+ """
502
+
503
+ if execution_options:
504
+ execution_options = util.immutabledict(execution_options).union(
505
+ _EXECUTE_OPTIONS
506
+ )
507
+ else:
508
+ execution_options = _EXECUTE_OPTIONS
509
+
510
+ return await greenlet_spawn(
511
+ self.sync_session.scalar,
512
+ statement,
513
+ params=params,
514
+ execution_options=execution_options,
515
+ bind_arguments=bind_arguments,
516
+ **kw,
517
+ )
518
+
519
+ @overload
520
+ async def scalars(
521
+ self,
522
+ statement: TypedReturnsRows[_T],
523
+ params: Optional[_CoreAnyExecuteParams] = None,
524
+ *,
525
+ execution_options: OrmExecuteOptionsParameter = util.EMPTY_DICT,
526
+ bind_arguments: Optional[_BindArguments] = None,
527
+ **kw: Any,
528
+ ) -> ScalarResult[_T]: ...
529
+
530
+ @overload
531
+ async def scalars(
532
+ self,
533
+ statement: Executable,
534
+ params: Optional[_CoreAnyExecuteParams] = None,
535
+ *,
536
+ execution_options: OrmExecuteOptionsParameter = util.EMPTY_DICT,
537
+ bind_arguments: Optional[_BindArguments] = None,
538
+ **kw: Any,
539
+ ) -> ScalarResult[Any]: ...
540
+
541
+ async def scalars(
542
+ self,
543
+ statement: Executable,
544
+ params: Optional[_CoreAnyExecuteParams] = None,
545
+ *,
546
+ execution_options: OrmExecuteOptionsParameter = util.EMPTY_DICT,
547
+ bind_arguments: Optional[_BindArguments] = None,
548
+ **kw: Any,
549
+ ) -> ScalarResult[Any]:
550
+ """Execute a statement and return scalar results.
551
+
552
+ :return: a :class:`_result.ScalarResult` object
553
+
554
+ .. versionadded:: 1.4.24 Added :meth:`_asyncio.AsyncSession.scalars`
555
+
556
+ .. versionadded:: 1.4.26 Added
557
+ :meth:`_asyncio.async_scoped_session.scalars`
558
+
559
+ .. seealso::
560
+
561
+ :meth:`_orm.Session.scalars` - main documentation for scalars
562
+
563
+ :meth:`_asyncio.AsyncSession.stream_scalars` - streaming version
564
+
565
+ """
566
+
567
+ result = await self.execute(
568
+ statement,
569
+ params=params,
570
+ execution_options=execution_options,
571
+ bind_arguments=bind_arguments,
572
+ **kw,
573
+ )
574
+ return result.scalars()
575
+
576
+ async def get(
577
+ self,
578
+ entity: _EntityBindKey[_O],
579
+ ident: _PKIdentityArgument,
580
+ *,
581
+ options: Optional[Sequence[ORMOption]] = None,
582
+ populate_existing: bool = False,
583
+ with_for_update: ForUpdateParameter = None,
584
+ identity_token: Optional[Any] = None,
585
+ execution_options: OrmExecuteOptionsParameter = util.EMPTY_DICT,
586
+ ) -> Union[_O, None]:
587
+ """Return an instance based on the given primary key identifier,
588
+ or ``None`` if not found.
589
+
590
+ .. seealso::
591
+
592
+ :meth:`_orm.Session.get` - main documentation for get
593
+
594
+
595
+ """
596
+
597
+ return await greenlet_spawn(
598
+ cast("Callable[..., _O]", self.sync_session.get),
599
+ entity,
600
+ ident,
601
+ options=options,
602
+ populate_existing=populate_existing,
603
+ with_for_update=with_for_update,
604
+ identity_token=identity_token,
605
+ execution_options=execution_options,
606
+ )
607
+
608
+ async def get_one(
609
+ self,
610
+ entity: _EntityBindKey[_O],
611
+ ident: _PKIdentityArgument,
612
+ *,
613
+ options: Optional[Sequence[ORMOption]] = None,
614
+ populate_existing: bool = False,
615
+ with_for_update: ForUpdateParameter = None,
616
+ identity_token: Optional[Any] = None,
617
+ execution_options: OrmExecuteOptionsParameter = util.EMPTY_DICT,
618
+ ) -> _O:
619
+ """Return an instance based on the given primary key identifier,
620
+ or raise an exception if not found.
621
+
622
+ Raises :class:`_exc.NoResultFound` if the query selects no rows.
623
+
624
+ ..versionadded: 2.0.22
625
+
626
+ .. seealso::
627
+
628
+ :meth:`_orm.Session.get_one` - main documentation for get_one
629
+
630
+ """
631
+
632
+ return await greenlet_spawn(
633
+ cast("Callable[..., _O]", self.sync_session.get_one),
634
+ entity,
635
+ ident,
636
+ options=options,
637
+ populate_existing=populate_existing,
638
+ with_for_update=with_for_update,
639
+ identity_token=identity_token,
640
+ execution_options=execution_options,
641
+ )
642
+
643
+ @overload
644
+ async def stream(
645
+ self,
646
+ statement: TypedReturnsRows[Unpack[_Ts]],
647
+ params: Optional[_CoreAnyExecuteParams] = None,
648
+ *,
649
+ execution_options: OrmExecuteOptionsParameter = util.EMPTY_DICT,
650
+ bind_arguments: Optional[_BindArguments] = None,
651
+ **kw: Any,
652
+ ) -> AsyncResult[Unpack[_Ts]]: ...
653
+
654
+ @overload
655
+ async def stream(
656
+ self,
657
+ statement: Executable,
658
+ params: Optional[_CoreAnyExecuteParams] = None,
659
+ *,
660
+ execution_options: OrmExecuteOptionsParameter = util.EMPTY_DICT,
661
+ bind_arguments: Optional[_BindArguments] = None,
662
+ **kw: Any,
663
+ ) -> AsyncResult[Unpack[TupleAny]]: ...
664
+
665
+ async def stream(
666
+ self,
667
+ statement: Executable,
668
+ params: Optional[_CoreAnyExecuteParams] = None,
669
+ *,
670
+ execution_options: OrmExecuteOptionsParameter = util.EMPTY_DICT,
671
+ bind_arguments: Optional[_BindArguments] = None,
672
+ **kw: Any,
673
+ ) -> AsyncResult[Unpack[TupleAny]]:
674
+ """Execute a statement and return a streaming
675
+ :class:`_asyncio.AsyncResult` object.
676
+
677
+ """
678
+
679
+ if execution_options:
680
+ execution_options = util.immutabledict(execution_options).union(
681
+ _STREAM_OPTIONS
682
+ )
683
+ else:
684
+ execution_options = _STREAM_OPTIONS
685
+
686
+ result = await greenlet_spawn(
687
+ self.sync_session.execute,
688
+ statement,
689
+ params=params,
690
+ execution_options=execution_options,
691
+ bind_arguments=bind_arguments,
692
+ **kw,
693
+ )
694
+ return AsyncResult(result)
695
+
696
+ @overload
697
+ async def stream_scalars(
698
+ self,
699
+ statement: TypedReturnsRows[_T],
700
+ params: Optional[_CoreAnyExecuteParams] = None,
701
+ *,
702
+ execution_options: OrmExecuteOptionsParameter = util.EMPTY_DICT,
703
+ bind_arguments: Optional[_BindArguments] = None,
704
+ **kw: Any,
705
+ ) -> AsyncScalarResult[_T]: ...
706
+
707
+ @overload
708
+ async def stream_scalars(
709
+ self,
710
+ statement: Executable,
711
+ params: Optional[_CoreAnyExecuteParams] = None,
712
+ *,
713
+ execution_options: OrmExecuteOptionsParameter = util.EMPTY_DICT,
714
+ bind_arguments: Optional[_BindArguments] = None,
715
+ **kw: Any,
716
+ ) -> AsyncScalarResult[Any]: ...
717
+
718
+ async def stream_scalars(
719
+ self,
720
+ statement: Executable,
721
+ params: Optional[_CoreAnyExecuteParams] = None,
722
+ *,
723
+ execution_options: OrmExecuteOptionsParameter = util.EMPTY_DICT,
724
+ bind_arguments: Optional[_BindArguments] = None,
725
+ **kw: Any,
726
+ ) -> AsyncScalarResult[Any]:
727
+ """Execute a statement and return a stream of scalar results.
728
+
729
+ :return: an :class:`_asyncio.AsyncScalarResult` object
730
+
731
+ .. versionadded:: 1.4.24
732
+
733
+ .. seealso::
734
+
735
+ :meth:`_orm.Session.scalars` - main documentation for scalars
736
+
737
+ :meth:`_asyncio.AsyncSession.scalars` - non streaming version
738
+
739
+ """
740
+
741
+ result = await self.stream(
742
+ statement,
743
+ params=params,
744
+ execution_options=execution_options,
745
+ bind_arguments=bind_arguments,
746
+ **kw,
747
+ )
748
+ return result.scalars()
749
+
750
+ async def delete(self, instance: object) -> None:
751
+ """Mark an instance as deleted.
752
+
753
+ The database delete operation occurs upon ``flush()``.
754
+
755
+ As this operation may need to cascade along unloaded relationships,
756
+ it is awaitable to allow for those queries to take place.
757
+
758
+ .. seealso::
759
+
760
+ :meth:`_orm.Session.delete` - main documentation for delete
761
+
762
+ """
763
+ await greenlet_spawn(self.sync_session.delete, instance)
764
+
765
+ async def delete_all(self, instances: Iterable[object]) -> None:
766
+ """Calls :meth:`.AsyncSession.delete` on multiple instances.
767
+
768
+ .. seealso::
769
+
770
+ :meth:`_orm.Session.delete_all` - main documentation for delete_all
771
+
772
+ """
773
+ await greenlet_spawn(self.sync_session.delete_all, instances)
774
+
775
+ async def merge(
776
+ self,
777
+ instance: _O,
778
+ *,
779
+ load: bool = True,
780
+ options: Optional[Sequence[ORMOption]] = None,
781
+ ) -> _O:
782
+ """Copy the state of a given instance into a corresponding instance
783
+ within this :class:`_asyncio.AsyncSession`.
784
+
785
+ .. seealso::
786
+
787
+ :meth:`_orm.Session.merge` - main documentation for merge
788
+
789
+ """
790
+ return await greenlet_spawn(
791
+ self.sync_session.merge, instance, load=load, options=options
792
+ )
793
+
794
+ async def merge_all(
795
+ self,
796
+ instances: Iterable[_O],
797
+ *,
798
+ load: bool = True,
799
+ options: Optional[Sequence[ORMOption]] = None,
800
+ ) -> Sequence[_O]:
801
+ """Calls :meth:`.AsyncSession.merge` on multiple instances.
802
+
803
+ .. seealso::
804
+
805
+ :meth:`_orm.Session.merge_all` - main documentation for merge_all
806
+
807
+ """
808
+ return await greenlet_spawn(
809
+ self.sync_session.merge_all, instances, load=load, options=options
810
+ )
811
+
812
+ async def flush(self, objects: Optional[Sequence[Any]] = None) -> None:
813
+ """Flush all the object changes to the database.
814
+
815
+ .. seealso::
816
+
817
+ :meth:`_orm.Session.flush` - main documentation for flush
818
+
819
+ """
820
+ await greenlet_spawn(self.sync_session.flush, objects=objects)
821
+
822
+ def get_transaction(self) -> Optional[AsyncSessionTransaction]:
823
+ """Return the current root transaction in progress, if any.
824
+
825
+ :return: an :class:`_asyncio.AsyncSessionTransaction` object, or
826
+ ``None``.
827
+
828
+ .. versionadded:: 1.4.18
829
+
830
+ """
831
+ trans = self.sync_session.get_transaction()
832
+ if trans is not None:
833
+ return AsyncSessionTransaction._retrieve_proxy_for_target(
834
+ trans, async_session=self
835
+ )
836
+ else:
837
+ return None
838
+
839
+ def get_nested_transaction(self) -> Optional[AsyncSessionTransaction]:
840
+ """Return the current nested transaction in progress, if any.
841
+
842
+ :return: an :class:`_asyncio.AsyncSessionTransaction` object, or
843
+ ``None``.
844
+
845
+ .. versionadded:: 1.4.18
846
+
847
+ """
848
+
849
+ trans = self.sync_session.get_nested_transaction()
850
+ if trans is not None:
851
+ return AsyncSessionTransaction._retrieve_proxy_for_target(
852
+ trans, async_session=self
853
+ )
854
+ else:
855
+ return None
856
+
857
+ def get_bind(
858
+ self,
859
+ mapper: Optional[_EntityBindKey[_O]] = None,
860
+ clause: Optional[ClauseElement] = None,
861
+ bind: Optional[_SessionBind] = None,
862
+ **kw: Any,
863
+ ) -> Union[Engine, Connection]:
864
+ """Return a "bind" to which the synchronous proxied :class:`_orm.Session`
865
+ is bound.
866
+
867
+ Unlike the :meth:`_orm.Session.get_bind` method, this method is
868
+ currently **not** used by this :class:`.AsyncSession` in any way
869
+ in order to resolve engines for requests.
870
+
871
+ .. note::
872
+
873
+ This method proxies directly to the :meth:`_orm.Session.get_bind`
874
+ method, however is currently **not** useful as an override target,
875
+ in contrast to that of the :meth:`_orm.Session.get_bind` method.
876
+ The example below illustrates how to implement custom
877
+ :meth:`_orm.Session.get_bind` schemes that work with
878
+ :class:`.AsyncSession` and :class:`.AsyncEngine`.
879
+
880
+ The pattern introduced at :ref:`session_custom_partitioning`
881
+ illustrates how to apply a custom bind-lookup scheme to a
882
+ :class:`_orm.Session` given a set of :class:`_engine.Engine` objects.
883
+ To apply a corresponding :meth:`_orm.Session.get_bind` implementation
884
+ for use with a :class:`.AsyncSession` and :class:`.AsyncEngine`
885
+ objects, continue to subclass :class:`_orm.Session` and apply it to
886
+ :class:`.AsyncSession` using
887
+ :paramref:`.AsyncSession.sync_session_class`. The inner method must
888
+ continue to return :class:`_engine.Engine` instances, which can be
889
+ acquired from a :class:`_asyncio.AsyncEngine` using the
890
+ :attr:`_asyncio.AsyncEngine.sync_engine` attribute::
891
+
892
+ # using example from "Custom Vertical Partitioning"
893
+
894
+
895
+ import random
896
+
897
+ from sqlalchemy.ext.asyncio import AsyncSession
898
+ from sqlalchemy.ext.asyncio import create_async_engine
899
+ from sqlalchemy.ext.asyncio import async_sessionmaker
900
+ from sqlalchemy.orm import Session
901
+
902
+ # construct async engines w/ async drivers
903
+ engines = {
904
+ "leader": create_async_engine("sqlite+aiosqlite:///leader.db"),
905
+ "other": create_async_engine("sqlite+aiosqlite:///other.db"),
906
+ "follower1": create_async_engine("sqlite+aiosqlite:///follower1.db"),
907
+ "follower2": create_async_engine("sqlite+aiosqlite:///follower2.db"),
908
+ }
909
+
910
+
911
+ class RoutingSession(Session):
912
+ def get_bind(self, mapper=None, clause=None, **kw):
913
+ # within get_bind(), return sync engines
914
+ if mapper and issubclass(mapper.class_, MyOtherClass):
915
+ return engines["other"].sync_engine
916
+ elif self._flushing or isinstance(clause, (Update, Delete)):
917
+ return engines["leader"].sync_engine
918
+ else:
919
+ return engines[
920
+ random.choice(["follower1", "follower2"])
921
+ ].sync_engine
922
+
923
+
924
+ # apply to AsyncSession using sync_session_class
925
+ AsyncSessionMaker = async_sessionmaker(sync_session_class=RoutingSession)
926
+
927
+ The :meth:`_orm.Session.get_bind` method is called in a non-asyncio,
928
+ implicitly non-blocking context in the same manner as ORM event hooks
929
+ and functions that are invoked via :meth:`.AsyncSession.run_sync`, so
930
+ routines that wish to run SQL commands inside of
931
+ :meth:`_orm.Session.get_bind` can continue to do so using
932
+ blocking-style code, which will be translated to implicitly async calls
933
+ at the point of invoking IO on the database drivers.
934
+
935
+ """ # noqa: E501
936
+
937
+ return self.sync_session.get_bind(
938
+ mapper=mapper, clause=clause, bind=bind, **kw
939
+ )
940
+
941
+ async def connection(
942
+ self,
943
+ bind_arguments: Optional[_BindArguments] = None,
944
+ execution_options: Optional[CoreExecuteOptionsParameter] = None,
945
+ **kw: Any,
946
+ ) -> AsyncConnection:
947
+ r"""Return a :class:`_asyncio.AsyncConnection` object corresponding to
948
+ this :class:`.Session` object's transactional state.
949
+
950
+ This method may also be used to establish execution options for the
951
+ database connection used by the current transaction.
952
+
953
+ .. versionadded:: 1.4.24 Added \**kw arguments which are passed
954
+ through to the underlying :meth:`_orm.Session.connection` method.
955
+
956
+ .. seealso::
957
+
958
+ :meth:`_orm.Session.connection` - main documentation for
959
+ "connection"
960
+
961
+ """
962
+
963
+ sync_connection = await greenlet_spawn(
964
+ self.sync_session.connection,
965
+ bind_arguments=bind_arguments,
966
+ execution_options=execution_options,
967
+ **kw,
968
+ )
969
+ return engine.AsyncConnection._retrieve_proxy_for_target(
970
+ sync_connection
971
+ )
972
+
973
+ def begin(self) -> AsyncSessionTransaction:
974
+ """Return an :class:`_asyncio.AsyncSessionTransaction` object.
975
+
976
+ The underlying :class:`_orm.Session` will perform the
977
+ "begin" action when the :class:`_asyncio.AsyncSessionTransaction`
978
+ object is entered::
979
+
980
+ async with async_session.begin():
981
+ ... # ORM transaction is begun
982
+
983
+ Note that database IO will not normally occur when the session-level
984
+ transaction is begun, as database transactions begin on an
985
+ on-demand basis. However, the begin block is async to accommodate
986
+ for a :meth:`_orm.SessionEvents.after_transaction_create`
987
+ event hook that may perform IO.
988
+
989
+ For a general description of ORM begin, see
990
+ :meth:`_orm.Session.begin`.
991
+
992
+ """
993
+
994
+ return AsyncSessionTransaction(self)
995
+
996
+ def begin_nested(self) -> AsyncSessionTransaction:
997
+ """Return an :class:`_asyncio.AsyncSessionTransaction` object
998
+ which will begin a "nested" transaction, e.g. SAVEPOINT.
999
+
1000
+ Behavior is the same as that of :meth:`_asyncio.AsyncSession.begin`.
1001
+
1002
+ For a general description of ORM begin nested, see
1003
+ :meth:`_orm.Session.begin_nested`.
1004
+
1005
+ .. seealso::
1006
+
1007
+ :ref:`aiosqlite_serializable` - special workarounds required
1008
+ with the SQLite asyncio driver in order for SAVEPOINT to work
1009
+ correctly.
1010
+
1011
+ """
1012
+
1013
+ return AsyncSessionTransaction(self, nested=True)
1014
+
1015
+ async def rollback(self) -> None:
1016
+ """Rollback the current transaction in progress.
1017
+
1018
+ .. seealso::
1019
+
1020
+ :meth:`_orm.Session.rollback` - main documentation for
1021
+ "rollback"
1022
+ """
1023
+ await greenlet_spawn(self.sync_session.rollback)
1024
+
1025
+ async def commit(self) -> None:
1026
+ """Commit the current transaction in progress.
1027
+
1028
+ .. seealso::
1029
+
1030
+ :meth:`_orm.Session.commit` - main documentation for
1031
+ "commit"
1032
+ """
1033
+ await greenlet_spawn(self.sync_session.commit)
1034
+
1035
+ async def close(self) -> None:
1036
+ """Close out the transactional resources and ORM objects used by this
1037
+ :class:`_asyncio.AsyncSession`.
1038
+
1039
+ .. seealso::
1040
+
1041
+ :meth:`_orm.Session.close` - main documentation for
1042
+ "close"
1043
+
1044
+ :ref:`session_closing` - detail on the semantics of
1045
+ :meth:`_asyncio.AsyncSession.close` and
1046
+ :meth:`_asyncio.AsyncSession.reset`.
1047
+
1048
+ """
1049
+ await greenlet_spawn(self.sync_session.close)
1050
+
1051
+ async def reset(self) -> None:
1052
+ """Close out the transactional resources and ORM objects used by this
1053
+ :class:`_orm.Session`, resetting the session to its initial state.
1054
+
1055
+ .. versionadded:: 2.0.22
1056
+
1057
+ .. seealso::
1058
+
1059
+ :meth:`_orm.Session.reset` - main documentation for
1060
+ "reset"
1061
+
1062
+ :ref:`session_closing` - detail on the semantics of
1063
+ :meth:`_asyncio.AsyncSession.close` and
1064
+ :meth:`_asyncio.AsyncSession.reset`.
1065
+
1066
+ """
1067
+ await greenlet_spawn(self.sync_session.reset)
1068
+
1069
+ async def aclose(self) -> None:
1070
+ """A synonym for :meth:`_asyncio.AsyncSession.close`.
1071
+
1072
+ The :meth:`_asyncio.AsyncSession.aclose` name is specifically
1073
+ to support the Python standard library ``@contextlib.aclosing``
1074
+ context manager function.
1075
+
1076
+ .. versionadded:: 2.0.20
1077
+
1078
+ """
1079
+ await self.close()
1080
+
1081
+ async def invalidate(self) -> None:
1082
+ """Close this Session, using connection invalidation.
1083
+
1084
+ For a complete description, see :meth:`_orm.Session.invalidate`.
1085
+ """
1086
+ await greenlet_spawn(self.sync_session.invalidate)
1087
+
1088
+ @classmethod
1089
+ @util.deprecated(
1090
+ "2.0",
1091
+ "The :meth:`.AsyncSession.close_all` method is deprecated and will be "
1092
+ "removed in a future release. Please refer to "
1093
+ ":func:`_asyncio.close_all_sessions`.",
1094
+ )
1095
+ async def close_all(cls) -> None:
1096
+ """Close all :class:`_asyncio.AsyncSession` sessions."""
1097
+ await close_all_sessions()
1098
+
1099
+ async def __aenter__(self: _AS) -> _AS:
1100
+ return self
1101
+
1102
+ async def __aexit__(self, type_: Any, value: Any, traceback: Any) -> None:
1103
+ task = asyncio.create_task(self.close())
1104
+ await asyncio.shield(task)
1105
+
1106
+ def _maker_context_manager(self: _AS) -> _AsyncSessionContextManager[_AS]:
1107
+ return _AsyncSessionContextManager(self)
1108
+
1109
+ # START PROXY METHODS AsyncSession
1110
+
1111
+ # code within this block is **programmatically,
1112
+ # statically generated** by tools/generate_proxy_methods.py
1113
+
1114
+ def __contains__(self, instance: object) -> bool:
1115
+ r"""Return True if the instance is associated with this session.
1116
+
1117
+ .. container:: class_bases
1118
+
1119
+ Proxied for the :class:`_orm.Session` class on
1120
+ behalf of the :class:`_asyncio.AsyncSession` class.
1121
+
1122
+ The instance may be pending or persistent within the Session for a
1123
+ result of True.
1124
+
1125
+
1126
+ """ # noqa: E501
1127
+
1128
+ return self._proxied.__contains__(instance)
1129
+
1130
+ def __iter__(self) -> Iterator[object]:
1131
+ r"""Iterate over all pending or persistent instances within this
1132
+ Session.
1133
+
1134
+ .. container:: class_bases
1135
+
1136
+ Proxied for the :class:`_orm.Session` class on
1137
+ behalf of the :class:`_asyncio.AsyncSession` class.
1138
+
1139
+
1140
+ """ # noqa: E501
1141
+
1142
+ return self._proxied.__iter__()
1143
+
1144
+ def add(self, instance: object, *, _warn: bool = True) -> None:
1145
+ r"""Place an object into this :class:`_orm.Session`.
1146
+
1147
+ .. container:: class_bases
1148
+
1149
+ Proxied for the :class:`_orm.Session` class on
1150
+ behalf of the :class:`_asyncio.AsyncSession` class.
1151
+
1152
+ Objects that are in the :term:`transient` state when passed to the
1153
+ :meth:`_orm.Session.add` method will move to the
1154
+ :term:`pending` state, until the next flush, at which point they
1155
+ will move to the :term:`persistent` state.
1156
+
1157
+ Objects that are in the :term:`detached` state when passed to the
1158
+ :meth:`_orm.Session.add` method will move to the :term:`persistent`
1159
+ state directly.
1160
+
1161
+ If the transaction used by the :class:`_orm.Session` is rolled back,
1162
+ objects which were transient when they were passed to
1163
+ :meth:`_orm.Session.add` will be moved back to the
1164
+ :term:`transient` state, and will no longer be present within this
1165
+ :class:`_orm.Session`.
1166
+
1167
+ .. seealso::
1168
+
1169
+ :meth:`_orm.Session.add_all`
1170
+
1171
+ :ref:`session_adding` - at :ref:`session_basics`
1172
+
1173
+
1174
+ """ # noqa: E501
1175
+
1176
+ return self._proxied.add(instance, _warn=_warn)
1177
+
1178
+ def add_all(self, instances: Iterable[object]) -> None:
1179
+ r"""Add the given collection of instances to this :class:`_orm.Session`.
1180
+
1181
+ .. container:: class_bases
1182
+
1183
+ Proxied for the :class:`_orm.Session` class on
1184
+ behalf of the :class:`_asyncio.AsyncSession` class.
1185
+
1186
+ See the documentation for :meth:`_orm.Session.add` for a general
1187
+ behavioral description.
1188
+
1189
+ .. seealso::
1190
+
1191
+ :meth:`_orm.Session.add`
1192
+
1193
+ :ref:`session_adding` - at :ref:`session_basics`
1194
+
1195
+
1196
+ """ # noqa: E501
1197
+
1198
+ return self._proxied.add_all(instances)
1199
+
1200
+ def expire(
1201
+ self, instance: object, attribute_names: Optional[Iterable[str]] = None
1202
+ ) -> None:
1203
+ r"""Expire the attributes on an instance.
1204
+
1205
+ .. container:: class_bases
1206
+
1207
+ Proxied for the :class:`_orm.Session` class on
1208
+ behalf of the :class:`_asyncio.AsyncSession` class.
1209
+
1210
+ Marks the attributes of an instance as out of date. When an expired
1211
+ attribute is next accessed, a query will be issued to the
1212
+ :class:`.Session` object's current transactional context in order to
1213
+ load all expired attributes for the given instance. Note that
1214
+ a highly isolated transaction will return the same values as were
1215
+ previously read in that same transaction, regardless of changes
1216
+ in database state outside of that transaction.
1217
+
1218
+ To expire all objects in the :class:`.Session` simultaneously,
1219
+ use :meth:`Session.expire_all`.
1220
+
1221
+ The :class:`.Session` object's default behavior is to
1222
+ expire all state whenever the :meth:`Session.rollback`
1223
+ or :meth:`Session.commit` methods are called, so that new
1224
+ state can be loaded for the new transaction. For this reason,
1225
+ calling :meth:`Session.expire` only makes sense for the specific
1226
+ case that a non-ORM SQL statement was emitted in the current
1227
+ transaction.
1228
+
1229
+ :param instance: The instance to be refreshed.
1230
+ :param attribute_names: optional list of string attribute names
1231
+ indicating a subset of attributes to be expired.
1232
+
1233
+ .. seealso::
1234
+
1235
+ :ref:`session_expire` - introductory material
1236
+
1237
+ :meth:`.Session.expire`
1238
+
1239
+ :meth:`.Session.refresh`
1240
+
1241
+ :meth:`_orm.Query.populate_existing`
1242
+
1243
+
1244
+ """ # noqa: E501
1245
+
1246
+ return self._proxied.expire(instance, attribute_names=attribute_names)
1247
+
1248
+ def expire_all(self) -> None:
1249
+ r"""Expires all persistent instances within this Session.
1250
+
1251
+ .. container:: class_bases
1252
+
1253
+ Proxied for the :class:`_orm.Session` class on
1254
+ behalf of the :class:`_asyncio.AsyncSession` class.
1255
+
1256
+ When any attributes on a persistent instance is next accessed,
1257
+ a query will be issued using the
1258
+ :class:`.Session` object's current transactional context in order to
1259
+ load all expired attributes for the given instance. Note that
1260
+ a highly isolated transaction will return the same values as were
1261
+ previously read in that same transaction, regardless of changes
1262
+ in database state outside of that transaction.
1263
+
1264
+ To expire individual objects and individual attributes
1265
+ on those objects, use :meth:`Session.expire`.
1266
+
1267
+ The :class:`.Session` object's default behavior is to
1268
+ expire all state whenever the :meth:`Session.rollback`
1269
+ or :meth:`Session.commit` methods are called, so that new
1270
+ state can be loaded for the new transaction. For this reason,
1271
+ calling :meth:`Session.expire_all` is not usually needed,
1272
+ assuming the transaction is isolated.
1273
+
1274
+ .. seealso::
1275
+
1276
+ :ref:`session_expire` - introductory material
1277
+
1278
+ :meth:`.Session.expire`
1279
+
1280
+ :meth:`.Session.refresh`
1281
+
1282
+ :meth:`_orm.Query.populate_existing`
1283
+
1284
+
1285
+ """ # noqa: E501
1286
+
1287
+ return self._proxied.expire_all()
1288
+
1289
+ def expunge(self, instance: object) -> None:
1290
+ r"""Remove the `instance` from this ``Session``.
1291
+
1292
+ .. container:: class_bases
1293
+
1294
+ Proxied for the :class:`_orm.Session` class on
1295
+ behalf of the :class:`_asyncio.AsyncSession` class.
1296
+
1297
+ This will free all internal references to the instance. Cascading
1298
+ will be applied according to the *expunge* cascade rule.
1299
+
1300
+
1301
+ """ # noqa: E501
1302
+
1303
+ return self._proxied.expunge(instance)
1304
+
1305
+ def expunge_all(self) -> None:
1306
+ r"""Remove all object instances from this ``Session``.
1307
+
1308
+ .. container:: class_bases
1309
+
1310
+ Proxied for the :class:`_orm.Session` class on
1311
+ behalf of the :class:`_asyncio.AsyncSession` class.
1312
+
1313
+ This is equivalent to calling ``expunge(obj)`` on all objects in this
1314
+ ``Session``.
1315
+
1316
+
1317
+ """ # noqa: E501
1318
+
1319
+ return self._proxied.expunge_all()
1320
+
1321
+ def is_modified(
1322
+ self, instance: object, include_collections: bool = True
1323
+ ) -> bool:
1324
+ r"""Return ``True`` if the given instance has locally
1325
+ modified attributes.
1326
+
1327
+ .. container:: class_bases
1328
+
1329
+ Proxied for the :class:`_orm.Session` class on
1330
+ behalf of the :class:`_asyncio.AsyncSession` class.
1331
+
1332
+ This method retrieves the history for each instrumented
1333
+ attribute on the instance and performs a comparison of the current
1334
+ value to its previously flushed or committed value, if any.
1335
+
1336
+ It is in effect a more expensive and accurate
1337
+ version of checking for the given instance in the
1338
+ :attr:`.Session.dirty` collection; a full test for
1339
+ each attribute's net "dirty" status is performed.
1340
+
1341
+ E.g.::
1342
+
1343
+ return session.is_modified(someobject)
1344
+
1345
+ A few caveats to this method apply:
1346
+
1347
+ * Instances present in the :attr:`.Session.dirty` collection may
1348
+ report ``False`` when tested with this method. This is because
1349
+ the object may have received change events via attribute mutation,
1350
+ thus placing it in :attr:`.Session.dirty`, but ultimately the state
1351
+ is the same as that loaded from the database, resulting in no net
1352
+ change here.
1353
+ * Scalar attributes may not have recorded the previously set
1354
+ value when a new value was applied, if the attribute was not loaded,
1355
+ or was expired, at the time the new value was received - in these
1356
+ cases, the attribute is assumed to have a change, even if there is
1357
+ ultimately no net change against its database value. SQLAlchemy in
1358
+ most cases does not need the "old" value when a set event occurs, so
1359
+ it skips the expense of a SQL call if the old value isn't present,
1360
+ based on the assumption that an UPDATE of the scalar value is
1361
+ usually needed, and in those few cases where it isn't, is less
1362
+ expensive on average than issuing a defensive SELECT.
1363
+
1364
+ The "old" value is fetched unconditionally upon set only if the
1365
+ attribute container has the ``active_history`` flag set to ``True``.
1366
+ This flag is set typically for primary key attributes and scalar
1367
+ object references that are not a simple many-to-one. To set this
1368
+ flag for any arbitrary mapped column, use the ``active_history``
1369
+ argument with :func:`.column_property`.
1370
+
1371
+ :param instance: mapped instance to be tested for pending changes.
1372
+ :param include_collections: Indicates if multivalued collections
1373
+ should be included in the operation. Setting this to ``False`` is a
1374
+ way to detect only local-column based properties (i.e. scalar columns
1375
+ or many-to-one foreign keys) that would result in an UPDATE for this
1376
+ instance upon flush.
1377
+
1378
+
1379
+ """ # noqa: E501
1380
+
1381
+ return self._proxied.is_modified(
1382
+ instance, include_collections=include_collections
1383
+ )
1384
+
1385
+ def in_transaction(self) -> bool:
1386
+ r"""Return True if this :class:`_orm.Session` has begun a transaction.
1387
+
1388
+ .. container:: class_bases
1389
+
1390
+ Proxied for the :class:`_orm.Session` class on
1391
+ behalf of the :class:`_asyncio.AsyncSession` class.
1392
+
1393
+ .. versionadded:: 1.4
1394
+
1395
+ .. seealso::
1396
+
1397
+ :attr:`_orm.Session.is_active`
1398
+
1399
+
1400
+
1401
+ """ # noqa: E501
1402
+
1403
+ return self._proxied.in_transaction()
1404
+
1405
+ def in_nested_transaction(self) -> bool:
1406
+ r"""Return True if this :class:`_orm.Session` has begun a nested
1407
+ transaction, e.g. SAVEPOINT.
1408
+
1409
+ .. container:: class_bases
1410
+
1411
+ Proxied for the :class:`_orm.Session` class on
1412
+ behalf of the :class:`_asyncio.AsyncSession` class.
1413
+
1414
+ .. versionadded:: 1.4
1415
+
1416
+
1417
+ """ # noqa: E501
1418
+
1419
+ return self._proxied.in_nested_transaction()
1420
+
1421
+ @property
1422
+ def dirty(self) -> Any:
1423
+ r"""The set of all persistent instances considered dirty.
1424
+
1425
+ .. container:: class_bases
1426
+
1427
+ Proxied for the :class:`_orm.Session` class
1428
+ on behalf of the :class:`_asyncio.AsyncSession` class.
1429
+
1430
+ E.g.::
1431
+
1432
+ some_mapped_object in session.dirty
1433
+
1434
+ Instances are considered dirty when they were modified but not
1435
+ deleted.
1436
+
1437
+ Note that this 'dirty' calculation is 'optimistic'; most
1438
+ attribute-setting or collection modification operations will
1439
+ mark an instance as 'dirty' and place it in this set, even if
1440
+ there is no net change to the attribute's value. At flush
1441
+ time, the value of each attribute is compared to its
1442
+ previously saved value, and if there's no net change, no SQL
1443
+ operation will occur (this is a more expensive operation so
1444
+ it's only done at flush time).
1445
+
1446
+ To check if an instance has actionable net changes to its
1447
+ attributes, use the :meth:`.Session.is_modified` method.
1448
+
1449
+
1450
+ """ # noqa: E501
1451
+
1452
+ return self._proxied.dirty
1453
+
1454
+ @property
1455
+ def deleted(self) -> Any:
1456
+ r"""The set of all instances marked as 'deleted' within this ``Session``
1457
+
1458
+ .. container:: class_bases
1459
+
1460
+ Proxied for the :class:`_orm.Session` class
1461
+ on behalf of the :class:`_asyncio.AsyncSession` class.
1462
+
1463
+ """ # noqa: E501
1464
+
1465
+ return self._proxied.deleted
1466
+
1467
+ @property
1468
+ def new(self) -> Any:
1469
+ r"""The set of all instances marked as 'new' within this ``Session``.
1470
+
1471
+ .. container:: class_bases
1472
+
1473
+ Proxied for the :class:`_orm.Session` class
1474
+ on behalf of the :class:`_asyncio.AsyncSession` class.
1475
+
1476
+ """ # noqa: E501
1477
+
1478
+ return self._proxied.new
1479
+
1480
+ @property
1481
+ def identity_map(self) -> IdentityMap:
1482
+ r"""Proxy for the :attr:`_orm.Session.identity_map` attribute
1483
+ on behalf of the :class:`_asyncio.AsyncSession` class.
1484
+
1485
+ """ # noqa: E501
1486
+
1487
+ return self._proxied.identity_map
1488
+
1489
+ @identity_map.setter
1490
+ def identity_map(self, attr: IdentityMap) -> None:
1491
+ self._proxied.identity_map = attr
1492
+
1493
+ @property
1494
+ def is_active(self) -> Any:
1495
+ r"""True if this :class:`.Session` not in "partial rollback" state.
1496
+
1497
+ .. container:: class_bases
1498
+
1499
+ Proxied for the :class:`_orm.Session` class
1500
+ on behalf of the :class:`_asyncio.AsyncSession` class.
1501
+
1502
+ .. versionchanged:: 1.4 The :class:`_orm.Session` no longer begins
1503
+ a new transaction immediately, so this attribute will be False
1504
+ when the :class:`_orm.Session` is first instantiated.
1505
+
1506
+ "partial rollback" state typically indicates that the flush process
1507
+ of the :class:`_orm.Session` has failed, and that the
1508
+ :meth:`_orm.Session.rollback` method must be emitted in order to
1509
+ fully roll back the transaction.
1510
+
1511
+ If this :class:`_orm.Session` is not in a transaction at all, the
1512
+ :class:`_orm.Session` will autobegin when it is first used, so in this
1513
+ case :attr:`_orm.Session.is_active` will return True.
1514
+
1515
+ Otherwise, if this :class:`_orm.Session` is within a transaction,
1516
+ and that transaction has not been rolled back internally, the
1517
+ :attr:`_orm.Session.is_active` will also return True.
1518
+
1519
+ .. seealso::
1520
+
1521
+ :ref:`faq_session_rollback`
1522
+
1523
+ :meth:`_orm.Session.in_transaction`
1524
+
1525
+
1526
+ """ # noqa: E501
1527
+
1528
+ return self._proxied.is_active
1529
+
1530
+ @property
1531
+ def autoflush(self) -> bool:
1532
+ r"""Proxy for the :attr:`_orm.Session.autoflush` attribute
1533
+ on behalf of the :class:`_asyncio.AsyncSession` class.
1534
+
1535
+ """ # noqa: E501
1536
+
1537
+ return self._proxied.autoflush
1538
+
1539
+ @autoflush.setter
1540
+ def autoflush(self, attr: bool) -> None:
1541
+ self._proxied.autoflush = attr
1542
+
1543
+ @property
1544
+ def no_autoflush(self) -> Any:
1545
+ r"""Return a context manager that disables autoflush.
1546
+
1547
+ .. container:: class_bases
1548
+
1549
+ Proxied for the :class:`_orm.Session` class
1550
+ on behalf of the :class:`_asyncio.AsyncSession` class.
1551
+
1552
+ e.g.::
1553
+
1554
+ with session.no_autoflush:
1555
+
1556
+ some_object = SomeClass()
1557
+ session.add(some_object)
1558
+ # won't autoflush
1559
+ some_object.related_thing = session.query(SomeRelated).first()
1560
+
1561
+ Operations that proceed within the ``with:`` block
1562
+ will not be subject to flushes occurring upon query
1563
+ access. This is useful when initializing a series
1564
+ of objects which involve existing database queries,
1565
+ where the uncompleted object should not yet be flushed.
1566
+
1567
+
1568
+ """ # noqa: E501
1569
+
1570
+ return self._proxied.no_autoflush
1571
+
1572
+ @property
1573
+ def info(self) -> Any:
1574
+ r"""A user-modifiable dictionary.
1575
+
1576
+ .. container:: class_bases
1577
+
1578
+ Proxied for the :class:`_orm.Session` class
1579
+ on behalf of the :class:`_asyncio.AsyncSession` class.
1580
+
1581
+ The initial value of this dictionary can be populated using the
1582
+ ``info`` argument to the :class:`.Session` constructor or
1583
+ :class:`.sessionmaker` constructor or factory methods. The dictionary
1584
+ here is always local to this :class:`.Session` and can be modified
1585
+ independently of all other :class:`.Session` objects.
1586
+
1587
+
1588
+ """ # noqa: E501
1589
+
1590
+ return self._proxied.info
1591
+
1592
+ @property
1593
+ def execution_options(self) -> _ExecuteOptions:
1594
+ r"""Proxy for the :attr:`_orm.Session.execution_options` attribute
1595
+ on behalf of the :class:`_asyncio.AsyncSession` class.
1596
+
1597
+ """ # noqa: E501
1598
+
1599
+ return self._proxied.execution_options
1600
+
1601
+ @execution_options.setter
1602
+ def execution_options(self, attr: _ExecuteOptions) -> None:
1603
+ self._proxied.execution_options = attr
1604
+
1605
+ @classmethod
1606
+ def object_session(cls, instance: object) -> Optional[Session]:
1607
+ r"""Return the :class:`.Session` to which an object belongs.
1608
+
1609
+ .. container:: class_bases
1610
+
1611
+ Proxied for the :class:`_orm.Session` class on
1612
+ behalf of the :class:`_asyncio.AsyncSession` class.
1613
+
1614
+ This is an alias of :func:`.object_session`.
1615
+
1616
+
1617
+ """ # noqa: E501
1618
+
1619
+ return Session.object_session(instance)
1620
+
1621
+ @classmethod
1622
+ def identity_key(
1623
+ cls,
1624
+ class_: Optional[Type[Any]] = None,
1625
+ ident: Union[Any, Tuple[Any, ...]] = None,
1626
+ *,
1627
+ instance: Optional[Any] = None,
1628
+ row: Optional[Union[Row[Unpack[TupleAny]], RowMapping]] = None,
1629
+ identity_token: Optional[Any] = None,
1630
+ ) -> _IdentityKeyType[Any]:
1631
+ r"""Return an identity key.
1632
+
1633
+ .. container:: class_bases
1634
+
1635
+ Proxied for the :class:`_orm.Session` class on
1636
+ behalf of the :class:`_asyncio.AsyncSession` class.
1637
+
1638
+ This is an alias of :func:`.util.identity_key`.
1639
+
1640
+
1641
+ """ # noqa: E501
1642
+
1643
+ return Session.identity_key(
1644
+ class_=class_,
1645
+ ident=ident,
1646
+ instance=instance,
1647
+ row=row,
1648
+ identity_token=identity_token,
1649
+ )
1650
+
1651
+ # END PROXY METHODS AsyncSession
1652
+
1653
+
1654
+ _AS = TypeVar("_AS", bound="AsyncSession")
1655
+
1656
+
1657
+ class async_sessionmaker(Generic[_AS]):
1658
+ """A configurable :class:`.AsyncSession` factory.
1659
+
1660
+ The :class:`.async_sessionmaker` factory works in the same way as the
1661
+ :class:`.sessionmaker` factory, to generate new :class:`.AsyncSession`
1662
+ objects when called, creating them given
1663
+ the configurational arguments established here.
1664
+
1665
+ e.g.::
1666
+
1667
+ from sqlalchemy.ext.asyncio import create_async_engine
1668
+ from sqlalchemy.ext.asyncio import AsyncSession
1669
+ from sqlalchemy.ext.asyncio import async_sessionmaker
1670
+
1671
+
1672
+ async def run_some_sql(
1673
+ async_session: async_sessionmaker[AsyncSession],
1674
+ ) -> None:
1675
+ async with async_session() as session:
1676
+ session.add(SomeObject(data="object"))
1677
+ session.add(SomeOtherObject(name="other object"))
1678
+ await session.commit()
1679
+
1680
+
1681
+ async def main() -> None:
1682
+ # an AsyncEngine, which the AsyncSession will use for connection
1683
+ # resources
1684
+ engine = create_async_engine(
1685
+ "postgresql+asyncpg://scott:tiger@localhost/"
1686
+ )
1687
+
1688
+ # create a reusable factory for new AsyncSession instances
1689
+ async_session = async_sessionmaker(engine)
1690
+
1691
+ await run_some_sql(async_session)
1692
+
1693
+ await engine.dispose()
1694
+
1695
+ The :class:`.async_sessionmaker` is useful so that different parts
1696
+ of a program can create new :class:`.AsyncSession` objects with a
1697
+ fixed configuration established up front. Note that :class:`.AsyncSession`
1698
+ objects may also be instantiated directly when not using
1699
+ :class:`.async_sessionmaker`.
1700
+
1701
+ .. versionadded:: 2.0 :class:`.async_sessionmaker` provides a
1702
+ :class:`.sessionmaker` class that's dedicated to the
1703
+ :class:`.AsyncSession` object, including pep-484 typing support.
1704
+
1705
+ .. seealso::
1706
+
1707
+ :ref:`asyncio_orm` - shows example use
1708
+
1709
+ :class:`.sessionmaker` - general overview of the
1710
+ :class:`.sessionmaker` architecture
1711
+
1712
+
1713
+ :ref:`session_getting` - introductory text on creating
1714
+ sessions using :class:`.sessionmaker`.
1715
+
1716
+ """ # noqa E501
1717
+
1718
+ class_: Type[_AS]
1719
+
1720
+ @overload
1721
+ def __init__(
1722
+ self,
1723
+ bind: Optional[_AsyncSessionBind] = ...,
1724
+ *,
1725
+ class_: Type[_AS],
1726
+ autoflush: bool = ...,
1727
+ expire_on_commit: bool = ...,
1728
+ info: Optional[_InfoType] = ...,
1729
+ **kw: Any,
1730
+ ): ...
1731
+
1732
+ @overload
1733
+ def __init__(
1734
+ self: "async_sessionmaker[AsyncSession]",
1735
+ bind: Optional[_AsyncSessionBind] = ...,
1736
+ *,
1737
+ autoflush: bool = ...,
1738
+ expire_on_commit: bool = ...,
1739
+ info: Optional[_InfoType] = ...,
1740
+ **kw: Any,
1741
+ ): ...
1742
+
1743
+ def __init__(
1744
+ self,
1745
+ bind: Optional[_AsyncSessionBind] = None,
1746
+ *,
1747
+ class_: Type[_AS] = AsyncSession, # type: ignore
1748
+ autoflush: bool = True,
1749
+ expire_on_commit: bool = True,
1750
+ info: Optional[_InfoType] = None,
1751
+ **kw: Any,
1752
+ ):
1753
+ r"""Construct a new :class:`.async_sessionmaker`.
1754
+
1755
+ All arguments here except for ``class_`` correspond to arguments
1756
+ accepted by :class:`.Session` directly. See the
1757
+ :meth:`.AsyncSession.__init__` docstring for more details on
1758
+ parameters.
1759
+
1760
+
1761
+ """
1762
+ kw["bind"] = bind
1763
+ kw["autoflush"] = autoflush
1764
+ kw["expire_on_commit"] = expire_on_commit
1765
+ if info is not None:
1766
+ kw["info"] = info
1767
+ self.kw = kw
1768
+ self.class_ = class_
1769
+
1770
+ def begin(self) -> _AsyncSessionContextManager[_AS]:
1771
+ """Produce a context manager that both provides a new
1772
+ :class:`_orm.AsyncSession` as well as a transaction that commits.
1773
+
1774
+
1775
+ e.g.::
1776
+
1777
+ async def main():
1778
+ Session = async_sessionmaker(some_engine)
1779
+
1780
+ async with Session.begin() as session:
1781
+ session.add(some_object)
1782
+
1783
+ # commits transaction, closes session
1784
+
1785
+ """
1786
+
1787
+ session = self()
1788
+ return session._maker_context_manager()
1789
+
1790
+ def __call__(self, **local_kw: Any) -> _AS:
1791
+ """Produce a new :class:`.AsyncSession` object using the configuration
1792
+ established in this :class:`.async_sessionmaker`.
1793
+
1794
+ In Python, the ``__call__`` method is invoked on an object when
1795
+ it is "called" in the same way as a function::
1796
+
1797
+ AsyncSession = async_sessionmaker(async_engine, expire_on_commit=False)
1798
+ session = AsyncSession() # invokes sessionmaker.__call__()
1799
+
1800
+ """ # noqa E501
1801
+ for k, v in self.kw.items():
1802
+ if k == "info" and "info" in local_kw:
1803
+ d = v.copy()
1804
+ d.update(local_kw["info"])
1805
+ local_kw["info"] = d
1806
+ else:
1807
+ local_kw.setdefault(k, v)
1808
+ return self.class_(**local_kw)
1809
+
1810
+ def configure(self, **new_kw: Any) -> None:
1811
+ """(Re)configure the arguments for this async_sessionmaker.
1812
+
1813
+ e.g.::
1814
+
1815
+ AsyncSession = async_sessionmaker(some_engine)
1816
+
1817
+ AsyncSession.configure(bind=create_async_engine("sqlite+aiosqlite://"))
1818
+ """ # noqa E501
1819
+
1820
+ self.kw.update(new_kw)
1821
+
1822
+ def __repr__(self) -> str:
1823
+ return "%s(class_=%r, %s)" % (
1824
+ self.__class__.__name__,
1825
+ self.class_.__name__,
1826
+ ", ".join("%s=%r" % (k, v) for k, v in self.kw.items()),
1827
+ )
1828
+
1829
+
1830
+ class _AsyncSessionContextManager(Generic[_AS]):
1831
+ __slots__ = ("async_session", "trans")
1832
+
1833
+ async_session: _AS
1834
+ trans: AsyncSessionTransaction
1835
+
1836
+ def __init__(self, async_session: _AS):
1837
+ self.async_session = async_session
1838
+
1839
+ async def __aenter__(self) -> _AS:
1840
+ self.trans = self.async_session.begin()
1841
+ await self.trans.__aenter__()
1842
+ return self.async_session
1843
+
1844
+ async def __aexit__(self, type_: Any, value: Any, traceback: Any) -> None:
1845
+ async def go() -> None:
1846
+ await self.trans.__aexit__(type_, value, traceback)
1847
+ await self.async_session.__aexit__(type_, value, traceback)
1848
+
1849
+ task = asyncio.create_task(go())
1850
+ await asyncio.shield(task)
1851
+
1852
+
1853
+ class AsyncSessionTransaction(
1854
+ ReversibleProxy[SessionTransaction],
1855
+ StartableContext["AsyncSessionTransaction"],
1856
+ ):
1857
+ """A wrapper for the ORM :class:`_orm.SessionTransaction` object.
1858
+
1859
+ This object is provided so that a transaction-holding object
1860
+ for the :meth:`_asyncio.AsyncSession.begin` may be returned.
1861
+
1862
+ The object supports both explicit calls to
1863
+ :meth:`_asyncio.AsyncSessionTransaction.commit` and
1864
+ :meth:`_asyncio.AsyncSessionTransaction.rollback`, as well as use as an
1865
+ async context manager.
1866
+
1867
+
1868
+ .. versionadded:: 1.4
1869
+
1870
+ """
1871
+
1872
+ __slots__ = ("session", "sync_transaction", "nested")
1873
+
1874
+ session: AsyncSession
1875
+ sync_transaction: Optional[SessionTransaction]
1876
+
1877
+ def __init__(self, session: AsyncSession, nested: bool = False):
1878
+ self.session = session
1879
+ self.nested = nested
1880
+ self.sync_transaction = None
1881
+
1882
+ @property
1883
+ def is_active(self) -> bool:
1884
+ return (
1885
+ self._sync_transaction() is not None
1886
+ and self._sync_transaction().is_active
1887
+ )
1888
+
1889
+ def _sync_transaction(self) -> SessionTransaction:
1890
+ if not self.sync_transaction:
1891
+ self._raise_for_not_started()
1892
+ return self.sync_transaction
1893
+
1894
+ async def rollback(self) -> None:
1895
+ """Roll back this :class:`_asyncio.AsyncTransaction`."""
1896
+ await greenlet_spawn(self._sync_transaction().rollback)
1897
+
1898
+ async def commit(self) -> None:
1899
+ """Commit this :class:`_asyncio.AsyncTransaction`."""
1900
+
1901
+ await greenlet_spawn(self._sync_transaction().commit)
1902
+
1903
+ @classmethod
1904
+ def _regenerate_proxy_for_target( # type: ignore[override]
1905
+ cls,
1906
+ target: SessionTransaction,
1907
+ async_session: AsyncSession,
1908
+ **additional_kw: Any, # noqa: U100
1909
+ ) -> AsyncSessionTransaction:
1910
+ sync_transaction = target
1911
+ nested = target.nested
1912
+ obj = cls.__new__(cls)
1913
+ obj.session = async_session
1914
+ obj.sync_transaction = obj._assign_proxied(sync_transaction)
1915
+ obj.nested = nested
1916
+ return obj
1917
+
1918
+ async def start(
1919
+ self, is_ctxmanager: bool = False
1920
+ ) -> AsyncSessionTransaction:
1921
+ self.sync_transaction = self._assign_proxied(
1922
+ await greenlet_spawn(
1923
+ self.session.sync_session.begin_nested
1924
+ if self.nested
1925
+ else self.session.sync_session.begin
1926
+ )
1927
+ )
1928
+ if is_ctxmanager:
1929
+ self.sync_transaction.__enter__()
1930
+ return self
1931
+
1932
+ async def __aexit__(self, type_: Any, value: Any, traceback: Any) -> None:
1933
+ await greenlet_spawn(
1934
+ self._sync_transaction().__exit__, type_, value, traceback
1935
+ )
1936
+
1937
+
1938
+ def async_object_session(instance: object) -> Optional[AsyncSession]:
1939
+ """Return the :class:`_asyncio.AsyncSession` to which the given instance
1940
+ belongs.
1941
+
1942
+ This function makes use of the sync-API function
1943
+ :class:`_orm.object_session` to retrieve the :class:`_orm.Session` which
1944
+ refers to the given instance, and from there links it to the original
1945
+ :class:`_asyncio.AsyncSession`.
1946
+
1947
+ If the :class:`_asyncio.AsyncSession` has been garbage collected, the
1948
+ return value is ``None``.
1949
+
1950
+ This functionality is also available from the
1951
+ :attr:`_orm.InstanceState.async_session` accessor.
1952
+
1953
+ :param instance: an ORM mapped instance
1954
+ :return: an :class:`_asyncio.AsyncSession` object, or ``None``.
1955
+
1956
+ .. versionadded:: 1.4.18
1957
+
1958
+ """
1959
+
1960
+ session = object_session(instance)
1961
+ if session is not None:
1962
+ return async_session(session)
1963
+ else:
1964
+ return None
1965
+
1966
+
1967
+ def async_session(session: Session) -> Optional[AsyncSession]:
1968
+ """Return the :class:`_asyncio.AsyncSession` which is proxying the given
1969
+ :class:`_orm.Session` object, if any.
1970
+
1971
+ :param session: a :class:`_orm.Session` instance.
1972
+ :return: a :class:`_asyncio.AsyncSession` instance, or ``None``.
1973
+
1974
+ .. versionadded:: 1.4.18
1975
+
1976
+ """
1977
+ return AsyncSession._retrieve_proxy_for_target(session, regenerate=False)
1978
+
1979
+
1980
+ async def close_all_sessions() -> None:
1981
+ """Close all :class:`_asyncio.AsyncSession` sessions.
1982
+
1983
+ .. versionadded:: 2.0.23
1984
+
1985
+ .. seealso::
1986
+
1987
+ :func:`.session.close_all_sessions`
1988
+
1989
+ """
1990
+ await greenlet_spawn(_sync_close_all_sessions)
1991
+
1992
+
1993
+ _instance_state._async_provider = async_session # type: ignore