instrumentation.py 21 KB

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