from ZODB.Connection import Connection
from time import time
import transaction

global_reset_counter = 0

def open(self, transaction_manager=None, mvcc=True, synch=True,
            delegate=True):
    """Register odb, the DB that this Connection uses.

    This method is called by the DB every time a Connection
    is opened.  Any invalidations received while the Connection
    was closed will be processed.

    If the global module function resetCaches() was called, the
    cache will be cleared.

    Parameters:
    odb: database that owns the Connection
    mvcc: boolean indicating whether MVCC is enabled
    transaction_manager: transaction manager to use.  None means
        use the default transaction manager.
    synch: boolean indicating whether Connection should
    register for afterCompletion() calls.
    """

    # TODO:  Why do we go to all the trouble of setting _db and
    # other attributes on open and clearing them on close?
    # A Connection is only ever associated with a single DB
    # and Storage.

    self._opened = time()
    self._synch = synch
    self._mvcc = mvcc and not self._version
    if transaction_manager is None:
        transaction_manager = transaction.manager

    self.transaction_manager = transaction_manager

    # js 28-5-2007 always call _flush_invalidations 
    self._flush_invalidations()
    if self._reset_counter != global_reset_counter:
        # New code is in place.  Start a new cache.
        self._resetCache()
    # else:
    #     import pdb; pdb.set_trace()
    #     self._flush_invalidations()

    if synch:
        transaction_manager.registerSynch(self)

    if self._cache is not None:
        self._cache.incrgc() # This is a good time to do some GC

    if delegate:
        # delegate open to secondary connections
        for connection in self.connections.values():
            if connection is not self:
                connection.open(transaction_manager, mvcc, synch, False)

Connection.open = open
