<commit_before># -*- coding: utf-8 -*-
##
##
## This file is part of CDS Indico.
## Copyright (C) 2002, 2003, 2004, 2005, 2006, 2007 CERN.
##
## CDS Indico is free software; you can redistribute it and/or
## modify it under the terms of the GNU General Public License as
## published by the Free Software Foundation; either version 2 of the
## License, or (at your option) any later version.
##
## CDS Indico is distributed in the hope that it will be useful, but
## WITHOUT ANY WARRANTY; without even the implied warranty of
## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
## General Public License for more details.
##
## You should have received a copy of the GNU General Public License
## along with CDS Indico; if not, write to the Free Software Foundation, Inc.,
## 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA.

"""This file contains the implementation of some classes dealing with the DB
    so it's usage is easier and more transparent to the rest of the application
"""
import os
import sys
import threading
import pkg_resources

from ZEO.ClientStorage import ClientStorage
from ZODB.DB import DB
import transaction
import ZODB

from MaKaC.consoleScripts.installBase import getIndicoInstallMode
skip_imports = getIndicoInstallMode()

if not skip_imports:
    from MaKaC.common.logger import Logger
    from MaKaC.i18n import _

class MaKaCDB(DB):
    """Subclass of ZODB.DB necessary to remove possible existing dependencies
        from IC"""

    def classFactory(self, connection, modulename, globalname):
        if globalname=="PersistentMapping":
            modulename="persistent.mapping"
        elif globalname=="PersistentList":
            modulename="persistent.list"
        elif modulename.startswith("IndexedCatalog.BTrees."):
            modulename="BTrees.%s"%modulename[22:]
        return DB.classFactory(self, connection, modulename, globalname)



class DBMgr:
    """This class provides the access point to the Shelf (every client will
        use this class in order to obtain a shelf) and some mechanism to
        ensure there is only one connection opened to the DB during a single
        request.
        This class must not be instantiated, an instance can be obtained
        though the "getInstance" method (implements the singleton pattern
        to ensure unicity)
        Needs to be checked if the class (static) attribute _instance is
        thread-safe: as it is shared by all the objects of this class,
        it could provoke concurrency troubles having 2 threads using the db
        connection at the same time. However, the model under which we are
        programming is not multi-threaded (mod_python seems to run different
        interpreters for each apache subprocess, see mod_python doc section
        4.1) so this thechnique can be used. This has to be taken into account
        when migrating the system to a multi-threading environment.
    """
    _instance = None

    def __init__( self, hostname=None, port=None ):
        import Configuration # Please leave this import here, db.py is imported during installation process
        cfg = Configuration.Config.getInstance()

        if not hostname:
            hostname = cfg.getDBConnectionParams()[0]
        if not port:
            port = cfg.getDBConnectionParams()[1]

        self._storage=ClientStorage((hostname, port), username=cfg.getDBUserName(), password=cfg.getDBPassword(), realm=cfg.getDBRealm())
        self._db=MaKaCDB(self._storage)
        self._conn={}

    @classmethod
    def getInstance( cls, *args, **kwargs ):
        if cls._instance == None:
            Logger.get('dbmgr').debug('cls._instance is None')
            cls._instance=DBMgr(*args, **kwargs)
        return cls._instance

    @staticmethod
    def _getUniqueIdentifier():
        return threading._get_ident()

    def _getConnObject(self):
        tid = DBMgr._getUniqueIdentifier()
        return self._conn[tid]

    def _delConnObject(self):
        tid = DBMgr._getUniqueIdentifier()
        del self._conn[tid]

    def startRequest( self ):
        """Initialise the DB and starts a new transaction.
        """

        tid = DBMgr._getUniqueIdentifier()

        self._conn[tid] = self._db.open()
        Logger.get('dbmgr').debug('Allocated connection for %s - table size is %s' % \
                                  (tid, len(self._conn)))

    def endRequest( self, commit=True ):
        """Closes the DB and commits changes.
        """
        if commit:
            self.commit()
        else:
            self.abort()

        #modification vendredi 010907
#        try:
#            self._conn.close()
#            self._conn=None
#        except:
#            pass

        self._getConnObject().close()
        self._delConnObject()

    def getDBConnection( self ):
        conn = self._getConnObject()
        if conn == None:
            raise Exception( _("request not started"))
        return conn

    def isConnected( self ):
        if self._getConnObject() == None:
            return False
        else:
            return True

    def getDBConnCache(self):
        conn = self._getConnObject()
        if conn == None:
            raise Exception( _("request not started"))
        return conn._cache

    def getDBClassFactory(self):
        return self._db.classFactory

    def commit(self, sub=False):
        if (sub):
            transaction.savepoint()<commit_msg>[FIX] isConnected bug<commit_after># -*- coding: utf-8 -*-
