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