SQLAlchemy 2.0.36__cp313-cp313-win32.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (273) hide show
  1. SQLAlchemy-2.0.36.dist-info/LICENSE +19 -0
  2. SQLAlchemy-2.0.36.dist-info/METADATA +243 -0
  3. SQLAlchemy-2.0.36.dist-info/RECORD +273 -0
  4. SQLAlchemy-2.0.36.dist-info/WHEEL +5 -0
  5. SQLAlchemy-2.0.36.dist-info/top_level.txt +1 -0
  6. sqlalchemy/__init__.py +294 -0
  7. sqlalchemy/connectors/__init__.py +18 -0
  8. sqlalchemy/connectors/aioodbc.py +174 -0
  9. sqlalchemy/connectors/asyncio.py +213 -0
  10. sqlalchemy/connectors/pyodbc.py +249 -0
  11. sqlalchemy/cyextension/__init__.py +6 -0
  12. sqlalchemy/cyextension/collections.cp313-win32.pyd +0 -0
  13. sqlalchemy/cyextension/collections.pyx +409 -0
  14. sqlalchemy/cyextension/immutabledict.cp313-win32.pyd +0 -0
  15. sqlalchemy/cyextension/immutabledict.pxd +8 -0
  16. sqlalchemy/cyextension/immutabledict.pyx +133 -0
  17. sqlalchemy/cyextension/processors.cp313-win32.pyd +0 -0
  18. sqlalchemy/cyextension/processors.pyx +68 -0
  19. sqlalchemy/cyextension/resultproxy.cp313-win32.pyd +0 -0
  20. sqlalchemy/cyextension/resultproxy.pyx +102 -0
  21. sqlalchemy/cyextension/util.cp313-win32.pyd +0 -0
  22. sqlalchemy/cyextension/util.pyx +91 -0
  23. sqlalchemy/dialects/__init__.py +61 -0
  24. sqlalchemy/dialects/_typing.py +25 -0
  25. sqlalchemy/dialects/mssql/__init__.py +88 -0
  26. sqlalchemy/dialects/mssql/aioodbc.py +64 -0
  27. sqlalchemy/dialects/mssql/base.py +4010 -0
  28. sqlalchemy/dialects/mssql/information_schema.py +254 -0
  29. sqlalchemy/dialects/mssql/json.py +133 -0
  30. sqlalchemy/dialects/mssql/provision.py +162 -0
  31. sqlalchemy/dialects/mssql/pymssql.py +126 -0
  32. sqlalchemy/dialects/mssql/pyodbc.py +745 -0
  33. sqlalchemy/dialects/mysql/__init__.py +101 -0
  34. sqlalchemy/dialects/mysql/aiomysql.py +333 -0
  35. sqlalchemy/dialects/mysql/asyncmy.py +337 -0
  36. sqlalchemy/dialects/mysql/base.py +3494 -0
  37. sqlalchemy/dialects/mysql/cymysql.py +84 -0
  38. sqlalchemy/dialects/mysql/dml.py +219 -0
  39. sqlalchemy/dialects/mysql/enumerated.py +244 -0
  40. sqlalchemy/dialects/mysql/expression.py +141 -0
  41. sqlalchemy/dialects/mysql/json.py +81 -0
  42. sqlalchemy/dialects/mysql/mariadb.py +32 -0
  43. sqlalchemy/dialects/mysql/mariadbconnector.py +277 -0
  44. sqlalchemy/dialects/mysql/mysqlconnector.py +180 -0
  45. sqlalchemy/dialects/mysql/mysqldb.py +303 -0
  46. sqlalchemy/dialects/mysql/provision.py +110 -0
  47. sqlalchemy/dialects/mysql/pymysql.py +137 -0
  48. sqlalchemy/dialects/mysql/pyodbc.py +138 -0
  49. sqlalchemy/dialects/mysql/reflection.py +677 -0
  50. sqlalchemy/dialects/mysql/reserved_words.py +571 -0
  51. sqlalchemy/dialects/mysql/types.py +774 -0
  52. sqlalchemy/dialects/oracle/__init__.py +67 -0
  53. sqlalchemy/dialects/oracle/base.py +3271 -0
  54. sqlalchemy/dialects/oracle/cx_oracle.py +1483 -0
  55. sqlalchemy/dialects/oracle/dictionary.py +507 -0
  56. sqlalchemy/dialects/oracle/oracledb.py +431 -0
  57. sqlalchemy/dialects/oracle/provision.py +220 -0
  58. sqlalchemy/dialects/oracle/types.py +287 -0
  59. sqlalchemy/dialects/postgresql/__init__.py +167 -0
  60. sqlalchemy/dialects/postgresql/_psycopg_common.py +187 -0
  61. sqlalchemy/dialects/postgresql/array.py +425 -0
  62. sqlalchemy/dialects/postgresql/asyncpg.py +1274 -0
  63. sqlalchemy/dialects/postgresql/base.py +5008 -0
  64. sqlalchemy/dialects/postgresql/dml.py +310 -0
  65. sqlalchemy/dialects/postgresql/ext.py +496 -0
  66. sqlalchemy/dialects/postgresql/hstore.py +397 -0
  67. sqlalchemy/dialects/postgresql/json.py +333 -0
  68. sqlalchemy/dialects/postgresql/named_types.py +509 -0
  69. sqlalchemy/dialects/postgresql/operators.py +129 -0
  70. sqlalchemy/dialects/postgresql/pg8000.py +662 -0
  71. sqlalchemy/dialects/postgresql/pg_catalog.py +300 -0
  72. sqlalchemy/dialects/postgresql/provision.py +175 -0
  73. sqlalchemy/dialects/postgresql/psycopg.py +772 -0
  74. sqlalchemy/dialects/postgresql/psycopg2.py +886 -0
  75. sqlalchemy/dialects/postgresql/psycopg2cffi.py +61 -0
  76. sqlalchemy/dialects/postgresql/ranges.py +1029 -0
  77. sqlalchemy/dialects/postgresql/types.py +303 -0
  78. sqlalchemy/dialects/sqlite/__init__.py +57 -0
  79. sqlalchemy/dialects/sqlite/aiosqlite.py +396 -0
  80. sqlalchemy/dialects/sqlite/base.py +2805 -0
  81. sqlalchemy/dialects/sqlite/dml.py +240 -0
  82. sqlalchemy/dialects/sqlite/json.py +92 -0
  83. sqlalchemy/dialects/sqlite/provision.py +198 -0
  84. sqlalchemy/dialects/sqlite/pysqlcipher.py +155 -0
  85. sqlalchemy/dialects/sqlite/pysqlite.py +756 -0
  86. sqlalchemy/dialects/type_migration_guidelines.txt +145 -0
  87. sqlalchemy/engine/__init__.py +62 -0
  88. sqlalchemy/engine/_py_processors.py +136 -0
  89. sqlalchemy/engine/_py_row.py +128 -0
  90. sqlalchemy/engine/_py_util.py +74 -0
  91. sqlalchemy/engine/base.py +3375 -0
  92. sqlalchemy/engine/characteristics.py +155 -0
  93. sqlalchemy/engine/create.py +875 -0
  94. sqlalchemy/engine/cursor.py +2181 -0
  95. sqlalchemy/engine/default.py +2365 -0
  96. sqlalchemy/engine/events.py +951 -0
  97. sqlalchemy/engine/interfaces.py +3403 -0
  98. sqlalchemy/engine/mock.py +131 -0
  99. sqlalchemy/engine/processors.py +61 -0
  100. sqlalchemy/engine/reflection.py +2098 -0
  101. sqlalchemy/engine/result.py +2382 -0
  102. sqlalchemy/engine/row.py +401 -0
  103. sqlalchemy/engine/strategies.py +19 -0
  104. sqlalchemy/engine/url.py +910 -0
  105. sqlalchemy/engine/util.py +167 -0
  106. sqlalchemy/event/__init__.py +25 -0
  107. sqlalchemy/event/api.py +225 -0
  108. sqlalchemy/event/attr.py +655 -0
  109. sqlalchemy/event/base.py +470 -0
  110. sqlalchemy/event/legacy.py +246 -0
  111. sqlalchemy/event/registry.py +386 -0
  112. sqlalchemy/events.py +17 -0
  113. sqlalchemy/exc.py +830 -0
  114. sqlalchemy/ext/__init__.py +11 -0
  115. sqlalchemy/ext/associationproxy.py +2013 -0
  116. sqlalchemy/ext/asyncio/__init__.py +25 -0
  117. sqlalchemy/ext/asyncio/base.py +279 -0
  118. sqlalchemy/ext/asyncio/engine.py +1466 -0
  119. sqlalchemy/ext/asyncio/exc.py +21 -0
  120. sqlalchemy/ext/asyncio/result.py +961 -0
  121. sqlalchemy/ext/asyncio/scoping.py +1614 -0
  122. sqlalchemy/ext/asyncio/session.py +1936 -0
  123. sqlalchemy/ext/automap.py +1691 -0
  124. sqlalchemy/ext/baked.py +574 -0
  125. sqlalchemy/ext/compiler.py +570 -0
  126. sqlalchemy/ext/declarative/__init__.py +65 -0
  127. sqlalchemy/ext/declarative/extensions.py +548 -0
  128. sqlalchemy/ext/horizontal_shard.py +481 -0
  129. sqlalchemy/ext/hybrid.py +1514 -0
  130. sqlalchemy/ext/indexable.py +341 -0
  131. sqlalchemy/ext/instrumentation.py +450 -0
  132. sqlalchemy/ext/mutable.py +1073 -0
  133. sqlalchemy/ext/mypy/__init__.py +6 -0
  134. sqlalchemy/ext/mypy/apply.py +320 -0
  135. sqlalchemy/ext/mypy/decl_class.py +515 -0
  136. sqlalchemy/ext/mypy/infer.py +590 -0
  137. sqlalchemy/ext/mypy/names.py +335 -0
  138. sqlalchemy/ext/mypy/plugin.py +303 -0
  139. sqlalchemy/ext/mypy/util.py +357 -0
  140. sqlalchemy/ext/orderinglist.py +416 -0
  141. sqlalchemy/ext/serializer.py +181 -0
  142. sqlalchemy/future/__init__.py +16 -0
  143. sqlalchemy/future/engine.py +15 -0
  144. sqlalchemy/inspection.py +174 -0
  145. sqlalchemy/log.py +288 -0
  146. sqlalchemy/orm/__init__.py +170 -0
  147. sqlalchemy/orm/_orm_constructors.py +2571 -0
  148. sqlalchemy/orm/_typing.py +179 -0
  149. sqlalchemy/orm/attributes.py +2835 -0
  150. sqlalchemy/orm/base.py +973 -0
  151. sqlalchemy/orm/bulk_persistence.py +2123 -0
  152. sqlalchemy/orm/clsregistry.py +571 -0
  153. sqlalchemy/orm/collections.py +1620 -0
  154. sqlalchemy/orm/context.py +3268 -0
  155. sqlalchemy/orm/decl_api.py +1883 -0
  156. sqlalchemy/orm/decl_base.py +2190 -0
  157. sqlalchemy/orm/dependency.py +1304 -0
  158. sqlalchemy/orm/descriptor_props.py +1076 -0
  159. sqlalchemy/orm/dynamic.py +300 -0
  160. sqlalchemy/orm/evaluator.py +379 -0
  161. sqlalchemy/orm/events.py +3261 -0
  162. sqlalchemy/orm/exc.py +228 -0
  163. sqlalchemy/orm/identity.py +302 -0
  164. sqlalchemy/orm/instrumentation.py +754 -0
  165. sqlalchemy/orm/interfaces.py +1474 -0
  166. sqlalchemy/orm/loading.py +1682 -0
  167. sqlalchemy/orm/mapped_collection.py +557 -0
  168. sqlalchemy/orm/mapper.py +4432 -0
  169. sqlalchemy/orm/path_registry.py +811 -0
  170. sqlalchemy/orm/persistence.py +1782 -0
  171. sqlalchemy/orm/properties.py +886 -0
  172. sqlalchemy/orm/query.py +3396 -0
  173. sqlalchemy/orm/relationships.py +3500 -0
  174. sqlalchemy/orm/scoping.py +2165 -0
  175. sqlalchemy/orm/session.py +5301 -0
  176. sqlalchemy/orm/state.py +1143 -0
  177. sqlalchemy/orm/state_changes.py +198 -0
  178. sqlalchemy/orm/strategies.py +3473 -0
  179. sqlalchemy/orm/strategy_options.py +2569 -0
  180. sqlalchemy/orm/sync.py +164 -0
  181. sqlalchemy/orm/unitofwork.py +796 -0
  182. sqlalchemy/orm/util.py +2424 -0
  183. sqlalchemy/orm/writeonly.py +678 -0
  184. sqlalchemy/pool/__init__.py +44 -0
  185. sqlalchemy/pool/base.py +1515 -0
  186. sqlalchemy/pool/events.py +370 -0
  187. sqlalchemy/pool/impl.py +581 -0
  188. sqlalchemy/py.typed +0 -0
  189. sqlalchemy/schema.py +70 -0
  190. sqlalchemy/sql/__init__.py +145 -0
  191. sqlalchemy/sql/_dml_constructors.py +140 -0
  192. sqlalchemy/sql/_elements_constructors.py +1850 -0
  193. sqlalchemy/sql/_orm_types.py +20 -0
  194. sqlalchemy/sql/_py_util.py +75 -0
  195. sqlalchemy/sql/_selectable_constructors.py +635 -0
  196. sqlalchemy/sql/_typing.py +460 -0
  197. sqlalchemy/sql/annotation.py +585 -0
  198. sqlalchemy/sql/base.py +2185 -0
  199. sqlalchemy/sql/cache_key.py +1057 -0
  200. sqlalchemy/sql/coercions.py +1405 -0
  201. sqlalchemy/sql/compiler.py +7818 -0
  202. sqlalchemy/sql/crud.py +1669 -0
  203. sqlalchemy/sql/ddl.py +1378 -0
  204. sqlalchemy/sql/default_comparator.py +552 -0
  205. sqlalchemy/sql/dml.py +1817 -0
  206. sqlalchemy/sql/elements.py +5499 -0
  207. sqlalchemy/sql/events.py +455 -0
  208. sqlalchemy/sql/expression.py +162 -0
  209. sqlalchemy/sql/functions.py +2055 -0
  210. sqlalchemy/sql/lambdas.py +1449 -0
  211. sqlalchemy/sql/naming.py +212 -0
  212. sqlalchemy/sql/operators.py +2579 -0
  213. sqlalchemy/sql/roles.py +323 -0
  214. sqlalchemy/sql/schema.py +6158 -0
  215. sqlalchemy/sql/selectable.py +7004 -0
  216. sqlalchemy/sql/sqltypes.py +3827 -0
  217. sqlalchemy/sql/traversals.py +1024 -0
  218. sqlalchemy/sql/type_api.py +2339 -0
  219. sqlalchemy/sql/util.py +1486 -0
  220. sqlalchemy/sql/visitors.py +1165 -0
  221. sqlalchemy/testing/__init__.py +96 -0
  222. sqlalchemy/testing/assertions.py +989 -0
  223. sqlalchemy/testing/assertsql.py +516 -0
  224. sqlalchemy/testing/asyncio.py +135 -0
  225. sqlalchemy/testing/config.py +427 -0
  226. sqlalchemy/testing/engines.py +472 -0
  227. sqlalchemy/testing/entities.py +117 -0
  228. sqlalchemy/testing/exclusions.py +435 -0
  229. sqlalchemy/testing/fixtures/__init__.py +28 -0
  230. sqlalchemy/testing/fixtures/base.py +366 -0
  231. sqlalchemy/testing/fixtures/mypy.py +312 -0
  232. sqlalchemy/testing/fixtures/orm.py +227 -0
  233. sqlalchemy/testing/fixtures/sql.py +503 -0
  234. sqlalchemy/testing/pickleable.py +155 -0
  235. sqlalchemy/testing/plugin/__init__.py +6 -0
  236. sqlalchemy/testing/plugin/bootstrap.py +51 -0
  237. sqlalchemy/testing/plugin/plugin_base.py +779 -0
  238. sqlalchemy/testing/plugin/pytestplugin.py +868 -0
  239. sqlalchemy/testing/profiling.py +324 -0
  240. sqlalchemy/testing/provision.py +496 -0
  241. sqlalchemy/testing/requirements.py +1818 -0
  242. sqlalchemy/testing/schema.py +224 -0
  243. sqlalchemy/testing/suite/__init__.py +19 -0
  244. sqlalchemy/testing/suite/test_cte.py +211 -0
  245. sqlalchemy/testing/suite/test_ddl.py +389 -0
  246. sqlalchemy/testing/suite/test_deprecations.py +153 -0
  247. sqlalchemy/testing/suite/test_dialect.py +740 -0
  248. sqlalchemy/testing/suite/test_insert.py +630 -0
  249. sqlalchemy/testing/suite/test_reflection.py +3225 -0
  250. sqlalchemy/testing/suite/test_results.py +502 -0
  251. sqlalchemy/testing/suite/test_rowcount.py +258 -0
  252. sqlalchemy/testing/suite/test_select.py +1999 -0
  253. sqlalchemy/testing/suite/test_sequence.py +317 -0
  254. sqlalchemy/testing/suite/test_types.py +2141 -0
  255. sqlalchemy/testing/suite/test_unicode_ddl.py +189 -0
  256. sqlalchemy/testing/suite/test_update_delete.py +139 -0
  257. sqlalchemy/testing/util.py +537 -0
  258. sqlalchemy/testing/warnings.py +52 -0
  259. sqlalchemy/types.py +76 -0
  260. sqlalchemy/util/__init__.py +160 -0
  261. sqlalchemy/util/_collections.py +715 -0
  262. sqlalchemy/util/_concurrency_py3k.py +288 -0
  263. sqlalchemy/util/_has_cy.py +40 -0
  264. sqlalchemy/util/_py_collections.py +541 -0
  265. sqlalchemy/util/compat.py +301 -0
  266. sqlalchemy/util/concurrency.py +108 -0
  267. sqlalchemy/util/deprecations.py +401 -0
  268. sqlalchemy/util/langhelpers.py +2218 -0
  269. sqlalchemy/util/preloaded.py +150 -0
  270. sqlalchemy/util/queue.py +322 -0
  271. sqlalchemy/util/tool_support.py +201 -0
  272. sqlalchemy/util/topological.py +120 -0
  273. sqlalchemy/util/typing.py +629 -0
