src/pyams_utils/zodb.py
changeset 1 3f89629b9e54
child 10 e87103c49c8a
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/src/pyams_utils/zodb.py	Thu Feb 19 00:46:48 2015 +0100
@@ -0,0 +1,55 @@
+#
+# Copyright (c) 2008-2015 Thierry Florac <tflorac AT ulthar.net>
+# All Rights Reserved.
+#
+# This software is subject to the provisions of the Zope Public License,
+# Version 2.1 (ZPL).  A copy of the ZPL should accompany this distribution.
+# THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED
+# WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+# WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS
+# FOR A PARTICULAR PURPOSE.
+#
+
+__docformat__ = 'restructuredtext'
+
+
+# import standard library
+
+# import interfaces
+from persistent.interfaces import IPersistent
+from transaction.interfaces import ITransactionManager
+from ZODB.interfaces import IConnection
+
+# import packages
+from pyams_utils.adapter import adapter_config
+
+
+@adapter_config(context=IPersistent, provides=IConnection)
+def get_connection(obj):
+    """An adapter which gets a ZODB connection of a persistent object.
+
+    We are assuming the object has a parent if it has been created in
+    this transaction.
+
+    Raises ValueError if it is impossible to get a connection.
+    """
+    cur = obj
+    while not getattr(cur, '_p_jar', None):
+        cur = getattr(cur, '__parent__', None)
+        if cur is None:
+            return None
+    return cur._p_jar
+
+
+# IPersistent adapters copied from zc.twist package
+# also register this for adapting from IConnection
+@adapter_config(context=IPersistent, provides=ITransactionManager)
+def get_transaction_manager(obj):
+    conn = IConnection(obj)  # typically this will be
+                             # zope.app.keyreference.persistent.connectionOfPersistent
+    try:
+        return conn.transaction_manager
+    except AttributeError:
+        return conn._txn_mgr
+        # or else we give up; who knows.  transaction_manager is the more
+        # recent spelling.