SQLAlchemy 2.1.0b2__cp313-cp313t-win_arm64.whl

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