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