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

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

Complete - # 22434: CEDA Observation - keywords (following Gemini method)
 http://team.ceda.ac.uk/trac/ceda/ticket/22434
Removed the SA session from all but the EPBxx instances

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 = create_engine(self._connection, echo=sql_echo)
38        self.metadata = MetaData(bind=self.engine)       
39        self._session = None
40        self._session_event_manager = session_event_manager
41        if self._script:
42            self._script(self.metadata)
43            self.metadata.create_all(bind=self.engine)
44            #self._session = scoped_session(sessionmaker())
45        if self.engine:
46            self.engine.connect()
47           
48    def createDbSession(self):
49        """
50           Returns a brand new connection to the DB.       
51           @return: a sqlalchemy.orm.session.Session instance if the ORM is fully configured, otherwise a sqlalchemy.engine.base.Connection instance
52        """
53        #session = scoped_session(sessionmaker(bind=self.engine))()
54        session = sessionmaker(bind=self.engine)()       
55        if self._session_event_manager:
56            self._session_event_manager(session)
57        return session       
58        #if self._session:
59        #    ret = self._session()
60        #    if self._session_event_manager:
61        #        self._session_event_manager(ret)
62        #    return ret
63        #if self.engine:
64        #    return self.engine.connect()
65
66    def closeDbSession(self, dbSession):
67        """
68          Commits and closes the given session/connection instance
69          :param dbSession: a Session/Connection instance
70        """
71        try:
72            dbSession.commit()
73            dbSession.close()
74        except:
75            dbSession.rollback()
76            dbSession.close()
77            raise
78       
79    def executeNative(self, sqlNative):
80        t = text(sqlNative)
81        return self._connection.execute(t)
82
83def doInsertOrUpdate(items, session, update = True):
84    if update:
85        session.commit()
86    else:
87        session.add_all(items)
88
89def getObjectId(clazz, obj_id, session): 
90    '''
91        Retrieves an entity
92        @param clazz: the entity type
93        @param obj_id: the entity id 
94    '''       
95    res = session.query(clazz).get(obj_id)
96    if res is None:
97        return None
98    return res
99
100def getAllObjects(clazz, session):     
101    res = session.query(clazz)
102    if res is None:
103        return None
104    return res
Note: See TracBrowser for help on using the repository browser.