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

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

Implementation of tickets #22390

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):
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        """
32        self._metadata = MetaData()
33        self._connection = connection
34        self._script = script
35        self._engine = create_engine(self._connection, echo=True)
36        if (self._script):
37            self._script(self._metadata)
38            #execfile(self._script, {'metadata': DbManager._metadata, 'engine': self._engine})
39            self._metadata.create_all(bind=self._engine)
40        self._session = scoped_session(sessionmaker(bind=self._engine))   
41 
42    def createDbSession(self):
43        """
44           Returns a brand new Session
45        """
46        return self._session()
47
48    def closeDbSession(self, dbSession):
49        """
50          Commits and closes the given session instance
51          :param dbSession: a Session instance
52        """
53        try:
54            dbSession.commit()
55            dbSession.close()
56        except:
57            dbSession.rollback()
58            dbSession.close()
59            raise
60       
61    def executeNative(self, sqlNative):
62        t = text(sqlNative)
63        return self._connection.execute(t)
64
65def doInsertOrUpdate(items, session, update = True):
66    if update:
67        session.commit()
68    else:
69        session.add_all(items)
70
71def getObjectId(clazz, id, session): 
72    '''
73        Retrieves an entity
74        @param clazz: the entity type
75        @param id: the entity id 
76    '''       
77    res = session.query(clazz).get(id)
78    if res is None:
79        return None
80    return res
81
82def getAllObjects(clazz, session):     
83    res = session.query(clazz)
84    if res is None:
85        return None
86    return res
Note: See TracBrowser for help on using the repository browser.