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

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