Commit 093951f1 authored by Tim Peters's avatar Tim Peters

__builtin__.get_transaction() is officially deprecated in ZODB 3.4.

Got rid of it in the Zope source.  The remaining instances are in
code stitched in from ZODB.  Those will go away by magic when
ZODB 3.4 gets stitched in.
parent 1895fa10
...@@ -73,4 +73,5 @@ Using the Medusa Monitor ...@@ -73,4 +73,5 @@ Using the Medusa Monitor
To commit changes you make, before exiting, you may have to do To commit changes you make, before exiting, you may have to do
another bit of magic: another bit of magic:
>>> get_transaction().commit() >>> import transaction
>>> transaction.commit()
...@@ -660,7 +660,7 @@ Zope History ...@@ -660,7 +660,7 @@ Zope History
has executed, it has the same effect as the "old" behavior inasmuch has executed, it has the same effect as the "old" behavior inasmuch
as no inconsistent state will ever be committed to the database as no inconsistent state will ever be committed to the database
as a result of this behavior unless someone really wants to shoot as a result of this behavior unless someone really wants to shoot
themselves by calling "get_transaction().commit()" during error themselves by calling "transaction.commit()" during error
handling code. handling code.
- TransientObjects (session data objects) may have lost state at - TransientObjects (session data objects) may have lost state at
...@@ -6538,7 +6538,7 @@ Zope History ...@@ -6538,7 +6538,7 @@ Zope History
- Subtransactions have been added (instead of temporary - Subtransactions have been added (instead of temporary
versions). If a true argument is given in a transaction commit versions). If a true argument is given in a transaction commit
or abort call (e.g. 'get_transaction().commit(1)'), then or abort call (e.g. 'transaction.commit(1)'), then
the commit or abort applies to a subtransaction of the the commit or abort applies to a subtransaction of the
current transaction. This is useful in a number of ways, current transaction. This is useful in a number of ways,
including: including:
......
...@@ -221,7 +221,7 @@ Zope Unit Testing ...@@ -221,7 +221,7 @@ Zope Unit Testing
app.acl_users.manage_addUser(<parameters>) app.acl_users.manage_addUser(<parameters>)
- a transaction will not be committed to the Zope object database - a transaction will not be committed to the Zope object database
until you call the global function "get_transaction().commit()", until you call "transaction.commit()",
so changes made to the ZODB are not visible to succeeding tests so changes made to the ZODB are not visible to succeeding tests
unless that function is called explicitly. unless that function is called explicitly.
......
...@@ -104,7 +104,7 @@ class TestBindings(unittest.TestCase): ...@@ -104,7 +104,7 @@ class TestBindings(unittest.TestCase):
from Testing.ZODButil import cleanDB from Testing.ZODButil import cleanDB
from AccessControl.SecurityManagement import noSecurityManager from AccessControl.SecurityManagement import noSecurityManager
noSecurityManager() noSecurityManager()
get_transaction().abort() transaction.abort()
self.connection.close() self.connection.close()
self.db.close() self.db.close()
cleanDB() cleanDB()
......
...@@ -57,7 +57,7 @@ class UserFolderTests(unittest.TestCase): ...@@ -57,7 +57,7 @@ class UserFolderTests(unittest.TestCase):
def tearDown(self): def tearDown(self):
noSecurityManager() noSecurityManager()
get_transaction().abort() transaction.abort()
self.app._p_jar.close() self.app._p_jar.close()
def login(self, name): def login(self, name):
......
...@@ -38,6 +38,8 @@ import os, re, zlib, marshal, cPickle ...@@ -38,6 +38,8 @@ import os, re, zlib, marshal, cPickle
from cgi import escape from cgi import escape
from urllib import quote from urllib import quote
import transaction
import Globals, OFS.Folder, OFS.SimpleItem, Acquisition, Products import Globals, OFS.Folder, OFS.SimpleItem, Acquisition, Products
import ZClasses, AccessControl.Owned import ZClasses, AccessControl.Owned
from OFS.Folder import Folder from OFS.Folder import Folder
...@@ -580,7 +582,7 @@ def initializeProduct(productp, name, home, app): ...@@ -580,7 +582,7 @@ def initializeProduct(productp, name, home, app):
'help': ('OFSP','Product_Refresh.stx')},) 'help': ('OFSP','Product_Refresh.stx')},)
if not doInstall(): if not doInstall():
get_transaction().abort() transaction.abort()
return product return product
# Give the ZClass fixup code in Application # Give the ZClass fixup code in Application
......
...@@ -320,7 +320,7 @@ def autoRefresh(jar): ...@@ -320,7 +320,7 @@ def autoRefresh(jar):
finishAutoRefresh(jar, auto_refresh_ids) finishAutoRefresh(jar, auto_refresh_ids)
from ZODB import Connection from ZODB import Connection
Connection.resetCaches() Connection.resetCaches()
get_transaction().commit() transaction.commit()
jar._resetCache() jar._resetCache()
transaction.begin() transaction.begin()
......
...@@ -19,6 +19,7 @@ from AccessControl import getSecurityManager ...@@ -19,6 +19,7 @@ from AccessControl import getSecurityManager
from DateTime import DateTime from DateTime import DateTime
import Globals, ExtensionClass import Globals, ExtensionClass
from ZopeUndo.Prefix import Prefix from ZopeUndo.Prefix import Prefix
import transaction
class UndoSupport(ExtensionClass.Base): class UndoSupport(ExtensionClass.Base):
...@@ -123,7 +124,7 @@ class UndoSupport(ExtensionClass.Base): ...@@ -123,7 +124,7 @@ class UndoSupport(ExtensionClass.Base):
for tid in transaction_info: for tid in transaction_info:
tid=tid.split() tid=tid.split()
if tid: if tid:
get_transaction().note("Undo %s" % ''.join(tid[1:])) transaction.get().note("Undo %s" % ''.join(tid[1:]))
tid=decode64(tid[0]) tid=decode64(tid[0])
undo(tid) undo(tid)
......
...@@ -35,6 +35,7 @@ from HelpSys.HelpSys import HelpSys ...@@ -35,6 +35,7 @@ from HelpSys.HelpSys import HelpSys
from Acquisition import aq_base from Acquisition import aq_base
from App.Product import doInstall from App.Product import doInstall
from App.config import getConfiguration from App.config import getConfiguration
import transaction
class Application(Globals.ApplicationDefaultPermissions, class Application(Globals.ApplicationDefaultPermissions,
ZDOM.Root, Folder.Folder, ZDOM.Root, Folder.Folder,
...@@ -82,7 +83,7 @@ class Application(Globals.ApplicationDefaultPermissions, ...@@ -82,7 +83,7 @@ class Application(Globals.ApplicationDefaultPermissions,
cpl=ApplicationManager() cpl=ApplicationManager()
cpl._init() cpl._init()
self._setObject('Control_Panel', cpl) self._setObject('Control_Panel', cpl)
get_transaction().note("Created Zope Application") transaction.get().note("Created Zope Application")
def id(self): def id(self):
try: return self.REQUEST['SCRIPT_NAME'][1:] try: return self.REQUEST['SCRIPT_NAME'][1:]
...@@ -289,8 +290,8 @@ class AppInitializer: ...@@ -289,8 +290,8 @@ class AppInitializer:
return self.app[0] return self.app[0]
def commit(self, note): def commit(self, note):
get_transaction().note(note) transaction.get().note(note)
get_transaction().commit() transaction.commit()
def initialize(self): def initialize(self):
app = self.getApp() app = self.getApp()
...@@ -533,13 +534,13 @@ class AppInitializer: ...@@ -533,13 +534,13 @@ class AppInitializer:
did_fixups=1 did_fixups=1
LOG('Zope', INFO, LOG('Zope', INFO,
'The global ZClass registry has successfully been rebuilt.') 'The global ZClass registry has successfully been rebuilt.')
get_transaction().note('Rebuilt global product registry') transaction.get().note('Rebuilt global product registry')
get_transaction().commit() transaction.commit()
except: except:
bad_things=1 bad_things=1
LOG('Zope', ERROR, 'The attempt to rebuild the registry failed.', LOG('Zope', ERROR, 'The attempt to rebuild the registry failed.',
error=sys.exc_info()) error=sys.exc_info())
get_transaction().abort() transaction.abort()
# Now we need to see if any (disk-based) products were installed # Now we need to see if any (disk-based) products were installed
# during intialization. If so (and the registry has no errors), # during intialization. If so (and the registry has no errors),
...@@ -566,7 +567,7 @@ class AppInitializer: ...@@ -566,7 +567,7 @@ class AppInitializer:
('Attempt to fixup ZClass dependencies after ' ('Attempt to fixup ZClass dependencies after '
'detecting an updated disk-based product failed.'), 'detecting an updated disk-based product failed.'),
error=sys.exc_info()) error=sys.exc_info())
get_transaction().abort() transaction.abort()
def install_products(self): def install_products(self):
app = self.getApp() app = self.getApp()
...@@ -588,8 +589,8 @@ def install_products(app): ...@@ -588,8 +589,8 @@ def install_products(app):
debug_mode = App.config.getConfiguration().debug_mode debug_mode = App.config.getConfiguration().debug_mode
get_transaction().note('Prior to product installs') transaction.get().note('Prior to product installs')
get_transaction().commit() transaction.commit()
products = get_products() products = get_products()
...@@ -799,16 +800,16 @@ def install_product(app, product_dir, product_name, meta_types, ...@@ -799,16 +800,16 @@ def install_product(app, product_dir, product_name, meta_types,
list(Folder.Folder.__ac_permissions__)+new_permissions) list(Folder.Folder.__ac_permissions__)+new_permissions)
if not doInstall(): if not doInstall():
get_transaction().abort() transaction().abort()
else: else:
get_transaction().note('Installed product '+product_name) transaction.get().note('Installed product '+product_name)
get_transaction().commit() transaction.commit()
except: except:
if log_exc: if log_exc:
LOG('Zope',ERROR,'Couldn\'t install %s' % product_name, LOG('Zope',ERROR,'Couldn\'t install %s' % product_name,
error=sys.exc_info()) error=sys.exc_info())
get_transaction().abort() transaction.abort()
if raise_exc: if raise_exc:
raise raise
...@@ -845,15 +846,15 @@ def install_standards(app): ...@@ -845,15 +846,15 @@ def install_standards(app):
#setattr(Application, fn, ob) #setattr(Application, fn, ob)
if wrote: if wrote:
app._standard_objects_have_been_added = 1 app._standard_objects_have_been_added = 1
get_transaction().note('Installed standard objects') transaction.get().note('Installed standard objects')
get_transaction().commit() transaction.commit()
def reinstall_product(app, product_name): def reinstall_product(app, product_name):
folder_permissions = get_folder_permissions() folder_permissions = get_folder_permissions()
meta_types=[] meta_types=[]
get_transaction().note('Prior to product reinstall') transaction.get().note('Prior to product reinstall')
get_transaction().commit() transaction.commit()
for product_dir in Products.__path__: for product_dir in Products.__path__:
product_names=os.listdir(product_dir) product_names=os.listdir(product_dir)
......
...@@ -27,6 +27,8 @@ from zExceptions import Unauthorized, BadRequest ...@@ -27,6 +27,8 @@ from zExceptions import Unauthorized, BadRequest
from webdav.Lockable import ResourceLockedError from webdav.Lockable import ResourceLockedError
from cgi import escape from cgi import escape
import transaction
CopyError='Copy Error' CopyError='Copy Error'
copy_re = re.compile('^copy([0-9]*)_of_(.*)') copy_re = re.compile('^copy([0-9]*)_of_(.*)')
...@@ -443,7 +445,7 @@ class CopySource(ExtensionClass.Base): ...@@ -443,7 +445,7 @@ class CopySource(ExtensionClass.Base):
# 1) Make sure the data about to be exported is current # 1) Make sure the data about to be exported is current
# 2) Ensure self._p_jar and container._p_jar are set even if # 2) Ensure self._p_jar and container._p_jar are set even if
# either one is a new object # either one is a new object
get_transaction().commit(1) transaction.commit(1)
if self._p_jar is None: if self._p_jar is None:
raise CopyError, ( raise CopyError, (
......
...@@ -34,6 +34,7 @@ from ZPublisher.HTTPRequest import FileUpload ...@@ -34,6 +34,7 @@ from ZPublisher.HTTPRequest import FileUpload
from ZPublisher.Iterators import filestream_iterator from ZPublisher.Iterators import filestream_iterator
from zExceptions import Redirect from zExceptions import Redirect
from cgi import escape from cgi import escape
import transaction
StringType=type('') StringType=type('')
manage_addFileForm=DTMLFile('dtml/imageAdd', globals(),Kind='File',kind='file') manage_addFileForm=DTMLFile('dtml/imageAdd', globals(),Kind='File',kind='file')
...@@ -509,7 +510,7 @@ class File(Persistent, Implicit, PropertyManager, ...@@ -509,7 +510,7 @@ class File(Persistent, Implicit, PropertyManager,
# Make sure we have an _p_jar, even if we are a new object, by # Make sure we have an _p_jar, even if we are a new object, by
# doing a sub-transaction commit. # doing a sub-transaction commit.
get_transaction().commit(1) transaction.commit(1)
if self._p_jar is None: if self._p_jar is None:
# Ugh # Ugh
...@@ -535,7 +536,7 @@ class File(Persistent, Implicit, PropertyManager, ...@@ -535,7 +536,7 @@ class File(Persistent, Implicit, PropertyManager,
data.next = next data.next = next
# Save the object so that we can release its memory. # Save the object so that we can release its memory.
get_transaction().commit(1) transaction.commit(1)
data._p_deactivate() data._p_deactivate()
# The object should be assigned an oid and be a ghost. # The object should be assigned an oid and be a ghost.
assert data._p_oid is not None assert data._p_oid is not None
......
...@@ -87,7 +87,7 @@ class CopySupportTestBase(unittest.TestCase): ...@@ -87,7 +87,7 @@ class CopySupportTestBase(unittest.TestCase):
# Hack, we need a _p_mtime for the file, so we make sure that it # Hack, we need a _p_mtime for the file, so we make sure that it
# has one. We use a subtransaction, which means we can rollback # has one. We use a subtransaction, which means we can rollback
# later and pretend we didn't touch the ZODB. # later and pretend we didn't touch the ZODB.
get_transaction().commit() transaction.commit()
except: except:
self.connection.close() self.connection.close()
raise raise
...@@ -97,7 +97,7 @@ class CopySupportTestBase(unittest.TestCase): ...@@ -97,7 +97,7 @@ class CopySupportTestBase(unittest.TestCase):
def _cleanApp( self ): def _cleanApp( self ):
get_transaction().abort() transaction.abort()
self.app._p_jar.sync() self.app._p_jar.sync()
self.connection.close() self.connection.close()
del self.app del self.app
......
...@@ -100,7 +100,7 @@ class FileTests(unittest.TestCase): ...@@ -100,7 +100,7 @@ class FileTests(unittest.TestCase):
setattr(self.app, ZCM_MANAGERS, ('dcm',)) setattr(self.app, ZCM_MANAGERS, ('dcm',))
# Hack, we need a _p_mtime for the file, so we make sure that it # Hack, we need a _p_mtime for the file, so we make sure that it
# has one. # has one.
get_transaction().commit() transaction.commit()
except: except:
self.connection.close() self.connection.close()
raise raise
...@@ -109,7 +109,7 @@ class FileTests(unittest.TestCase): ...@@ -109,7 +109,7 @@ class FileTests(unittest.TestCase):
def tearDown( self ): def tearDown( self ):
del self.file del self.file
get_transaction().abort() transaction.abort()
self.connection.close() self.connection.close()
del self.app del self.app
del self.responseOut del self.responseOut
......
...@@ -14,6 +14,7 @@ import os, sys, unittest ...@@ -14,6 +14,7 @@ import os, sys, unittest
import string, random, cStringIO, time, re import string, random, cStringIO, time, re
import ZODB import ZODB
import transaction
from OFS.Application import Application from OFS.Application import Application
from OFS.Folder import manage_addFolder from OFS.Folder import manage_addFolder
from OFS.Image import manage_addFile from OFS.Image import manage_addFile
...@@ -73,7 +74,7 @@ class TestRequestRange(unittest.TestCase): ...@@ -73,7 +74,7 @@ class TestRequestRange(unittest.TestCase):
# Hack, we need a _p_mtime for the file, so we make sure that it # Hack, we need a _p_mtime for the file, so we make sure that it
# has one. We use a subtransaction, which means we can rollback # has one. We use a subtransaction, which means we can rollback
# later and pretend we didn't touch the ZODB. # later and pretend we didn't touch the ZODB.
get_transaction().commit() transaction.commit()
except: except:
self.connection.close() self.connection.close()
raise raise
...@@ -81,7 +82,7 @@ class TestRequestRange(unittest.TestCase): ...@@ -81,7 +82,7 @@ class TestRequestRange(unittest.TestCase):
def tearDown(self): def tearDown(self):
try: self.app._delObject(TESTFOLDER_NAME) try: self.app._delObject(TESTFOLDER_NAME)
except AttributeError: pass except AttributeError: pass
get_transaction().abort() transaction.abort()
self.app._p_jar.sync() self.app._p_jar.sync()
self.connection.close() self.connection.close()
self.app = None self.app = None
......
...@@ -16,6 +16,7 @@ import os, sys, unittest ...@@ -16,6 +16,7 @@ import os, sys, unittest
import string, cStringIO, re import string, cStringIO, re
import ZODB, Acquisition, transaction import ZODB, Acquisition, transaction
import transaction
from Acquisition import aq_base from Acquisition import aq_base
from OFS.Application import Application from OFS.Application import Application
from OFS.Folder import manage_addFolder from OFS.Folder import manage_addFolder
...@@ -137,7 +138,7 @@ class TestTraverse( unittest.TestCase ): ...@@ -137,7 +138,7 @@ class TestTraverse( unittest.TestCase ):
# Hack, we need a _p_mtime for the file, so we make sure that it # Hack, we need a _p_mtime for the file, so we make sure that it
# has one. We use a subtransaction, which means we can rollback # has one. We use a subtransaction, which means we can rollback
# later and pretend we didn't touch the ZODB. # later and pretend we didn't touch the ZODB.
get_transaction().commit() transaction.commit()
except: except:
self.connection.close() self.connection.close()
raise raise
...@@ -154,7 +155,7 @@ class TestTraverse( unittest.TestCase ): ...@@ -154,7 +155,7 @@ class TestTraverse( unittest.TestCase ):
del self.oldPolicy del self.oldPolicy
del self.policy del self.policy
del self.folder1 del self.folder1
get_transaction().abort() transaction.abort()
self.app._p_jar.sync() self.app._p_jar.sync()
self.connection.close() self.connection.close()
del self.app del self.app
......
...@@ -25,6 +25,8 @@ from App.Dialogs import MessageDialog ...@@ -25,6 +25,8 @@ from App.Dialogs import MessageDialog
from OFS.ObjectManager import BeforeDeleteException from OFS.ObjectManager import BeforeDeleteException
from cgi import escape from cgi import escape
import transaction
class VersionException(BeforeDeleteException): pass class VersionException(BeforeDeleteException): pass
manage_addVersionForm=Globals.DTMLFile('dtml/versionAdd', globals()) manage_addVersionForm=Globals.DTMLFile('dtml/versionAdd', globals())
...@@ -154,7 +156,7 @@ class Version(Persistent,Implicit,RoleManager,Item): ...@@ -154,7 +156,7 @@ class Version(Persistent,Implicit,RoleManager,Item):
s=self.cookie s=self.cookie
d=self._p_jar.getVersion() d=self._p_jar.getVersion()
if d==s: d='' if d==s: d=''
get_transaction().note(remark) transaction.get().note(remark)
db.commitVersion(s, d) db.commitVersion(s, d)
if REQUEST is not None: if REQUEST is not None:
...@@ -168,7 +170,7 @@ class Version(Persistent,Implicit,RoleManager,Item): ...@@ -168,7 +170,7 @@ class Version(Persistent,Implicit,RoleManager,Item):
Globals.VersionBase[self.cookie].abort() Globals.VersionBase[self.cookie].abort()
else: else:
# ZODB 3 # ZODB 3
get_transaction().note(remark) transaction.get().note(remark)
db.abortVersion(self.cookie) db.abortVersion(self.cookie)
if REQUEST is not None: if REQUEST is not None:
......
...@@ -24,7 +24,7 @@ class ZPTRegressions(unittest.TestCase): ...@@ -24,7 +24,7 @@ class ZPTRegressions(unittest.TestCase):
self.text = 'text of page template' self.text = 'text of page template'
def tearDown(self): def tearDown(self):
get_transaction().abort() transaction.abort()
self.app._p_jar.close() self.app._p_jar.close()
def testAddWithParams(self): def testAddWithParams(self):
......
...@@ -21,6 +21,8 @@ def log_write(subsystem, severity, summary, detail, error): ...@@ -21,6 +21,8 @@ def log_write(subsystem, severity, summary, detail, error):
import ZODB import ZODB
from ZODB.MappingStorage import MappingStorage from ZODB.MappingStorage import MappingStorage
import transaction
from Products.PluginIndexes.TextIndex import TextIndex from Products.PluginIndexes.TextIndex import TextIndex
from Products.PluginIndexes.TextIndex import GlobbingLexicon from Products.PluginIndexes.TextIndex import GlobbingLexicon
...@@ -61,7 +63,7 @@ class Tests(unittest.TestCase): ...@@ -61,7 +63,7 @@ class Tests(unittest.TestCase):
self.jar = jar self.jar = jar
if not jar.root().has_key('index'): if not jar.root().has_key('index'):
jar.root()['index'] = TextIndex.TextIndex('text') jar.root()['index'] = TextIndex.TextIndex('text')
get_transaction().commit() transaction.commit()
return jar.root()['index'] return jar.root()['index']
def dbclose(self): def dbclose(self):
...@@ -69,7 +71,7 @@ class Tests(unittest.TestCase): ...@@ -69,7 +71,7 @@ class Tests(unittest.TestCase):
self.jar = None self.jar = None
def tearDown(self): def tearDown(self):
get_transaction().abort() transaction.abort()
if self.jar is not None: if self.jar is not None:
self.dbclose() self.dbclose()
if self.db is not None: if self.db is not None:
...@@ -90,11 +92,11 @@ class Tests(unittest.TestCase): ...@@ -90,11 +92,11 @@ class Tests(unittest.TestCase):
self.doc.text='this is the time, when all good zopes' self.doc.text='this is the time, when all good zopes'
index.index_object(0, self.doc) index.index_object(0, self.doc)
get_transaction().commit() transaction.commit()
self.doc.text='time waits for no one' self.doc.text='time waits for no one'
index.index_object(1, self.doc) index.index_object(1, self.doc)
get_transaction().commit() transaction.commit()
self.dbclose() self.dbclose()
index=self.dbopen() index=self.dbopen()
...@@ -116,19 +118,19 @@ class Tests(unittest.TestCase): ...@@ -116,19 +118,19 @@ class Tests(unittest.TestCase):
self.doc.text='this is the time, when all good zopes' self.doc.text='this is the time, when all good zopes'
index.index_object(0, self.doc) index.index_object(0, self.doc)
get_transaction().commit() transaction.commit()
self.doc.text='time waits for no one' self.doc.text='time waits for no one'
index.index_object(1, self.doc) index.index_object(1, self.doc)
get_transaction().commit() transaction.commit()
self.doc.text='the next task is to test' self.doc.text='the next task is to test'
index.index_object(3, self.doc) index.index_object(3, self.doc)
get_transaction().commit() transaction.commit()
self.doc.text='time time' self.doc.text='time time'
index.index_object(2, self.doc) index.index_object(2, self.doc)
get_transaction().commit() transaction.commit()
self.dbclose() self.dbclose()
index=self.dbopen() index=self.dbopen()
...@@ -166,7 +168,7 @@ class Tests(unittest.TestCase): ...@@ -166,7 +168,7 @@ class Tests(unittest.TestCase):
for i in range(len(self.sample_texts)): for i in range(len(self.sample_texts)):
self.doc.text=self.sample_texts[i] self.doc.text=self.sample_texts[i]
index.index_object(i, self.doc) index.index_object(i, self.doc)
get_transaction().commit() transaction.commit()
self.dbclose() self.dbclose()
......
...@@ -16,6 +16,7 @@ if __name__ == "__main__": ...@@ -16,6 +16,7 @@ if __name__ == "__main__":
#os.chdir('../../..') #os.chdir('../../..')
from Testing import makerequest from Testing import makerequest
import ZODB # in order to get Persistence.Persistent working import ZODB # in order to get Persistence.Persistent working
import transaction
import Acquisition import Acquisition
from Acquisition import aq_base from Acquisition import aq_base
from Products.Sessions.BrowserIdManager import BrowserIdManager, \ from Products.Sessions.BrowserIdManager import BrowserIdManager, \
...@@ -66,13 +67,13 @@ def _getDB(): ...@@ -66,13 +67,13 @@ def _getDB():
app = Application() app = Application()
root['Application']= app root['Application']= app
_populate(app) _populate(app)
get_transaction().commit() transaction.commit()
stuff['db'] = db stuff['db'] = db
conn.close() conn.close()
return db return db
def _delDB(): def _delDB():
get_transaction().abort() transaction.abort()
del stuff['db'] del stuff['db']
class Foo(Acquisition.Implicit): pass class Foo(Acquisition.Implicit): pass
...@@ -99,10 +100,10 @@ def _populate(app): ...@@ -99,10 +100,10 @@ def _populate(app):
app._setObject(sdm_name, session_data_manager) app._setObject(sdm_name, session_data_manager)
app._setObject(tf_name, tf) app._setObject(tf_name, tf)
get_transaction().commit() transaction.commit()
app.temp_folder._setObject(toc_name, toc) app.temp_folder._setObject(toc_name, toc)
get_transaction().commit() transaction.commit()
class TestMultiThread(TestCase): class TestMultiThread(TestCase):
def testOverlappingBrowserIds(self): def testOverlappingBrowserIds(self):
...@@ -191,17 +192,17 @@ class BaseReaderWriter(threading.Thread): ...@@ -191,17 +192,17 @@ class BaseReaderWriter(threading.Thread):
except ConflictError: except ConflictError:
print "W", print "W",
except: except:
get_transaction().abort() transaction.abort()
print log_time() print log_time()
traceback.print_exc() traceback.print_exc()
raise raise
i = i + 1 i = i + 1
get_transaction().abort() transaction.abort()
self.conn.close() self.conn.close()
time.sleep(random.randrange(10) * .1) time.sleep(random.randrange(10) * .1)
finally: finally:
get_transaction().abort() transaction.abort()
self.conn.close() self.conn.close()
del self.app del self.app
self.finished = 1 self.finished = 1
...@@ -217,11 +218,11 @@ class ReaderThread(BaseReaderWriter): ...@@ -217,11 +218,11 @@ class ReaderThread(BaseReaderWriter):
data = session_data_manager.getSessionData(create=1) data = session_data_manager.getSessionData(create=1)
t = time.time() t = time.time()
data[t] = 1 data[t] = 1
get_transaction().commit() transaction.commit()
for i in range(self.iters): for i in range(self.iters):
data = session_data_manager.getSessionData() data = session_data_manager.getSessionData()
time.sleep(random.choice(range(3))) time.sleep(random.choice(range(3)))
get_transaction().commit() transaction.commit()
class WriterThread(BaseReaderWriter): class WriterThread(BaseReaderWriter):
def run1(self): def run1(self):
...@@ -232,9 +233,9 @@ class WriterThread(BaseReaderWriter): ...@@ -232,9 +233,9 @@ class WriterThread(BaseReaderWriter):
n = random.choice(range(3)) n = random.choice(range(3))
time.sleep(n) time.sleep(n)
if n % 2 == 0: if n % 2 == 0:
get_transaction().commit() transaction.commit()
else: else:
get_transaction().abort() transaction.abort()
class ValuesGetterThread(BaseReaderWriter): class ValuesGetterThread(BaseReaderWriter):
def run1(self): def run1(self):
...@@ -245,9 +246,9 @@ class ValuesGetterThread(BaseReaderWriter): ...@@ -245,9 +246,9 @@ class ValuesGetterThread(BaseReaderWriter):
n = random.choice(range(3)) n = random.choice(range(3))
time.sleep(n) time.sleep(n)
if n % 2 == 0: if n % 2 == 0:
get_transaction().commit() transaction.commit()
else: else:
get_transaction().abort() transaction.abort()
def test_suite(): def test_suite():
......
...@@ -16,6 +16,7 @@ from Testing import makerequest ...@@ -16,6 +16,7 @@ from Testing import makerequest
import ZODB # in order to get Persistence.Persistent working import ZODB # in order to get Persistence.Persistent working
from ZODB.POSException import InvalidObjectReference, ConflictError from ZODB.POSException import InvalidObjectReference, ConflictError
from ZODB.DemoStorage import DemoStorage from ZODB.DemoStorage import DemoStorage
import transaction
from OFS.DTMLMethod import DTMLMethod from OFS.DTMLMethod import DTMLMethod
import Acquisition import Acquisition
from Acquisition import aq_base from Acquisition import aq_base
...@@ -49,14 +50,14 @@ def _getDB(): ...@@ -49,14 +50,14 @@ def _getDB():
root = conn.root() root = conn.root()
app = Application() app = Application()
root['Application']= app root['Application']= app
get_transaction().commit(1) transaction.commit(1)
_populate(app) _populate(app)
stuff['db'] = db stuff['db'] = db
conn.close() conn.close()
return db return db
def _delDB(): def _delDB():
get_transaction().abort() transaction.abort()
del stuff['db'] del stuff['db']
class Foo(Acquisition.Implicit): pass class Foo(Acquisition.Implicit): pass
...@@ -87,14 +88,14 @@ def _populate(app): ...@@ -87,14 +88,14 @@ def _populate(app):
app._setObject(sdm_name, session_data_manager) app._setObject(sdm_name, session_data_manager)
app._setObject(tf_name, tf) app._setObject(tf_name, tf)
get_transaction().commit() transaction.commit()
app.temp_folder._setObject(toc_name, toc) app.temp_folder._setObject(toc_name, toc)
get_transaction().commit() transaction.commit()
# index_html necessary for publishing emulation for testAutoReqPopulate # index_html necessary for publishing emulation for testAutoReqPopulate
app._setObject('index_html', DTMLMethod('', __name__='foo')) app._setObject('index_html', DTMLMethod('', __name__='foo'))
get_transaction().commit() transaction.commit()
class TestBase(TestCase): class TestBase(TestCase):
def setUp(self): def setUp(self):
...@@ -177,17 +178,19 @@ class TestSessionManager(TestBase): ...@@ -177,17 +178,19 @@ class TestSessionManager(TestBase):
def testGhostUnghostSessionManager(self): def testGhostUnghostSessionManager(self):
sdm = self.app.session_data_manager sdm = self.app.session_data_manager
get_transaction().commit() transaction.commit()
sd = sdm.getSessionData() sd = sdm.getSessionData()
sd.set('foo', 'bar') sd.set('foo', 'bar')
sdm._p_changed = None sdm._p_changed = None
get_transaction().commit() transaction.commit()
self.failUnless(sdm.getSessionData().get('foo') == 'bar') self.failUnless(sdm.getSessionData().get('foo') == 'bar')
def testSubcommit(self): def testSubcommit(self):
sd = self.app.session_data_manager.getSessionData() sd = self.app.session_data_manager.getSessionData()
sd.set('foo', 'bar') sd.set('foo', 'bar')
self.failUnless(get_transaction().commit(1) == None) # TODO: transaction.commit() always returns None. Is that
# all this is trying to test?
self.failUnless(transaction.commit(1) == None)
def testForeignObject(self): def testForeignObject(self):
self.assertRaises(InvalidObjectReference, self._foreignAdd) self.assertRaises(InvalidObjectReference, self._foreignAdd)
...@@ -201,7 +204,7 @@ class TestSessionManager(TestBase): ...@@ -201,7 +204,7 @@ class TestSessionManager(TestBase):
# we want to fail for some other reason: # we want to fail for some other reason:
sd = self.app.session_data_manager.getSessionData() sd = self.app.session_data_manager.getSessionData()
sd.set('foo', ob) sd.set('foo', ob)
get_transaction().commit() transaction.commit()
def testAqWrappedObjectsFail(self): def testAqWrappedObjectsFail(self):
a = Foo() a = Foo()
...@@ -209,7 +212,7 @@ class TestSessionManager(TestBase): ...@@ -209,7 +212,7 @@ class TestSessionManager(TestBase):
aq_wrapped = a.__of__(b) aq_wrapped = a.__of__(b)
sd = self.app.session_data_manager.getSessionData() sd = self.app.session_data_manager.getSessionData()
sd.set('foo', aq_wrapped) sd.set('foo', aq_wrapped)
self.assertRaises(TypeError, get_transaction().commit) self.assertRaises(TypeError, transaction.commit)
def testAutoReqPopulate(self): def testAutoReqPopulate(self):
self.app.REQUEST['PARENTS'] = [self.app] self.app.REQUEST['PARENTS'] = [self.app]
......
import Zope2 import Zope2
from ZPublisher.BeforeTraverse import NameCaller, rewriteBeforeTraverse from ZPublisher.BeforeTraverse import NameCaller, rewriteBeforeTraverse
from Products.SiteAccess.AccessRule import AccessRule from Products.SiteAccess.AccessRule import AccessRule
import transaction
def updata(self): def updata(self):
"""Convert SiteAccess objects from 1.x to 2.x""" """Convert SiteAccess objects from 1.x to 2.x"""
...@@ -33,5 +34,5 @@ if __name__ == '__main__': ...@@ -33,5 +34,5 @@ if __name__ == '__main__':
print "Converting SiteAccess objects from 1.x to 2.x ..." print "Converting SiteAccess objects from 1.x to 2.x ..."
app = Zope2.app() app = Zope2.app()
_cvt_btr(app) _cvt_btr(app)
get_transaction().commit() transaction.commit()
print "Done." print "Done."
...@@ -36,7 +36,7 @@ class VHMRegressions(unittest.TestCase): ...@@ -36,7 +36,7 @@ class VHMRegressions(unittest.TestCase):
self.tearDown() self.tearDown()
def tearDown(self): def tearDown(self):
get_transaction().abort() transaction.abort()
self.app._p_jar.close() self.app._p_jar.close()
def testAbsoluteUrl(self): def testAbsoluteUrl(self):
......
...@@ -27,7 +27,7 @@ class SiteErrorLogTests(unittest.TestCase): ...@@ -27,7 +27,7 @@ class SiteErrorLogTests(unittest.TestCase):
self.tearDown() self.tearDown()
def tearDown(self): def tearDown(self):
get_transaction().abort() transaction.abort()
self.app._p_jar.close() self.app._p_jar.close()
def testInstantiation(self): def testInstantiation(self):
......
...@@ -16,6 +16,8 @@ ...@@ -16,6 +16,8 @@
import ZODB import ZODB
import Globals import Globals
from ZODB import FileStorage, DB from ZODB import FileStorage, DB
import transaction
import Products.Sessions.BrowserIdManager import Products.Sessions.BrowserIdManager
import Products.Sessions.SessionDataManager import Products.Sessions.SessionDataManager
import Products.TemporaryFolder.TemporaryFolder import Products.TemporaryFolder.TemporaryFolder
...@@ -45,4 +47,4 @@ app._setObject('browser_id_manager', bid) ...@@ -45,4 +47,4 @@ app._setObject('browser_id_manager', bid)
app._setObject('session_data_manager', sdm) app._setObject('session_data_manager', sdm)
app._p_changed = 1 app._p_changed = 1
get_transaction().commit() transaction.commit()
...@@ -5,6 +5,7 @@ if __name__=='__main__': ...@@ -5,6 +5,7 @@ if __name__=='__main__':
sys.path.insert(0, '../../..') sys.path.insert(0, '../../..')
import ZODB # in order to get Persistence.Persistent working import ZODB # in order to get Persistence.Persistent working
import transaction
from Testing import makerequest from Testing import makerequest
import Acquisition import Acquisition
from Acquisition import aq_base from Acquisition import aq_base
...@@ -34,7 +35,7 @@ def _getApp(): ...@@ -34,7 +35,7 @@ def _getApp():
root = conn.root() root = conn.root()
app = Application() app = Application()
root['Application']= app root['Application']= app
get_transaction().commit() transaction.commit()
stuff['app'] = app stuff['app'] = app
stuff['conn'] = conn stuff['conn'] = conn
stuff['db'] = db stuff['db'] = db
...@@ -47,7 +48,7 @@ def _openApp(): ...@@ -47,7 +48,7 @@ def _openApp():
return conn, app return conn, app
def _delApp(): def _delApp():
get_transaction().abort() transaction.abort()
stuff['conn'].close() stuff['conn'].close()
del stuff['conn'] del stuff['conn']
del stuff['app'] del stuff['app']
...@@ -68,7 +69,7 @@ class TestBase(TestCase): ...@@ -68,7 +69,7 @@ class TestBase(TestCase):
self.app._setObject('sm', sm) self.app._setObject('sm', sm)
def tearDown(self): def tearDown(self):
get_transaction().abort() transaction.abort()
_delApp() _delApp()
del self.app del self.app
Products.Transience.Transience.time = oldtime Products.Transience.Transience.time = oldtime
......
...@@ -23,14 +23,14 @@ from Products.Transience.TransactionHelper import PreventTransactionCommit, \ ...@@ -23,14 +23,14 @@ from Products.Transience.TransactionHelper import PreventTransactionCommit, \
class TestTransactionHelper(TestCase): class TestTransactionHelper(TestCase):
def setUp(self): def setUp(self):
self.t = get_transaction() self.t = transaction.get()
def tearDown(self): def tearDown(self):
self.t = None self.t = None
def testUncommittable(self): def testUncommittable(self):
makeTransactionUncommittable(self.t, "test") makeTransactionUncommittable(self.t, "test")
self.assertRaises(PreventTransactionCommit, get_transaction().commit) self.assertRaises(PreventTransactionCommit, transaction.commit)
transaction.abort() transaction.abort()
def test_suite(): def test_suite():
......
...@@ -16,6 +16,7 @@ from time import clock ...@@ -16,6 +16,7 @@ from time import clock
import ZODB import ZODB
from ZODB.FileStorage import FileStorage from ZODB.FileStorage import FileStorage
from BTrees.IOBTree import IOBTree from BTrees.IOBTree import IOBTree
import transaction
from Products.ZCTextIndex.ZCTextIndex import ZCTextIndex from Products.ZCTextIndex.ZCTextIndex import ZCTextIndex
from Products.ZCTextIndex.HTMLSplitter import HTMLWordSplitter from Products.ZCTextIndex.HTMLSplitter import HTMLWordSplitter
...@@ -58,7 +59,7 @@ def make_old_index(): ...@@ -58,7 +59,7 @@ def make_old_index():
def main(db, root, dir): def main(db, root, dir):
rt["index"] = index = INDEX() rt["index"] = index = INDEX()
rt["files"] = paths = IOBTree() rt["files"] = paths = IOBTree()
get_transaction().commit() transaction.commit()
zodb_time = 0.0 zodb_time = 0.0
pack_time = 0.0 pack_time = 0.0
...@@ -83,7 +84,7 @@ def main(db, root, dir): ...@@ -83,7 +84,7 @@ def main(db, root, dir):
f.close() f.close()
if docid % TXN_INTERVAL == 0: if docid % TXN_INTERVAL == 0:
z0 = clock() z0 = clock()
get_transaction().commit() transaction.commit()
z1 = clock() z1 = clock()
zodb_time += z1 - z0 zodb_time += z1 - z0
if VERBOSE: if VERBOSE:
...@@ -97,7 +98,7 @@ def main(db, root, dir): ...@@ -97,7 +98,7 @@ def main(db, root, dir):
if VERBOSE: if VERBOSE:
print "pack took", p1 - p0, pack_time print "pack took", p1 - p0, pack_time
z0 = clock() z0 = clock()
get_transaction().commit() transaction.commit()
z1 = t1 = clock() z1 = t1 = clock()
total_time = t1 - t0 total_time = t1 - t0
zodb_time += z1 - z0 zodb_time += z1 - z0
......
...@@ -42,6 +42,7 @@ index from the database: ...@@ -42,6 +42,7 @@ index from the database:
import ZODB import ZODB
import ZODB.FileStorage import ZODB.FileStorage
import transaction
from Products.ZCTextIndex.Lexicon import \ from Products.ZCTextIndex.Lexicon import \
Lexicon, CaseNormalizer, Splitter, StopWordRemover Lexicon, CaseNormalizer, Splitter, StopWordRemover
from Products.ZCTextIndex.ZCTextIndex import ZCTextIndex from Products.ZCTextIndex.ZCTextIndex import ZCTextIndex
...@@ -92,7 +93,7 @@ def index(rt, mboxfile, db, profiler): ...@@ -92,7 +93,7 @@ def index(rt, mboxfile, db, profiler):
rt["documents"] = docs = IOBTree() rt["documents"] = docs = IOBTree()
else: else:
docs = None docs = None
get_transaction().commit() transaction.commit()
mbox = mailbox.UnixMailbox(open(mboxfile, 'rb')) mbox = mailbox.UnixMailbox(open(mboxfile, 'rb'))
if VERBOSE: if VERBOSE:
...@@ -107,7 +108,7 @@ def index(rt, mboxfile, db, profiler): ...@@ -107,7 +108,7 @@ def index(rt, mboxfile, db, profiler):
idx_time += itime idx_time += itime
pack_time += ptime pack_time += ptime
get_transaction().commit() transaction.commit()
if PACK_INTERVAL and i % PACK_INTERVAL != 0: if PACK_INTERVAL and i % PACK_INTERVAL != 0:
if VERBOSE >= 2: if VERBOSE >= 2:
...@@ -148,7 +149,7 @@ def indexmbox(mbox, idx, docs, db): ...@@ -148,7 +149,7 @@ def indexmbox(mbox, idx, docs, db):
if not EXCLUDE_TEXT: if not EXCLUDE_TEXT:
docs[i] = msg docs[i] = msg
if i % TXN_SIZE == 0: if i % TXN_SIZE == 0:
get_transaction().commit() transaction.commit()
i1 = time.clock() i1 = time.clock()
idx_time += i1 - i0 idx_time += i1 - i0
if VERBOSE and i % 50 == 0: if VERBOSE and i % 50 == 0:
......
...@@ -51,6 +51,7 @@ from Persistence import Persistent ...@@ -51,6 +51,7 @@ from Persistence import Persistent
from BTrees.IOBTree import IOBTree from BTrees.IOBTree import IOBTree
from BTrees.OIBTree import OIBTree from BTrees.OIBTree import OIBTree
from BTrees.IIBTree import IIBTree from BTrees.IIBTree import IIBTree
import transaction
from Products.ZCTextIndex.NBest import NBest from Products.ZCTextIndex.NBest import NBest
from Products.ZCTextIndex.OkapiIndex import OkapiIndex from Products.ZCTextIndex.OkapiIndex import OkapiIndex
...@@ -552,7 +553,7 @@ class Indexer: ...@@ -552,7 +553,7 @@ class Indexer:
def commit(self): def commit(self):
if self.trans_count > 0: if self.trans_count > 0:
print "committing..." print "committing..."
get_transaction().commit() transaction.commit()
self.trans_count = 0 self.trans_count = 0
self.pack_count += 1 self.pack_count += 1
if self.pack_count >= self.pack_limit > 0: if self.pack_count >= self.pack_limit > 0:
......
...@@ -15,6 +15,8 @@ ...@@ -15,6 +15,8 @@
import os import os
from unittest import TestCase, TestSuite, main, makeSuite from unittest import TestCase, TestSuite, main, makeSuite
import transaction
from BTrees.Length import Length from BTrees.Length import Length
from Products.ZCTextIndex.Lexicon import Lexicon, Splitter from Products.ZCTextIndex.Lexicon import Lexicon, Splitter
from Products.ZCTextIndex.CosineIndex import CosineIndex from Products.ZCTextIndex.CosineIndex import CosineIndex
...@@ -178,7 +180,7 @@ class TestIndexConflict(TestCase): ...@@ -178,7 +180,7 @@ class TestIndexConflict(TestCase):
self.openDB() self.openDB()
r1 = self.db.open().root() r1 = self.db.open().root()
r1['i'] = self.index r1['i'] = self.index
get_transaction().commit() transaction.commit()
r2 = self.db.open().root() r2 = self.db.open().root()
copy = r2['i'] copy = r2['i']
...@@ -192,10 +194,10 @@ class TestIndexConflict(TestCase): ...@@ -192,10 +194,10 @@ class TestIndexConflict(TestCase):
self.assertEqual(self.index._p_serial, copy._p_serial) self.assertEqual(self.index._p_serial, copy._p_serial)
self.index.index_doc(0, 'The time has come') self.index.index_doc(0, 'The time has come')
get_transaction().commit() transaction.commit()
copy.index_doc(1, 'That time has gone') copy.index_doc(1, 'That time has gone')
get_transaction().commit() transaction.commit()
def test_reindex_doc_conflict(self): def test_reindex_doc_conflict(self):
self.index = OkapiIndex(Lexicon()) self.index = OkapiIndex(Lexicon())
...@@ -204,7 +206,7 @@ class TestIndexConflict(TestCase): ...@@ -204,7 +206,7 @@ class TestIndexConflict(TestCase):
self.openDB() self.openDB()
r1 = self.db.open().root() r1 = self.db.open().root()
r1['i'] = self.index r1['i'] = self.index
get_transaction().commit() transaction.commit()
r2 = self.db.open().root() r2 = self.db.open().root()
copy = r2['i'] copy = r2['i']
...@@ -218,10 +220,10 @@ class TestIndexConflict(TestCase): ...@@ -218,10 +220,10 @@ class TestIndexConflict(TestCase):
self.assertEqual(self.index._p_serial, copy._p_serial) self.assertEqual(self.index._p_serial, copy._p_serial)
self.index.index_doc(0, 'Sometimes change isn\'t bad') self.index.index_doc(0, 'Sometimes change isn\'t bad')
get_transaction().commit() transaction.commit()
copy.index_doc(1, 'Then again, who asked you?') copy.index_doc(1, 'Then again, who asked you?')
get_transaction().commit() transaction.commit()
class TestUpgrade(TestCase): class TestUpgrade(TestCase):
......
...@@ -16,6 +16,7 @@ import os, sys ...@@ -16,6 +16,7 @@ import os, sys
from unittest import TestCase, TestSuite, main, makeSuite from unittest import TestCase, TestSuite, main, makeSuite
import ZODB import ZODB
import transaction
from Products.ZCTextIndex.Lexicon import Lexicon from Products.ZCTextIndex.Lexicon import Lexicon
from Products.ZCTextIndex.Lexicon import Splitter, CaseNormalizer from Products.ZCTextIndex.Lexicon import Splitter, CaseNormalizer
...@@ -165,7 +166,7 @@ class TestLexiconConflict(TestCase): ...@@ -165,7 +166,7 @@ class TestLexiconConflict(TestCase):
self.openDB() self.openDB()
r1 = self.db.open().root() r1 = self.db.open().root()
r1['l'] = self.l r1['l'] = self.l
get_transaction().commit() transaction.commit()
r2 = self.db.open().root() r2 = self.db.open().root()
copy = r2['l'] copy = r2['l']
...@@ -177,11 +178,11 @@ class TestLexiconConflict(TestCase): ...@@ -177,11 +178,11 @@ class TestLexiconConflict(TestCase):
self.assertEqual(self.l._p_serial, copy._p_serial) self.assertEqual(self.l._p_serial, copy._p_serial)
self.l.sourceToWordIds('mary had a little lamb') self.l.sourceToWordIds('mary had a little lamb')
get_transaction().commit() transaction.commit()
copy.sourceToWordIds('whose fleece was') copy.sourceToWordIds('whose fleece was')
copy.sourceToWordIds('white as snow') copy.sourceToWordIds('white as snow')
get_transaction().commit() transaction.commit()
self.assertEqual(copy.length(), 11) self.assertEqual(copy.length(), 11)
self.assertEqual(copy.length(), len(copy._words)) self.assertEqual(copy.length(), len(copy._words))
......
...@@ -80,7 +80,8 @@ ZCatalog ...@@ -80,7 +80,8 @@ ZCatalog
> cat.refreshCatalog(pghandler=ZLogHandler()) > cat.refreshCatalog(pghandler=ZLogHandler())
> >
> # Don't forget to commit > # Don't forget to commit
> get_transaction().commit() > import transaction
> transaction.commit()
The constructor of the handler can be given an optional parameter The constructor of the handler can be given an optional parameter
......
...@@ -35,6 +35,7 @@ from AccessControl.Permissions import \ ...@@ -35,6 +35,7 @@ from AccessControl.Permissions import \
manage_zcatalog_entries, manage_zcatalog_indexes, search_zcatalog manage_zcatalog_entries, manage_zcatalog_indexes, search_zcatalog
from ZCatalogIndexes import ZCatalogIndexes from ZCatalogIndexes import ZCatalogIndexes
from ZODB.POSException import ConflictError from ZODB.POSException import ConflictError
import transaction
from Products.PluginIndexes.common.PluggableIndex \ from Products.PluginIndexes.common.PluggableIndex \
import PluggableIndexInterface import PluggableIndexInterface
from Products.PluginIndexes.TextIndex import Splitter from Products.PluginIndexes.TextIndex import Splitter
...@@ -566,7 +567,7 @@ class ZCatalog(Folder, Persistent, Implicit): ...@@ -566,7 +567,7 @@ class ZCatalog(Folder, Persistent, Implicit):
if self.threshold is not None: if self.threshold is not None:
# figure out whether or not to commit a subtransaction. # figure out whether or not to commit a subtransaction.
t = id(get_transaction()) t = id(transaction.get())
if t != self._v_transaction: if t != self._v_transaction:
self._v_total = 0 self._v_total = 0
self._v_transaction = t self._v_transaction = t
...@@ -581,7 +582,7 @@ class ZCatalog(Folder, Persistent, Implicit): ...@@ -581,7 +582,7 @@ class ZCatalog(Folder, Persistent, Implicit):
# we should commit a subtransaction if our threshhold is # we should commit a subtransaction if our threshhold is
# exceeded within the boundaries of the current transaction. # exceeded within the boundaries of the current transaction.
if self._v_total > self.threshold: if self._v_total > self.threshold:
get_transaction().commit(1) transaction.commit(1)
self._p_jar.cacheGC() self._p_jar.cacheGC()
self._v_total = 0 self._v_total = 0
if pghandler: if pghandler:
......
...@@ -122,6 +122,8 @@ whrandom.seed(1,2,3) ...@@ -122,6 +122,8 @@ whrandom.seed(1,2,3)
from string import strip, find, split, lower, atoi from string import strip, find, split, lower, atoi
from urllib import quote from urllib import quote
import transaction
VERBOSE = 0 VERBOSE = 0
def do(db, f, args, returnf=None): def do(db, f, args, returnf=None):
...@@ -192,7 +194,7 @@ def loadmail(dest, name, mbox, max=-1): ...@@ -192,7 +194,7 @@ def loadmail(dest, name, mbox, max=-1):
sys.stdout.write(fmt % (i, f.tell())) sys.stdout.write(fmt % (i, f.tell()))
sys.stdout.flush() sys.stdout.flush()
if i and (i%5000 == 0): if i and (i%5000 == 0):
get_transaction().commit() transaction.commit()
dest._p_jar._cache.minimize() dest._p_jar._cache.minimize()
loadmessage(dest, message, i) loadmessage(dest, message, i)
...@@ -201,7 +203,7 @@ def loadmail(dest, name, mbox, max=-1): ...@@ -201,7 +203,7 @@ def loadmail(dest, name, mbox, max=-1):
dest.number_of_messages=i dest.number_of_messages=i
print print
get_transaction().commit() transaction.commit()
def loadinc(name, mb, f, max=99999999, wait=1): def loadinc(name, mb, f, max=99999999, wait=1):
from ZODB.POSException import ConflictError from ZODB.POSException import ConflictError
...@@ -236,17 +238,17 @@ def loadinc(name, mb, f, max=99999999, wait=1): ...@@ -236,17 +238,17 @@ def loadinc(name, mb, f, max=99999999, wait=1):
except ConflictError, v: except ConflictError, v:
# print v.args # print v.args
rconflicts=rconflicts+1 rconflicts=rconflicts+1
get_transaction().abort() transaction.abort()
else: else:
try: try:
get_transaction().commit() transaction.commit()
i=i+1 i=i+1
message=mb.next() message=mb.next()
body=message.fp.read() body=message.fp.read()
headers=list(message.headers) headers=list(message.headers)
except ConflictError: except ConflictError:
wconflicts=wconflicts+1 wconflicts=wconflicts+1
get_transaction().abort() transaction.abort()
doc=app=mdest=0 doc=app=mdest=0
jar.close() jar.close()
...@@ -276,7 +278,7 @@ def indexf(app): ...@@ -276,7 +278,7 @@ def indexf(app):
r=RE() r=RE()
r.PARENTS=[0, app.mail] r.PARENTS=[0, app.mail]
app.cat.manage_catalogFoundItems(r,r,'','',['DTML Document']) app.cat.manage_catalogFoundItems(r,r,'','',['DTML Document'])
get_transaction().commit() transaction.commit()
def index(): def index():
os.environ['STUPID_LOG_FILE']='' os.environ['STUPID_LOG_FILE']=''
...@@ -306,7 +308,7 @@ def index(): ...@@ -306,7 +308,7 @@ def index():
app.cat.addIndex('PrincipiaSearchSource', 'ZCTextIndex', extra) app.cat.addIndex('PrincipiaSearchSource', 'ZCTextIndex', extra)
get_transaction().commit() transaction.commit()
system = AccessControl.SpecialUsers.system system = AccessControl.SpecialUsers.system
AccessControl.SecurityManagement.newSecurityManager(None, system) AccessControl.SecurityManagement.newSecurityManager(None, system)
r=RE() r=RE()
...@@ -325,7 +327,7 @@ def initmaili(n): ...@@ -325,7 +327,7 @@ def initmaili(n):
else: else:
Products.BTreeFolder.BTreeFolder.manage_addBTreeFolder(app, n) Products.BTreeFolder.BTreeFolder.manage_addBTreeFolder(app, n)
get_transaction().commit() transaction.commit()
app._p_jar.close() app._p_jar.close()
def hist(n): def hist(n):
...@@ -409,7 +411,7 @@ def catdel(): ...@@ -409,7 +411,7 @@ def catdel():
mem = VmSize() mem = VmSize()
del app.cat del app.cat
get_transaction().commit() transaction.commit()
t = time.time() - t t = time.time() - t
c = time.clock() - c c = time.clock() - c
...@@ -635,14 +637,14 @@ def incedit(edits, wait, ndel=20, nins=20): ...@@ -635,14 +637,14 @@ def incedit(edits, wait, ndel=20, nins=20):
except ConflictError, v: except ConflictError, v:
#print v.args #print v.args
rconflicts=rconflicts+1 rconflicts=rconflicts+1
get_transaction().abort() transaction.abort()
else: else:
try: try:
get_transaction().commit() transaction.commit()
did=str(edits.pop()) did=str(edits.pop())
except ConflictError: except ConflictError:
wconflicts=wconflicts+1 wconflicts=wconflicts+1
get_transaction().abort() transaction.abort()
doc=app=0 doc=app=0
jar.close() jar.close()
......
...@@ -18,6 +18,8 @@ here = os.getcwd() ...@@ -18,6 +18,8 @@ here = os.getcwd()
import Zope2 import Zope2
import ZODB, ZODB.FileStorage import ZODB, ZODB.FileStorage
import transaction
from Products.ZCatalog import ZCatalog,Vocabulary from Products.ZCatalog import ZCatalog,Vocabulary
from Products.ZCatalog.Catalog import CatalogError from Products.ZCatalog.Catalog import CatalogError
import Persistence import Persistence
...@@ -68,7 +70,7 @@ class testZODB: ...@@ -68,7 +70,7 @@ class testZODB:
def write(self,name,obj): def write(self,name,obj):
self.root[name] = obj self.root[name] = obj
get_transaction().commit() transaction.commit()
def read(self,name): def read(self,name):
...@@ -462,7 +464,7 @@ class testSearches(dispatcher.Dispatcher,unittest.TestCase): ...@@ -462,7 +464,7 @@ class testSearches(dispatcher.Dispatcher,unittest.TestCase):
cat.uncatalog_object(mid) cat.uncatalog_object(mid)
if kw.get("commit",1)==1: if kw.get("commit",1)==1:
get_transaction().commit() transaction.commit()
time.sleep(0.1) time.sleep(0.1)
except ZODB.POSException.ConflictError: except ZODB.POSException.ConflictError:
uncat_conflicts = uncat_conflicts + 1 uncat_conflicts = uncat_conflicts + 1
...@@ -471,14 +473,14 @@ class testSearches(dispatcher.Dispatcher,unittest.TestCase): ...@@ -471,14 +473,14 @@ class testSearches(dispatcher.Dispatcher,unittest.TestCase):
cat.catalog_object(obj,mid) cat.catalog_object(obj,mid)
if kw.get("commit",1)==1: if kw.get("commit",1)==1:
get_transaction().commit() transaction.commit()
time.sleep(0.1) time.sleep(0.1)
except ZODB.POSException.ConflictError: except ZODB.POSException.ConflictError:
cat_conflicts = cat_conflicts + 1 cat_conflicts = cat_conflicts + 1
try: try:
get_transaction().commit() transaction.commit()
except: pass except: pass
...@@ -551,7 +553,7 @@ class testSearches(dispatcher.Dispatcher,unittest.TestCase): ...@@ -551,7 +553,7 @@ class testSearches(dispatcher.Dispatcher,unittest.TestCase):
try: try:
cat.catalogObject(obj,mid) cat.catalogObject(obj,mid)
get_transaction().commit() transaction.commit()
except: except:
cat_conflicts = cat_conflicts + 1 cat_conflicts = cat_conflicts + 1
......
...@@ -25,6 +25,8 @@ from Products.ZCatalog import ZCatalog ...@@ -25,6 +25,8 @@ from Products.ZCatalog import ZCatalog
from unittest import TestCase, TestSuite, JUnitTextTestRunner,\ from unittest import TestCase, TestSuite, JUnitTextTestRunner,\
VerboseTextTestRunner, makeSuite VerboseTextTestRunner, makeSuite
import transaction
from Products.PluginIndexes.FieldIndex.FieldIndex import FieldIndex from Products.PluginIndexes.FieldIndex.FieldIndex import FieldIndex
from Products.PluginIndexes.TextIndex.TextIndex import TextIndex from Products.PluginIndexes.TextIndex.TextIndex import TextIndex
from Products.PluginIndexes.TextIndex.Lexicon import Lexicon from Products.PluginIndexes.TextIndex.Lexicon import Lexicon
...@@ -68,7 +70,7 @@ class TestTimeIndex(TestCase): ...@@ -68,7 +70,7 @@ class TestTimeIndex(TestCase):
t = time.time() t = time.time()
loadmail(self.app.catalogtest, 'zopemail', loadmail(self.app.catalogtest, 'zopemail',
os.path.join(here, 'zope.mbox'), 500) os.path.join(here, 'zope.mbox'), 500)
get_transaction().commit() transaction.commit()
loadtime = time.time() - t loadtime = time.time() - t
out("loading data took %s seconds.. " % loadtime) out("loading data took %s seconds.. " % loadtime)
t = time.time() t = time.time()
...@@ -92,7 +94,7 @@ class TestTimeIndex(TestCase): ...@@ -92,7 +94,7 @@ class TestTimeIndex(TestCase):
max = 500 max = 500
m = loadmail(self.app.catalogtest, 'zopemail', m = loadmail(self.app.catalogtest, 'zopemail',
os.path.join(here, 'zope.mbox'), max, c) os.path.join(here, 'zope.mbox'), max, c)
get_transaction().commit() transaction.commit()
total = time.time() - t total = time.time() - t
out("total time for load and index was %s seconds.. " % total) out("total time for load and index was %s seconds.. " % total)
t = time.time() t = time.time()
...@@ -118,11 +120,11 @@ class TestTimeIndex(TestCase): ...@@ -118,11 +120,11 @@ class TestTimeIndex(TestCase):
self.setUp() self.setUp()
c = self.app.catalogtest.catalog c = self.app.catalogtest.catalog
c.threshold = x c.threshold = x
get_transaction().commit() transaction.commit()
t = time.time() t = time.time()
loadmail(self.app.catalogtest, 'zopemail', loadmail(self.app.catalogtest, 'zopemail',
os.path.join(here, 'zope.mbox'), 500, c) os.path.join(here, 'zope.mbox'), 500, c)
get_transaction().commit() transaction.commit()
total = time.time() - t total = time.time() - t
out("total time with subcommit thresh %s was %s seconds.. " out("total time with subcommit thresh %s was %s seconds.. "
% (x,total)) % (x,total))
......
...@@ -34,6 +34,7 @@ from Products.ZCatalog.Catalog import Catalog ...@@ -34,6 +34,7 @@ from Products.ZCatalog.Catalog import Catalog
from Products.ZCatalog.Catalog import CatalogError from Products.ZCatalog.Catalog import CatalogError
from ZODB.DB import DB from ZODB.DB import DB
from ZODB.DemoStorage import DemoStorage from ZODB.DemoStorage import DemoStorage
import transaction
from Products.PluginIndexes.FieldIndex.FieldIndex import FieldIndex from Products.PluginIndexes.FieldIndex.FieldIndex import FieldIndex
from Products.PluginIndexes.KeywordIndex.KeywordIndex import KeywordIndex from Products.PluginIndexes.KeywordIndex.KeywordIndex import KeywordIndex
...@@ -52,7 +53,7 @@ def createDatabase(): ...@@ -52,7 +53,7 @@ def createDatabase():
root = conn.root() root = conn.root()
app = OFS.Application.Application() app = OFS.Application.Application()
root['Application'] = app root['Application'] = app
get_transaction().commit() transaction.commit()
# Init products # Init products
#OFS.Application.initialize(app) #OFS.Application.initialize(app)
......
...@@ -18,6 +18,8 @@ $Id$ ...@@ -18,6 +18,8 @@ $Id$
import os import os
import transaction
import Globals import Globals
from Acquisition import aq_base, aq_inner, aq_parent from Acquisition import aq_base, aq_inner, aq_parent
from AccessControl.ZopeGuards import guarded_getattr from AccessControl.ZopeGuards import guarded_getattr
...@@ -52,7 +54,7 @@ class SimpleTrailblazer: ...@@ -52,7 +54,7 @@ class SimpleTrailblazer:
o = context.restrictedTraverse(id) o = context.restrictedTraverse(id)
# Commit a subtransaction to assign the new object to # Commit a subtransaction to assign the new object to
# the correct database. # the correct database.
get_transaction().commit(1) transaction.commit(1)
return o return o
def traverseOrConstruct(self, path, omit_final=0): def traverseOrConstruct(self, path, omit_final=0):
...@@ -105,7 +107,7 @@ class CustomTrailblazer (SimpleTrailblazer): ...@@ -105,7 +107,7 @@ class CustomTrailblazer (SimpleTrailblazer):
obj = context.unrestrictedTraverse(id) obj = context.unrestrictedTraverse(id)
# Commit a subtransaction to assign the new object to # Commit a subtransaction to assign the new object to
# the correct database. # the correct database.
get_transaction().commit(1) transaction.commit(1)
return obj return obj
...@@ -171,7 +173,7 @@ class MountedObject(MountPoint, SimpleItem): ...@@ -171,7 +173,7 @@ class MountedObject(MountPoint, SimpleItem):
obj = Application() obj = Application()
root[real_root] = obj root[real_root] = obj
# Get it into the database # Get it into the database
get_transaction().commit(1) transaction.commit(1)
else: else:
raise raise
......
...@@ -19,6 +19,7 @@ import sys ...@@ -19,6 +19,7 @@ import sys
import unittest import unittest
import Testing import Testing
import ZODB import ZODB
import transaction
from OFS.Application import Application from OFS.Application import Application
from OFS.Folder import Folder from OFS.Folder import Folder
import App.config import App.config
...@@ -94,15 +95,15 @@ class DBTabTests (unittest.TestCase): ...@@ -94,15 +95,15 @@ class DBTabTests (unittest.TestCase):
root = conn.root() root = conn.root()
root['Application'] = app = Application() root['Application'] = app = Application()
self.app = app self.app = app
get_transaction().commit() # Get app._p_jar set transaction.commit() # Get app._p_jar set
manage_addMounts(app, ('/mount1', '/mount2')) manage_addMounts(app, ('/mount1', '/mount2'))
get_transaction().commit() # Get the mount points ready transaction.commit() # Get the mount points ready
def tearDown(self): def tearDown(self):
App.config.setConfiguration(original_config) App.config.setConfiguration(original_config)
get_transaction().abort() transaction.abort()
self.app._p_jar.close() self.app._p_jar.close()
del self.app del self.app
del self.db del self.db
...@@ -123,7 +124,7 @@ class DBTabTests (unittest.TestCase): ...@@ -123,7 +124,7 @@ class DBTabTests (unittest.TestCase):
self.assertEqual(app.mount1._p_changed, 1) self.assertEqual(app.mount1._p_changed, 1)
self.assertEqual(app.mount2._p_changed, 1) self.assertEqual(app.mount2._p_changed, 1)
self.assertEqual(app._p_changed, 1) self.assertEqual(app._p_changed, 1)
get_transaction().commit() transaction.commit()
self.assertEqual(app.mount1._p_changed, 0) self.assertEqual(app.mount1._p_changed, 0)
self.assertEqual(app.mount2._p_changed, 0) self.assertEqual(app.mount2._p_changed, 0)
self.assertEqual(app._p_changed, 0) self.assertEqual(app._p_changed, 0)
...@@ -173,7 +174,7 @@ class DBTabTests (unittest.TestCase): ...@@ -173,7 +174,7 @@ class DBTabTests (unittest.TestCase):
self.app.mount2 = Folder() self.app.mount2 = Folder()
self.app.mount2.id = 'mount2' self.app.mount2.id = 'mount2'
self.assert_(getMountPoint(self.app.mount2) is None) self.assert_(getMountPoint(self.app.mount2) is None)
get_transaction().commit() transaction.commit()
self.assert_(getMountPoint(self.app.mount2) is None) self.assert_(getMountPoint(self.app.mount2) is None)
......
...@@ -13,6 +13,8 @@ ...@@ -13,6 +13,8 @@
import TM, ThreadLock import TM, ThreadLock
from TM import Surrogate from TM import Surrogate
import transaction
thunk_lock=ThreadLock.allocate_lock() thunk_lock=ThreadLock.allocate_lock()
class THUNKED_TM(TM.TM): class THUNKED_TM(TM.TM):
...@@ -23,7 +25,7 @@ class THUNKED_TM(TM.TM): ...@@ -23,7 +25,7 @@ class THUNKED_TM(TM.TM):
if not self._registered: if not self._registered:
thunk_lock.acquire() thunk_lock.acquire()
try: try:
get_transaction().register(Surrogate(self)) transaction.get().register(Surrogate(self))
self._begin() self._begin()
except: except:
thunk_lock.release() thunk_lock.release()
......
...@@ -13,6 +13,7 @@ ...@@ -13,6 +13,7 @@
"""Provide support for linking an external transaction manager with Zope's """Provide support for linking an external transaction manager with Zope's
""" """
import transaction
class TM: class TM:
"""Mix-in class that provides transaction management support """Mix-in class that provides transaction management support
...@@ -35,7 +36,7 @@ class TM: ...@@ -35,7 +36,7 @@ class TM:
def _register(self): def _register(self):
if not self._registered: if not self._registered:
try: try:
get_transaction().register(Surrogate(self)) transaction.get().register(Surrogate(self))
self._begin() self._begin()
self._registered = 1 self._registered = 1
self._finalize = 0 self._finalize = 0
......
...@@ -25,6 +25,8 @@ __version__='$Revision: 1.11 $'[11:-2] ...@@ -25,6 +25,8 @@ __version__='$Revision: 1.11 $'[11:-2]
import string, sys import string, sys
from string import strip, split, find, join from string import strip, split, find, join
import transaction
failures=0 failures=0
calls=0 calls=0
...@@ -71,7 +73,7 @@ class DB: ...@@ -71,7 +73,7 @@ class DB:
def register(self): def register(self):
if self._registered: return if self._registered: return
get_transaction().register(self) transaction.get().register(self)
self._registered=1 self._registered=1
......
...@@ -15,6 +15,8 @@ import os, sys ...@@ -15,6 +15,8 @@ import os, sys
if __name__ == '__main__': if __name__ == '__main__':
execfile(os.path.join(sys.path[0], 'framework.py')) execfile(os.path.join(sys.path[0], 'framework.py'))
import transaction
from Testing.ZopeTestCase import base from Testing.ZopeTestCase import base
from Testing.ZopeTestCase import utils from Testing.ZopeTestCase import utils
...@@ -135,7 +137,7 @@ class TestTestCase(HookTest): ...@@ -135,7 +137,7 @@ class TestTestCase(HookTest):
def getObjectsInTransaction(self): def getObjectsInTransaction(self):
# Lets us spy into the transaction # Lets us spy into the transaction
t = get_transaction() t = transaction.get()
if hasattr(t, '_objects'): # Zope < 2.8 if hasattr(t, '_objects'): # Zope < 2.8
return t._objects return t._objects
elif hasattr(t, '_resources'): # Zope >= 2.8 elif hasattr(t, '_resources'): # Zope >= 2.8
......
...@@ -30,6 +30,8 @@ from Testing import ZopeTestCase ...@@ -30,6 +30,8 @@ from Testing import ZopeTestCase
from AccessControl import Unauthorized from AccessControl import Unauthorized
import urllib import urllib
import transaction
# Create the error_log object # Create the error_log object
ZopeTestCase.utils.setupSiteErrorLog() ZopeTestCase.utils.setupSiteErrorLog()
...@@ -73,11 +75,11 @@ class TestWebserver(ZopeTestCase.ZopeTestCase): ...@@ -73,11 +75,11 @@ class TestWebserver(ZopeTestCase.ZopeTestCase):
self.folder.change_title.changeOwnership(manager) self.folder.change_title.changeOwnership(manager)
# Commit so the ZServer threads can see the changes # Commit so the ZServer threads can see the changes
get_transaction().commit() transaction.commit()
def beforeClose(self): def beforeClose(self):
# Commit after cleanup # Commit after cleanup
get_transaction().commit() transaction.commit()
def testAccessPublicObject(self): def testAccessPublicObject(self):
# Test access to a public resource # Test access to a public resource
...@@ -177,9 +179,9 @@ class TestSandboxedWebserver(ZopeTestCase.Sandboxed, TestWebserver): ...@@ -177,9 +179,9 @@ class TestSandboxedWebserver(ZopeTestCase.Sandboxed, TestWebserver):
# Additionally, it allows us to commit transactions without # Additionally, it allows us to commit transactions without
# harming the test ZODB. # harming the test ZODB.
self.folder.foo = 1 self.folder.foo = 1
get_transaction().commit() transaction.commit()
self.folder.foo = 2 self.folder.foo = 2
get_transaction().commit() transaction.commit()
def test_suite(): def test_suite():
......
...@@ -14,6 +14,8 @@ if __name__ == '__main__': ...@@ -14,6 +14,8 @@ if __name__ == '__main__':
from Testing import ZopeTestCase from Testing import ZopeTestCase
import transaction
from AccessControl.Permissions import add_documents_images_and_files from AccessControl.Permissions import add_documents_images_and_files
from AccessControl.Permissions import delete_objects from AccessControl.Permissions import delete_objects
import tempfile import tempfile
...@@ -29,7 +31,7 @@ class TestCopyPaste(ZopeTestCase.ZopeTestCase): ...@@ -29,7 +31,7 @@ class TestCopyPaste(ZopeTestCase.ZopeTestCase):
self.folder.addDTMLMethod('doc', file='foo') self.folder.addDTMLMethod('doc', file='foo')
# _p_oids are None until we commit a subtransaction # _p_oids are None until we commit a subtransaction
self.assertEqual(self.folder._p_oid, None) self.assertEqual(self.folder._p_oid, None)
get_transaction().commit(1) transaction.commit(1)
self.failIfEqual(self.folder._p_oid, None) self.failIfEqual(self.folder._p_oid, None)
def testCutPaste(self): def testCutPaste(self):
...@@ -80,7 +82,7 @@ class TestImportExport(ZopeTestCase.ZopeTestCase): ...@@ -80,7 +82,7 @@ class TestImportExport(ZopeTestCase.ZopeTestCase):
self.folder.addDTMLMethod('doc', file='foo') self.folder.addDTMLMethod('doc', file='foo')
# _p_oids are None until we commit a subtransaction # _p_oids are None until we commit a subtransaction
self.assertEqual(self.folder._p_oid, None) self.assertEqual(self.folder._p_oid, None)
get_transaction().commit(1) transaction.commit(1)
self.failIfEqual(self.folder._p_oid, None) self.failIfEqual(self.folder._p_oid, None)
def testExport(self): def testExport(self):
...@@ -158,7 +160,7 @@ class DummyObject(SimpleItem): ...@@ -158,7 +160,7 @@ class DummyObject(SimpleItem):
app = ZopeTestCase.app() app = ZopeTestCase.app()
app._setObject('dummy1', DummyObject()) app._setObject('dummy1', DummyObject())
app._setObject('dummy2', DummyObject()) app._setObject('dummy2', DummyObject())
get_transaction().commit() transaction.commit()
ZopeTestCase.close(app) ZopeTestCase.close(app)
...@@ -295,45 +297,45 @@ class TestTransactionAbort(ZopeTestCase.ZopeTestCase): ...@@ -295,45 +297,45 @@ class TestTransactionAbort(ZopeTestCase.ZopeTestCase):
def testTransactionAbort(self): def testTransactionAbort(self):
self.folder.foo = 1 self.folder.foo = 1
self.failUnless(hasattr(self.folder, 'foo')) self.failUnless(hasattr(self.folder, 'foo'))
get_transaction().abort() transaction.abort()
# The foo attribute is still present # The foo attribute is still present
self.failUnless(hasattr(self.folder, 'foo')) self.failUnless(hasattr(self.folder, 'foo'))
def testSubTransactionAbort(self): def testSubTransactionAbort(self):
self.folder.foo = 1 self.folder.foo = 1
self.failUnless(hasattr(self.folder, 'foo')) self.failUnless(hasattr(self.folder, 'foo'))
get_transaction().commit(1) transaction.commit(1)
get_transaction().abort() transaction.abort()
# This time the abort nukes the foo attribute... # This time the abort nukes the foo attribute...
self.failIf(hasattr(self.folder, 'foo')) self.failIf(hasattr(self.folder, 'foo'))
def testTransactionAbortPersistent(self): def testTransactionAbortPersistent(self):
self.folder._p_foo = 1 self.folder._p_foo = 1
self.failUnless(hasattr(self.folder, '_p_foo')) self.failUnless(hasattr(self.folder, '_p_foo'))
get_transaction().abort() transaction.abort()
# The _p_foo attribute is still present # The _p_foo attribute is still present
self.failUnless(hasattr(self.folder, '_p_foo')) self.failUnless(hasattr(self.folder, '_p_foo'))
def testSubTransactionAbortPersistent(self): def testSubTransactionAbortPersistent(self):
self.folder._p_foo = 1 self.folder._p_foo = 1
self.failUnless(hasattr(self.folder, '_p_foo')) self.failUnless(hasattr(self.folder, '_p_foo'))
get_transaction().commit(1) transaction.commit(1)
get_transaction().abort() transaction.abort()
# This time the abort nukes the _p_foo attribute... # This time the abort nukes the _p_foo attribute...
self.failIf(hasattr(self.folder, '_p_foo')) self.failIf(hasattr(self.folder, '_p_foo'))
def testTransactionAbortVolatile(self): def testTransactionAbortVolatile(self):
self.folder._v_foo = 1 self.folder._v_foo = 1
self.failUnless(hasattr(self.folder, '_v_foo')) self.failUnless(hasattr(self.folder, '_v_foo'))
get_transaction().abort() transaction.abort()
# The _v_foo attribute is still present # The _v_foo attribute is still present
self.failUnless(hasattr(self.folder, '_v_foo')) self.failUnless(hasattr(self.folder, '_v_foo'))
def testSubTransactionAbortVolatile(self): def testSubTransactionAbortVolatile(self):
self.folder._v_foo = 1 self.folder._v_foo = 1
self.failUnless(hasattr(self.folder, '_v_foo')) self.failUnless(hasattr(self.folder, '_v_foo'))
get_transaction().commit(1) transaction.commit(1)
get_transaction().abort() transaction.abort()
# This time the abort nukes the _v_foo attribute... # This time the abort nukes the _v_foo attribute...
self.failIf(hasattr(self.folder, '_v_foo')) self.failIf(hasattr(self.folder, '_v_foo'))
......
...@@ -7,6 +7,7 @@ ...@@ -7,6 +7,7 @@
# $Id: utils.py,v 1.21 2005/02/11 09:00:21 shh42 Exp $ # $Id: utils.py,v 1.21 2005/02/11 09:00:21 shh42 Exp $
import transaction
def setupCoreSessions(app=None): def setupCoreSessions(app=None):
'''Sets up the session_data_manager e.a.''' '''Sets up the session_data_manager e.a.'''
...@@ -47,7 +48,8 @@ def setupCoreSessions(app=None): ...@@ -47,7 +48,8 @@ def setupCoreSessions(app=None):
app._setObject('session_data_manager', sdm) app._setObject('session_data_manager', sdm)
commit = 1 commit = 1
if commit: get_transaction().commit() if commit:
transaction.commit()
def setupZGlobals(app=None): def setupZGlobals(app=None):
...@@ -59,7 +61,7 @@ def setupZGlobals(app=None): ...@@ -59,7 +61,7 @@ def setupZGlobals(app=None):
if not root.has_key('ZGlobals'): if not root.has_key('ZGlobals'):
from BTrees.OOBTree import OOBTree from BTrees.OOBTree import OOBTree
root['ZGlobals'] = OOBTree() root['ZGlobals'] = OOBTree()
get_transaction().commit() transaction.commit()
def setupSiteErrorLog(app=None): def setupSiteErrorLog(app=None):
...@@ -74,7 +76,7 @@ def setupSiteErrorLog(app=None): ...@@ -74,7 +76,7 @@ def setupSiteErrorLog(app=None):
pass pass
else: else:
app._setObject('error_log', SiteErrorLog()) app._setObject('error_log', SiteErrorLog())
get_transaction().commit() transaction.commit()
import os, time import os, time
...@@ -85,7 +87,7 @@ def importObjectFromFile(container, filename, quiet=0): ...@@ -85,7 +87,7 @@ def importObjectFromFile(container, filename, quiet=0):
start = time.time() start = time.time()
if not quiet: _print("Importing %s ... " % os.path.basename(filename)) if not quiet: _print("Importing %s ... " % os.path.basename(filename))
container._importObjectFromFile(filename, verify=0) container._importObjectFromFile(filename, verify=0)
get_transaction().commit() transaction.commit()
if not quiet: _print('done (%.3fs)\n' % (time.time() - start)) if not quiet: _print('done (%.3fs)\n' % (time.time() - start))
......
...@@ -13,6 +13,8 @@ ...@@ -13,6 +13,8 @@
"""Provide management of common instance property sheets """Provide management of common instance property sheets
""" """
import transaction
import OFS.PropertySheets, Globals, OFS.SimpleItem, OFS.PropertyManager import OFS.PropertySheets, Globals, OFS.SimpleItem, OFS.PropertyManager
import Acquisition import Acquisition
from AccessControl.Permission import pname from AccessControl.Permission import pname
...@@ -24,13 +26,13 @@ class ClassCaretaker: ...@@ -24,13 +26,13 @@ class ClassCaretaker:
klass=self._k klass=self._k
setattr(klass, name, v) setattr(klass, name, v)
if not getattr(klass,'_p_changed',None): if not getattr(klass,'_p_changed',None):
get_transaction().register(klass) transaction.get().register(klass)
klass._p_changed=1 klass._p_changed=1
def __delattr__(self, name): def __delattr__(self, name):
klass=self._k klass=self._k
delattr(klass, name) delattr(klass, name)
if not getattr(klass,'_p_changed',None): if not getattr(klass,'_p_changed',None):
get_transaction().register(klass) transaction.get().register(klass)
klass._p_changed=1 klass._p_changed=1
...@@ -271,7 +273,7 @@ Globals.default__class_init__(ZInstanceSheet) ...@@ -271,7 +273,7 @@ Globals.default__class_init__(ZInstanceSheet)
def rclass(klass): def rclass(klass):
if not getattr(klass, '_p_changed', 0): if not getattr(klass, '_p_changed', 0):
get_transaction().register(klass) transaction.get().register(klass)
klass._p_changed=1 klass._p_changed=1
class ZInstanceSheetsSheet(OFS.Traversable.Traversable, class ZInstanceSheetsSheet(OFS.Traversable.Traversable,
......
...@@ -23,6 +23,8 @@ from Products.PythonScripts.PythonScript import PythonScript ...@@ -23,6 +23,8 @@ from Products.PythonScripts.PythonScript import PythonScript
from zExceptions import BadRequest, Redirect from zExceptions import BadRequest, Redirect
import webdav.Collection import webdav.Collection
import transaction
import marshal import marshal
if not hasattr(Products, 'meta_types'): if not hasattr(Products, 'meta_types'):
...@@ -301,17 +303,14 @@ class ZClass( Base ...@@ -301,17 +303,14 @@ class ZClass( Base
hasattr(self._zclass_, '_p_deactivate') hasattr(self._zclass_, '_p_deactivate')
) )
copy._zclass_.__dict__.update( copy._zclass_.__dict__.update(self._zclass_.__dict__)
self._zclass_.__dict__) transaction.get().register(copy._zclass_)
get_transaction().register(
copy._zclass_)
self._p_jar.exchange(self._zclass_, copy._zclass_) self._p_jar.exchange(self._zclass_, copy._zclass_)
self._zclass_=copy._zclass_ self._zclass_=copy._zclass_
copy._zclass_propertysheets_class.__dict__.update( copy._zclass_propertysheets_class.__dict__.update(
self._zclass_propertysheets_class.__dict__) self._zclass_propertysheets_class.__dict__)
get_transaction().register( transaction.get().register(copy._zclass_propertysheets_class)
copy._zclass_propertysheets_class)
self._p_jar.exchange(self._zclass_propertysheets_class, self._p_jar.exchange(self._zclass_propertysheets_class,
copy._zclass_propertysheets_class) copy._zclass_propertysheets_class)
self._zclass_propertysheets_class=copy._zclass_propertysheets_class self._zclass_propertysheets_class=copy._zclass_propertysheets_class
...@@ -319,8 +318,7 @@ class ZClass( Base ...@@ -319,8 +318,7 @@ class ZClass( Base
if hasattr(self.propertysheets.__class__, '_p_oid'): if hasattr(self.propertysheets.__class__, '_p_oid'):
copy.propertysheets.__class__.__dict__.update( copy.propertysheets.__class__.__dict__.update(
self.propertysheets.__class__.__dict__) self.propertysheets.__class__.__dict__)
get_transaction().register( transaction.get().register(copy.propertysheets.__class__)
copy.propertysheets.__class__)
self._p_jar.exchange(self.propertysheets.__class__, self._p_jar.exchange(self.propertysheets.__class__,
copy.propertysheets.__class__) copy.propertysheets.__class__)
...@@ -520,7 +518,7 @@ class ZClass( Base ...@@ -520,7 +518,7 @@ class ZClass( Base
c=self._zclass_ c=self._zclass_
setattr(c, name, value) setattr(c, name, value)
if not c._p_changed: if not c._p_changed:
get_transaction().register(c) transaction.get().register(c)
c._p_changed=1 c._p_changed=1
delClassAttr__roles__ = () # Private delClassAttr__roles__ = () # Private
...@@ -528,7 +526,7 @@ class ZClass( Base ...@@ -528,7 +526,7 @@ class ZClass( Base
c=self._zclass_ c=self._zclass_
delattr(c, name) delattr(c, name)
if not c._p_changed: if not c._p_changed:
get_transaction().register(c) transaction.get().register(c)
c._p_changed=1 c._p_changed=1
def classDefinedPermissions(self): def classDefinedPermissions(self):
......
...@@ -275,13 +275,10 @@ def get_module_info(module_name, modules={}, ...@@ -275,13 +275,10 @@ def get_module_info(module_name, modules={},
transactions_manager=getattr( transactions_manager=getattr(
module,'zpublisher_transactions_manager', None) module,'zpublisher_transactions_manager', None)
if not transactions_manager: if not transactions_manager:
try: get_transaction() # Create a default transactions manager for use
except: pass # by software that uses ZPublisher and ZODB but
else: # not the rest of Zope.
# Create a default transactions manager for use transactions_manager = DefaultTransactionsManager()
# by software that uses ZPublisher and ZODB but
# not the rest of Zope.
transactions_manager = DefaultTransactionsManager()
info= (bobo_before, bobo_after, object, realm, debug_mode, info= (bobo_before, bobo_after, object, realm, debug_mode,
error_hook, validated_hook, transactions_manager) error_hook, validated_hook, transactions_manager)
...@@ -302,13 +299,13 @@ class DefaultTransactionsManager: ...@@ -302,13 +299,13 @@ class DefaultTransactionsManager:
def begin(self): def begin(self):
transaction.begin() transaction.begin()
def commit(self): def commit(self):
get_transaction().commit() transaction.commit()
def abort(self): def abort(self):
get_transaction().abort() transaction.abort()
def recordMetaData(self, object, request): def recordMetaData(self, object, request):
# Is this code needed? # Is this code needed?
request_get = request.get request_get = request.get
T=get_transaction() T= transaction.get()
T.note(request_get('PATH_INFO')) T.note(request_get('PATH_INFO'))
auth_user=request_get('AUTHENTICATED_USER',None) auth_user=request_get('AUTHENTICATED_USER',None)
if auth_user is not None: if auth_user is not None:
......
...@@ -167,8 +167,9 @@ ZServer monitor server ...@@ -167,8 +167,9 @@ ZServer monitor server
Remember if you make changes to Zope objects and want those changes to be Remember if you make changes to Zope objects and want those changes to be
saved you need to commmit the transaction:: saved you need to commmit the transaction::
>>> get_transaction().commit() >>> import transaction
>>> transaction.commit()
ZServer WebDAV support ZServer WebDAV support
......
...@@ -213,20 +213,15 @@ class TransactionsManager: ...@@ -213,20 +213,15 @@ class TransactionsManager:
transaction=transaction): transaction=transaction):
transaction.begin() transaction.begin()
def commit(self, def commit(self):
# Optimize global var lookups: transaction.commit()
get_transaction=get_transaction):
get_transaction().commit()
def abort(self, def abort(self):
# Optimize global var lookups: transaction.abort()
get_transaction=get_transaction):
get_transaction().abort()
def recordMetaData(self, object, request, def recordMetaData(self, object, request,
# Optimize global var lookups: # Optimize global var lookups:
hasattr=hasattr, getattr=getattr, hasattr=hasattr, getattr=getattr,
get_transaction=get_transaction,
LOG=LOG, WARNING=WARNING, LOG=LOG, WARNING=WARNING,
): ):
request_get = request.get request_get = request.get
...@@ -260,7 +255,7 @@ class TransactionsManager: ...@@ -260,7 +255,7 @@ class TransactionsManager:
# used to retrieve the object. # used to retrieve the object.
path = request_get('PATH_INFO') path = request_get('PATH_INFO')
T=get_transaction() T = transaction.get()
T.note(path) T.note(path)
auth_user=request_get('AUTHENTICATED_USER',None) auth_user=request_get('AUTHENTICATED_USER',None)
if auth_user is not None: if auth_user is not None:
......
...@@ -39,6 +39,8 @@ import os ...@@ -39,6 +39,8 @@ import os
import sys import sys
import signal import signal
import transaction
import zdaemon import zdaemon
import Zope2.Startup import Zope2.Startup
...@@ -214,7 +216,7 @@ class ZopeCmd(ZDCmd): ...@@ -214,7 +216,7 @@ class ZopeCmd(ZDCmd):
self.options.python , self.options.python ,
'import Zope2; app=Zope2.app();' 'import Zope2; app=Zope2.app();'
'app.acl_users._doAddUser(\'%s\', \'%s\', [\'Manager\'], []);' 'app.acl_users._doAddUser(\'%s\', \'%s\', [\'Manager\'], []);'
'get_transaction().commit()' 'transaction.commit()'
) % (name, password) ) % (name, password)
os.system(cmdline) os.system(cmdline)
......
...@@ -29,6 +29,7 @@ from AccessControl import getSecurityManager ...@@ -29,6 +29,7 @@ from AccessControl import getSecurityManager
from zExceptions import BadRequest, Forbidden from zExceptions import BadRequest, Forbidden
from common import isDavCollection from common import isDavCollection
from common import PreconditionFailed from common import PreconditionFailed
import transaction
def safe_quote(url, mark=r'%'): def safe_quote(url, mark=r'%'):
if url.find(mark) > -1: if url.find(mark) > -1:
...@@ -288,7 +289,7 @@ class PropPatch: ...@@ -288,7 +289,7 @@ class PropPatch:
return result return result
# This is lame, but I cant find a way to keep ZPublisher # This is lame, but I cant find a way to keep ZPublisher
# from sticking a traceback into my xml response :( # from sticking a traceback into my xml response :(
get_transaction().abort() transaction.abort()
result=result.replace( '200 OK', '424 Failed Dependency') result=result.replace( '200 OK', '424 Failed Dependency')
return result return result
...@@ -410,7 +411,7 @@ class Lock: ...@@ -410,7 +411,7 @@ class Lock:
# One or more subitems probably failed, so close the multistatus # One or more subitems probably failed, so close the multistatus
# element and clear out all succesful locks # element and clear out all succesful locks
result.write('</d:multistatus>') result.write('</d:multistatus>')
get_transaction().abort() # This *SHOULD* clear all succesful locks transaction.abort() # This *SHOULD* clear all succesful locks
return token, result.getvalue() return token, result.getvalue()
...@@ -472,7 +473,7 @@ class Unlock: ...@@ -472,7 +473,7 @@ class Unlock:
# One or more subitems probably failed, so close the multistatus # One or more subitems probably failed, so close the multistatus
# element and clear out all succesful unlocks # element and clear out all succesful unlocks
result.write('</d:multistatus>') result.write('</d:multistatus>')
get_transaction().abort() transaction.abort()
return result.getvalue() return result.getvalue()
......
...@@ -28,6 +28,7 @@ $Id$ ...@@ -28,6 +28,7 @@ $Id$
import sys import sys
from optparse import OptionParser from optparse import OptionParser
import transaction
from Products.ZCatalog.ProgressHandler import StdoutHandler from Products.ZCatalog.ProgressHandler import StdoutHandler
...@@ -71,7 +72,7 @@ def reindexIndexes(optioons, args): ...@@ -71,7 +72,7 @@ def reindexIndexes(optioons, args):
for id in args: for id in args:
print 'Reindexing index %s at %s' % (id, options.catalog) print 'Reindexing index %s at %s' % (id, options.catalog)
catalog.reindexIndex(id, None, handler) catalog.reindexIndex(id, None, handler)
get_transaction().commit() transaction.commit()
def refreshMetadata(options, args): def refreshMetadata(options, args):
...@@ -82,7 +83,7 @@ def refreshMetadata(options, args): ...@@ -82,7 +83,7 @@ def refreshMetadata(options, args):
print 'Refresh metadata at %s' % options.catalog print 'Refresh metadata at %s' % options.catalog
catalog.refreshMetadata(handler) catalog.refreshMetadata(handler)
get_transaction().commit() transaction.commit()
def reindexAll(options, args): def reindexAll(options, args):
...@@ -93,7 +94,7 @@ def reindexAll(options, args): ...@@ -93,7 +94,7 @@ def reindexAll(options, args):
print 'Reindexing complete ZCatalog at %s' % options.catalog print 'Reindexing complete ZCatalog at %s' % options.catalog
catalog.refreshCatalog(options.clearCatalog, handler) catalog.refreshCatalog(options.clearCatalog, handler)
get_transaction().commit() transaction.commit()
if __name__ == '__main__': if __name__ == '__main__':
......
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment