instrumentation.py 18 KB

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