source: mauRepo/MolesManager/trunk/src/libs/commons_db.py @ 8344

Subversion URL: http://proj.badc.rl.ac.uk/svn/ndg/mauRepo/MolesManager/trunk/src/libs/commons_db.py@8344
Revision 8344, 3.7 KB checked in by mnagni, 7 years ago (diff)

Share project "HPFos" into " http://proj.badc.rl.ac.uk/svn/ndg/mauRepo"

Line 
1'''
2Created on 17 Nov 2011
3
4@author: mnagni
5'''
6from sqlalchemy import MetaData, create_engine
7from sqlalchemy.orm import sessionmaker, scoped_session
8from sqlalchemy.sql.expression import text
9class DbManagerCollection(object):
10    """
11        Represents a collection of DbManagers. The key of the dictionary passed as argument to the constructor
12        will be used to retrieve a specific db instance.         
13    """
14    def __init__(self, dbManagers = {}): 
15        self._dbManagers = dbManagers
16       
17    def createSession(self, name):
18        if self._dbManagers.has_key(name):
19            return self._dbManagers[name].createDbSession()
20
21class DbManager(object):
22   
23
24    """
25        Represents a database instance managed by an SQLAlchemy engine.       
26    """
27    def __init__(self, connection, script = None, sql_echo=False, session_event_manager = None):
28        """
29          @param connection: the URL used to open a connection to the database
30          @param script: a python module defining the classes mapping
31          @param sql_echo: sets the SQLalchemy create_engine.echo param. Default is False
32          @param session_event_manager: a python method defining session events \
33          (see http://docs.sqlalchemy.org/en/latest/orm/events.html?highlight=session%20events#sqlalchemy.orm.events.SessionEvents)     
34        """
35        self._connection = connection       
36        self._script = script
37        self.engine = None
38        try:
39            self.engine = create_engine(self._connection, echo=sql_echo)
40        except Exception as e:
41            print e
42        self.metadata = MetaData(bind=self.engine)       
43        self._session = None
44        self._session_event_manager = session_event_manager
45        if self._script:
46            self._script(self.metadata)
47            self.metadata.create_all(bind=self.engine)
48            #self._session = scoped_session(sessionmaker())
49        if self.engine:
50            self.engine.connect()
51           
52    def createDbSession(self):
53        """
54           Returns a brand new connection to the DB.       
55           @return: a sqlalchemy.orm.session.Session instance if the ORM is fully configured, otherwise a sqlalchemy.engine.base.Connection instance
56        """
57        #session = scoped_session(sessionmaker(bind=self.engine))()
58        session = sessionmaker(bind=self.engine)()       
59        if self._session_event_manager:
60            self._session_event_manager(session)
61        return session       
62        #if self._session:
63        #    ret = self._session()
64        #    if self._session_event_manager:
65        #        self._session_event_manager(ret)
66        #    return ret
67        #if self.engine:
68        #    return self.engine.connect()
69
70    def closeDbSession(self, dbSession):
71        """
72          Commits and closes the given session/connection instance
73          :param dbSession: a Session/Connection instance
74        """
75        try:
76            dbSession.commit()
77            dbSession.close()
78        except:
79            dbSession.rollback()
80            dbSession.close()
81            raise
82       
83    def executeNative(self, sqlNative):
84        t = text(sqlNative)
85        return self._connection.execute(t)
86
87def doInsertOrUpdate(items, session, update = True):
88    if update:
89        session.commit()
90    else:
91        session.add_all(items)
92
93def getObjectId(clazz, obj_id, session): 
94    '''
95        Retrieves an entity
96        @param clazz: the entity type
97        @param obj_id: the entity id 
98    '''       
99    res = session.query(clazz).get(obj_id)
100    if res is None:
101        return None
102    return res
103
104def getAllObjects(clazz, session):     
105    res = session.query(clazz)
106    if res is None:
107        return None
108    return res
Note: See TracBrowser for help on using the repository browser.