instrumentation.py 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652
  1. # orm/instrumentation.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. """Defines SQLAlchemy's system of class instrumentation.
  8. This module is usually not directly visible to user applications, but
  9. defines a large part of the ORM's interactivity.
  10. instrumentation.py deals with registration of end-user classes
  11. for state tracking. It interacts closely with state.py
  12. and attributes.py which establish per-instance and per-class-attribute
  13. instrumentation, respectively.
  14. The class instrumentation system can be customized on a per-class
  15. or global basis using the :mod:`sqlalchemy.ext.instrumentation`
  16. module, which provides the means to build and specify
  17. alternate instrumentation forms.
  18. .. versionchanged: 0.8
  19. The instrumentation extension system was moved out of the
  20. ORM and into the external :mod:`sqlalchemy.ext.instrumentation`
  21. package. When that package is imported, it installs
  22. itself within sqlalchemy.orm so that its more comprehensive
  23. resolution mechanics take effect.
  24. """
  25. import weakref
  26. from . import base
  27. from . import collections
  28. from . import exc
  29. from . import interfaces
  30. from . import state
  31. from .. import util
  32. from ..util import HasMemoized
  33. DEL_ATTR = util.symbol("DEL_ATTR")
  34. class ClassManager(HasMemoized, dict):
  35. """Tracks state information at the class level."""
  36. MANAGER_ATTR = base.DEFAULT_MANAGER_ATTR
  37. STATE_ATTR = base.DEFAULT_STATE_ATTR
  38. _state_setter = staticmethod(util.attrsetter(STATE_ATTR))
  39. expired_attribute_loader = None
  40. "previously known as deferred_scalar_loader"
  41. init_method = None
  42. factory = None
  43. mapper = None
  44. declarative_scan = None
  45. registry = None
  46. @property
  47. @util.deprecated(
  48. "1.4",
  49. message="The ClassManager.deferred_scalar_loader attribute is now "
  50. "named expired_attribute_loader",
  51. )
  52. def deferred_scalar_loader(self):
  53. return self.expired_attribute_loader
  54. @deferred_scalar_loader.setter
  55. @util.deprecated(
  56. "1.4",
  57. message="The ClassManager.deferred_scalar_loader attribute is now "
  58. "named expired_attribute_loader",
  59. )
  60. def deferred_scalar_loader(self, obj):
  61. self.expired_attribute_loader = obj
  62. def __init__(self, class_):
  63. self.class_ = class_
  64. self.info = {}
  65. self.new_init = None
  66. self.local_attrs = {}
  67. self.originals = {}
  68. self._finalized = False
  69. self._bases = [
  70. mgr
  71. for mgr in [
  72. manager_of_class(base)
  73. for base in self.class_.__bases__
  74. if isinstance(base, type)
  75. ]
  76. if mgr is not None
  77. ]
  78. for base_ in self._bases:
  79. self.update(base_)
  80. self.dispatch._events._new_classmanager_instance(class_, self)
  81. for basecls in class_.__mro__:
  82. mgr = manager_of_class(basecls)
  83. if mgr is not None:
  84. self.dispatch._update(mgr.dispatch)
  85. self.manage()
  86. if "__del__" in class_.__dict__:
  87. util.warn(
  88. "__del__() method on class %s will "
  89. "cause unreachable cycles and memory leaks, "
  90. "as SQLAlchemy instrumentation often creates "
  91. "reference cycles. Please remove this method." % class_
  92. )
  93. def _update_state(
  94. self,
  95. finalize=False,
  96. mapper=None,
  97. registry=None,
  98. declarative_scan=None,
  99. expired_attribute_loader=None,
  100. init_method=None,
  101. ):
  102. if mapper:
  103. self.mapper = mapper
  104. if registry:
  105. registry._add_manager(self)
  106. if declarative_scan:
  107. self.declarative_scan = weakref.ref(declarative_scan)
  108. if expired_attribute_loader:
  109. self.expired_attribute_loader = expired_attribute_loader
  110. if init_method:
  111. assert not self._finalized, (
  112. "class is already instrumented, "
  113. "init_method %s can't be applied" % init_method
  114. )
  115. self.init_method = init_method
  116. if not self._finalized:
  117. self.original_init = (
  118. self.init_method
  119. if self.init_method is not None
  120. and self.class_.__init__ is object.__init__
  121. else self.class_.__init__
  122. )
  123. if finalize and not self._finalized:
  124. self._finalize()
  125. def _finalize(self):
  126. if self._finalized:
  127. return
  128. self._finalized = True
  129. self._instrument_init()
  130. _instrumentation_factory.dispatch.class_instrument(self.class_)
  131. def __hash__(self):
  132. return id(self)
  133. def __eq__(self, other):
  134. return other is self
  135. @property
  136. def is_mapped(self):
  137. return "mapper" in self.__dict__
  138. @HasMemoized.memoized_attribute
  139. def _all_key_set(self):
  140. return frozenset(self)
  141. @HasMemoized.memoized_attribute
  142. def _collection_impl_keys(self):
  143. return frozenset(
  144. [attr.key for attr in self.values() if attr.impl.collection]
  145. )
  146. @HasMemoized.memoized_attribute
  147. def _scalar_loader_impls(self):
  148. return frozenset(
  149. [
  150. attr.impl
  151. for attr in self.values()
  152. if attr.impl.accepts_scalar_loader
  153. ]
  154. )
  155. @HasMemoized.memoized_attribute
  156. def _loader_impls(self):
  157. return frozenset([attr.impl for attr in self.values()])
  158. @util.memoized_property
  159. def mapper(self): # noqa: F811
  160. # raises unless self.mapper has been assigned
  161. raise exc.UnmappedClassError(self.class_)
  162. def _all_sqla_attributes(self, exclude=None):
  163. """return an iterator of all classbound attributes that are
  164. implement :class:`.InspectionAttr`.
  165. This includes :class:`.QueryableAttribute` as well as extension
  166. types such as :class:`.hybrid_property` and
  167. :class:`.AssociationProxy`.
  168. """
  169. found = {}
  170. # constraints:
  171. # 1. yield keys in cls.__dict__ order
  172. # 2. if a subclass has the same key as a superclass, include that
  173. # key as part of the ordering of the superclass, because an
  174. # overridden key is usually installed by the mapper which is going
  175. # on a different ordering
  176. # 3. don't use getattr() as this fires off descriptors
  177. for supercls in self.class_.__mro__[0:-1]:
  178. inherits = supercls.__mro__[1]
  179. for key in supercls.__dict__:
  180. found.setdefault(key, supercls)
  181. if key in inherits.__dict__:
  182. continue
  183. val = found[key].__dict__[key]
  184. if (
  185. isinstance(val, interfaces.InspectionAttr)
  186. and val.is_attribute
  187. ):
  188. yield key, val
  189. def _get_class_attr_mro(self, key, default=None):
  190. """return an attribute on the class without tripping it."""
  191. for supercls in self.class_.__mro__:
  192. if key in supercls.__dict__:
  193. return supercls.__dict__[key]
  194. else:
  195. return default
  196. def _attr_has_impl(self, key):
  197. """Return True if the given attribute is fully initialized.
  198. i.e. has an impl.
  199. """
  200. return key in self and self[key].impl is not None
  201. def _subclass_manager(self, cls):
  202. """Create a new ClassManager for a subclass of this ClassManager's
  203. class.
  204. This is called automatically when attributes are instrumented so that
  205. the attributes can be propagated to subclasses against their own
  206. class-local manager, without the need for mappers etc. to have already
  207. pre-configured managers for the full class hierarchy. Mappers
  208. can post-configure the auto-generated ClassManager when needed.
  209. """
  210. return register_class(cls, finalize=False)
  211. def _instrument_init(self):
  212. self.new_init = _generate_init(self.class_, self, self.original_init)
  213. self.install_member("__init__", self.new_init)
  214. @util.memoized_property
  215. def _state_constructor(self):
  216. self.dispatch.first_init(self, self.class_)
  217. return state.InstanceState
  218. def manage(self):
  219. """Mark this instance as the manager for its class."""
  220. setattr(self.class_, self.MANAGER_ATTR, self)
  221. @util.hybridmethod
  222. def manager_getter(self):
  223. return _default_manager_getter
  224. @util.hybridmethod
  225. def state_getter(self):
  226. """Return a (instance) -> InstanceState callable.
  227. "state getter" callables should raise either KeyError or
  228. AttributeError if no InstanceState could be found for the
  229. instance.
  230. """
  231. return _default_state_getter
  232. @util.hybridmethod
  233. def dict_getter(self):
  234. return _default_dict_getter
  235. def instrument_attribute(self, key, inst, propagated=False):
  236. if propagated:
  237. if key in self.local_attrs:
  238. return # don't override local attr with inherited attr
  239. else:
  240. self.local_attrs[key] = inst
  241. self.install_descriptor(key, inst)
  242. self._reset_memoizations()
  243. self[key] = inst
  244. for cls in self.class_.__subclasses__():
  245. manager = self._subclass_manager(cls)
  246. manager.instrument_attribute(key, inst, True)
  247. def subclass_managers(self, recursive):
  248. for cls in self.class_.__subclasses__():
  249. mgr = manager_of_class(cls)
  250. if mgr is not None and mgr is not self:
  251. yield mgr
  252. if recursive:
  253. for m in mgr.subclass_managers(True):
  254. yield m
  255. def post_configure_attribute(self, key):
  256. _instrumentation_factory.dispatch.attribute_instrument(
  257. self.class_, key, self[key]
  258. )
  259. def uninstrument_attribute(self, key, propagated=False):
  260. if key not in self:
  261. return
  262. if propagated:
  263. if key in self.local_attrs:
  264. return # don't get rid of local attr
  265. else:
  266. del self.local_attrs[key]
  267. self.uninstall_descriptor(key)
  268. self._reset_memoizations()
  269. del self[key]
  270. for cls in self.class_.__subclasses__():
  271. manager = manager_of_class(cls)
  272. if manager:
  273. manager.uninstrument_attribute(key, True)
  274. def unregister(self):
  275. """remove all instrumentation established by this ClassManager."""
  276. for key in list(self.originals):
  277. self.uninstall_member(key)
  278. self.mapper = self.dispatch = self.new_init = None
  279. self.info.clear()
  280. for key in list(self):
  281. if key in self.local_attrs:
  282. self.uninstrument_attribute(key)
  283. if self.MANAGER_ATTR in self.class_.__dict__:
  284. delattr(self.class_, self.MANAGER_ATTR)
  285. def install_descriptor(self, key, inst):
  286. if key in (self.STATE_ATTR, self.MANAGER_ATTR):
  287. raise KeyError(
  288. "%r: requested attribute name conflicts with "
  289. "instrumentation attribute of the same name." % key
  290. )
  291. setattr(self.class_, key, inst)
  292. def uninstall_descriptor(self, key):
  293. delattr(self.class_, key)
  294. def install_member(self, key, implementation):
  295. if key in (self.STATE_ATTR, self.MANAGER_ATTR):
  296. raise KeyError(
  297. "%r: requested attribute name conflicts with "
  298. "instrumentation attribute of the same name." % key
  299. )
  300. self.originals.setdefault(key, self.class_.__dict__.get(key, DEL_ATTR))
  301. setattr(self.class_, key, implementation)
  302. def uninstall_member(self, key):
  303. original = self.originals.pop(key, None)
  304. if original is not DEL_ATTR:
  305. setattr(self.class_, key, original)
  306. else:
  307. delattr(self.class_, key)
  308. def instrument_collection_class(self, key, collection_class):
  309. return collections.prepare_instrumentation(collection_class)
  310. def initialize_collection(self, key, state, factory):
  311. user_data = factory()
  312. adapter = collections.CollectionAdapter(
  313. self.get_impl(key), state, user_data
  314. )
  315. return adapter, user_data
  316. def is_instrumented(self, key, search=False):
  317. if search:
  318. return key in self
  319. else:
  320. return key in self.local_attrs
  321. def get_impl(self, key):
  322. return self[key].impl
  323. @property
  324. def attributes(self):
  325. return iter(self.values())
  326. # InstanceState management
  327. def new_instance(self, state=None):
  328. instance = self.class_.__new__(self.class_)
  329. if state is None:
  330. state = self._state_constructor(instance, self)
  331. self._state_setter(instance, state)
  332. return instance
  333. def setup_instance(self, instance, state=None):
  334. if state is None:
  335. state = self._state_constructor(instance, self)
  336. self._state_setter(instance, state)
  337. def teardown_instance(self, instance):
  338. delattr(instance, self.STATE_ATTR)
  339. def _serialize(self, state, state_dict):
  340. return _SerializeManager(state, state_dict)
  341. def _new_state_if_none(self, instance):
  342. """Install a default InstanceState if none is present.
  343. A private convenience method used by the __init__ decorator.
  344. """
  345. if hasattr(instance, self.STATE_ATTR):
  346. return False
  347. elif self.class_ is not instance.__class__ and self.is_mapped:
  348. # this will create a new ClassManager for the
  349. # subclass, without a mapper. This is likely a
  350. # user error situation but allow the object
  351. # to be constructed, so that it is usable
  352. # in a non-ORM context at least.
  353. return self._subclass_manager(
  354. instance.__class__
  355. )._new_state_if_none(instance)
  356. else:
  357. state = self._state_constructor(instance, self)
  358. self._state_setter(instance, state)
  359. return state
  360. def has_state(self, instance):
  361. return hasattr(instance, self.STATE_ATTR)
  362. def has_parent(self, state, key, optimistic=False):
  363. """TODO"""
  364. return self.get_impl(key).hasparent(state, optimistic=optimistic)
  365. def __bool__(self):
  366. """All ClassManagers are non-zero regardless of attribute state."""
  367. return True
  368. __nonzero__ = __bool__
  369. def __repr__(self):
  370. return "<%s of %r at %x>" % (
  371. self.__class__.__name__,
  372. self.class_,
  373. id(self),
  374. )
  375. class _SerializeManager(object):
  376. """Provide serialization of a :class:`.ClassManager`.
  377. The :class:`.InstanceState` uses ``__init__()`` on serialize
  378. and ``__call__()`` on deserialize.
  379. """
  380. def __init__(self, state, d):
  381. self.class_ = state.class_
  382. manager = state.manager
  383. manager.dispatch.pickle(state, d)
  384. def __call__(self, state, inst, state_dict):
  385. state.manager = manager = manager_of_class(self.class_)
  386. if manager is None:
  387. raise exc.UnmappedInstanceError(
  388. inst,
  389. "Cannot deserialize object of type %r - "
  390. "no mapper() has "
  391. "been configured for this class within the current "
  392. "Python process!" % self.class_,
  393. )
  394. elif manager.is_mapped and not manager.mapper.configured:
  395. manager.mapper._check_configure()
  396. # setup _sa_instance_state ahead of time so that
  397. # unpickle events can access the object normally.
  398. # see [ticket:2362]
  399. if inst is not None:
  400. manager.setup_instance(inst, state)
  401. manager.dispatch.unpickle(state, state_dict)
  402. class InstrumentationFactory(object):
  403. """Factory for new ClassManager instances."""
  404. def create_manager_for_cls(self, class_):
  405. assert class_ is not None
  406. assert manager_of_class(class_) is None
  407. # give a more complicated subclass
  408. # a chance to do what it wants here
  409. manager, factory = self._locate_extended_factory(class_)
  410. if factory is None:
  411. factory = ClassManager
  412. manager = factory(class_)
  413. self._check_conflicts(class_, factory)
  414. manager.factory = factory
  415. return manager
  416. def _locate_extended_factory(self, class_):
  417. """Overridden by a subclass to do an extended lookup."""
  418. return None, None
  419. def _check_conflicts(self, class_, factory):
  420. """Overridden by a subclass to test for conflicting factories."""
  421. return
  422. def unregister(self, class_):
  423. manager = manager_of_class(class_)
  424. manager.unregister()
  425. self.dispatch.class_uninstrument(class_)
  426. # this attribute is replaced by sqlalchemy.ext.instrumentation
  427. # when imported.
  428. _instrumentation_factory = InstrumentationFactory()
  429. # these attributes are replaced by sqlalchemy.ext.instrumentation
  430. # when a non-standard InstrumentationManager class is first
  431. # used to instrument a class.
  432. instance_state = _default_state_getter = base.instance_state
  433. instance_dict = _default_dict_getter = base.instance_dict
  434. manager_of_class = _default_manager_getter = base.manager_of_class
  435. def register_class(
  436. class_,
  437. finalize=True,
  438. mapper=None,
  439. registry=None,
  440. declarative_scan=None,
  441. expired_attribute_loader=None,
  442. init_method=None,
  443. ):
  444. """Register class instrumentation.
  445. Returns the existing or newly created class manager.
  446. """
  447. manager = manager_of_class(class_)
  448. if manager is None:
  449. manager = _instrumentation_factory.create_manager_for_cls(class_)
  450. manager._update_state(
  451. mapper=mapper,
  452. registry=registry,
  453. declarative_scan=declarative_scan,
  454. expired_attribute_loader=expired_attribute_loader,
  455. init_method=init_method,
  456. finalize=finalize,
  457. )
  458. return manager
  459. def unregister_class(class_):
  460. """Unregister class instrumentation."""
  461. _instrumentation_factory.unregister(class_)
  462. def is_instrumented(instance, key):
  463. """Return True if the given attribute on the given instance is
  464. instrumented by the attributes package.
  465. This function may be used regardless of instrumentation
  466. applied directly to the class, i.e. no descriptors are required.
  467. """
  468. return manager_of_class(instance.__class__).is_instrumented(
  469. key, search=True
  470. )
  471. def _generate_init(class_, class_manager, original_init):
  472. """Build an __init__ decorator that triggers ClassManager events."""
  473. # TODO: we should use the ClassManager's notion of the
  474. # original '__init__' method, once ClassManager is fixed
  475. # to always reference that.
  476. if original_init is None:
  477. original_init = class_.__init__
  478. # Go through some effort here and don't change the user's __init__
  479. # calling signature, including the unlikely case that it has
  480. # a return value.
  481. # FIXME: need to juggle local names to avoid constructor argument
  482. # clashes.
  483. func_body = """\
  484. def __init__(%(apply_pos)s):
  485. new_state = class_manager._new_state_if_none(%(self_arg)s)
  486. if new_state:
  487. return new_state._initialize_instance(%(apply_kw)s)
  488. else:
  489. return original_init(%(apply_kw)s)
  490. """
  491. func_vars = util.format_argspec_init(original_init, grouped=False)
  492. func_text = func_body % func_vars
  493. if util.py2k:
  494. func = getattr(original_init, "im_func", original_init)
  495. func_defaults = getattr(func, "func_defaults", None)
  496. else:
  497. func_defaults = getattr(original_init, "__defaults__", None)
  498. func_kw_defaults = getattr(original_init, "__kwdefaults__", None)
  499. env = locals().copy()
  500. env["__name__"] = __name__
  501. exec(func_text, env)
  502. __init__ = env["__init__"]
  503. __init__.__doc__ = original_init.__doc__
  504. __init__._sa_original_init = original_init
  505. if func_defaults:
  506. __init__.__defaults__ = func_defaults
  507. if not util.py2k and func_kw_defaults:
  508. __init__.__kwdefaults__ = func_kw_defaults
  509. return __init__