deprecated_interfaces.py 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487
  1. # orm/deprecated_interfaces.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. from .. import event, util
  8. from .interfaces import EXT_CONTINUE
  9. @util.langhelpers.dependency_for("sqlalchemy.orm.interfaces")
  10. class MapperExtension(object):
  11. """Base implementation for :class:`.Mapper` event hooks.
  12. .. note::
  13. :class:`.MapperExtension` is deprecated. Please
  14. refer to :func:`.event.listen` as well as
  15. :class:`.MapperEvents`.
  16. New extension classes subclass :class:`.MapperExtension` and are specified
  17. using the ``extension`` mapper() argument, which is a single
  18. :class:`.MapperExtension` or a list of such::
  19. from sqlalchemy.orm.interfaces import MapperExtension
  20. class MyExtension(MapperExtension):
  21. def before_insert(self, mapper, connection, instance):
  22. print "instance %s before insert !" % instance
  23. m = mapper(User, users_table, extension=MyExtension())
  24. A single mapper can maintain a chain of ``MapperExtension``
  25. objects. When a particular mapping event occurs, the
  26. corresponding method on each ``MapperExtension`` is invoked
  27. serially, and each method has the ability to halt the chain
  28. from proceeding further::
  29. m = mapper(User, users_table, extension=[ext1, ext2, ext3])
  30. Each ``MapperExtension`` method returns the symbol
  31. EXT_CONTINUE by default. This symbol generally means "move
  32. to the next ``MapperExtension`` for processing". For methods
  33. that return objects like translated rows or new object
  34. instances, EXT_CONTINUE means the result of the method
  35. should be ignored. In some cases it's required for a
  36. default mapper activity to be performed, such as adding a
  37. new instance to a result list.
  38. The symbol EXT_STOP has significance within a chain
  39. of ``MapperExtension`` objects that the chain will be stopped
  40. when this symbol is returned. Like EXT_CONTINUE, it also
  41. has additional significance in some cases that a default
  42. mapper activity will not be performed.
  43. """
  44. @classmethod
  45. def _adapt_instrument_class(cls, self, listener):
  46. cls._adapt_listener_methods(self, listener, ('instrument_class',))
  47. @classmethod
  48. def _adapt_listener(cls, self, listener):
  49. cls._adapt_listener_methods(
  50. self, listener,
  51. (
  52. 'init_instance',
  53. 'init_failed',
  54. 'reconstruct_instance',
  55. 'before_insert',
  56. 'after_insert',
  57. 'before_update',
  58. 'after_update',
  59. 'before_delete',
  60. 'after_delete'
  61. ))
  62. @classmethod
  63. def _adapt_listener_methods(cls, self, listener, methods):
  64. for meth in methods:
  65. me_meth = getattr(MapperExtension, meth)
  66. ls_meth = getattr(listener, meth)
  67. if not util.methods_equivalent(me_meth, ls_meth):
  68. if meth == 'reconstruct_instance':
  69. def go(ls_meth):
  70. def reconstruct(instance, ctx):
  71. ls_meth(self, instance)
  72. return reconstruct
  73. event.listen(self.class_manager, 'load',
  74. go(ls_meth), raw=False, propagate=True)
  75. elif meth == 'init_instance':
  76. def go(ls_meth):
  77. def init_instance(instance, args, kwargs):
  78. ls_meth(self, self.class_,
  79. self.class_manager.original_init,
  80. instance, args, kwargs)
  81. return init_instance
  82. event.listen(self.class_manager, 'init',
  83. go(ls_meth), raw=False, propagate=True)
  84. elif meth == 'init_failed':
  85. def go(ls_meth):
  86. def init_failed(instance, args, kwargs):
  87. util.warn_exception(
  88. ls_meth, self, self.class_,
  89. self.class_manager.original_init,
  90. instance, args, kwargs)
  91. return init_failed
  92. event.listen(self.class_manager, 'init_failure',
  93. go(ls_meth), raw=False, propagate=True)
  94. else:
  95. event.listen(self, "%s" % meth, ls_meth,
  96. raw=False, retval=True, propagate=True)
  97. def instrument_class(self, mapper, class_):
  98. """Receive a class when the mapper is first constructed, and has
  99. applied instrumentation to the mapped class.
  100. The return value is only significant within the ``MapperExtension``
  101. chain; the parent mapper's behavior isn't modified by this method.
  102. """
  103. return EXT_CONTINUE
  104. def init_instance(self, mapper, class_, oldinit, instance, args, kwargs):
  105. """Receive an instance when its constructor is called.
  106. This method is only called during a userland construction of
  107. an object. It is not called when an object is loaded from the
  108. database.
  109. The return value is only significant within the ``MapperExtension``
  110. chain; the parent mapper's behavior isn't modified by this method.
  111. """
  112. return EXT_CONTINUE
  113. def init_failed(self, mapper, class_, oldinit, instance, args, kwargs):
  114. """Receive an instance when its constructor has been called,
  115. and raised an exception.
  116. This method is only called during a userland construction of
  117. an object. It is not called when an object is loaded from the
  118. database.
  119. The return value is only significant within the ``MapperExtension``
  120. chain; the parent mapper's behavior isn't modified by this method.
  121. """
  122. return EXT_CONTINUE
  123. def reconstruct_instance(self, mapper, instance):
  124. """Receive an object instance after it has been created via
  125. ``__new__``, and after initial attribute population has
  126. occurred.
  127. This typically occurs when the instance is created based on
  128. incoming result rows, and is only called once for that
  129. instance's lifetime.
  130. Note that during a result-row load, this method is called upon
  131. the first row received for this instance. Note that some
  132. attributes and collections may or may not be loaded or even
  133. initialized, depending on what's present in the result rows.
  134. The return value is only significant within the ``MapperExtension``
  135. chain; the parent mapper's behavior isn't modified by this method.
  136. """
  137. return EXT_CONTINUE
  138. def before_insert(self, mapper, connection, instance):
  139. """Receive an object instance before that instance is inserted
  140. into its table.
  141. This is a good place to set up primary key values and such
  142. that aren't handled otherwise.
  143. Column-based attributes can be modified within this method
  144. which will result in the new value being inserted. However
  145. *no* changes to the overall flush plan can be made, and
  146. manipulation of the ``Session`` will not have the desired effect.
  147. To manipulate the ``Session`` within an extension, use
  148. ``SessionExtension``.
  149. The return value is only significant within the ``MapperExtension``
  150. chain; the parent mapper's behavior isn't modified by this method.
  151. """
  152. return EXT_CONTINUE
  153. def after_insert(self, mapper, connection, instance):
  154. """Receive an object instance after that instance is inserted.
  155. The return value is only significant within the ``MapperExtension``
  156. chain; the parent mapper's behavior isn't modified by this method.
  157. """
  158. return EXT_CONTINUE
  159. def before_update(self, mapper, connection, instance):
  160. """Receive an object instance before that instance is updated.
  161. Note that this method is called for all instances that are marked as
  162. "dirty", even those which have no net changes to their column-based
  163. attributes. An object is marked as dirty when any of its column-based
  164. attributes have a "set attribute" operation called or when any of its
  165. collections are modified. If, at update time, no column-based
  166. attributes have any net changes, no UPDATE statement will be issued.
  167. This means that an instance being sent to before_update is *not* a
  168. guarantee that an UPDATE statement will be issued (although you can
  169. affect the outcome here).
  170. To detect if the column-based attributes on the object have net
  171. changes, and will therefore generate an UPDATE statement, use
  172. ``object_session(instance).is_modified(instance,
  173. include_collections=False)``.
  174. Column-based attributes can be modified within this method
  175. which will result in the new value being updated. However
  176. *no* changes to the overall flush plan can be made, and
  177. manipulation of the ``Session`` will not have the desired effect.
  178. To manipulate the ``Session`` within an extension, use
  179. ``SessionExtension``.
  180. The return value is only significant within the ``MapperExtension``
  181. chain; the parent mapper's behavior isn't modified by this method.
  182. """
  183. return EXT_CONTINUE
  184. def after_update(self, mapper, connection, instance):
  185. """Receive an object instance after that instance is updated.
  186. The return value is only significant within the ``MapperExtension``
  187. chain; the parent mapper's behavior isn't modified by this method.
  188. """
  189. return EXT_CONTINUE
  190. def before_delete(self, mapper, connection, instance):
  191. """Receive an object instance before that instance is deleted.
  192. Note that *no* changes to the overall flush plan can be made
  193. here; and manipulation of the ``Session`` will not have the
  194. desired effect. To manipulate the ``Session`` within an
  195. extension, use ``SessionExtension``.
  196. The return value is only significant within the ``MapperExtension``
  197. chain; the parent mapper's behavior isn't modified by this method.
  198. """
  199. return EXT_CONTINUE
  200. def after_delete(self, mapper, connection, instance):
  201. """Receive an object instance after that instance is deleted.
  202. The return value is only significant within the ``MapperExtension``
  203. chain; the parent mapper's behavior isn't modified by this method.
  204. """
  205. return EXT_CONTINUE
  206. @util.langhelpers.dependency_for("sqlalchemy.orm.interfaces")
  207. class SessionExtension(object):
  208. """Base implementation for :class:`.Session` event hooks.
  209. .. note::
  210. :class:`.SessionExtension` is deprecated. Please
  211. refer to :func:`.event.listen` as well as
  212. :class:`.SessionEvents`.
  213. Subclasses may be installed into a :class:`.Session` (or
  214. :class:`.sessionmaker`) using the ``extension`` keyword
  215. argument::
  216. from sqlalchemy.orm.interfaces import SessionExtension
  217. class MySessionExtension(SessionExtension):
  218. def before_commit(self, session):
  219. print "before commit!"
  220. Session = sessionmaker(extension=MySessionExtension())
  221. The same :class:`.SessionExtension` instance can be used
  222. with any number of sessions.
  223. """
  224. @classmethod
  225. def _adapt_listener(cls, self, listener):
  226. for meth in [
  227. 'before_commit',
  228. 'after_commit',
  229. 'after_rollback',
  230. 'before_flush',
  231. 'after_flush',
  232. 'after_flush_postexec',
  233. 'after_begin',
  234. 'after_attach',
  235. 'after_bulk_update',
  236. 'after_bulk_delete',
  237. ]:
  238. me_meth = getattr(SessionExtension, meth)
  239. ls_meth = getattr(listener, meth)
  240. if not util.methods_equivalent(me_meth, ls_meth):
  241. event.listen(self, meth, getattr(listener, meth))
  242. def before_commit(self, session):
  243. """Execute right before commit is called.
  244. Note that this may not be per-flush if a longer running
  245. transaction is ongoing."""
  246. def after_commit(self, session):
  247. """Execute after a commit has occurred.
  248. Note that this may not be per-flush if a longer running
  249. transaction is ongoing."""
  250. def after_rollback(self, session):
  251. """Execute after a rollback has occurred.
  252. Note that this may not be per-flush if a longer running
  253. transaction is ongoing."""
  254. def before_flush(self, session, flush_context, instances):
  255. """Execute before flush process has started.
  256. `instances` is an optional list of objects which were passed to
  257. the ``flush()`` method. """
  258. def after_flush(self, session, flush_context):
  259. """Execute after flush has completed, but before commit has been
  260. called.
  261. Note that the session's state is still in pre-flush, i.e. 'new',
  262. 'dirty', and 'deleted' lists still show pre-flush state as well
  263. as the history settings on instance attributes."""
  264. def after_flush_postexec(self, session, flush_context):
  265. """Execute after flush has completed, and after the post-exec
  266. state occurs.
  267. This will be when the 'new', 'dirty', and 'deleted' lists are in
  268. their final state. An actual commit() may or may not have
  269. occurred, depending on whether or not the flush started its own
  270. transaction or participated in a larger transaction. """
  271. def after_begin(self, session, transaction, connection):
  272. """Execute after a transaction is begun on a connection
  273. `transaction` is the SessionTransaction. This method is called
  274. after an engine level transaction is begun on a connection. """
  275. def after_attach(self, session, instance):
  276. """Execute after an instance is attached to a session.
  277. This is called after an add, delete or merge. """
  278. def after_bulk_update(self, session, query, query_context, result):
  279. """Execute after a bulk update operation to the session.
  280. This is called after a session.query(...).update()
  281. `query` is the query object that this update operation was
  282. called on. `query_context` was the query context object.
  283. `result` is the result object returned from the bulk operation.
  284. """
  285. def after_bulk_delete(self, session, query, query_context, result):
  286. """Execute after a bulk delete operation to the session.
  287. This is called after a session.query(...).delete()
  288. `query` is the query object that this delete operation was
  289. called on. `query_context` was the query context object.
  290. `result` is the result object returned from the bulk operation.
  291. """
  292. @util.langhelpers.dependency_for("sqlalchemy.orm.interfaces")
  293. class AttributeExtension(object):
  294. """Base implementation for :class:`.AttributeImpl` event hooks, events
  295. that fire upon attribute mutations in user code.
  296. .. note::
  297. :class:`.AttributeExtension` is deprecated. Please
  298. refer to :func:`.event.listen` as well as
  299. :class:`.AttributeEvents`.
  300. :class:`.AttributeExtension` is used to listen for set,
  301. remove, and append events on individual mapped attributes.
  302. It is established on an individual mapped attribute using
  303. the `extension` argument, available on
  304. :func:`.column_property`, :func:`.relationship`, and
  305. others::
  306. from sqlalchemy.orm.interfaces import AttributeExtension
  307. from sqlalchemy.orm import mapper, relationship, column_property
  308. class MyAttrExt(AttributeExtension):
  309. def append(self, state, value, initiator):
  310. print "append event !"
  311. return value
  312. def set(self, state, value, oldvalue, initiator):
  313. print "set event !"
  314. return value
  315. mapper(SomeClass, sometable, properties={
  316. 'foo':column_property(sometable.c.foo, extension=MyAttrExt()),
  317. 'bar':relationship(Bar, extension=MyAttrExt())
  318. })
  319. Note that the :class:`.AttributeExtension` methods
  320. :meth:`~.AttributeExtension.append` and
  321. :meth:`~.AttributeExtension.set` need to return the
  322. ``value`` parameter. The returned value is used as the
  323. effective value, and allows the extension to change what is
  324. ultimately persisted.
  325. AttributeExtension is assembled within the descriptors associated
  326. with a mapped class.
  327. """
  328. active_history = True
  329. """indicates that the set() method would like to receive the 'old' value,
  330. even if it means firing lazy callables.
  331. Note that ``active_history`` can also be set directly via
  332. :func:`.column_property` and :func:`.relationship`.
  333. """
  334. @classmethod
  335. def _adapt_listener(cls, self, listener):
  336. event.listen(self, 'append', listener.append,
  337. active_history=listener.active_history,
  338. raw=True, retval=True)
  339. event.listen(self, 'remove', listener.remove,
  340. active_history=listener.active_history,
  341. raw=True, retval=True)
  342. event.listen(self, 'set', listener.set,
  343. active_history=listener.active_history,
  344. raw=True, retval=True)
  345. def append(self, state, value, initiator):
  346. """Receive a collection append event.
  347. The returned value will be used as the actual value to be
  348. appended.
  349. """
  350. return value
  351. def remove(self, state, value, initiator):
  352. """Receive a remove event.
  353. No return value is defined.
  354. """
  355. pass
  356. def set(self, state, value, oldvalue, initiator):
  357. """Receive a set event.
  358. The returned value will be used as the actual value to be
  359. set.
  360. """
  361. return value