##
##
## This file is part of CDS Indico.
## Copyright (C) 2002, 2003, 2004, 2005, 2006, 2007 CERN.
##
## CDS Indico is free software; you can redistribute it and/or
## modify it under the terms of the GNU General Public License as
## published by the Free Software Foundation; either version 2 of the
## License, or (at your option) any later version.
##
## CDS Indico is distributed in the hope that it will be useful, but
## WITHOUT ANY WARRANTY; without even the implied warranty of
## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
## General Public License for more details.
##
## You should have received a copy of the GNU General Public License
## along with CDS Indico; if not, write to the Free Software Foundation, Inc.,
## 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA.

"""This file contains the implementation of some classes dealing with the DB
    so it's usage is easier and more transparent to the rest of the application
"""
import os
import sys
import threading
import pkg_resources

from ZEO.ClientStorage import ClientStorage
from ZODB.DB import DB
import transaction
import ZODB

from MaKaC.consoleScripts.installBase import getIndicoInstallMode
skip_imports = getIndicoInstallMode()

if not skip_imports:
    from MaKaC.common.logger import Logger
    from MaKaC.i18n import _

class MaKaCDB(DB):
    """Subclass of ZODB.DB necessary to remove possible existing dependencies
        from IC"""

    def classFactory(self, connection, modulename, globalname):
        if globalname=="PersistentMapping":
            modulename="persistent.mapping"
        elif globalname=="PersistentList":
            modulename="persistent.list"
        elif modulename.startswith("IndexedCatalog.BTrees."):
            modulename="BTrees.%s"%modulename[22:]
        return DB.classFactory(self, connection, modulename, globalname)



class DBMgr:
    """This class provides the access point to the Shelf (every client will
        use this class in order to obtain a shelf) and some mechanism to
        ensure there is only one connection opened to the DB during a single
        request.
        This class must not be instantiated, an instance can be obtained
        though the "getInstance" method (implements the singleton pattern
        to ensure unicity)
        Needs to be checked if the class (static) attribute _instance is
        thread-safe: as it is shared by all the objects of this class,
        it could provoke concurrency troubles having 2 threads using the db
        connection at the same time. However, the model under which we are
        programming is not multi-threaded (mod_python seems to run different
        interpreters for each apache subprocess, see mod_python doc section
        4.1) so this thechnique can be used. This has to be taken into account
        when migrating the system to a multi-threading environment.
    """
    _instance = None

    def __init__( self, hostname=None, port=None ):
        import Configuration # Please leave this import here, db.py is imported during installation process
        cfg = Configuration.Config.getInstance()

        if not hostname:
            hostname = cfg.getDBConnectionParams()[0]
        if not port:
            port = cfg.getDBConnectionParams()[1]

        self._storage=ClientStorage((hostname, port), username=cfg.getDBUserName(), password=<PASSWORD>(), realm=cfg.getDBRealm())
        self._db=MaKaCDB(self._storage)
        self._conn={}

    @classmethod
    def getInstance( cls, *args, **kwargs ):
        if cls._instance == None:
            Logger.get('dbmgr').debug('cls._instance is None')
            cls._instance=DBMgr(*args, **kwargs)
        return cls._instance

    @staticmethod
    def _getUniqueIdentifier():
        return threading._get_ident()

    def _getConnObject(self):
        tid = DBMgr._getUniqueIdentifier()
        return self._conn[tid]

    def _delConnObject(self):
        tid = DBMgr._getUniqueIdentifier()
        del self._conn[tid]

    def startRequest( self ):
        """Initialise the DB and starts a new transaction.
        """

        tid = DBMgr._getUniqueIdentifier()

        self._conn[tid] = self._db.open()
        Logger.get('dbmgr').debug('Allocated connection for %s - table size is %s' % \
                                  (tid, len(self._conn)))

    def endRequest( self, commit=True ):
        """Closes the DB and commits changes.
        """
        if commit:
            self.commit()
        else:
            self.abort()

        #modification vendredi 010907
#        try:
#            self._conn.close()
#            self._conn=None
#        except:
#            pass

        self._getConnObject().close()
        self._delConnObject()

    def getDBConnection( self ):
        return self._getConnObject()

    def isConnected( self ):
        tid = DBMgr._getUniqueIdentifier()

        return tid in self._conn

    def getDBConnCache(self):
        conn = self._getConnObject()
        return conn._cache

    def getDBClassFactory(self):
        return self._db.classFactory

    def commit(self, sub=False):
        if (sub):
            transaction.savepoint()
{'fraction_non_alphanumeric': 0.0825147347740668, 'fraction_numerical': 0.010290953316493592, 'mean_word_length': 2.6951261666090565, 'pattern_counts': {'":': 4, '<': 4, '<?xml version=': 0, '>': 4, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 2, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '4502243', 'n_tokens_mistral': 2927, 'n_tokens_neox': 2791, 'n_words': 1075}