|
1 # |
|
2 # Copyright (c) 2008-2015 Thierry Florac <tflorac AT ulthar.net> |
|
3 # All Rights Reserved. |
|
4 # |
|
5 # This software is subject to the provisions of the Zope Public License, |
|
6 # Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution. |
|
7 # THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED |
|
8 # WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED |
|
9 # WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS |
|
10 # FOR A PARTICULAR PURPOSE. |
|
11 # |
|
12 |
|
13 __docformat__ = 'restructuredtext' |
|
14 |
|
15 |
|
16 # import standard library |
|
17 |
|
18 # import interfaces |
|
19 from persistent.interfaces import IPersistent |
|
20 from transaction.interfaces import ITransactionManager |
|
21 from ZODB.interfaces import IConnection |
|
22 |
|
23 # import packages |
|
24 from pyams_utils.adapter import adapter_config |
|
25 |
|
26 |
|
27 @adapter_config(context=IPersistent, provides=IConnection) |
|
28 def get_connection(obj): |
|
29 """An adapter which gets a ZODB connection of a persistent object. |
|
30 |
|
31 We are assuming the object has a parent if it has been created in |
|
32 this transaction. |
|
33 |
|
34 Raises ValueError if it is impossible to get a connection. |
|
35 """ |
|
36 cur = obj |
|
37 while not getattr(cur, '_p_jar', None): |
|
38 cur = getattr(cur, '__parent__', None) |
|
39 if cur is None: |
|
40 return None |
|
41 return cur._p_jar |
|
42 |
|
43 |
|
44 # IPersistent adapters copied from zc.twist package |
|
45 # also register this for adapting from IConnection |
|
46 @adapter_config(context=IPersistent, provides=ITransactionManager) |
|
47 def get_transaction_manager(obj): |
|
48 conn = IConnection(obj) # typically this will be |
|
49 # zope.app.keyreference.persistent.connectionOfPersistent |
|
50 try: |
|
51 return conn.transaction_manager |
|
52 except AttributeError: |
|
53 return conn._txn_mgr |
|
54 # or else we give up; who knows. transaction_manager is the more |
|
55 # recent spelling. |