@@ -0,0 +1,2165 @@
1
+ # orm/scoping.py
2
+ # Copyright (C) 2005-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
+
8
+ from __future__ import annotations
9
+
10
+ from typing import Any
11
+ from typing import Callable
12
+ from typing import Dict
13
+ from typing import Generic
14
+ from typing import Iterable
15
+ from typing import Iterator
16
+ from typing import Optional
17
+ from typing import overload
18
+ from typing import Sequence
19
+ from typing import Tuple
20
+ from typing import Type
21
+ from typing import TYPE_CHECKING
22
+ from typing import TypeVar
23
+ from typing import Union
24
+
25
+ from .session import _S
26
+ from .session import Session
27
+ from .. import exc as sa_exc
28
+ from .. import util
29
+ from ..util import create_proxy_methods
30
+ from ..util import ScopedRegistry
31
+ from ..util import ThreadLocalRegistry
32
+ from ..util import warn
33
+ from ..util import warn_deprecated
34
+ from ..util.typing import Protocol
35
+
36
+ if TYPE_CHECKING:
37
+ from ._typing import _EntityType
38
+ from ._typing import _IdentityKeyType
39
+ from ._typing import OrmExecuteOptionsParameter
40
+ from .identity import IdentityMap
41
+ from .interfaces import ORMOption
42
+ from .mapper import Mapper
43
+ from .query import Query
44
+ from .query import RowReturningQuery
45
+ from .session import _BindArguments
46
+ from .session import _EntityBindKey
47
+ from .session import _PKIdentityArgument
48
+ from .session import _SessionBind
49
+ from .session import sessionmaker
50
+ from .session import SessionTransaction
51
+ from ..engine import Connection
52
+ from ..engine import CursorResult
53
+ from ..engine import Engine
54
+ from ..engine import Result
55
+ from ..engine import Row
56
+ from ..engine import RowMapping
57
+ from ..engine.interfaces import _CoreAnyExecuteParams
58
+ from ..engine.interfaces import _CoreSingleExecuteParams
59
+ from ..engine.interfaces import CoreExecuteOptionsParameter
60
+ from ..engine.result import ScalarResult
61
+ from ..sql._typing import _ColumnsClauseArgument
62
+ from ..sql._typing import _T0
63
+ from ..sql._typing import _T1
64
+ from ..sql._typing import _T2
65
+ from ..sql._typing import _T3
66
+ from ..sql._typing import _T4
67
+ from ..sql._typing import _T5
68
+ from ..sql._typing import _T6
69
+ from ..sql._typing import _T7
70
+ from ..sql._typing import _TypedColumnClauseArgument as _TCCA
71
+ from ..sql.base import Executable
72
+ from ..sql.dml import UpdateBase
73
+ from ..sql.elements import ClauseElement
74
+ from ..sql.roles import TypedColumnsClauseRole
75
+ from ..sql.selectable import ForUpdateParameter
76
+ from ..sql.selectable import TypedReturnsRows
77
+
78
+ _T = TypeVar("_T", bound=Any)
79
+
80
+
81
+ class QueryPropertyDescriptor(Protocol):
82
+ """Describes the type applied to a class-level
83
+ :meth:`_orm.scoped_session.query_property` attribute.
84
+
85
+ .. versionadded:: 2.0.5
86
+
87
+ """
88
+
89
+ def __get__(self, instance: Any, owner: Type[_T]) -> Query[_T]: ...
90
+
91
+
92
+ _O = TypeVar("_O", bound=object)
93
+
94
+ __all__ = ["scoped_session"]
95
+
96
+
97
+ @create_proxy_methods(
98
+ Session,
99
+ ":class:`_orm.Session`",
100
+ ":class:`_orm.scoping.scoped_session`",
101
+ classmethods=["close_all", "object_session", "identity_key"],
102
+ methods=[
103
+ "__contains__",
104
+ "__iter__",
105
+ "add",
106
+ "add_all",
107
+ "begin",
108
+ "begin_nested",
109
+ "close",
110
+ "reset",
111
+ "commit",
112
+ "connection",
113
+ "delete",
114
+ "execute",
115
+ "expire",
116
+ "expire_all",
117
+ "expunge",
118
+ "expunge_all",
119
+ "flush",
120
+ "get",
121
+ "get_one",
122
+ "get_bind",
123
+ "is_modified",
124
+ "bulk_save_objects",
125
+ "bulk_insert_mappings",
126
+ "bulk_update_mappings",
127
+ "merge",
128
+ "query",
129
+ "refresh",
130
+ "rollback",
131
+ "scalar",
132
+ "scalars",
133
+ ],
134
+ attributes=[
135
+ "bind",
136
+ "dirty",
137
+ "deleted",
138
+ "new",
139
+ "identity_map",
140
+ "is_active",
141
+ "autoflush",
142
+ "no_autoflush",
143
+ "info",
144
+ ],
145
+ )
146
+ class scoped_session(Generic[_S]):
147
+ """Provides scoped management of :class:`.Session` objects.
148
+
149
+ See :ref:`unitofwork_contextual` for a tutorial.
150
+
151
+ .. note::
152
+
153
+ When using :ref:`asyncio_toplevel`, the async-compatible
154
+ :class:`_asyncio.async_scoped_session` class should be
155
+ used in place of :class:`.scoped_session`.
156
+
157
+ """
158
+
159
+ _support_async: bool = False
160
+
161
+ session_factory: sessionmaker[_S]
162
+ """The `session_factory` provided to `__init__` is stored in this
163
+ attribute and may be accessed at a later time. This can be useful when
164
+ a new non-scoped :class:`.Session` is needed."""
165
+
166
+ registry: ScopedRegistry[_S]
167
+
168
+ def __init__(
169
+ self,
170
+ session_factory: sessionmaker[_S],
171
+ scopefunc: Optional[Callable[[], Any]] = None,
172
+ ):
173
+ """Construct a new :class:`.scoped_session`.
174
+
175
+ :param session_factory: a factory to create new :class:`.Session`
176
+ instances. This is usually, but not necessarily, an instance
177
+ of :class:`.sessionmaker`.
178
+ :param scopefunc: optional function which defines
179
+ the current scope. If not passed, the :class:`.scoped_session`
180
+ object assumes "thread-local" scope, and will use
181
+ a Python ``threading.local()`` in order to maintain the current
182
+ :class:`.Session`. If passed, the function should return
183
+ a hashable token; this token will be used as the key in a
184
+ dictionary in order to store and retrieve the current
185
+ :class:`.Session`.
186
+
187
+ """
188
+ self.session_factory = session_factory
189
+
190
+ if scopefunc:
191
+ self.registry = ScopedRegistry(session_factory, scopefunc)
192
+ else:
193
+ self.registry = ThreadLocalRegistry(session_factory)
194
+
195
+ @property
196
+ def _proxied(self) -> _S:
197
+ return self.registry()
198
+
199
+ def __call__(self, **kw: Any) -> _S:
200
+ r"""Return the current :class:`.Session`, creating it
201
+ using the :attr:`.scoped_session.session_factory` if not present.
202
+
203
+ :param \**kw: Keyword arguments will be passed to the
204
+ :attr:`.scoped_session.session_factory` callable, if an existing
205
+ :class:`.Session` is not present. If the :class:`.Session` is present
206
+ and keyword arguments have been passed,
207
+ :exc:`~sqlalchemy.exc.InvalidRequestError` is raised.
208
+
209
+ """
210
+ if kw:
211
+ if self.registry.has():
212
+ raise sa_exc.InvalidRequestError(
213
+ "Scoped session is already present; "
214
+ "no new arguments may be specified."
215
+ )
216
+ else:
217
+ sess = self.session_factory(**kw)
218
+ self.registry.set(sess)
219
+ else:
220
+ sess = self.registry()
221
+ if not self._support_async and sess._is_asyncio:
222
+ warn_deprecated(
223
+ "Using `scoped_session` with asyncio is deprecated and "
224
+ "will raise an error in a future version. "
225
+ "Please use `async_scoped_session` instead.",
226
+ "1.4.23",
227
+ )
228
+ return sess
229
+
230
+ def configure(self, **kwargs: Any) -> None:
231
+ """reconfigure the :class:`.sessionmaker` used by this
232
+ :class:`.scoped_session`.
233
+
234
+ See :meth:`.sessionmaker.configure`.
235
+
236
+ """
237
+
238
+ if self.registry.has():
239
+ warn(
240
+ "At least one scoped session is already present. "
241
+ " configure() can not affect sessions that have "
242
+ "already been created."
243
+ )
244
+
245
+ self.session_factory.configure(**kwargs)
246
+
247
+ def remove(self) -> None:
248
+ """Dispose of the current :class:`.Session`, if present.
249
+
250
+ This will first call :meth:`.Session.close` method
251
+ on the current :class:`.Session`, which releases any existing
252
+ transactional/connection resources still being held; transactions
253
+ specifically are rolled back. The :class:`.Session` is then
254
+ discarded. Upon next usage within the same scope,
255
+ the :class:`.scoped_session` will produce a new
256
+ :class:`.Session` object.
257
+
258
+ """
259
+
260
+ if self.registry.has():
261
+ self.registry().close()
262
+ self.registry.clear()
263
+
264
+ def query_property(
265
+ self, query_cls: Optional[Type[Query[_T]]] = None
266
+ ) -> QueryPropertyDescriptor:
267
+ """return a class property which produces a legacy
268
+ :class:`_query.Query` object against the class and the current
269
+ :class:`.Session` when called.
270
+
271
+ .. legacy:: The :meth:`_orm.scoped_session.query_property` accessor
272
+ is specific to the legacy :class:`.Query` object and is not
273
+ considered to be part of :term:`2.0-style` ORM use.
274
+
275
+ e.g.::
276
+
277
+ from sqlalchemy.orm import QueryPropertyDescriptor
278
+ from sqlalchemy.orm import scoped_session
279
+ from sqlalchemy.orm import sessionmaker
280
+
281
+ Session = scoped_session(sessionmaker())
282
+
283
+ class MyClass:
284
+ query: QueryPropertyDescriptor = Session.query_property()
285
+
286
+ # after mappers are defined
287
+ result = MyClass.query.filter(MyClass.name=='foo').all()
288
+
289
+ Produces instances of the session's configured query class by
290
+ default. To override and use a custom implementation, provide
291
+ a ``query_cls`` callable. The callable will be invoked with
292
+ the class's mapper as a positional argument and a session
293
+ keyword argument.
294
+
295
+ There is no limit to the number of query properties placed on
296
+ a class.
297
+
298
+ """
299
+
300
+ class query:
301
+ def __get__(s, instance: Any, owner: Type[_O]) -> Query[_O]:
302
+ if query_cls:
303
+ # custom query class
304
+ return query_cls(owner, session=self.registry()) # type: ignore # noqa: E501
305
+ else:
306
+ # session's configured query class
307
+ return self.registry().query(owner)
308
+
309
+ return query()
310
+
311
+ # START PROXY METHODS scoped_session
312
+
313
+ # code within this block is **programmatically,
314
+ # statically generated** by tools/generate_proxy_methods.py
315
+
316
+ def __contains__(self, instance: object) -> bool:
317
+ r"""Return True if the instance is associated with this session.
318
+
319
+ .. container:: class_bases
320
+
321
+ Proxied for the :class:`_orm.Session` class on
322
+ behalf of the :class:`_orm.scoping.scoped_session` class.
323
+
324
+ The instance may be pending or persistent within the Session for a
325
+ result of True.
326
+
327
+
328
+ """ # noqa: E501
329
+
330
+ return self._proxied.__contains__(instance)
331
+
332
+ def __iter__(self) -> Iterator[object]:
333
+ r"""Iterate over all pending or persistent instances within this
334
+ Session.
335
+
336
+ .. container:: class_bases
337
+
338
+ Proxied for the :class:`_orm.Session` class on
339
+ behalf of the :class:`_orm.scoping.scoped_session` class.
340
+
341
+
342
+ """ # noqa: E501
343
+
344
+ return self._proxied.__iter__()
345
+
346
+ def add(self, instance: object, _warn: bool = True) -> None:
347
+ r"""Place an object into this :class:`_orm.Session`.
348
+
349
+ .. container:: class_bases
350
+
351
+ Proxied for the :class:`_orm.Session` class on
352
+ behalf of the :class:`_orm.scoping.scoped_session` class.
353
+
354
+ Objects that are in the :term:`transient` state when passed to the
355
+ :meth:`_orm.Session.add` method will move to the
356
+ :term:`pending` state, until the next flush, at which point they
357
+ will move to the :term:`persistent` state.
358
+
359
+ Objects that are in the :term:`detached` state when passed to the
360
+ :meth:`_orm.Session.add` method will move to the :term:`persistent`
361
+ state directly.
362
+
363
+ If the transaction used by the :class:`_orm.Session` is rolled back,
364
+ objects which were transient when they were passed to
365
+ :meth:`_orm.Session.add` will be moved back to the
366
+ :term:`transient` state, and will no longer be present within this
367
+ :class:`_orm.Session`.
368
+
369
+ .. seealso::
370
+
371
+ :meth:`_orm.Session.add_all`
372
+
373
+ :ref:`session_adding` - at :ref:`session_basics`
374
+
375
+
376
+ """ # noqa: E501
377
+
378
+ return self._proxied.add(instance, _warn=_warn)
379
+
380
+ def add_all(self, instances: Iterable[object]) -> None:
381
+ r"""Add the given collection of instances to this :class:`_orm.Session`.
382
+
383
+ .. container:: class_bases
384
+
385
+ Proxied for the :class:`_orm.Session` class on
386
+ behalf of the :class:`_orm.scoping.scoped_session` class.
387
+
388
+ See the documentation for :meth:`_orm.Session.add` for a general
389
+ behavioral description.
390
+
391
+ .. seealso::
392
+
393
+ :meth:`_orm.Session.add`
394
+
395
+ :ref:`session_adding` - at :ref:`session_basics`
396
+
397
+
398
+ """ # noqa: E501
399
+
400
+ return self._proxied.add_all(instances)
401
+
402
+ def begin(self, nested: bool = False) -> SessionTransaction:
403
+ r"""Begin a transaction, or nested transaction,
404
+ on this :class:`.Session`, if one is not already begun.
405
+
406
+ .. container:: class_bases
407
+
408
+ Proxied for the :class:`_orm.Session` class on
409
+ behalf of the :class:`_orm.scoping.scoped_session` class.
410
+
411
+ The :class:`_orm.Session` object features **autobegin** behavior,
412
+ so that normally it is not necessary to call the
413
+ :meth:`_orm.Session.begin`
414
+ method explicitly. However, it may be used in order to control
415
+ the scope of when the transactional state is begun.
416
+
417
+ When used to begin the outermost transaction, an error is raised
418
+ if this :class:`.Session` is already inside of a transaction.
419
+
420
+ :param nested: if True, begins a SAVEPOINT transaction and is
421
+ equivalent to calling :meth:`~.Session.begin_nested`. For
422
+ documentation on SAVEPOINT transactions, please see
423
+ :ref:`session_begin_nested`.
424
+
425
+ :return: the :class:`.SessionTransaction` object. Note that
426
+ :class:`.SessionTransaction`
427
+ acts as a Python context manager, allowing :meth:`.Session.begin`
428
+ to be used in a "with" block. See :ref:`session_explicit_begin` for
429
+ an example.
430
+
431
+ .. seealso::
432
+
433
+ :ref:`session_autobegin`
434
+
435
+ :ref:`unitofwork_transaction`
436
+
437
+ :meth:`.Session.begin_nested`
438
+
439
+
440
+
441
+ """ # noqa: E501
442
+
443
+ return self._proxied.begin(nested=nested)
444
+
445
+ def begin_nested(self) -> SessionTransaction:
446
+ r"""Begin a "nested" transaction on this Session, e.g. SAVEPOINT.
447
+
448
+ .. container:: class_bases
449
+
450
+ Proxied for the :class:`_orm.Session` class on
451
+ behalf of the :class:`_orm.scoping.scoped_session` class.
452
+
453
+ The target database(s) and associated drivers must support SQL
454
+ SAVEPOINT for this method to function correctly.
455
+
456
+ For documentation on SAVEPOINT
457
+ transactions, please see :ref:`session_begin_nested`.
458
+
459
+ :return: the :class:`.SessionTransaction` object. Note that
460
+ :class:`.SessionTransaction` acts as a context manager, allowing
461
+ :meth:`.Session.begin_nested` to be used in a "with" block.
462
+ See :ref:`session_begin_nested` for a usage example.
463
+
464
+ .. seealso::
465
+
466
+ :ref:`session_begin_nested`
467
+
468
+ :ref:`pysqlite_serializable` - special workarounds required
469
+ with the SQLite driver in order for SAVEPOINT to work
470
+ correctly. For asyncio use cases, see the section
471
+ :ref:`aiosqlite_serializable`.
472
+
473
+
474
+ """ # noqa: E501
475
+
476
+ return self._proxied.begin_nested()
477
+
478
+ def close(self) -> None:
479
+ r"""Close out the transactional resources and ORM objects used by this
480
+ :class:`_orm.Session`.
481
+
482
+ .. container:: class_bases
483
+
484
+ Proxied for the :class:`_orm.Session` class on
485
+ behalf of the :class:`_orm.scoping.scoped_session` class.
486
+
487
+ This expunges all ORM objects associated with this
488
+ :class:`_orm.Session`, ends any transaction in progress and
489
+ :term:`releases` any :class:`_engine.Connection` objects which this
490
+ :class:`_orm.Session` itself has checked out from associated
491
+ :class:`_engine.Engine` objects. The operation then leaves the
492
+ :class:`_orm.Session` in a state which it may be used again.
493
+
494
+ .. tip::
495
+
496
+ In the default running mode the :meth:`_orm.Session.close`
497
+ method **does not prevent the Session from being used again**.
498
+ The :class:`_orm.Session` itself does not actually have a
499
+ distinct "closed" state; it merely means
500
+ the :class:`_orm.Session` will release all database connections
501
+ and ORM objects.
502
+
503
+ Setting the parameter :paramref:`_orm.Session.close_resets_only`
504
+ to ``False`` will instead make the ``close`` final, meaning that
505
+ any further action on the session will be forbidden.
506
+
507
+ .. versionchanged:: 1.4 The :meth:`.Session.close` method does not
508
+ immediately create a new :class:`.SessionTransaction` object;
509
+ instead, the new :class:`.SessionTransaction` is created only if
510
+ the :class:`.Session` is used again for a database operation.
511
+
512
+ .. seealso::
513
+
514
+ :ref:`session_closing` - detail on the semantics of
515
+ :meth:`_orm.Session.close` and :meth:`_orm.Session.reset`.
516
+
517
+ :meth:`_orm.Session.reset` - a similar method that behaves like
518
+ ``close()`` with the parameter
519
+ :paramref:`_orm.Session.close_resets_only` set to ``True``.
520
+
521
+
522
+ """ # noqa: E501
523
+
524
+ return self._proxied.close()
525
+
526
+ def reset(self) -> None:
527
+ r"""Close out the transactional resources and ORM objects used by this
528
+ :class:`_orm.Session`, resetting the session to its initial state.
529
+
530
+ .. container:: class_bases
531
+
532
+ Proxied for the :class:`_orm.Session` class on
533
+ behalf of the :class:`_orm.scoping.scoped_session` class.
534
+
535
+ This method provides for same "reset-only" behavior that the
536
+ :meth:`_orm.Session.close` method has provided historically, where the
537
+ state of the :class:`_orm.Session` is reset as though the object were
538
+ brand new, and ready to be used again.
539
+ This method may then be useful for :class:`_orm.Session` objects
540
+ which set :paramref:`_orm.Session.close_resets_only` to ``False``,
541
+ so that "reset only" behavior is still available.
542
+
543
+ .. versionadded:: 2.0.22
544
+
545
+ .. seealso::
546
+
547
+ :ref:`session_closing` - detail on the semantics of
548
+ :meth:`_orm.Session.close` and :meth:`_orm.Session.reset`.
549
+
550
+ :meth:`_orm.Session.close` - a similar method will additionally
551
+ prevent re-use of the Session when the parameter
552
+ :paramref:`_orm.Session.close_resets_only` is set to ``False``.
553
+
554
+ """ # noqa: E501
555
+
556
+ return self._proxied.reset()
557
+
558
+ def commit(self) -> None:
559
+ r"""Flush pending changes and commit the current transaction.
560
+
561
+ .. container:: class_bases
562
+
563
+ Proxied for the :class:`_orm.Session` class on
564
+ behalf of the :class:`_orm.scoping.scoped_session` class.
565
+
566
+ When the COMMIT operation is complete, all objects are fully
567
+ :term:`expired`, erasing their internal contents, which will be
568
+ automatically re-loaded when the objects are next accessed. In the
569
+ interim, these objects are in an expired state and will not function if
570
+ they are :term:`detached` from the :class:`.Session`. Additionally,
571
+ this re-load operation is not supported when using asyncio-oriented
572
+ APIs. The :paramref:`.Session.expire_on_commit` parameter may be used
573
+ to disable this behavior.
574
+
575
+ When there is no transaction in place for the :class:`.Session`,
576
+ indicating that no operations were invoked on this :class:`.Session`
577
+ since the previous call to :meth:`.Session.commit`, the method will
578
+ begin and commit an internal-only "logical" transaction, that does not
579
+ normally affect the database unless pending flush changes were
580
+ detected, but will still invoke event handlers and object expiration
581
+ rules.
582
+
583
+ The outermost database transaction is committed unconditionally,
584
+ automatically releasing any SAVEPOINTs in effect.
585
+
586
+ .. seealso::
587
+
588
+ :ref:`session_committing`
589
+
590
+ :ref:`unitofwork_transaction`
591
+
592
+ :ref:`asyncio_orm_avoid_lazyloads`
593
+
594
+
595
+ """ # noqa: E501
596
+
597
+ return self._proxied.commit()
598
+
599
+ def connection(
600
+ self,
601
+ bind_arguments: Optional[_BindArguments] = None,
602
+ execution_options: Optional[CoreExecuteOptionsParameter] = None,
603
+ ) -> Connection:
604
+ r"""Return a :class:`_engine.Connection` object corresponding to this
605
+ :class:`.Session` object's transactional state.
606
+
607
+ .. container:: class_bases
608
+
609
+ Proxied for the :class:`_orm.Session` class on
610
+ behalf of the :class:`_orm.scoping.scoped_session` class.
611
+
612
+ Either the :class:`_engine.Connection` corresponding to the current
613
+ transaction is returned, or if no transaction is in progress, a new
614
+ one is begun and the :class:`_engine.Connection`
615
+ returned (note that no
616
+ transactional state is established with the DBAPI until the first
617
+ SQL statement is emitted).
618
+
619
+ Ambiguity in multi-bind or unbound :class:`.Session` objects can be
620
+ resolved through any of the optional keyword arguments. This
621
+ ultimately makes usage of the :meth:`.get_bind` method for resolution.
622
+
623
+ :param bind_arguments: dictionary of bind arguments. May include
624
+ "mapper", "bind", "clause", other custom arguments that are passed
625
+ to :meth:`.Session.get_bind`.
626
+
627
+ :param execution_options: a dictionary of execution options that will
628
+ be passed to :meth:`_engine.Connection.execution_options`, **when the
629
+ connection is first procured only**. If the connection is already
630
+ present within the :class:`.Session`, a warning is emitted and
631
+ the arguments are ignored.
632
+
633
+ .. seealso::
634
+
635
+ :ref:`session_transaction_isolation`
636
+
637
+
638
+ """ # noqa: E501
639
+
640
+ return self._proxied.connection(
641
+ bind_arguments=bind_arguments, execution_options=execution_options
642
+ )
643
+
644
+ def delete(self, instance: object) -> None:
645
+ r"""Mark an instance as deleted.
646
+
647
+ .. container:: class_bases
648
+
649
+ Proxied for the :class:`_orm.Session` class on
650
+ behalf of the :class:`_orm.scoping.scoped_session` class.
651
+
652
+ The object is assumed to be either :term:`persistent` or
653
+ :term:`detached` when passed; after the method is called, the
654
+ object will remain in the :term:`persistent` state until the next
655
+ flush proceeds. During this time, the object will also be a member
656
+ of the :attr:`_orm.Session.deleted` collection.
657
+
658
+ When the next flush proceeds, the object will move to the
659
+ :term:`deleted` state, indicating a ``DELETE`` statement was emitted
660
+ for its row within the current transaction. When the transaction
661
+ is successfully committed,
662
+ the deleted object is moved to the :term:`detached` state and is
663
+ no longer present within this :class:`_orm.Session`.
664
+
665
+ .. seealso::
666
+
667
+ :ref:`session_deleting` - at :ref:`session_basics`
668
+
669
+
670
+ """ # noqa: E501
671
+
672
+ return self._proxied.delete(instance)
673
+
674
+ @overload
675
+ def execute(
676
+ self,
677
+ statement: TypedReturnsRows[_T],
678
+ params: Optional[_CoreAnyExecuteParams] = None,
679
+ *,
680
+ execution_options: OrmExecuteOptionsParameter = util.EMPTY_DICT,
681
+ bind_arguments: Optional[_BindArguments] = None,
682
+ _parent_execute_state: Optional[Any] = None,
683
+ _add_event: Optional[Any] = None,
684
+ ) -> Result[_T]: ...
685
+
686
+ @overload
687
+ def execute(
688
+ self,
689
+ statement: UpdateBase,
690
+ params: Optional[_CoreAnyExecuteParams] = None,
691
+ *,
692
+ execution_options: OrmExecuteOptionsParameter = util.EMPTY_DICT,
693
+ bind_arguments: Optional[_BindArguments] = None,
694
+ _parent_execute_state: Optional[Any] = None,
695
+ _add_event: Optional[Any] = None,
696
+ ) -> CursorResult[Any]: ...
697
+
698
+ @overload
699
+ def execute(
700
+ self,
701
+ statement: Executable,
702
+ params: Optional[_CoreAnyExecuteParams] = None,
703
+ *,
704
+ execution_options: OrmExecuteOptionsParameter = util.EMPTY_DICT,
705
+ bind_arguments: Optional[_BindArguments] = None,
706
+ _parent_execute_state: Optional[Any] = None,
707
+ _add_event: Optional[Any] = None,
708
+ ) -> Result[Any]: ...
709
+
710
+ def execute(
711
+ self,
712
+ statement: Executable,
713
+ params: Optional[_CoreAnyExecuteParams] = None,
714
+ *,
715
+ execution_options: OrmExecuteOptionsParameter = util.EMPTY_DICT,
716
+ bind_arguments: Optional[_BindArguments] = None,
717
+ _parent_execute_state: Optional[Any] = None,
718
+ _add_event: Optional[Any] = None,
719
+ ) -> Result[Any]:
720
+ r"""Execute a SQL expression construct.
721
+
722
+ .. container:: class_bases
723
+
724
+ Proxied for the :class:`_orm.Session` class on
725
+ behalf of the :class:`_orm.scoping.scoped_session` class.
726
+
727
+ Returns a :class:`_engine.Result` object representing
728
+ results of the statement execution.
729
+
730
+ E.g.::
731
+
732
+ from sqlalchemy import select
733
+ result = session.execute(
734
+ select(User).where(User.id == 5)
735
+ )
736
+
737
+ The API contract of :meth:`_orm.Session.execute` is similar to that
738
+ of :meth:`_engine.Connection.execute`, the :term:`2.0 style` version
739
+ of :class:`_engine.Connection`.
740
+
741
+ .. versionchanged:: 1.4 the :meth:`_orm.Session.execute` method is
742
+ now the primary point of ORM statement execution when using
743
+ :term:`2.0 style` ORM usage.
744
+
745
+ :param statement:
746
+ An executable statement (i.e. an :class:`.Executable` expression
747
+ such as :func:`_expression.select`).
748
+
749
+ :param params:
750
+ Optional dictionary, or list of dictionaries, containing
751
+ bound parameter values. If a single dictionary, single-row
752
+ execution occurs; if a list of dictionaries, an
753
+ "executemany" will be invoked. The keys in each dictionary
754
+ must correspond to parameter names present in the statement.
755
+
756
+ :param execution_options: optional dictionary of execution options,
757
+ which will be associated with the statement execution. This
758
+ dictionary can provide a subset of the options that are accepted
759
+ by :meth:`_engine.Connection.execution_options`, and may also
760
+ provide additional options understood only in an ORM context.
761
+
762
+ .. seealso::
763
+
764
+ :ref:`orm_queryguide_execution_options` - ORM-specific execution
765
+ options
766
+
767
+ :param bind_arguments: dictionary of additional arguments to determine
768
+ the bind. May include "mapper", "bind", or other custom arguments.
769
+ Contents of this dictionary are passed to the
770
+ :meth:`.Session.get_bind` method.
771
+
772
+ :return: a :class:`_engine.Result` object.
773
+
774
+
775
+
776
+ """ # noqa: E501
777
+
778
+ return self._proxied.execute(
779
+ statement,
780
+ params=params,
781
+ execution_options=execution_options,
782
+ bind_arguments=bind_arguments,
783
+ _parent_execute_state=_parent_execute_state,
784
+ _add_event=_add_event,
785
+ )
786
+
787
+ def expire(
788
+ self, instance: object, attribute_names: Optional[Iterable[str]] = None
789
+ ) -> None:
790
+ r"""Expire the attributes on an instance.
791
+
792
+ .. container:: class_bases
793
+
794
+ Proxied for the :class:`_orm.Session` class on
795
+ behalf of the :class:`_orm.scoping.scoped_session` class.
796
+
797
+ Marks the attributes of an instance as out of date. When an expired
798
+ attribute is next accessed, a query will be issued to the
799
+ :class:`.Session` object's current transactional context in order to
800
+ load all expired attributes for the given instance. Note that
801
+ a highly isolated transaction will return the same values as were
802
+ previously read in that same transaction, regardless of changes
803
+ in database state outside of that transaction.
804
+
805
+ To expire all objects in the :class:`.Session` simultaneously,
806
+ use :meth:`Session.expire_all`.
807
+
808
+ The :class:`.Session` object's default behavior is to
809
+ expire all state whenever the :meth:`Session.rollback`
810
+ or :meth:`Session.commit` methods are called, so that new
811
+ state can be loaded for the new transaction. For this reason,
812
+ calling :meth:`Session.expire` only makes sense for the specific
813
+ case that a non-ORM SQL statement was emitted in the current
814
+ transaction.
815
+
816
+ :param instance: The instance to be refreshed.
817
+ :param attribute_names: optional list of string attribute names
818
+ indicating a subset of attributes to be expired.
819
+
820
+ .. seealso::
821
+
822
+ :ref:`session_expire` - introductory material
823
+
824
+ :meth:`.Session.expire`
825
+
826
+ :meth:`.Session.refresh`
827
+
828
+ :meth:`_orm.Query.populate_existing`
829
+
830
+
831
+ """ # noqa: E501
832
+
833
+ return self._proxied.expire(instance, attribute_names=attribute_names)
834
+
835
+ def expire_all(self) -> None:
836
+ r"""Expires all persistent instances within this Session.
837
+
838
+ .. container:: class_bases
839
+
840
+ Proxied for the :class:`_orm.Session` class on
841
+ behalf of the :class:`_orm.scoping.scoped_session` class.
842
+
843
+ When any attributes on a persistent instance is next accessed,
844
+ a query will be issued using the
845
+ :class:`.Session` object's current transactional context in order to
846
+ load all expired attributes for the given instance. Note that
847
+ a highly isolated transaction will return the same values as were
848
+ previously read in that same transaction, regardless of changes
849
+ in database state outside of that transaction.
850
+
851
+ To expire individual objects and individual attributes
852
+ on those objects, use :meth:`Session.expire`.
853
+
854
+ The :class:`.Session` object's default behavior is to
855
+ expire all state whenever the :meth:`Session.rollback`
856
+ or :meth:`Session.commit` methods are called, so that new
857
+ state can be loaded for the new transaction. For this reason,
858
+ calling :meth:`Session.expire_all` is not usually needed,
859
+ assuming the transaction is isolated.
860
+
861
+ .. seealso::
862
+
863
+ :ref:`session_expire` - introductory material
864
+
865
+ :meth:`.Session.expire`
866
+
867
+ :meth:`.Session.refresh`
868
+
869
+ :meth:`_orm.Query.populate_existing`
870
+
871
+
872
+ """ # noqa: E501
873
+
874
+ return self._proxied.expire_all()
875
+
876
+ def expunge(self, instance: object) -> None:
877
+ r"""Remove the `instance` from this ``Session``.
878
+
879
+ .. container:: class_bases
880
+
881
+ Proxied for the :class:`_orm.Session` class on
882
+ behalf of the :class:`_orm.scoping.scoped_session` class.
883
+
884
+ This will free all internal references to the instance. Cascading
885
+ will be applied according to the *expunge* cascade rule.
886
+
887
+
888
+ """ # noqa: E501
889
+
890
+ return self._proxied.expunge(instance)
891
+
892
+ def expunge_all(self) -> None:
893
+ r"""Remove all object instances from this ``Session``.
894
+
895
+ .. container:: class_bases
896
+
897
+ Proxied for the :class:`_orm.Session` class on
898
+ behalf of the :class:`_orm.scoping.scoped_session` class.
899
+
900
+ This is equivalent to calling ``expunge(obj)`` on all objects in this
901
+ ``Session``.
902
+
903
+
904
+ """ # noqa: E501
905
+
906
+ return self._proxied.expunge_all()
907
+
908
+ def flush(self, objects: Optional[Sequence[Any]] = None) -> None:
909
+ r"""Flush all the object changes to the database.
910
+
911
+ .. container:: class_bases
912
+
913
+ Proxied for the :class:`_orm.Session` class on
914
+ behalf of the :class:`_orm.scoping.scoped_session` class.
915
+
916
+ Writes out all pending object creations, deletions and modifications
917
+ to the database as INSERTs, DELETEs, UPDATEs, etc. Operations are
918
+ automatically ordered by the Session's unit of work dependency
919
+ solver.
920
+
921
+ Database operations will be issued in the current transactional
922
+ context and do not affect the state of the transaction, unless an
923
+ error occurs, in which case the entire transaction is rolled back.
924
+ You may flush() as often as you like within a transaction to move
925
+ changes from Python to the database's transaction buffer.
926
+
927
+ :param objects: Optional; restricts the flush operation to operate
928
+ only on elements that are in the given collection.
929
+
930
+ This feature is for an extremely narrow set of use cases where
931
+ particular objects may need to be operated upon before the
932
+ full flush() occurs. It is not intended for general use.
933
+
934
+
935
+ """ # noqa: E501
936
+
937
+ return self._proxied.flush(objects=objects)
938
+
939
+ def get(
940
+ self,
941
+ entity: _EntityBindKey[_O],
942
+ ident: _PKIdentityArgument,
943
+ *,
944
+ options: Optional[Sequence[ORMOption]] = None,
945
+ populate_existing: bool = False,
946
+ with_for_update: ForUpdateParameter = None,
947
+ identity_token: Optional[Any] = None,
948
+ execution_options: OrmExecuteOptionsParameter = util.EMPTY_DICT,
949
+ bind_arguments: Optional[_BindArguments] = None,
950
+ ) -> Optional[_O]:
951
+ r"""Return an instance based on the given primary key identifier,
952
+ or ``None`` if not found.
953
+
954
+ .. container:: class_bases
955
+
956
+ Proxied for the :class:`_orm.Session` class on
957
+ behalf of the :class:`_orm.scoping.scoped_session` class.
958
+
959
+ E.g.::
960
+
961
+ my_user = session.get(User, 5)
962
+
963
+ some_object = session.get(VersionedFoo, (5, 10))
964
+
965
+ some_object = session.get(
966
+ VersionedFoo,
967
+ {"id": 5, "version_id": 10}
968
+ )
969
+
970
+ .. versionadded:: 1.4 Added :meth:`_orm.Session.get`, which is moved
971
+ from the now legacy :meth:`_orm.Query.get` method.
972
+
973
+ :meth:`_orm.Session.get` is special in that it provides direct
974
+ access to the identity map of the :class:`.Session`.
975
+ If the given primary key identifier is present
976
+ in the local identity map, the object is returned
977
+ directly from this collection and no SQL is emitted,
978
+ unless the object has been marked fully expired.
979
+ If not present,
980
+ a SELECT is performed in order to locate the object.
981
+
982
+ :meth:`_orm.Session.get` also will perform a check if
983
+ the object is present in the identity map and
984
+ marked as expired - a SELECT
985
+ is emitted to refresh the object as well as to
986
+ ensure that the row is still present.
987
+ If not, :class:`~sqlalchemy.orm.exc.ObjectDeletedError` is raised.
988
+
989
+ :param entity: a mapped class or :class:`.Mapper` indicating the
990
+ type of entity to be loaded.
991
+
992
+ :param ident: A scalar, tuple, or dictionary representing the
993
+ primary key. For a composite (e.g. multiple column) primary key,
994
+ a tuple or dictionary should be passed.
995
+
996
+ For a single-column primary key, the scalar calling form is typically
997
+ the most expedient. If the primary key of a row is the value "5",
998
+ the call looks like::
999
+
1000
+ my_object = session.get(SomeClass, 5)
1001
+
1002
+ The tuple form contains primary key values typically in
1003
+ the order in which they correspond to the mapped
1004
+ :class:`_schema.Table`
1005
+ object's primary key columns, or if the
1006
+ :paramref:`_orm.Mapper.primary_key` configuration parameter were
1007
+ used, in
1008
+ the order used for that parameter. For example, if the primary key
1009
+ of a row is represented by the integer
1010
+ digits "5, 10" the call would look like::
1011
+
1012
+ my_object = session.get(SomeClass, (5, 10))
1013
+
1014
+ The dictionary form should include as keys the mapped attribute names
1015
+ corresponding to each element of the primary key. If the mapped class
1016
+ has the attributes ``id``, ``version_id`` as the attributes which
1017
+ store the object's primary key value, the call would look like::
1018
+
1019
+ my_object = session.get(SomeClass, {"id": 5, "version_id": 10})
1020
+
1021
+ :param options: optional sequence of loader options which will be
1022
+ applied to the query, if one is emitted.
1023
+
1024
+ :param populate_existing: causes the method to unconditionally emit
1025
+ a SQL query and refresh the object with the newly loaded data,
1026
+ regardless of whether or not the object is already present.
1027
+
1028
+ :param with_for_update: optional boolean ``True`` indicating FOR UPDATE
1029
+ should be used, or may be a dictionary containing flags to
1030
+ indicate a more specific set of FOR UPDATE flags for the SELECT;
1031
+ flags should match the parameters of
1032
+ :meth:`_query.Query.with_for_update`.
1033
+ Supersedes the :paramref:`.Session.refresh.lockmode` parameter.
1034
+
1035
+ :param execution_options: optional dictionary of execution options,
1036
+ which will be associated with the query execution if one is emitted.
1037
+ This dictionary can provide a subset of the options that are
1038
+ accepted by :meth:`_engine.Connection.execution_options`, and may
1039
+ also provide additional options understood only in an ORM context.
1040
+
1041
+ .. versionadded:: 1.4.29
1042
+
1043
+ .. seealso::
1044
+
1045
+ :ref:`orm_queryguide_execution_options` - ORM-specific execution
1046
+ options
1047
+
1048
+ :param bind_arguments: dictionary of additional arguments to determine
1049
+ the bind. May include "mapper", "bind", or other custom arguments.
1050
+ Contents of this dictionary are passed to the
1051
+ :meth:`.Session.get_bind` method.
1052
+
1053
+ .. versionadded: 2.0.0rc1
1054
+
1055
+ :return: The object instance, or ``None``.
1056
+
1057
+
1058
+ """ # noqa: E501
1059
+
1060
+ return self._proxied.get(
1061
+ entity,
1062
+ ident,
1063
+ options=options,
1064
+ populate_existing=populate_existing,
1065
+ with_for_update=with_for_update,
1066
+ identity_token=identity_token,
1067
+ execution_options=execution_options,
1068
+ bind_arguments=bind_arguments,
1069
+ )
1070
+
1071
+ def get_one(
1072
+ self,
1073
+ entity: _EntityBindKey[_O],
1074
+ ident: _PKIdentityArgument,
1075
+ *,
1076
+ options: Optional[Sequence[ORMOption]] = None,
1077
+ populate_existing: bool = False,
1078
+ with_for_update: ForUpdateParameter = None,
1079
+ identity_token: Optional[Any] = None,
1080
+ execution_options: OrmExecuteOptionsParameter = util.EMPTY_DICT,
1081
+ bind_arguments: Optional[_BindArguments] = None,
1082
+ ) -> _O:
1083
+ r"""Return exactly one instance based on the given primary key
1084
+ identifier, or raise an exception if not found.
1085
+
1086
+ .. container:: class_bases
1087
+
1088
+ Proxied for the :class:`_orm.Session` class on
1089
+ behalf of the :class:`_orm.scoping.scoped_session` class.
1090
+
1091
+ Raises ``sqlalchemy.orm.exc.NoResultFound`` if the query
1092
+ selects no rows.
1093
+
1094
+ For a detailed documentation of the arguments see the
1095
+ method :meth:`.Session.get`.
1096
+
1097
+ .. versionadded:: 2.0.22
1098
+
1099
+ :return: The object instance.
1100
+
1101
+ .. seealso::
1102
+
1103
+ :meth:`.Session.get` - equivalent method that instead
1104
+ returns ``None`` if no row was found with the provided primary
1105
+ key
1106
+
1107
+
1108
+ """ # noqa: E501
1109
+
1110
+ return self._proxied.get_one(
1111
+ entity,
1112
+ ident,
1113
+ options=options,
1114
+ populate_existing=populate_existing,
1115
+ with_for_update=with_for_update,
1116
+ identity_token=identity_token,
1117
+ execution_options=execution_options,
1118
+ bind_arguments=bind_arguments,
1119
+ )
1120
+
1121
+ def get_bind(
1122
+ self,
1123
+ mapper: Optional[_EntityBindKey[_O]] = None,
1124
+ *,
1125
+ clause: Optional[ClauseElement] = None,
1126
+ bind: Optional[_SessionBind] = None,
1127
+ _sa_skip_events: Optional[bool] = None,
1128
+ _sa_skip_for_implicit_returning: bool = False,
1129
+ **kw: Any,
1130
+ ) -> Union[Engine, Connection]:
1131
+ r"""Return a "bind" to which this :class:`.Session` is bound.
1132
+
1133
+ .. container:: class_bases
1134
+
1135
+ Proxied for the :class:`_orm.Session` class on
1136
+ behalf of the :class:`_orm.scoping.scoped_session` class.
1137
+
1138
+ The "bind" is usually an instance of :class:`_engine.Engine`,
1139
+ except in the case where the :class:`.Session` has been
1140
+ explicitly bound directly to a :class:`_engine.Connection`.
1141
+
1142
+ For a multiply-bound or unbound :class:`.Session`, the
1143
+ ``mapper`` or ``clause`` arguments are used to determine the
1144
+ appropriate bind to return.
1145
+
1146
+ Note that the "mapper" argument is usually present
1147
+ when :meth:`.Session.get_bind` is called via an ORM
1148
+ operation such as a :meth:`.Session.query`, each
1149
+ individual INSERT/UPDATE/DELETE operation within a
1150
+ :meth:`.Session.flush`, call, etc.
1151
+
1152
+ The order of resolution is:
1153
+
1154
+ 1. if mapper given and :paramref:`.Session.binds` is present,
1155
+ locate a bind based first on the mapper in use, then
1156
+ on the mapped class in use, then on any base classes that are
1157
+ present in the ``__mro__`` of the mapped class, from more specific
1158
+ superclasses to more general.
1159
+ 2. if clause given and ``Session.binds`` is present,
1160
+ locate a bind based on :class:`_schema.Table` objects
1161
+ found in the given clause present in ``Session.binds``.
1162
+ 3. if ``Session.binds`` is present, return that.
1163
+ 4. if clause given, attempt to return a bind
1164
+ linked to the :class:`_schema.MetaData` ultimately
1165
+ associated with the clause.
1166
+ 5. if mapper given, attempt to return a bind
1167
+ linked to the :class:`_schema.MetaData` ultimately
1168
+ associated with the :class:`_schema.Table` or other
1169
+ selectable to which the mapper is mapped.
1170
+ 6. No bind can be found, :exc:`~sqlalchemy.exc.UnboundExecutionError`
1171
+ is raised.
1172
+
1173
+ Note that the :meth:`.Session.get_bind` method can be overridden on
1174
+ a user-defined subclass of :class:`.Session` to provide any kind
1175
+ of bind resolution scheme. See the example at
1176
+ :ref:`session_custom_partitioning`.
1177
+
1178
+ :param mapper:
1179
+ Optional mapped class or corresponding :class:`_orm.Mapper` instance.
1180
+ The bind can be derived from a :class:`_orm.Mapper` first by
1181
+ consulting the "binds" map associated with this :class:`.Session`,
1182
+ and secondly by consulting the :class:`_schema.MetaData` associated
1183
+ with the :class:`_schema.Table` to which the :class:`_orm.Mapper` is
1184
+ mapped for a bind.
1185
+
1186
+ :param clause:
1187
+ A :class:`_expression.ClauseElement` (i.e.
1188
+ :func:`_expression.select`,
1189
+ :func:`_expression.text`,
1190
+ etc.). If the ``mapper`` argument is not present or could not
1191
+ produce a bind, the given expression construct will be searched
1192
+ for a bound element, typically a :class:`_schema.Table`
1193
+ associated with
1194
+ bound :class:`_schema.MetaData`.
1195
+
1196
+ .. seealso::
1197
+
1198
+ :ref:`session_partitioning`
1199
+
1200
+ :paramref:`.Session.binds`
1201
+
1202
+ :meth:`.Session.bind_mapper`
1203
+
1204
+ :meth:`.Session.bind_table`
1205
+
1206
+
1207
+ """ # noqa: E501
1208
+
1209
+ return self._proxied.get_bind(
1210
+ mapper=mapper,
1211
+ clause=clause,
1212
+ bind=bind,
1213
+ _sa_skip_events=_sa_skip_events,
1214
+ _sa_skip_for_implicit_returning=_sa_skip_for_implicit_returning,
1215
+ **kw,
1216
+ )
1217
+
1218
+ def is_modified(
1219
+ self, instance: object, include_collections: bool = True
1220
+ ) -> bool:
1221
+ r"""Return ``True`` if the given instance has locally
1222
+ modified attributes.
1223
+
1224
+ .. container:: class_bases
1225
+
1226
+ Proxied for the :class:`_orm.Session` class on
1227
+ behalf of the :class:`_orm.scoping.scoped_session` class.
1228
+
1229
+ This method retrieves the history for each instrumented
1230
+ attribute on the instance and performs a comparison of the current
1231
+ value to its previously flushed or committed value, if any.
1232
+
1233
+ It is in effect a more expensive and accurate
1234
+ version of checking for the given instance in the
1235
+ :attr:`.Session.dirty` collection; a full test for
1236
+ each attribute's net "dirty" status is performed.
1237
+
1238
+ E.g.::
1239
+
1240
+ return session.is_modified(someobject)
1241
+
1242
+ A few caveats to this method apply:
1243
+
1244
+ * Instances present in the :attr:`.Session.dirty` collection may
1245
+ report ``False`` when tested with this method. This is because
1246
+ the object may have received change events via attribute mutation,
1247
+ thus placing it in :attr:`.Session.dirty`, but ultimately the state
1248
+ is the same as that loaded from the database, resulting in no net
1249
+ change here.
1250
+ * Scalar attributes may not have recorded the previously set
1251
+ value when a new value was applied, if the attribute was not loaded,
1252
+ or was expired, at the time the new value was received - in these
1253
+ cases, the attribute is assumed to have a change, even if there is
1254
+ ultimately no net change against its database value. SQLAlchemy in
1255
+ most cases does not need the "old" value when a set event occurs, so
1256
+ it skips the expense of a SQL call if the old value isn't present,
1257
+ based on the assumption that an UPDATE of the scalar value is
1258
+ usually needed, and in those few cases where it isn't, is less
1259
+ expensive on average than issuing a defensive SELECT.
1260
+
1261
+ The "old" value is fetched unconditionally upon set only if the
1262
+ attribute container has the ``active_history`` flag set to ``True``.
1263
+ This flag is set typically for primary key attributes and scalar
1264
+ object references that are not a simple many-to-one. To set this
1265
+ flag for any arbitrary mapped column, use the ``active_history``
1266
+ argument with :func:`.column_property`.
1267
+
1268
+ :param instance: mapped instance to be tested for pending changes.
1269
+ :param include_collections: Indicates if multivalued collections
1270
+ should be included in the operation. Setting this to ``False`` is a
1271
+ way to detect only local-column based properties (i.e. scalar columns
1272
+ or many-to-one foreign keys) that would result in an UPDATE for this
1273
+ instance upon flush.
1274
+
1275
+
1276
+ """ # noqa: E501
1277
+
1278
+ return self._proxied.is_modified(
1279
+ instance, include_collections=include_collections
1280
+ )
1281
+
1282
+ def bulk_save_objects(
1283
+ self,
1284
+ objects: Iterable[object],
1285
+ return_defaults: bool = False,
1286
+ update_changed_only: bool = True,
1287
+ preserve_order: bool = True,
1288
+ ) -> None:
1289
+ r"""Perform a bulk save of the given list of objects.
1290
+
1291
+ .. container:: class_bases
1292
+
1293
+ Proxied for the :class:`_orm.Session` class on
1294
+ behalf of the :class:`_orm.scoping.scoped_session` class.
1295
+
1296
+ .. legacy::
1297
+
1298
+ This method is a legacy feature as of the 2.0 series of
1299
+ SQLAlchemy. For modern bulk INSERT and UPDATE, see
1300
+ the sections :ref:`orm_queryguide_bulk_insert` and
1301
+ :ref:`orm_queryguide_bulk_update`.
1302
+
1303
+ For general INSERT and UPDATE of existing ORM mapped objects,
1304
+ prefer standard :term:`unit of work` data management patterns,
1305
+ introduced in the :ref:`unified_tutorial` at
1306
+ :ref:`tutorial_orm_data_manipulation`. SQLAlchemy 2.0
1307
+ now uses :ref:`engine_insertmanyvalues` with modern dialects
1308
+ which solves previous issues of bulk INSERT slowness.
1309
+
1310
+ :param objects: a sequence of mapped object instances. The mapped
1311
+ objects are persisted as is, and are **not** associated with the
1312
+ :class:`.Session` afterwards.
1313
+
1314
+ For each object, whether the object is sent as an INSERT or an
1315
+ UPDATE is dependent on the same rules used by the :class:`.Session`
1316
+ in traditional operation; if the object has the
1317
+ :attr:`.InstanceState.key`
1318
+ attribute set, then the object is assumed to be "detached" and
1319
+ will result in an UPDATE. Otherwise, an INSERT is used.
1320
+
1321
+ In the case of an UPDATE, statements are grouped based on which
1322
+ attributes have changed, and are thus to be the subject of each
1323
+ SET clause. If ``update_changed_only`` is False, then all
1324
+ attributes present within each object are applied to the UPDATE
1325
+ statement, which may help in allowing the statements to be grouped
1326
+ together into a larger executemany(), and will also reduce the
1327
+ overhead of checking history on attributes.
1328
+
1329
+ :param return_defaults: when True, rows that are missing values which
1330
+ generate defaults, namely integer primary key defaults and sequences,
1331
+ will be inserted **one at a time**, so that the primary key value
1332
+ is available. In particular this will allow joined-inheritance
1333
+ and other multi-table mappings to insert correctly without the need
1334
+ to provide primary key values ahead of time; however,
1335
+ :paramref:`.Session.bulk_save_objects.return_defaults` **greatly
1336
+ reduces the performance gains** of the method overall. It is strongly
1337
+ advised to please use the standard :meth:`_orm.Session.add_all`
1338
+ approach.
1339
+
1340
+ :param update_changed_only: when True, UPDATE statements are rendered
1341
+ based on those attributes in each state that have logged changes.
1342
+ When False, all attributes present are rendered into the SET clause
1343
+ with the exception of primary key attributes.
1344
+
1345
+ :param preserve_order: when True, the order of inserts and updates
1346
+ matches exactly the order in which the objects are given. When
1347
+ False, common types of objects are grouped into inserts
1348
+ and updates, to allow for more batching opportunities.
1349
+
1350
+ .. seealso::
1351
+
1352
+ :doc:`queryguide/dml`
1353
+
1354
+ :meth:`.Session.bulk_insert_mappings`
1355
+
1356
+ :meth:`.Session.bulk_update_mappings`
1357
+
1358
+
1359
+ """ # noqa: E501
1360
+
1361
+ return self._proxied.bulk_save_objects(
1362
+ objects,
1363
+ return_defaults=return_defaults,
1364
+ update_changed_only=update_changed_only,
1365
+ preserve_order=preserve_order,
1366
+ )
1367
+
1368
+ def bulk_insert_mappings(
1369
+ self,
1370
+ mapper: Mapper[Any],
1371
+ mappings: Iterable[Dict[str, Any]],
1372
+ return_defaults: bool = False,
1373
+ render_nulls: bool = False,
1374
+ ) -> None:
1375
+ r"""Perform a bulk insert of the given list of mapping dictionaries.
1376
+
1377
+ .. container:: class_bases
1378
+
1379
+ Proxied for the :class:`_orm.Session` class on
1380
+ behalf of the :class:`_orm.scoping.scoped_session` class.
1381
+
1382
+ .. legacy::
1383
+
1384
+ This method is a legacy feature as of the 2.0 series of
1385
+ SQLAlchemy. For modern bulk INSERT and UPDATE, see
1386
+ the sections :ref:`orm_queryguide_bulk_insert` and
1387
+ :ref:`orm_queryguide_bulk_update`. The 2.0 API shares
1388
+ implementation details with this method and adds new features
1389
+ as well.
1390
+
1391
+ :param mapper: a mapped class, or the actual :class:`_orm.Mapper`
1392
+ object,
1393
+ representing the single kind of object represented within the mapping
1394
+ list.
1395
+
1396
+ :param mappings: a sequence of dictionaries, each one containing the
1397
+ state of the mapped row to be inserted, in terms of the attribute
1398
+ names on the mapped class. If the mapping refers to multiple tables,
1399
+ such as a joined-inheritance mapping, each dictionary must contain all
1400
+ keys to be populated into all tables.
1401
+
1402
+ :param return_defaults: when True, the INSERT process will be altered
1403
+ to ensure that newly generated primary key values will be fetched.
1404
+ The rationale for this parameter is typically to enable
1405
+ :ref:`Joined Table Inheritance <joined_inheritance>` mappings to
1406
+ be bulk inserted.
1407
+
1408
+ .. note:: for backends that don't support RETURNING, the
1409
+ :paramref:`_orm.Session.bulk_insert_mappings.return_defaults`
1410
+ parameter can significantly decrease performance as INSERT
1411
+ statements can no longer be batched. See
1412
+ :ref:`engine_insertmanyvalues`
1413
+ for background on which backends are affected.
1414
+
1415
+ :param render_nulls: When True, a value of ``None`` will result
1416
+ in a NULL value being included in the INSERT statement, rather
1417
+ than the column being omitted from the INSERT. This allows all
1418
+ the rows being INSERTed to have the identical set of columns which
1419
+ allows the full set of rows to be batched to the DBAPI. Normally,
1420
+ each column-set that contains a different combination of NULL values
1421
+ than the previous row must omit a different series of columns from
1422
+ the rendered INSERT statement, which means it must be emitted as a
1423
+ separate statement. By passing this flag, the full set of rows
1424
+ are guaranteed to be batchable into one batch; the cost however is
1425
+ that server-side defaults which are invoked by an omitted column will
1426
+ be skipped, so care must be taken to ensure that these are not
1427
+ necessary.
1428
+
1429
+ .. warning::
1430
+
1431
+ When this flag is set, **server side default SQL values will
1432
+ not be invoked** for those columns that are inserted as NULL;
1433
+ the NULL value will be sent explicitly. Care must be taken
1434
+ to ensure that no server-side default functions need to be
1435
+ invoked for the operation as a whole.
1436
+
1437
+ .. seealso::
1438
+
1439
+ :doc:`queryguide/dml`
1440
+
1441
+ :meth:`.Session.bulk_save_objects`
1442
+
1443
+ :meth:`.Session.bulk_update_mappings`
1444
+
1445
+
1446
+ """ # noqa: E501
1447
+
1448
+ return self._proxied.bulk_insert_mappings(
1449
+ mapper,
1450
+ mappings,
1451
+ return_defaults=return_defaults,
1452
+ render_nulls=render_nulls,
1453
+ )
1454
+
1455
+ def bulk_update_mappings(
1456
+ self, mapper: Mapper[Any], mappings: Iterable[Dict[str, Any]]
1457
+ ) -> None:
1458
+ r"""Perform a bulk update of the given list of mapping dictionaries.
1459
+
1460
+ .. container:: class_bases
1461
+
1462
+ Proxied for the :class:`_orm.Session` class on
1463
+ behalf of the :class:`_orm.scoping.scoped_session` class.
1464
+
1465
+ .. legacy::
1466
+
1467
+ This method is a legacy feature as of the 2.0 series of
1468
+ SQLAlchemy. For modern bulk INSERT and UPDATE, see
1469
+ the sections :ref:`orm_queryguide_bulk_insert` and
1470
+ :ref:`orm_queryguide_bulk_update`. The 2.0 API shares
1471
+ implementation details with this method and adds new features
1472
+ as well.
1473
+
1474
+ :param mapper: a mapped class, or the actual :class:`_orm.Mapper`
1475
+ object,
1476
+ representing the single kind of object represented within the mapping
1477
+ list.
1478
+
1479
+ :param mappings: a sequence of dictionaries, each one containing the
1480
+ state of the mapped row to be updated, in terms of the attribute names
1481
+ on the mapped class. If the mapping refers to multiple tables, such
1482
+ as a joined-inheritance mapping, each dictionary may contain keys
1483
+ corresponding to all tables. All those keys which are present and
1484
+ are not part of the primary key are applied to the SET clause of the
1485
+ UPDATE statement; the primary key values, which are required, are
1486
+ applied to the WHERE clause.
1487
+
1488
+
1489
+ .. seealso::
1490
+
1491
+ :doc:`queryguide/dml`
1492
+
1493
+ :meth:`.Session.bulk_insert_mappings`
1494
+
1495
+ :meth:`.Session.bulk_save_objects`
1496
+
1497
+
1498
+ """ # noqa: E501
1499
+
1500
+ return self._proxied.bulk_update_mappings(mapper, mappings)
1501
+
1502
+ def merge(
1503
+ self,
1504
+ instance: _O,
1505
+ *,
1506
+ load: bool = True,
1507
+ options: Optional[Sequence[ORMOption]] = None,
1508
+ ) -> _O:
1509
+ r"""Copy the state of a given instance into a corresponding instance
1510
+ within this :class:`.Session`.
1511
+
1512
+ .. container:: class_bases
1513
+
1514
+ Proxied for the :class:`_orm.Session` class on
1515
+ behalf of the :class:`_orm.scoping.scoped_session` class.
1516
+
1517
+ :meth:`.Session.merge` examines the primary key attributes of the
1518
+ source instance, and attempts to reconcile it with an instance of the
1519
+ same primary key in the session. If not found locally, it attempts
1520
+ to load the object from the database based on primary key, and if
1521
+ none can be located, creates a new instance. The state of each
1522
+ attribute on the source instance is then copied to the target
1523
+ instance. The resulting target instance is then returned by the
1524
+ method; the original source instance is left unmodified, and
1525
+ un-associated with the :class:`.Session` if not already.
1526
+
1527
+ This operation cascades to associated instances if the association is
1528
+ mapped with ``cascade="merge"``.
1529
+
1530
+ See :ref:`unitofwork_merging` for a detailed discussion of merging.
1531
+
1532
+ :param instance: Instance to be merged.
1533
+ :param load: Boolean, when False, :meth:`.merge` switches into
1534
+ a "high performance" mode which causes it to forego emitting history
1535
+ events as well as all database access. This flag is used for
1536
+ cases such as transferring graphs of objects into a :class:`.Session`
1537
+ from a second level cache, or to transfer just-loaded objects
1538
+ into the :class:`.Session` owned by a worker thread or process
1539
+ without re-querying the database.
1540
+
1541
+ The ``load=False`` use case adds the caveat that the given
1542
+ object has to be in a "clean" state, that is, has no pending changes
1543
+ to be flushed - even if the incoming object is detached from any
1544
+ :class:`.Session`. This is so that when
1545
+ the merge operation populates local attributes and
1546
+ cascades to related objects and
1547
+ collections, the values can be "stamped" onto the
1548
+ target object as is, without generating any history or attribute
1549
+ events, and without the need to reconcile the incoming data with
1550
+ any existing related objects or collections that might not
1551
+ be loaded. The resulting objects from ``load=False`` are always
1552
+ produced as "clean", so it is only appropriate that the given objects
1553
+ should be "clean" as well, else this suggests a mis-use of the
1554
+ method.
1555
+ :param options: optional sequence of loader options which will be
1556
+ applied to the :meth:`_orm.Session.get` method when the merge
1557
+ operation loads the existing version of the object from the database.
1558
+
1559
+ .. versionadded:: 1.4.24
1560
+
1561
+
1562
+ .. seealso::
1563
+
1564
+ :func:`.make_transient_to_detached` - provides for an alternative
1565
+ means of "merging" a single object into the :class:`.Session`
1566
+
1567
+
1568
+ """ # noqa: E501
1569
+
1570
+ return self._proxied.merge(instance, load=load, options=options)
1571
+
1572
+ @overload
1573
+ def query(self, _entity: _EntityType[_O]) -> Query[_O]: ...
1574
+
1575
+ @overload
1576
+ def query(
1577
+ self, _colexpr: TypedColumnsClauseRole[_T]
1578
+ ) -> RowReturningQuery[Tuple[_T]]: ...
1579
+
1580
+ # START OVERLOADED FUNCTIONS self.query RowReturningQuery 2-8
1581
+
1582
+ # code within this block is **programmatically,
1583
+ # statically generated** by tools/generate_tuple_map_overloads.py
1584
+
1585
+ @overload
1586
+ def query(
1587
+ self, __ent0: _TCCA[_T0], __ent1: _TCCA[_T1]
1588
+ ) -> RowReturningQuery[Tuple[_T0, _T1]]: ...
1589
+
1590
+ @overload
1591
+ def query(
1592
+ self, __ent0: _TCCA[_T0], __ent1: _TCCA[_T1], __ent2: _TCCA[_T2]
1593
+ ) -> RowReturningQuery[Tuple[_T0, _T1, _T2]]: ...
1594
+
1595
+ @overload
1596
+ def query(
1597
+ self,
1598
+ __ent0: _TCCA[_T0],
1599
+ __ent1: _TCCA[_T1],
1600
+ __ent2: _TCCA[_T2],
1601
+ __ent3: _TCCA[_T3],
1602
+ ) -> RowReturningQuery[Tuple[_T0, _T1, _T2, _T3]]: ...
1603
+
1604
+ @overload
1605
+ def query(
1606
+ self,
1607
+ __ent0: _TCCA[_T0],
1608
+ __ent1: _TCCA[_T1],
1609
+ __ent2: _TCCA[_T2],
1610
+ __ent3: _TCCA[_T3],
1611
+ __ent4: _TCCA[_T4],
1612
+ ) -> RowReturningQuery[Tuple[_T0, _T1, _T2, _T3, _T4]]: ...
1613
+
1614
+ @overload
1615
+ def query(
1616
+ self,
1617
+ __ent0: _TCCA[_T0],
1618
+ __ent1: _TCCA[_T1],
1619
+ __ent2: _TCCA[_T2],
1620
+ __ent3: _TCCA[_T3],
1621
+ __ent4: _TCCA[_T4],
1622
+ __ent5: _TCCA[_T5],
1623
+ ) -> RowReturningQuery[Tuple[_T0, _T1, _T2, _T3, _T4, _T5]]: ...
1624
+
1625
+ @overload
1626
+ def query(
1627
+ self,
1628
+ __ent0: _TCCA[_T0],
1629
+ __ent1: _TCCA[_T1],
1630
+ __ent2: _TCCA[_T2],
1631
+ __ent3: _TCCA[_T3],
1632
+ __ent4: _TCCA[_T4],
1633
+ __ent5: _TCCA[_T5],
1634
+ __ent6: _TCCA[_T6],
1635
+ ) -> RowReturningQuery[Tuple[_T0, _T1, _T2, _T3, _T4, _T5, _T6]]: ...
1636
+
1637
+ @overload
1638
+ def query(
1639
+ self,
1640
+ __ent0: _TCCA[_T0],
1641
+ __ent1: _TCCA[_T1],
1642
+ __ent2: _TCCA[_T2],
1643
+ __ent3: _TCCA[_T3],
1644
+ __ent4: _TCCA[_T4],
1645
+ __ent5: _TCCA[_T5],
1646
+ __ent6: _TCCA[_T6],
1647
+ __ent7: _TCCA[_T7],
1648
+ ) -> RowReturningQuery[Tuple[_T0, _T1, _T2, _T3, _T4, _T5, _T6, _T7]]: ...
1649
+
1650
+ # END OVERLOADED FUNCTIONS self.query
1651
+
1652
+ @overload
1653
+ def query(
1654
+ self, *entities: _ColumnsClauseArgument[Any], **kwargs: Any
1655
+ ) -> Query[Any]: ...
1656
+
1657
+ def query(
1658
+ self, *entities: _ColumnsClauseArgument[Any], **kwargs: Any
1659
+ ) -> Query[Any]:
1660
+ r"""Return a new :class:`_query.Query` object corresponding to this
1661
+ :class:`_orm.Session`.
1662
+
1663
+ .. container:: class_bases
1664
+
1665
+ Proxied for the :class:`_orm.Session` class on
1666
+ behalf of the :class:`_orm.scoping.scoped_session` class.
1667
+
1668
+ Note that the :class:`_query.Query` object is legacy as of
1669
+ SQLAlchemy 2.0; the :func:`_sql.select` construct is now used
1670
+ to construct ORM queries.
1671
+
1672
+ .. seealso::
1673
+
1674
+ :ref:`unified_tutorial`
1675
+
1676
+ :ref:`queryguide_toplevel`
1677
+
1678
+ :ref:`query_api_toplevel` - legacy API doc
1679
+
1680
+
1681
+ """ # noqa: E501
1682
+
1683
+ return self._proxied.query(*entities, **kwargs)
1684
+
1685
+ def refresh(
1686
+ self,
1687
+ instance: object,
1688
+ attribute_names: Optional[Iterable[str]] = None,
1689
+ with_for_update: ForUpdateParameter = None,
1690
+ ) -> None:
1691
+ r"""Expire and refresh attributes on the given instance.
1692
+
1693
+ .. container:: class_bases
1694
+
1695
+ Proxied for the :class:`_orm.Session` class on
1696
+ behalf of the :class:`_orm.scoping.scoped_session` class.
1697
+
1698
+ The selected attributes will first be expired as they would when using
1699
+ :meth:`_orm.Session.expire`; then a SELECT statement will be issued to
1700
+ the database to refresh column-oriented attributes with the current
1701
+ value available in the current transaction.
1702
+
1703
+ :func:`_orm.relationship` oriented attributes will also be immediately
1704
+ loaded if they were already eagerly loaded on the object, using the
1705
+ same eager loading strategy that they were loaded with originally.
1706
+
1707
+ .. versionadded:: 1.4 - the :meth:`_orm.Session.refresh` method
1708
+ can also refresh eagerly loaded attributes.
1709
+
1710
+ :func:`_orm.relationship` oriented attributes that would normally
1711
+ load using the ``select`` (or "lazy") loader strategy will also
1712
+ load **if they are named explicitly in the attribute_names
1713
+ collection**, emitting a SELECT statement for the attribute using the
1714
+ ``immediate`` loader strategy. If lazy-loaded relationships are not
1715
+ named in :paramref:`_orm.Session.refresh.attribute_names`, then
1716
+ they remain as "lazy loaded" attributes and are not implicitly
1717
+ refreshed.
1718
+
1719
+ .. versionchanged:: 2.0.4 The :meth:`_orm.Session.refresh` method
1720
+ will now refresh lazy-loaded :func:`_orm.relationship` oriented
1721
+ attributes for those which are named explicitly in the
1722
+ :paramref:`_orm.Session.refresh.attribute_names` collection.
1723
+
1724
+ .. tip::
1725
+
1726
+ While the :meth:`_orm.Session.refresh` method is capable of
1727
+ refreshing both column and relationship oriented attributes, its
1728
+ primary focus is on refreshing of local column-oriented attributes
1729
+ on a single instance. For more open ended "refresh" functionality,
1730
+ including the ability to refresh the attributes on many objects at
1731
+ once while having explicit control over relationship loader
1732
+ strategies, use the
1733
+ :ref:`populate existing <orm_queryguide_populate_existing>` feature
1734
+ instead.
1735
+
1736
+ Note that a highly isolated transaction will return the same values as
1737
+ were previously read in that same transaction, regardless of changes
1738
+ in database state outside of that transaction. Refreshing
1739
+ attributes usually only makes sense at the start of a transaction
1740
+ where database rows have not yet been accessed.
1741
+
1742
+ :param attribute_names: optional. An iterable collection of
1743
+ string attribute names indicating a subset of attributes to
1744
+ be refreshed.
1745
+
1746
+ :param with_for_update: optional boolean ``True`` indicating FOR UPDATE
1747
+ should be used, or may be a dictionary containing flags to
1748
+ indicate a more specific set of FOR UPDATE flags for the SELECT;
1749
+ flags should match the parameters of
1750
+ :meth:`_query.Query.with_for_update`.
1751
+ Supersedes the :paramref:`.Session.refresh.lockmode` parameter.
1752
+
1753
+ .. seealso::
1754
+
1755
+ :ref:`session_expire` - introductory material
1756
+
1757
+ :meth:`.Session.expire`
1758
+
1759
+ :meth:`.Session.expire_all`
1760
+
1761
+ :ref:`orm_queryguide_populate_existing` - allows any ORM query
1762
+ to refresh objects as they would be loaded normally.
1763
+
1764
+
1765
+ """ # noqa: E501
1766
+
1767
+ return self._proxied.refresh(
1768
+ instance,
1769
+ attribute_names=attribute_names,
1770
+ with_for_update=with_for_update,
1771
+ )
1772
+
1773
+ def rollback(self) -> None:
1774
+ r"""Rollback the current transaction in progress.
1775
+
1776
+ .. container:: class_bases
1777
+
1778
+ Proxied for the :class:`_orm.Session` class on
1779
+ behalf of the :class:`_orm.scoping.scoped_session` class.
1780
+
1781
+ If no transaction is in progress, this method is a pass-through.
1782
+
1783
+ The method always rolls back
1784
+ the topmost database transaction, discarding any nested
1785
+ transactions that may be in progress.
1786
+
1787
+ .. seealso::
1788
+
1789
+ :ref:`session_rollback`
1790
+
1791
+ :ref:`unitofwork_transaction`
1792
+
1793
+
1794
+ """ # noqa: E501
1795
+
1796
+ return self._proxied.rollback()
1797
+
1798
+ @overload
1799
+ def scalar(
1800
+ self,
1801
+ statement: TypedReturnsRows[Tuple[_T]],
1802
+ params: Optional[_CoreSingleExecuteParams] = None,
1803
+ *,
1804
+ execution_options: OrmExecuteOptionsParameter = util.EMPTY_DICT,
1805
+ bind_arguments: Optional[_BindArguments] = None,
1806
+ **kw: Any,
1807
+ ) -> Optional[_T]: ...
1808
+
1809
+ @overload
1810
+ def scalar(
1811
+ self,
1812
+ statement: Executable,
1813
+ params: Optional[_CoreSingleExecuteParams] = None,
1814
+ *,
1815
+ execution_options: OrmExecuteOptionsParameter = util.EMPTY_DICT,
1816
+ bind_arguments: Optional[_BindArguments] = None,
1817
+ **kw: Any,
1818
+ ) -> Any: ...
1819
+
1820
+ def scalar(
1821
+ self,
1822
+ statement: Executable,
1823
+ params: Optional[_CoreSingleExecuteParams] = None,
1824
+ *,
1825
+ execution_options: OrmExecuteOptionsParameter = util.EMPTY_DICT,
1826
+ bind_arguments: Optional[_BindArguments] = None,
1827
+ **kw: Any,
1828
+ ) -> Any:
1829
+ r"""Execute a statement and return a scalar result.
1830
+
1831
+ .. container:: class_bases
1832
+
1833
+ Proxied for the :class:`_orm.Session` class on
1834
+ behalf of the :class:`_orm.scoping.scoped_session` class.
1835
+
1836
+ Usage and parameters are the same as that of
1837
+ :meth:`_orm.Session.execute`; the return result is a scalar Python
1838
+ value.
1839
+
1840
+
1841
+ """ # noqa: E501
1842
+
1843
+ return self._proxied.scalar(
1844
+ statement,
1845
+ params=params,
1846
+ execution_options=execution_options,
1847
+ bind_arguments=bind_arguments,
1848
+ **kw,
1849
+ )
1850
+
1851
+ @overload
1852
+ def scalars(
1853
+ self,
1854
+ statement: TypedReturnsRows[Tuple[_T]],
1855
+ params: Optional[_CoreAnyExecuteParams] = None,
1856
+ *,
1857
+ execution_options: OrmExecuteOptionsParameter = util.EMPTY_DICT,
1858
+ bind_arguments: Optional[_BindArguments] = None,
1859
+ **kw: Any,
1860
+ ) -> ScalarResult[_T]: ...
1861
+
1862
+ @overload
1863
+ def scalars(
1864
+ self,
1865
+ statement: Executable,
1866
+ params: Optional[_CoreAnyExecuteParams] = None,
1867
+ *,
1868
+ execution_options: OrmExecuteOptionsParameter = util.EMPTY_DICT,
1869
+ bind_arguments: Optional[_BindArguments] = None,
1870
+ **kw: Any,
1871
+ ) -> ScalarResult[Any]: ...
1872
+
1873
+ def scalars(
1874
+ self,
1875
+ statement: Executable,
1876
+ params: Optional[_CoreAnyExecuteParams] = None,
1877
+ *,
1878
+ execution_options: OrmExecuteOptionsParameter = util.EMPTY_DICT,
1879
+ bind_arguments: Optional[_BindArguments] = None,
1880
+ **kw: Any,
1881
+ ) -> ScalarResult[Any]:
1882
+ r"""Execute a statement and return the results as scalars.
1883
+
1884
+ .. container:: class_bases
1885
+
1886
+ Proxied for the :class:`_orm.Session` class on
1887
+ behalf of the :class:`_orm.scoping.scoped_session` class.
1888
+
1889
+ Usage and parameters are the same as that of
1890
+ :meth:`_orm.Session.execute`; the return result is a
1891
+ :class:`_result.ScalarResult` filtering object which
1892
+ will return single elements rather than :class:`_row.Row` objects.
1893
+
1894
+ :return: a :class:`_result.ScalarResult` object
1895
+
1896
+ .. versionadded:: 1.4.24 Added :meth:`_orm.Session.scalars`
1897
+
1898
+ .. versionadded:: 1.4.26 Added :meth:`_orm.scoped_session.scalars`
1899
+
1900
+ .. seealso::
1901
+
1902
+ :ref:`orm_queryguide_select_orm_entities` - contrasts the behavior
1903
+ of :meth:`_orm.Session.execute` to :meth:`_orm.Session.scalars`
1904
+
1905
+
1906
+ """ # noqa: E501
1907
+
1908
+ return self._proxied.scalars(
1909
+ statement,
1910
+ params=params,
1911
+ execution_options=execution_options,
1912
+ bind_arguments=bind_arguments,
1913
+ **kw,
1914
+ )
1915
+
1916
+ @property
1917
+ def bind(self) -> Optional[Union[Engine, Connection]]:
1918
+ r"""Proxy for the :attr:`_orm.Session.bind` attribute
1919
+ on behalf of the :class:`_orm.scoping.scoped_session` class.
1920
+
1921
+ """ # noqa: E501
1922
+
1923
+ return self._proxied.bind
1924
+
1925
+ @bind.setter
1926
+ def bind(self, attr: Optional[Union[Engine, Connection]]) -> None:
1927
+ self._proxied.bind = attr
1928
+
1929
+ @property
1930
+ def dirty(self) -> Any:
1931
+ r"""The set of all persistent instances considered dirty.
1932
+
1933
+ .. container:: class_bases
1934
+
1935
+ Proxied for the :class:`_orm.Session` class
1936
+ on behalf of the :class:`_orm.scoping.scoped_session` class.
1937
+
1938
+ E.g.::
1939
+
1940
+ some_mapped_object in session.dirty
1941
+
1942
+ Instances are considered dirty when they were modified but not
1943
+ deleted.
1944
+
1945
+ Note that this 'dirty' calculation is 'optimistic'; most
1946
+ attribute-setting or collection modification operations will
1947
+ mark an instance as 'dirty' and place it in this set, even if
1948
+ there is no net change to the attribute's value. At flush
1949
+ time, the value of each attribute is compared to its
1950
+ previously saved value, and if there's no net change, no SQL
1951
+ operation will occur (this is a more expensive operation so
1952
+ it's only done at flush time).
1953
+
1954
+ To check if an instance has actionable net changes to its
1955
+ attributes, use the :meth:`.Session.is_modified` method.
1956
+
1957
+
1958
+ """ # noqa: E501
1959
+
1960
+ return self._proxied.dirty
1961
+
1962
+ @property
1963
+ def deleted(self) -> Any:
1964
+ r"""The set of all instances marked as 'deleted' within this ``Session``
1965
+
1966
+ .. container:: class_bases
1967
+
1968
+ Proxied for the :class:`_orm.Session` class
1969
+ on behalf of the :class:`_orm.scoping.scoped_session` class.
1970
+
1971
+ """ # noqa: E501
1972
+
1973
+ return self._proxied.deleted
1974
+
1975
+ @property
1976
+ def new(self) -> Any:
1977
+ r"""The set of all instances marked as 'new' within this ``Session``.
1978
+
1979
+ .. container:: class_bases
1980
+
1981
+ Proxied for the :class:`_orm.Session` class
1982
+ on behalf of the :class:`_orm.scoping.scoped_session` class.
1983
+
1984
+ """ # noqa: E501
1985
+
1986
+ return self._proxied.new
1987
+
1988
+ @property
1989
+ def identity_map(self) -> IdentityMap:
1990
+ r"""Proxy for the :attr:`_orm.Session.identity_map` attribute
1991
+ on behalf of the :class:`_orm.scoping.scoped_session` class.
1992
+
1993
+ """ # noqa: E501
1994
+
1995
+ return self._proxied.identity_map
1996
+
1997
+ @identity_map.setter
1998
+ def identity_map(self, attr: IdentityMap) -> None:
1999
+ self._proxied.identity_map = attr
2000
+
2001
+ @property
2002
+ def is_active(self) -> Any:
2003
+ r"""True if this :class:`.Session` not in "partial rollback" state.
2004
+
2005
+ .. container:: class_bases
2006
+
2007
+ Proxied for the :class:`_orm.Session` class
2008
+ on behalf of the :class:`_orm.scoping.scoped_session` class.
2009
+
2010
+ .. versionchanged:: 1.4 The :class:`_orm.Session` no longer begins
2011
+ a new transaction immediately, so this attribute will be False
2012
+ when the :class:`_orm.Session` is first instantiated.
2013
+
2014
+ "partial rollback" state typically indicates that the flush process
2015
+ of the :class:`_orm.Session` has failed, and that the
2016
+ :meth:`_orm.Session.rollback` method must be emitted in order to
2017
+ fully roll back the transaction.
2018
+
2019
+ If this :class:`_orm.Session` is not in a transaction at all, the
2020
+ :class:`_orm.Session` will autobegin when it is first used, so in this
2021
+ case :attr:`_orm.Session.is_active` will return True.
2022
+
2023
+ Otherwise, if this :class:`_orm.Session` is within a transaction,
2024
+ and that transaction has not been rolled back internally, the
2025
+ :attr:`_orm.Session.is_active` will also return True.
2026
+
2027
+ .. seealso::
2028
+
2029
+ :ref:`faq_session_rollback`
2030
+
2031
+ :meth:`_orm.Session.in_transaction`
2032
+
2033
+
2034
+ """ # noqa: E501
2035
+
2036
+ return self._proxied.is_active
2037
+
2038
+ @property
2039
+ def autoflush(self) -> bool:
2040
+ r"""Proxy for the :attr:`_orm.Session.autoflush` attribute
2041
+ on behalf of the :class:`_orm.scoping.scoped_session` class.
2042
+
2043
+ """ # noqa: E501
2044
+
2045
+ return self._proxied.autoflush
2046
+
2047
+ @autoflush.setter
2048
+ def autoflush(self, attr: bool) -> None:
2049
+ self._proxied.autoflush = attr
2050
+
2051
+ @property
2052
+ def no_autoflush(self) -> Any:
2053
+ r"""Return a context manager that disables autoflush.
2054
+
2055
+ .. container:: class_bases
2056
+
2057
+ Proxied for the :class:`_orm.Session` class
2058
+ on behalf of the :class:`_orm.scoping.scoped_session` class.
2059
+
2060
+ e.g.::
2061
+
2062
+ with session.no_autoflush:
2063
+
2064
+ some_object = SomeClass()
2065
+ session.add(some_object)
2066
+ # won't autoflush
2067
+ some_object.related_thing = session.query(SomeRelated).first()
2068
+
2069
+ Operations that proceed within the ``with:`` block
2070
+ will not be subject to flushes occurring upon query
2071
+ access. This is useful when initializing a series
2072
+ of objects which involve existing database queries,
2073
+ where the uncompleted object should not yet be flushed.
2074
+
2075
+
2076
+ """ # noqa: E501
2077
+
2078
+ return self._proxied.no_autoflush
2079
+
2080
+ @property
2081
+ def info(self) -> Any:
2082
+ r"""A user-modifiable dictionary.
2083
+
2084
+ .. container:: class_bases
2085
+
2086
+ Proxied for the :class:`_orm.Session` class
2087
+ on behalf of the :class:`_orm.scoping.scoped_session` class.
2088
+
2089
+ The initial value of this dictionary can be populated using the
2090
+ ``info`` argument to the :class:`.Session` constructor or
2091
+ :class:`.sessionmaker` constructor or factory methods. The dictionary
2092
+ here is always local to this :class:`.Session` and can be modified
2093
+ independently of all other :class:`.Session` objects.
2094
+
2095
+
2096
+ """ # noqa: E501
2097
+
2098
+ return self._proxied.info
2099
+
2100
+ @classmethod
2101
+ def close_all(cls) -> None:
2102
+ r"""Close *all* sessions in memory.
2103
+
2104
+ .. container:: class_bases
2105
+
2106
+ Proxied for the :class:`_orm.Session` class on
2107
+ behalf of the :class:`_orm.scoping.scoped_session` class.
2108
+
2109
+ .. deprecated:: 1.3 The :meth:`.Session.close_all` method is deprecated and will be removed in a future release. Please refer to :func:`.session.close_all_sessions`.
2110
+
2111
+ """ # noqa: E501
2112
+
2113
+ return Session.close_all()
2114
+
2115
+ @classmethod
2116
+ def object_session(cls, instance: object) -> Optional[Session]:
2117
+ r"""Return the :class:`.Session` to which an object belongs.
2118
+
2119
+ .. container:: class_bases
2120
+
2121
+ Proxied for the :class:`_orm.Session` class on
2122
+ behalf of the :class:`_orm.scoping.scoped_session` class.
2123
+
2124
+ This is an alias of :func:`.object_session`.
2125
+
2126
+
2127
+ """ # noqa: E501
2128
+
2129
+ return Session.object_session(instance)
2130
+
2131
+ @classmethod
2132
+ def identity_key(
2133
+ cls,
2134
+ class_: Optional[Type[Any]] = None,
2135
+ ident: Union[Any, Tuple[Any, ...]] = None,
2136
+ *,
2137
+ instance: Optional[Any] = None,
2138
+ row: Optional[Union[Row[Any], RowMapping]] = None,
2139
+ identity_token: Optional[Any] = None,
2140
+ ) -> _IdentityKeyType[Any]:
2141
+ r"""Return an identity key.
2142
+
2143
+ .. container:: class_bases
2144
+
2145
+ Proxied for the :class:`_orm.Session` class on
2146
+ behalf of the :class:`_orm.scoping.scoped_session` class.
2147
+
2148
+ This is an alias of :func:`.util.identity_key`.
2149
+
2150
+
2151
+ """ # noqa: E501
2152
+
2153
+ return Session.identity_key(
2154
+ class_=class_,
2155
+ ident=ident,
2156
+ instance=instance,
2157
+ row=row,
2158
+ identity_token=identity_token,
2159
+ )
2160
+
2161
+ # END PROXY METHODS scoped_session
2162
+
2163
+
2164
+ ScopedSession = scoped_session
2165
+ """Old name for backwards compatibility."""