SQLAlchemy 2.1.0rc1__cp315-cp315-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 (276) hide show
  1. sqlalchemy/__init__.py +299 -0
  2. sqlalchemy/connectors/__init__.py +18 -0
  3. sqlalchemy/connectors/aioodbc.py +171 -0
  4. sqlalchemy/connectors/asyncio.py +476 -0
  5. sqlalchemy/connectors/pyodbc.py +248 -0
  6. sqlalchemy/dialects/__init__.py +62 -0
  7. sqlalchemy/dialects/_typing.py +29 -0
  8. sqlalchemy/dialects/mssql/__init__.py +88 -0
  9. sqlalchemy/dialects/mssql/aioodbc.py +63 -0
  10. sqlalchemy/dialects/mssql/base.py +4833 -0
  11. sqlalchemy/dialects/mssql/information_schema.py +345 -0
  12. sqlalchemy/dialects/mssql/json.py +140 -0
  13. sqlalchemy/dialects/mssql/mssqlpython.py +242 -0
  14. sqlalchemy/dialects/mssql/provision.py +196 -0
  15. sqlalchemy/dialects/mssql/pymssql.py +130 -0
  16. sqlalchemy/dialects/mssql/pyodbc.py +697 -0
  17. sqlalchemy/dialects/mysql/__init__.py +106 -0
  18. sqlalchemy/dialects/mysql/_mariadb_shim.py +312 -0
  19. sqlalchemy/dialects/mysql/aiomysql.py +260 -0
  20. sqlalchemy/dialects/mysql/asyncmy.py +241 -0
  21. sqlalchemy/dialects/mysql/base.py +3896 -0
  22. sqlalchemy/dialects/mysql/cymysql.py +107 -0
  23. sqlalchemy/dialects/mysql/dml.py +279 -0
  24. sqlalchemy/dialects/mysql/enumerated.py +277 -0
  25. sqlalchemy/dialects/mysql/expression.py +146 -0
  26. sqlalchemy/dialects/mysql/json.py +92 -0
  27. sqlalchemy/dialects/mysql/mariadb.py +67 -0
  28. sqlalchemy/dialects/mysql/mariadbconnector.py +314 -0
  29. sqlalchemy/dialects/mysql/mysqlconnector.py +291 -0
  30. sqlalchemy/dialects/mysql/mysqldb.py +318 -0
  31. sqlalchemy/dialects/mysql/provision.py +153 -0
  32. sqlalchemy/dialects/mysql/pymysql.py +188 -0
  33. sqlalchemy/dialects/mysql/pyodbc.py +157 -0
  34. sqlalchemy/dialects/mysql/reflection.py +724 -0
  35. sqlalchemy/dialects/mysql/reserved_words.py +570 -0
  36. sqlalchemy/dialects/mysql/types.py +845 -0
  37. sqlalchemy/dialects/oracle/__init__.py +85 -0
  38. sqlalchemy/dialects/oracle/base.py +3847 -0
  39. sqlalchemy/dialects/oracle/cx_oracle.py +1736 -0
  40. sqlalchemy/dialects/oracle/dictionary.py +507 -0
  41. sqlalchemy/dialects/oracle/json.py +157 -0
  42. sqlalchemy/dialects/oracle/oracledb.py +898 -0
  43. sqlalchemy/dialects/oracle/provision.py +288 -0
  44. sqlalchemy/dialects/oracle/types.py +367 -0
  45. sqlalchemy/dialects/oracle/vector.py +366 -0
  46. sqlalchemy/dialects/postgresql/__init__.py +170 -0
  47. sqlalchemy/dialects/postgresql/_psycopg_common.py +232 -0
  48. sqlalchemy/dialects/postgresql/array.py +534 -0
  49. sqlalchemy/dialects/postgresql/asyncpg.py +1318 -0
  50. sqlalchemy/dialects/postgresql/base.py +5935 -0
  51. sqlalchemy/dialects/postgresql/bitstring.py +327 -0
  52. sqlalchemy/dialects/postgresql/dml.py +360 -0
  53. sqlalchemy/dialects/postgresql/ext.py +599 -0
  54. sqlalchemy/dialects/postgresql/hstore.py +422 -0
  55. sqlalchemy/dialects/postgresql/json.py +411 -0
  56. sqlalchemy/dialects/postgresql/named_types.py +535 -0
  57. sqlalchemy/dialects/postgresql/operators.py +129 -0
  58. sqlalchemy/dialects/postgresql/pg8000.py +655 -0
  59. sqlalchemy/dialects/postgresql/pg_catalog.py +345 -0
  60. sqlalchemy/dialects/postgresql/provision.py +202 -0
  61. sqlalchemy/dialects/postgresql/psycopg.py +800 -0
  62. sqlalchemy/dialects/postgresql/psycopg2.py +860 -0
  63. sqlalchemy/dialects/postgresql/psycopg2cffi.py +62 -0
  64. sqlalchemy/dialects/postgresql/ranges.py +1002 -0
  65. sqlalchemy/dialects/postgresql/types.py +388 -0
  66. sqlalchemy/dialects/sqlite/__init__.py +59 -0
  67. sqlalchemy/dialects/sqlite/aiosqlite.py +375 -0
  68. sqlalchemy/dialects/sqlite/base.py +3103 -0
  69. sqlalchemy/dialects/sqlite/dml.py +314 -0
  70. sqlalchemy/dialects/sqlite/json.py +134 -0
  71. sqlalchemy/dialects/sqlite/provision.py +237 -0
  72. sqlalchemy/dialects/sqlite/pysqlcipher.py +166 -0
  73. sqlalchemy/dialects/sqlite/pysqlite.py +959 -0
  74. sqlalchemy/dialects/type_migration_guidelines.txt +145 -0
  75. sqlalchemy/engine/__init__.py +62 -0
  76. sqlalchemy/engine/_processors_cy.cp315-win32.pyd +0 -0
  77. sqlalchemy/engine/_processors_cy.py +92 -0
  78. sqlalchemy/engine/_result_cy.cp315-win32.pyd +0 -0
  79. sqlalchemy/engine/_result_cy.py +711 -0
  80. sqlalchemy/engine/_row_cy.cp315-win32.pyd +0 -0
  81. sqlalchemy/engine/_row_cy.py +232 -0
  82. sqlalchemy/engine/_util_cy.cp315-win32.pyd +0 -0
  83. sqlalchemy/engine/_util_cy.py +136 -0
  84. sqlalchemy/engine/base.py +3357 -0
  85. sqlalchemy/engine/characteristics.py +155 -0
  86. sqlalchemy/engine/create.py +877 -0
  87. sqlalchemy/engine/cursor.py +2425 -0
  88. sqlalchemy/engine/default.py +2627 -0
  89. sqlalchemy/engine/events.py +965 -0
  90. sqlalchemy/engine/interfaces.py +3636 -0
  91. sqlalchemy/engine/mock.py +133 -0
  92. sqlalchemy/engine/processors.py +83 -0
  93. sqlalchemy/engine/reflection.py +2141 -0
  94. sqlalchemy/engine/result.py +2012 -0
  95. sqlalchemy/engine/row.py +397 -0
  96. sqlalchemy/engine/strategies.py +16 -0
  97. sqlalchemy/engine/url.py +922 -0
  98. sqlalchemy/engine/util.py +164 -0
  99. sqlalchemy/event/__init__.py +26 -0
  100. sqlalchemy/event/api.py +220 -0
  101. sqlalchemy/event/attr.py +675 -0
  102. sqlalchemy/event/base.py +473 -0
  103. sqlalchemy/event/legacy.py +259 -0
  104. sqlalchemy/event/registry.py +391 -0
  105. sqlalchemy/events.py +17 -0
  106. sqlalchemy/exc.py +939 -0
  107. sqlalchemy/ext/__init__.py +10 -0
  108. sqlalchemy/ext/associationproxy.py +2073 -0
  109. sqlalchemy/ext/asyncio/__init__.py +29 -0
  110. sqlalchemy/ext/asyncio/base.py +281 -0
  111. sqlalchemy/ext/asyncio/engine.py +1487 -0
  112. sqlalchemy/ext/asyncio/exc.py +21 -0
  113. sqlalchemy/ext/asyncio/result.py +994 -0
  114. sqlalchemy/ext/asyncio/scoping.py +1679 -0
  115. sqlalchemy/ext/asyncio/session.py +2006 -0
  116. sqlalchemy/ext/automap.py +1702 -0
  117. sqlalchemy/ext/baked.py +558 -0
  118. sqlalchemy/ext/compiler.py +601 -0
  119. sqlalchemy/ext/declarative/__init__.py +65 -0
  120. sqlalchemy/ext/declarative/extensions.py +561 -0
  121. sqlalchemy/ext/horizontal_shard.py +481 -0
  122. sqlalchemy/ext/hybrid.py +1877 -0
  123. sqlalchemy/ext/indexable.py +364 -0
  124. sqlalchemy/ext/instrumentation.py +450 -0
  125. sqlalchemy/ext/mutable.py +1081 -0
  126. sqlalchemy/ext/orderinglist.py +440 -0
  127. sqlalchemy/ext/serializer.py +184 -0
  128. sqlalchemy/future/__init__.py +17 -0
  129. sqlalchemy/future/engine.py +15 -0
  130. sqlalchemy/inspection.py +188 -0
  131. sqlalchemy/log.py +279 -0
  132. sqlalchemy/orm/__init__.py +176 -0
  133. sqlalchemy/orm/_orm_constructors.py +2694 -0
  134. sqlalchemy/orm/_typing.py +180 -0
  135. sqlalchemy/orm/attributes.py +2868 -0
  136. sqlalchemy/orm/base.py +991 -0
  137. sqlalchemy/orm/bulk_persistence.py +2168 -0
  138. sqlalchemy/orm/clsregistry.py +630 -0
  139. sqlalchemy/orm/collections.py +1569 -0
  140. sqlalchemy/orm/context.py +3475 -0
  141. sqlalchemy/orm/decl_api.py +2283 -0
  142. sqlalchemy/orm/decl_base.py +2320 -0
  143. sqlalchemy/orm/dependency.py +1306 -0
  144. sqlalchemy/orm/descriptor_props.py +1183 -0
  145. sqlalchemy/orm/dynamic.py +306 -0
  146. sqlalchemy/orm/evaluator.py +378 -0
  147. sqlalchemy/orm/events.py +3387 -0
  148. sqlalchemy/orm/exc.py +237 -0
  149. sqlalchemy/orm/identity.py +302 -0
  150. sqlalchemy/orm/instrumentation.py +749 -0
  151. sqlalchemy/orm/interfaces.py +1595 -0
  152. sqlalchemy/orm/loading.py +1712 -0
  153. sqlalchemy/orm/mapped_collection.py +557 -0
  154. sqlalchemy/orm/mapper.py +4465 -0
  155. sqlalchemy/orm/path_registry.py +907 -0
  156. sqlalchemy/orm/persistence.py +1790 -0
  157. sqlalchemy/orm/properties.py +972 -0
  158. sqlalchemy/orm/query.py +3528 -0
  159. sqlalchemy/orm/relationships.py +3608 -0
  160. sqlalchemy/orm/scoping.py +2233 -0
  161. sqlalchemy/orm/session.py +5468 -0
  162. sqlalchemy/orm/state.py +1175 -0
  163. sqlalchemy/orm/state_changes.py +196 -0
  164. sqlalchemy/orm/strategies.py +3552 -0
  165. sqlalchemy/orm/strategy_options.py +2648 -0
  166. sqlalchemy/orm/sync.py +164 -0
  167. sqlalchemy/orm/unitofwork.py +797 -0
  168. sqlalchemy/orm/util.py +2461 -0
  169. sqlalchemy/orm/writeonly.py +701 -0
  170. sqlalchemy/pool/__init__.py +41 -0
  171. sqlalchemy/pool/base.py +1540 -0
  172. sqlalchemy/pool/events.py +375 -0
  173. sqlalchemy/pool/impl.py +583 -0
  174. sqlalchemy/py.typed +0 -0
  175. sqlalchemy/schema.py +75 -0
  176. sqlalchemy/sql/__init__.py +156 -0
  177. sqlalchemy/sql/_annotated_cols.py +402 -0
  178. sqlalchemy/sql/_cache_key_cy.cp315-win32.pyd +0 -0
  179. sqlalchemy/sql/_cache_key_cy.py +363 -0
  180. sqlalchemy/sql/_dml_constructors.py +132 -0
  181. sqlalchemy/sql/_elements_constructors.py +2190 -0
  182. sqlalchemy/sql/_orm_types.py +19 -0
  183. sqlalchemy/sql/_selectable_constructors.py +840 -0
  184. sqlalchemy/sql/_typing.py +500 -0
  185. sqlalchemy/sql/_util_cy.cp315-win32.pyd +0 -0
  186. sqlalchemy/sql/_util_cy.pxd +11 -0
  187. sqlalchemy/sql/_util_cy.py +127 -0
  188. sqlalchemy/sql/annotation.py +590 -0
  189. sqlalchemy/sql/base.py +2702 -0
  190. sqlalchemy/sql/cache_key.py +915 -0
  191. sqlalchemy/sql/coercions.py +1373 -0
  192. sqlalchemy/sql/compiler.py +8453 -0
  193. sqlalchemy/sql/crud.py +1816 -0
  194. sqlalchemy/sql/ddl.py +1962 -0
  195. sqlalchemy/sql/default_comparator.py +660 -0
  196. sqlalchemy/sql/dml.py +2018 -0
  197. sqlalchemy/sql/elements.py +6057 -0
  198. sqlalchemy/sql/events.py +458 -0
  199. sqlalchemy/sql/expression.py +171 -0
  200. sqlalchemy/sql/functions.py +2380 -0
  201. sqlalchemy/sql/lambdas.py +1442 -0
  202. sqlalchemy/sql/naming.py +204 -0
  203. sqlalchemy/sql/operators.py +2909 -0
  204. sqlalchemy/sql/roles.py +332 -0
  205. sqlalchemy/sql/schema.py +7075 -0
  206. sqlalchemy/sql/selectable.py +7634 -0
  207. sqlalchemy/sql/sqltypes.py +4130 -0
  208. sqlalchemy/sql/traversals.py +1041 -0
  209. sqlalchemy/sql/type_api.py +2450 -0
  210. sqlalchemy/sql/util.py +1496 -0
  211. sqlalchemy/sql/visitors.py +1153 -0
  212. sqlalchemy/testing/__init__.py +97 -0
  213. sqlalchemy/testing/assertions.py +1007 -0
  214. sqlalchemy/testing/assertsql.py +519 -0
  215. sqlalchemy/testing/asyncio.py +128 -0
  216. sqlalchemy/testing/cancellation.py +237 -0
  217. sqlalchemy/testing/config.py +440 -0
  218. sqlalchemy/testing/engines.py +482 -0
  219. sqlalchemy/testing/entities.py +117 -0
  220. sqlalchemy/testing/exclusions.py +501 -0
  221. sqlalchemy/testing/fixtures/__init__.py +30 -0
  222. sqlalchemy/testing/fixtures/base.py +426 -0
  223. sqlalchemy/testing/fixtures/mypy.py +247 -0
  224. sqlalchemy/testing/fixtures/orm.py +227 -0
  225. sqlalchemy/testing/fixtures/sql.py +538 -0
  226. sqlalchemy/testing/pickleable.py +155 -0
  227. sqlalchemy/testing/plugin/__init__.py +6 -0
  228. sqlalchemy/testing/plugin/bootstrap.py +50 -0
  229. sqlalchemy/testing/plugin/plugin_base.py +828 -0
  230. sqlalchemy/testing/plugin/pytestplugin.py +896 -0
  231. sqlalchemy/testing/profiles_file.py +350 -0
  232. sqlalchemy/testing/profiling.py +294 -0
  233. sqlalchemy/testing/provision.py +633 -0
  234. sqlalchemy/testing/requirements.py +1971 -0
  235. sqlalchemy/testing/schema.py +198 -0
  236. sqlalchemy/testing/suite/__init__.py +19 -0
  237. sqlalchemy/testing/suite/test_cte.py +237 -0
  238. sqlalchemy/testing/suite/test_ddl.py +420 -0
  239. sqlalchemy/testing/suite/test_dialect.py +776 -0
  240. sqlalchemy/testing/suite/test_insert.py +630 -0
  241. sqlalchemy/testing/suite/test_reflection.py +3815 -0
  242. sqlalchemy/testing/suite/test_results.py +660 -0
  243. sqlalchemy/testing/suite/test_rowcount.py +258 -0
  244. sqlalchemy/testing/suite/test_select.py +2112 -0
  245. sqlalchemy/testing/suite/test_sequence.py +317 -0
  246. sqlalchemy/testing/suite/test_table_via_select.py +686 -0
  247. sqlalchemy/testing/suite/test_types.py +2271 -0
  248. sqlalchemy/testing/suite/test_unicode_ddl.py +189 -0
  249. sqlalchemy/testing/suite/test_update_delete.py +139 -0
  250. sqlalchemy/testing/util.py +575 -0
  251. sqlalchemy/testing/warnings.py +52 -0
  252. sqlalchemy/types.py +75 -0
  253. sqlalchemy/util/__init__.py +165 -0
  254. sqlalchemy/util/_collections.py +688 -0
  255. sqlalchemy/util/_collections_cy.cp315-win32.pyd +0 -0
  256. sqlalchemy/util/_collections_cy.pxd +8 -0
  257. sqlalchemy/util/_collections_cy.py +516 -0
  258. sqlalchemy/util/_has_cython.py +48 -0
  259. sqlalchemy/util/_immutabledict_cy.cp315-win32.pyd +0 -0
  260. sqlalchemy/util/_immutabledict_cy.py +240 -0
  261. sqlalchemy/util/compat.py +298 -0
  262. sqlalchemy/util/concurrency.py +272 -0
  263. sqlalchemy/util/cython.py +95 -0
  264. sqlalchemy/util/deprecations.py +401 -0
  265. sqlalchemy/util/langhelpers.py +2797 -0
  266. sqlalchemy/util/preloaded.py +153 -0
  267. sqlalchemy/util/queue.py +304 -0
  268. sqlalchemy/util/tool_support.py +202 -0
  269. sqlalchemy/util/topological.py +120 -0
  270. sqlalchemy/util/typing.py +709 -0
  271. sqlalchemy-2.1.0rc1.dist-info/METADATA +270 -0
  272. sqlalchemy-2.1.0rc1.dist-info/RECORD +276 -0
  273. sqlalchemy-2.1.0rc1.dist-info/WHEEL +5 -0
  274. sqlalchemy-2.1.0rc1.dist-info/licenses/AUTHORS +30 -0
  275. sqlalchemy-2.1.0rc1.dist-info/licenses/LICENSE +19 -0
  276. sqlalchemy-2.1.0rc1.dist-info/top_level.txt +1 -0
