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

Subversion URL: http://proj.badc.rl.ac.uk/svn/ndg/mauRepo/MolesManager/trunk/src/libs/epb.py@8344
Revision 8344, 7.0 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 10 Jan 2012
3
4@author: mnagni
5'''
6from sqlalchemy.orm import subqueryload
7from sqlalchemy.sql.expression import text
8from sqlalchemy.orm.util import identity_key
9
10class EPB(object):
11
12    @classmethod
13    def buildFilter(self, key, keyValue):
14        try:
15            return '%s = \'%s\'' % (key, keyValue)
16        except RuntimeError as er:
17            print er
18
19    @classmethod
20    def search(self, clazz, inst_key, session):
21        """
22            Searches a required instance by id
23            @param clazz: the class type to search for
24            @param inst_key: the instance id for which the search is done. If None return a query object
25            @param session: a session to use for the query
26            @return the required instance
27        """
28        if inst_key:
29            res = session.query(clazz).get(inst_key)
30        else:
31            res = session.query(clazz)
32           
33        if res is None:
34            return None
35        return res           
36       
37
38
39    @classmethod
40    def searchEager(self, clazz, inst_id, session):
41        """
42            Searches a required instance by id loading eagerly ALL its field. Please use carefully because \
43            it could impact the performance
44            @param clazz: the class type to search for
45            @param inst_id: the instance id for which the search is done
46            @param session: a session to use for the query   
47            @return the required instance                   
48        """
49        res = session.query(clazz).options(subqueryload('*')).get(inst_id)
50        if res is None:
51            return None
52           
53        return res
54
55    @classmethod
56    def searchSelectiveLoad(self, clazz, inst_id, attrs, session):
57        """
58            Searches a required instance by id loading \
59            the specified fields. The parameter "attrs" is a single string or a list of attributes
60            owned by the instance of "clazz". Furthermore such list may contain
61            also the children of the main attributes. For example "attrs" may look
62            like
63            ['resultAccumulation', 'identifier.authority', 'resultTime.position.dateTime8601.month', \
64                      'relatedParty.party', 'result.source.function', 'permission', \
65                      'geographicExtent', 'phenomenonTime', 'keywords', 'description', \
66                      'inSupportOf.abstract', 'dataLineage']
67            the first parameter refers to the main class so is equivalent to
68            clazz.resultAccumulation
69            the second parameter is equivalent to invoke
70            clazz.identifier.authority
71            As single string "attrs" could be as well just 'identifier.authority'
72            @param clazz: the class type to search for
73            @param inst_id: the instance id for which the search is done
74            @param attrs: a single string or a list of attributes to load
75            @param session: a session to use for the query
76            @return the required instance             
77        """         
78        if session is None:
79            raise Exception("Session is None!")       
80        res = EPB.search(clazz, inst_id, session)
81        if res is None:
82            return None
83        self._drillData(res, attrs)
84        return res
85
86    @classmethod
87    def loadAttributes(self, instance, attributes, session):
88        """
89            Loads the given instance with the required attributes.
90            The parameter "attributes" is a single string or a list of attributes
91            owned by the instance of "clazz". Furthermore such list may contain
92            also the children of the main attributes. For example "attrs" may look
93            like
94            ['resultAccumulation', 'identifier.authority', 'resultTime.position.dateTime8601.month', \
95                      'relatedParty.party', 'result.source.function', 'permission', \
96                      'geographicExtent', 'phenomenonTime', 'keywords', 'description', \
97                      'inSupportOf.abstract', 'dataLineage']
98            the first parameter refers to the main class so is equivalent to
99            clazz.resultAccumulation
100            the second parameter is equivalent to invoke
101            clazz.identifier.authority
102            As single string "attributes" could be as well just 'identifier.authority'
103            It does not return anything because it does not close the session
104            @param instance: an instance containing the appropriate id
105            @param attributes: a single string or a list of attributes to load
106            @param session: the session to use for the operation                             
107        """
108        if instance is None:
109            raise Exception("Instance is None!")
110        if session is None:
111            raise Exception("Session is None!")
112        session.merge(instance)
113        self._drillData(instance, attributes)                   
114
115
116    @classmethod   
117    def searchOrCreate(self, clazz, session, clazz_id = None):
118        if clazz_id is not None:
119            return EPB.search(clazz, clazz_id, session)
120        else:                       
121            return clazz()
122       
123
124    @classmethod
125    def getAllObjects(self, clazz, session):     
126        res = session.query(clazz)
127        if res is None:
128            return None
129        return res
130
131    @classmethod
132    def persistInstance(self, instance, session):
133        """
134            Adds a new migration object.
135            @param migrationObj: the migration object to add
136            @param session: an sqlalchemy Session object. If None (default) the method creates
137            @return an updated, session independant, object instance reflecting the new persisted object
138        """       
139        session.add(instance)
140        session.commit()
141        id_key = identity_key(instance=instance)
142        instance = EPB.search(id_key[0], id_key[1], session)
143        #instance = ret
144
145    @classmethod
146    def executeNative(self, sqlNative, session):
147        return session.execute(text(sqlNative))     
148
149    @classmethod
150    def _getSession(self, dbManager, session = None):
151        if session:
152            return session       
153        return dbManager.createDbSession()
154
155    @classmethod
156    def _drillData(self, obj, attrs):
157        """
158            @param obj: its an instance already living inside an SQLAlchemy session
159            @param attrs: a list of attributes owned by the obj parameter. It accepts dot separated attributes as childern of obj attributes.
160        """
161        #if is a single field wrap it in a list and recalls itself
162        if not isinstance(attrs, list):
163            self._drillData(obj, [attrs])
164        for item in attrs:
165            attr = item.split('.')[0]           
166            if isinstance(obj, list):
167                for element in obj:
168                    self._drillData(element, [item])
169            else:
170                if hasattr(obj, attr):
171                    nobj = getattr(obj, attr) 
172                    if len(attr) != len(item):
173                        self._drillData(nobj, [item[len(attr) + 1:]])
174
175       
Note: See TracBrowser for help on using the repository browser.