@@ -0,0 +1,749 @@
1
+ # orm/instrumentation.py
2
+ # Copyright (C) 2005-2026 the SQLAlchemy authors and contributors
3
+ # <see AUTHORS file>
4
+ #
5
+ # This module is part of SQLAlchemy and is released under
6
+ # the MIT License: https://www.opensource.org/licenses/mit-license.php
7
+ # mypy: allow-untyped-defs, allow-untyped-calls
8
+
9
+ """Defines SQLAlchemy's system of class instrumentation.
10
+
11
+ This module is usually not directly visible to user applications, but
12
+ defines a large part of the ORM's interactivity.
13
+
14
+ instrumentation.py deals with registration of end-user classes
15
+ for state tracking. It interacts closely with state.py
16
+ and attributes.py which establish per-instance and per-class-attribute
17
+ instrumentation, respectively.
18
+
19
+ The class instrumentation system can be customized on a per-class
20
+ or global basis using the :mod:`sqlalchemy.ext.instrumentation`
21
+ module, which provides the means to build and specify
22
+ alternate instrumentation forms.
23
+
24
+ """
25
+
26
+ from __future__ import annotations
27
+
28
+ from typing import Any
29
+ from typing import Callable
30
+ from typing import cast
31
+ from typing import Collection
32
+ from typing import Dict
33
+ from typing import Generic
34
+ from typing import Iterable
35
+ from typing import List
36
+ from typing import Literal
37
+ from typing import Optional
38
+ from typing import Protocol
39
+ from typing import Set
40
+ from typing import Tuple
41
+ from typing import Type
42
+ from typing import TYPE_CHECKING
43
+ from typing import TypeVar
44
+ from typing import Union
45
+ import weakref
46
+
47
+ from . import base
48
+ from . import collections
49
+ from . import exc
50
+ from . import interfaces
51
+ from . import state
52
+ from ._typing import _O
53
+ from .attributes import _is_collection_attribute_impl
54
+ from .. import util
55
+ from ..event import EventTarget
56
+ from ..util import HasMemoized
57
+
58
+ if TYPE_CHECKING:
59
+ from ._typing import _RegistryType
60
+ from .attributes import _AttributeImpl
61
+ from .attributes import QueryableAttribute
62
+ from .collections import _AdaptedCollectionProtocol
63
+ from .collections import _CollectionFactoryType
64
+ from .decl_base import _MapperConfig
65
+ from .events import InstanceEvents
66
+ from .mapper import Mapper
67
+ from .state import InstanceState
68
+ from ..event import dispatcher
69
+
70
+ _T = TypeVar("_T", bound=Any)
71
+ DEL_ATTR = util.symbol("DEL_ATTR")
72
+
73
+
74
+ class _ExpiredAttributeLoaderProto(Protocol):
75
+ def __call__(
76
+ self,
77
+ state: state.InstanceState[Any],
78
+ toload: Set[str],
79
+ passive: base.PassiveFlag,
80
+ ) -> None: ...
81
+
82
+
83
+ class _ManagerFactory(Protocol):
84
+ def __call__(self, class_: Type[_O]) -> ClassManager[_O]: ...
85
+
86
+
87
+ class ClassManager(
88
+ HasMemoized,
89
+ Dict[str, "QueryableAttribute[Any]"],
90
+ Generic[_O],
91
+ EventTarget,
92
+ ):
93
+ """Tracks state information at the class level."""
94
+
95
+ dispatch: dispatcher[ClassManager[_O]]
96
+
97
+ MANAGER_ATTR = base.DEFAULT_MANAGER_ATTR
98
+ STATE_ATTR = base.DEFAULT_STATE_ATTR
99
+
100
+ _state_setter = staticmethod(util.attrsetter(STATE_ATTR))
101
+
102
+ expired_attribute_loader: _ExpiredAttributeLoaderProto
103
+ "previously known as deferred_scalar_loader"
104
+
105
+ init_method: Optional[Callable[..., None]]
106
+ original_init: Optional[Callable[..., None]] = None
107
+
108
+ factory: Optional[_ManagerFactory]
109
+
110
+ declarative_scan: Optional[weakref.ref[_MapperConfig]] = None
111
+
112
+ registry: _RegistryType
113
+
114
+ if not TYPE_CHECKING:
115
+ # starts as None during setup
116
+ registry = None
117
+
118
+ class_: Type[_O]
119
+
120
+ _bases: List[ClassManager[Any]]
121
+
122
+ @property
123
+ @util.deprecated(
124
+ "1.4",
125
+ message="The ClassManager.deferred_scalar_loader attribute is now "
126
+ "named expired_attribute_loader",
127
+ )
128
+ def deferred_scalar_loader(self):
129
+ return self.expired_attribute_loader
130
+
131
+ @deferred_scalar_loader.setter
132
+ @util.deprecated(
133
+ "1.4",
134
+ message="The ClassManager.deferred_scalar_loader attribute is now "
135
+ "named expired_attribute_loader",
136
+ )
137
+ def deferred_scalar_loader(self, obj):
138
+ self.expired_attribute_loader = obj
139
+
140
+ def __init__(self, class_):
141
+ self.class_ = class_
142
+ self.info = {}
143
+ self.new_init = None
144
+ self.local_attrs = {}
145
+ self.originals = {}
146
+ self._finalized = False
147
+ self.factory = None
148
+ self.init_method = None
149
+
150
+ self._bases = [
151
+ mgr
152
+ for mgr in cast(
153
+ "List[Optional[ClassManager[Any]]]",
154
+ [
155
+ opt_manager_of_class(base)
156
+ for base in self.class_.__bases__
157
+ if isinstance(base, type)
158
+ ],
159
+ )
160
+ if mgr is not None
161
+ ]
162
+
163
+ for base_ in self._bases:
164
+ self.update(base_)
165
+
166
+ cast(
167
+ "InstanceEvents", self.dispatch._events
168
+ )._new_classmanager_instance(class_, self)
169
+
170
+ for basecls in class_.__mro__:
171
+ mgr = opt_manager_of_class(basecls)
172
+ if mgr is not None:
173
+ self.dispatch._update(mgr.dispatch)
174
+
175
+ self.manage()
176
+
177
+ if "__del__" in class_.__dict__:
178
+ util.warn(
179
+ "__del__() method on class %s will "
180
+ "cause unreachable cycles and memory leaks, "
181
+ "as SQLAlchemy instrumentation often creates "
182
+ "reference cycles. Please remove this method." % class_
183
+ )
184
+
185
+ def _update_state(
186
+ self,
187
+ finalize: bool = False,
188
+ mapper: Optional[Mapper[_O]] = None,
189
+ registry: Optional[_RegistryType] = None,
190
+ declarative_scan: Optional[_MapperConfig] = None,
191
+ expired_attribute_loader: Optional[
192
+ _ExpiredAttributeLoaderProto
193
+ ] = None,
194
+ init_method: Optional[Callable[..., None]] = None,
195
+ ) -> None:
196
+ if mapper:
197
+ self.mapper = mapper #
198
+ if registry:
199
+ registry._add_manager(self)
200
+ if declarative_scan:
201
+ self.declarative_scan = weakref.ref(declarative_scan)
202
+ if expired_attribute_loader:
203
+ self.expired_attribute_loader = expired_attribute_loader
204
+
205
+ if init_method:
206
+ assert not self._finalized, (
207
+ "class is already instrumented, "
208
+ "init_method %s can't be applied" % init_method
209
+ )
210
+ self.init_method = init_method
211
+
212
+ if not self._finalized:
213
+ self.original_init = (
214
+ self.init_method
215
+ if self.init_method is not None
216
+ and self.class_.__init__ is object.__init__
217
+ else self.class_.__init__
218
+ )
219
+
220
+ if finalize and not self._finalized:
221
+ self._finalize()
222
+
223
+ def _finalize(self) -> None:
224
+ if self._finalized:
225
+ return
226
+ self._finalized = True
227
+
228
+ self._instrument_init()
229
+
230
+ _instrumentation_factory.dispatch.class_instrument(self.class_)
231
+
232
+ def __hash__(self) -> int: # type: ignore[override]
233
+ return id(self)
234
+
235
+ def __eq__(self, other: Any) -> bool:
236
+ return other is self
237
+
238
+ @property
239
+ def is_mapped(self) -> bool:
240
+ return "mapper" in self.__dict__
241
+
242
+ @HasMemoized.memoized_attribute
243
+ def _all_key_set(self):
244
+ return frozenset(self)
245
+
246
+ @HasMemoized.memoized_attribute
247
+ def _collection_impl_keys(self):
248
+ return frozenset(
249
+ [attr.key for attr in self.values() if attr.impl.collection]
250
+ )
251
+
252
+ @HasMemoized.memoized_attribute
253
+ def _scalar_loader_impls(self):
254
+ return frozenset(
255
+ [
256
+ attr.impl
257
+ for attr in self.values()
258
+ if attr.impl.accepts_scalar_loader
259
+ ]
260
+ )
261
+
262
+ @HasMemoized.memoized_attribute
263
+ def _loader_impls(self):
264
+ return frozenset([attr.impl for attr in self.values()])
265
+
266
+ @util.memoized_property
267
+ def mapper(self) -> Mapper[_O]:
268
+ # raises unless self.mapper has been assigned
269
+ raise exc.UnmappedClassError(self.class_)
270
+
271
+ def _all_sqla_attributes(self, exclude=None):
272
+ """return an iterator of all classbound attributes that are
273
+ implement :class:`.InspectionAttr`.
274
+
275
+ This includes :class:`.QueryableAttribute` as well as extension
276
+ types such as :class:`.hybrid_property` and
277
+ :class:`.AssociationProxy`.
278
+
279
+ """
280
+
281
+ found: Dict[str, Any] = {}
282
+
283
+ # constraints:
284
+ # 1. yield keys in cls.__dict__ order
285
+ # 2. if a subclass has the same key as a superclass, include that
286
+ # key as part of the ordering of the superclass, because an
287
+ # overridden key is usually installed by the mapper which is going
288
+ # on a different ordering
289
+ # 3. don't use getattr() as this fires off descriptors
290
+
291
+ for supercls in self.class_.__mro__[0:-1]:
292
+ inherits = supercls.__mro__[1]
293
+ for key in supercls.__dict__:
294
+ found.setdefault(key, supercls)
295
+ if key in inherits.__dict__:
296
+ continue
297
+ val = found[key].__dict__[key]
298
+ if (
299
+ isinstance(val, interfaces.InspectionAttr)
300
+ and val.is_attribute
301
+ ):
302
+ yield key, val
303
+
304
+ def _get_class_attr_mro(self, key, default=None):
305
+ """return an attribute on the class without tripping it."""
306
+
307
+ for supercls in self.class_.__mro__:
308
+ if key in supercls.__dict__:
309
+ return supercls.__dict__[key]
310
+ else:
311
+ return default
312
+
313
+ def _attr_has_impl(self, key: str) -> bool:
314
+ """Return True if the given attribute is fully initialized.
315
+
316
+ i.e. has an impl.
317
+ """
318
+
319
+ return key in self and self[key].impl is not None
320
+
321
+ def _subclass_manager(self, cls: Type[_T]) -> ClassManager[_T]:
322
+ """Create a new ClassManager for a subclass of this ClassManager's
323
+ class.
324
+
325
+ This is called automatically when attributes are instrumented so that
326
+ the attributes can be propagated to subclasses against their own
327
+ class-local manager, without the need for mappers etc. to have already
328
+ pre-configured managers for the full class hierarchy. Mappers
329
+ can post-configure the auto-generated ClassManager when needed.
330
+
331
+ """
332
+ return register_class(cls, finalize=False)
333
+
334
+ def _instrument_init(self):
335
+ self.new_init = _generate_init(self.class_, self, self.original_init)
336
+ self.install_member("__init__", self.new_init)
337
+
338
+ @util.memoized_property
339
+ def _state_constructor(self) -> Type[state.InstanceState[_O]]:
340
+ return state.InstanceState
341
+
342
+ def manage(self):
343
+ """Mark this instance as the manager for its class."""
344
+
345
+ setattr(self.class_, self.MANAGER_ATTR, self)
346
+
347
+ @util.hybridmethod
348
+ def manager_getter(self):
349
+ return _default_manager_getter
350
+
351
+ @util.hybridmethod
352
+ def state_getter(self):
353
+ """Return a (instance) -> InstanceState callable.
354
+
355
+ "state getter" callables should raise either KeyError or
356
+ AttributeError if no InstanceState could be found for the
357
+ instance.
358
+ """
359
+
360
+ return _default_state_getter
361
+
362
+ @util.hybridmethod
363
+ def dict_getter(self):
364
+ return _default_dict_getter
365
+
366
+ def instrument_attribute(
367
+ self,
368
+ key: str,
369
+ inst: QueryableAttribute[Any],
370
+ propagated: bool = False,
371
+ ) -> None:
372
+ if propagated:
373
+ if key in self.local_attrs:
374
+ return # don't override local attr with inherited attr
375
+ else:
376
+ self.local_attrs[key] = inst
377
+ self.install_descriptor(key, inst)
378
+ self._reset_memoizations()
379
+ self[key] = inst
380
+
381
+ for cls in self.class_.__subclasses__():
382
+ manager = self._subclass_manager(cls)
383
+ manager.instrument_attribute(key, inst, True)
384
+
385
+ def subclass_managers(self, recursive):
386
+ for cls in self.class_.__subclasses__():
387
+ mgr = opt_manager_of_class(cls)
388
+ if mgr is not None and mgr is not self:
389
+ yield mgr
390
+ if recursive:
391
+ yield from mgr.subclass_managers(True)
392
+
393
+ def post_configure_attribute(self, key):
394
+ _instrumentation_factory.dispatch.attribute_instrument(
395
+ self.class_, key, self[key]
396
+ )
397
+
398
+ def uninstrument_attribute(self, key, propagated=False):
399
+ if key not in self:
400
+ return
401
+ if propagated:
402
+ if key in self.local_attrs:
403
+ return # don't get rid of local attr
404
+ else:
405
+ del self.local_attrs[key]
406
+ self.uninstall_descriptor(key)
407
+ self._reset_memoizations()
408
+ del self[key]
409
+ for cls in self.class_.__subclasses__():
410
+ manager = opt_manager_of_class(cls)
411
+ if manager:
412
+ manager.uninstrument_attribute(key, True)
413
+
414
+ def unregister(self) -> None:
415
+ """remove all instrumentation established by this ClassManager."""
416
+
417
+ for key in list(self.originals):
418
+ self.uninstall_member(key)
419
+
420
+ self.mapper = None
421
+ self.dispatch = None # type: ignore[assignment]
422
+ self.new_init = None
423
+ self.info.clear()
424
+
425
+ for key in list(self):
426
+ if key in self.local_attrs:
427
+ self.uninstrument_attribute(key)
428
+
429
+ if self.MANAGER_ATTR in self.class_.__dict__:
430
+ delattr(self.class_, self.MANAGER_ATTR)
431
+
432
+ def install_descriptor(
433
+ self, key: str, inst: QueryableAttribute[Any]
434
+ ) -> None:
435
+ if key in (self.STATE_ATTR, self.MANAGER_ATTR):
436
+ raise KeyError(
437
+ "%r: requested attribute name conflicts with "
438
+ "instrumentation attribute of the same name." % key
439
+ )
440
+ setattr(self.class_, key, inst)
441
+
442
+ def uninstall_descriptor(self, key: str) -> None:
443
+ delattr(self.class_, key)
444
+
445
+ def install_member(self, key: str, implementation: Any) -> None:
446
+ if key in (self.STATE_ATTR, self.MANAGER_ATTR):
447
+ raise KeyError(
448
+ "%r: requested attribute name conflicts with "
449
+ "instrumentation attribute of the same name." % key
450
+ )
451
+ self.originals.setdefault(key, self.class_.__dict__.get(key, DEL_ATTR))
452
+ setattr(self.class_, key, implementation)
453
+
454
+ def uninstall_member(self, key: str) -> None:
455
+ original = self.originals.pop(key, None)
456
+ if original is not DEL_ATTR:
457
+ setattr(self.class_, key, original)
458
+ else:
459
+ delattr(self.class_, key)
460
+
461
+ def instrument_collection_class(
462
+ self, key: str, collection_class: Type[Collection[Any]]
463
+ ) -> _CollectionFactoryType:
464
+ return collections._prepare_instrumentation(collection_class)
465
+
466
+ def initialize_collection(
467
+ self,
468
+ key: str,
469
+ state: InstanceState[_O],
470
+ factory: _CollectionFactoryType,
471
+ ) -> Tuple[collections.CollectionAdapter, _AdaptedCollectionProtocol]:
472
+ user_data = factory()
473
+ impl = self.get_impl(key)
474
+ assert _is_collection_attribute_impl(impl)
475
+ adapter = collections.CollectionAdapter(impl, state, user_data)
476
+ return adapter, user_data
477
+
478
+ def is_instrumented(self, key: str, search: bool = False) -> bool:
479
+ if search:
480
+ return key in self
481
+ else:
482
+ return key in self.local_attrs
483
+
484
+ def get_impl(self, key: str) -> _AttributeImpl:
485
+ return self[key].impl
486
+
487
+ @property
488
+ def attributes(self) -> Iterable[Any]:
489
+ return iter(self.values())
490
+
491
+ # InstanceState management
492
+
493
+ def new_instance(self, state: Optional[InstanceState[_O]] = None) -> _O:
494
+ # here, we would prefer _O to be bound to "object"
495
+ # so that mypy sees that __new__ is present. currently
496
+ # it's bound to Any as there were other problems not having
497
+ # it that way but these can be revisited
498
+ instance = self.class_.__new__(self.class_)
499
+ if state is None:
500
+ state = self._state_constructor(instance, self)
501
+ self._state_setter(instance, state)
502
+ return instance
503
+
504
+ def setup_instance(
505
+ self, instance: _O, state: Optional[InstanceState[_O]] = None
506
+ ) -> None:
507
+ if state is None:
508
+ state = self._state_constructor(instance, self)
509
+ self._state_setter(instance, state)
510
+
511
+ def teardown_instance(self, instance: _O) -> None:
512
+ delattr(instance, self.STATE_ATTR)
513
+
514
+ def _serialize(
515
+ self, state: InstanceState[_O], state_dict: Dict[str, Any]
516
+ ) -> _SerializeManager:
517
+ return _SerializeManager(state, state_dict)
518
+
519
+ def _new_state_if_none(
520
+ self, instance: _O
521
+ ) -> Union[Literal[False], InstanceState[_O]]:
522
+ """Install a default InstanceState if none is present.
523
+
524
+ A private convenience method used by the __init__ decorator.
525
+
526
+ """
527
+ if hasattr(instance, self.STATE_ATTR):
528
+ return False
529
+ elif self.class_ is not instance.__class__ and self.is_mapped:
530
+ # this will create a new ClassManager for the
531
+ # subclass, without a mapper. This is likely a
532
+ # user error situation but allow the object
533
+ # to be constructed, so that it is usable
534
+ # in a non-ORM context at least.
535
+ return self._subclass_manager(
536
+ instance.__class__
537
+ )._new_state_if_none(instance)
538
+ else:
539
+ state = self._state_constructor(instance, self)
540
+ self._state_setter(instance, state)
541
+ return state
542
+
543
+ def has_state(self, instance: _O) -> bool:
544
+ return hasattr(instance, self.STATE_ATTR)
545
+
546
+ def has_parent(
547
+ self, state: InstanceState[_O], key: str, optimistic: bool = False
548
+ ) -> bool:
549
+ """TODO"""
550
+ return self.get_impl(key).hasparent(state, optimistic=optimistic)
551
+
552
+ def __bool__(self) -> bool:
553
+ """All ClassManagers are non-zero regardless of attribute state."""
554
+ return True
555
+
556
+ def __repr__(self) -> str:
557
+ return "<%s of %r at %x>" % (
558
+ self.__class__.__name__,
559
+ self.class_,
560
+ id(self),
561
+ )
562
+
563
+
564
+ class _SerializeManager:
565
+ """Provide serialization of a :class:`.ClassManager`.
566
+
567
+ The :class:`.InstanceState` uses ``__init__()`` on serialize
568
+ and ``__call__()`` on deserialize.
569
+
570
+ """
571
+
572
+ def __init__(self, state: state.InstanceState[Any], d: Dict[str, Any]):
573
+ self.class_ = state.class_
574
+ manager = state.manager
575
+ manager.dispatch.pickle(state, d)
576
+
577
+ def __call__(self, state, inst, state_dict):
578
+ state.manager = manager = opt_manager_of_class(self.class_)
579
+ if manager is None:
580
+ raise exc.UnmappedInstanceError(
581
+ inst,
582
+ "Cannot deserialize object of type %r - "
583
+ "no mapper() has "
584
+ "been configured for this class within the current "
585
+ "Python process!" % self.class_,
586
+ )
587
+ elif manager.is_mapped and not manager.mapper.configured:
588
+ manager.mapper._check_configure()
589
+
590
+ # setup _sa_instance_state ahead of time so that
591
+ # unpickle events can access the object normally.
592
+ # see [ticket:2362]
593
+ if inst is not None:
594
+ manager.setup_instance(inst, state)
595
+ manager.dispatch.unpickle(state, state_dict)
596
+
597
+
598
+ class InstrumentationFactory(EventTarget):
599
+ """Factory for new ClassManager instances."""
600
+
601
+ dispatch: dispatcher[InstrumentationFactory]
602
+
603
+ def create_manager_for_cls(self, class_: Type[_O]) -> ClassManager[_O]:
604
+ assert class_ is not None
605
+ assert opt_manager_of_class(class_) is None
606
+
607
+ # give a more complicated subclass
608
+ # a chance to do what it wants here
609
+ manager, factory = self._locate_extended_factory(class_)
610
+
611
+ if factory is None:
612
+ factory = ClassManager
613
+ manager = ClassManager(class_)
614
+ else:
615
+ assert manager is not None
616
+
617
+ self._check_conflicts(class_, factory)
618
+
619
+ manager.factory = factory
620
+
621
+ return manager
622
+
623
+ def _locate_extended_factory(
624
+ self, class_: Type[_O]
625
+ ) -> Tuple[Optional[ClassManager[_O]], Optional[_ManagerFactory]]:
626
+ """Overridden by a subclass to do an extended lookup."""
627
+ return None, None
628
+
629
+ def _check_conflicts(
630
+ self, class_: Type[_O], factory: Callable[[Type[_O]], ClassManager[_O]]
631
+ ) -> None:
632
+ """Overridden by a subclass to test for conflicting factories."""
633
+
634
+ def unregister(self, class_: Type[_O]) -> None:
635
+ manager = manager_of_class(class_)
636
+ manager.unregister()
637
+ self.dispatch.class_uninstrument(class_)
638
+
639
+
640
+ # this attribute is replaced by sqlalchemy.ext.instrumentation
641
+ # when imported.
642
+ _instrumentation_factory = InstrumentationFactory()
643
+
644
+ # these attributes are replaced by sqlalchemy.ext.instrumentation
645
+ # when a non-standard InstrumentationManager class is first
646
+ # used to instrument a class.
647
+ instance_state = _default_state_getter = base.instance_state
648
+
649
+ instance_dict = _default_dict_getter = base.instance_dict
650
+
651
+ manager_of_class = _default_manager_getter = base.manager_of_class
652
+ opt_manager_of_class = _default_opt_manager_getter = base.opt_manager_of_class
653
+
654
+
655
+ def register_class(
656
+ class_: Type[_O],
657
+ finalize: bool = True,
658
+ mapper: Optional[Mapper[_O]] = None,
659
+ registry: Optional[_RegistryType] = None,
660
+ declarative_scan: Optional[_MapperConfig] = None,
661
+ expired_attribute_loader: Optional[_ExpiredAttributeLoaderProto] = None,
662
+ init_method: Optional[Callable[..., None]] = None,
663
+ ) -> ClassManager[_O]:
664
+ """Register class instrumentation.
665
+
666
+ Returns the existing or newly created class manager.
667
+
668
+ """
669
+
670
+ manager = opt_manager_of_class(class_)
671
+ if manager is None:
672
+ manager = _instrumentation_factory.create_manager_for_cls(class_)
673
+ manager._update_state(
674
+ mapper=mapper,
675
+ registry=registry,
676
+ declarative_scan=declarative_scan,
677
+ expired_attribute_loader=expired_attribute_loader,
678
+ init_method=init_method,
679
+ finalize=finalize,
680
+ )
681
+
682
+ return manager
683
+
684
+
685
+ def unregister_class(class_):
686
+ """Unregister class instrumentation."""
687
+
688
+ _instrumentation_factory.unregister(class_)
689
+
690
+
691
+ def is_instrumented(instance, key):
692
+ """Return True if the given attribute on the given instance is
693
+ instrumented by the attributes package.
694
+
695
+ This function may be used regardless of instrumentation
696
+ applied directly to the class, i.e. no descriptors are required.
697
+
698
+ """
699
+ return manager_of_class(instance.__class__).is_instrumented(
700
+ key, search=True
701
+ )
702
+
703
+
704
+ def _generate_init(class_, class_manager, original_init):
705
+ """Build an __init__ decorator that triggers ClassManager events."""
706
+
707
+ # TODO: we should use the ClassManager's notion of the
708
+ # original '__init__' method, once ClassManager is fixed
709
+ # to always reference that.
710
+
711
+ if original_init is None:
712
+ original_init = class_.__init__
713
+
714
+ # Go through some effort here and don't change the user's __init__
715
+ # calling signature, including the unlikely case that it has
716
+ # a return value.
717
+ # FIXME: need to juggle local names to avoid constructor argument
718
+ # clashes.
719
+ func_body = """\
720
+ def __init__(%(apply_pos)s):
721
+ new_state = class_manager._new_state_if_none(%(self_arg)s)
722
+ if new_state:
723
+ return new_state._initialize_instance(%(apply_kw)s)
724
+ else:
725
+ return original_init(%(apply_kw)s)
726
+ """
727
+ func_vars = util.format_argspec_init(original_init, grouped=False)
728
+ func_text = func_body % func_vars
729
+
730
+ func_defaults = getattr(original_init, "__defaults__", None)
731
+ func_kw_defaults = getattr(original_init, "__kwdefaults__", None)
732
+
733
+ env = locals().copy()
734
+ env["__name__"] = __name__
735
+ __init__: Any = util.exec_code_in_env(
736
+ func_text,
737
+ env,
738
+ "__init__",
739
+ f"__init__ for class {class_.__module__}.{class_.__qualname__}",
740
+ )
741
+ __init__.__doc__ = original_init.__doc__
742
+ __init__._sa_original_init = original_init
743
+
744
+ if func_defaults:
745
+ __init__.__defaults__ = func_defaults
746
+ if func_kw_defaults:
747
+ __init__.__kwdefaults__ = func_kw_defaults
748
+
749
+ return __init__