source: mauRepo/MolesManager/trunk/src/MolesManager/moles3epb.py @ 8295

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

added a method on moles3epb to retrieve a CEDA_Observation author

Line 
1'''
2Created on 10 Jan 2012
3
4@author: mnagni
5'''
6from libs.epb import EPB
7from libs.migration.exception.exceptions import NoDBManager
8from ea_model.ceda_metadatamodel.ceda_observationcollection.ceda_observationcollection import CEDA_ObservationCollection
9from ea_model.ceda_metadatamodel.ceda_observation.ceda_observation import CEDA_Observation
10from ea_model.iso_19115_2006_metadata_corrigendum.reference_system_information.md_identifier import MD_Identifier
11from ea_model.iso_19115_2006_metadata_corrigendum.citation_and_responsible_party_information.ci_citation import CI_Citation
12from ea_model.moles3_4.observationcollection.mo_observationcollection import MO_ObservationCollection
13from ea_model.moles3_4.observation.mo_observation import MO_Observation
14from ea_model.ceda_metadatamodel.ceda_project.ceda_project import CEDA_Project
15from sqlalchemy import Table, Column, ForeignKey, Integer, String
16from sqlalchemy.orm import mapper
17from MolesManager.ceda_guid import CedaGUID
18from ea_model.moles3_4.utilities.mo_responsiblepartyinfo import MO_ResponsiblePartyInfo
19from ea_model.moles3_4.utilities.mo_rolevalue import MO_RoleValue
20
21
22class Moles3EPB(EPB):
23
24    _molesDB = None
25   
26    @classmethod
27    def overrrideDBManager(self, dbManager):
28        """
29            Sets the MigrationEPB libs.commons_db.DbManager
30        """
31        Moles3EPB._molesDB = dbManager
32        Moles3EPB._initCEDA_Customization()
33
34    @classmethod
35    def _initCEDA_Customization(self):
36        Moles3EPB._associateCEDA_GUID()
37        Moles3EPB._initSearchIndexes()       
38       
39    @classmethod
40    def _associateCEDA_GUID(self):
41        guid_table = Table('ceda_guid', Moles3EPB._molesDB.metadata, \
42                           Column('id', String, primary_key=True), \
43                           Column('ceda_observationcollection', Integer, ForeignKey('ceda_observationcollection.id')), 
44                           Column('ceda_observation', Integer, ForeignKey('ceda_observation.id')))
45        mapper(CedaGUID, guid_table)
46        Moles3EPB._molesDB.metadata.create_all()
47
48    @classmethod
49    def _initSearchIndexes(self):
50        #To Be Done - CHECK IF THE COLUMN ALREADY EXISTS!
51        # We don't want sqlalchemy to know about this column so we add it externally.
52        try:
53            Moles3EPB._molesDB.engine.execute("alter table md_identifier add column code_search_vector tsvector")                 
54
55            # This indexes the tsvector column
56
57            Moles3EPB._molesDB.engine.execute("create index md_identifier_code_search_index on md_identifier using gin(code_search_vector)")
58
59            # This sets up the trigger that keeps the tsvector column up to date.
60            Moles3EPB._molesDB.engine.execute("create trigger md_identifier_code_search_update before update or insert on md_identifier \
61                for each row execute procedure tsvector_update_trigger('code_search_vector', 'pg_catalog.english', code)")                       
62        except Exception as e:
63            pass
64
65    @classmethod       
66    def search(self, clazz, inst_id, session = None):
67        intSession = Moles3EPB._getSession(session)
68        return EPB.search(clazz, inst_id, intSession)
69
70    @classmethod       
71    def searchEager(self, clazz, inst_id, session = None):
72        intSession = Moles3EPB._getSession(session)
73        return EPB.searchEager(clazz, inst_id, intSession)
74
75    @classmethod       
76    def addCedaObject(self, ceda_observation, session = None, commit = False):
77        """
78            Adds and eventually commit a CEDA Object in MOLES3 db
79            @param ceda_observation: the CEDA object to persist
80            @param session: the external session to use. If None a new session will be open to add and commit the object and then closed at the exit. The object is committed
81            @param commit: defines if the object has to be committed immediately or not.
82        """
83        intSession = Moles3EPB._getSession(session)
84        intSession.add(ceda_observation)
85        if commit:
86            intSession.commit()
87        #Moles3EPB._closeSession(session)
88
89    @classmethod
90    def retrieveGUIDFromInstance(self, instance, session = None):
91        """
92            Returns the CedaGUID object associated with the given instance.
93            @param instance: an instance of CEDA_Observation os CEDA_ObservationCollection 
94        """
95        intSession = Moles3EPB._getSession(session)
96        if instance is None:
97            return None
98        if type(instance) == CEDA_ObservationCollection:
99            return intSession.query(CedaGUID).filter(CedaGUID.ceda_observationcollection==instance.id).first()
100        elif type(instance) == CEDA_Observation:
101            return intSession.query(CedaGUID).filter(CedaGUID.ceda_observation==instance.id).first()
102           
103   
104    @classmethod
105    def observationCollectionHasObservation(self, obs_coll_id, obs_id, session = None):
106        """
107            Checks if a CEDA_Collection contains a given CEDA_Observation.
108            @param obs_coll_id: the CEDA_ObservationColleciton id
109            @param obs_id: the CEDA_Observation id
110            @return: True if the collection contains the given observation, False otherwise 
111        """
112        intSession = Moles3EPB._getSession(session)
113        return intSession.query(CEDA_ObservationCollection, CEDA_Observation).filter(CEDA_ObservationCollection.id==obs_coll_id).filter(CEDA_Observation.id==obs_id).count() > 0
114
115    @classmethod
116    def observationAuthor(self, obs_id, session = None):
117        """
118            Lists the CEDA_Observation author.
119            @param obs_id: the CEDA_Observation id           
120            @return: True if the collection contains the given observation, False otherwise 
121        """
122        intSession = Moles3EPB._getSession(session)
123        ret = intSession.query(MO_ResponsiblePartyInfo).join(MO_Observation). \
124            filter(MO_ResponsiblePartyInfo.role == MO_RoleValue.cl_author). \
125            filter(MO_Observation.id == obs_id)
126        return ret
127
128    @classmethod
129    def extractObservationByTitleKeywords(self, keywords, session = None):
130        """
131            Loooks for CEDA_Observation containing a specific title (observation.identifier.code)
132            @param keywords: a space separated terms string
133            @return: a tuple containing a CEDA_Observation satisfying the queryllection.idenfitier element having the title 
134        """               
135        intSession = Moles3EPB._getSession(session)
136        # search_vector is a ts_vector column. To search for terms, you use the
137        # @@ operator. plainto_tsquery turns a string into a query that can be
138        # used with @@. So this adds a where clause like "WHERE search_vector
139        # @@ plaint_tsquery(<search string>)"
140        q = intSession.query(CEDA_Observation). \
141            join(MO_Observation).join(MO_ObservationCollection.identifier). \
142            filter('md_identifier.code_search_vector @@ to_tsquery(:terms)')
143        # This binds the :terms placeholder to the searchterms string. User input
144        # should always be put into queries this way to prevent SQL injection.
145        q = q.params(terms=keywords)
146        return q
147
148
149    @classmethod
150    def extractCollectionIdentifierByTitle(self, i_title, session = None):
151        """
152            Searches for an MD_Identifier from a CEDA_ObservationCollection contains a specific title (observation.identifier.code)
153            @param i_title: the CEDA_ObservationCollection.identifier.title value to search for
154            @return: a tuple containing a CEDA_ObservationCollection and the CEDA_ObservationCollection.idenfitier element having the title 
155        """
156        intSession = Moles3EPB._getSession(session)
157        return intSession.query(CEDA_ObservationCollection, MD_Identifier). \
158            join(MO_ObservationCollection).join(MO_ObservationCollection.identifier). \
159            join(MD_Identifier.authority).filter(CI_Citation.title.like('%' + i_title + '%'))
160
161    @classmethod
162    def extractObservationsForProject(self, project, session = None):
163        """
164            Searches for the CEDA_Observation associated with a CEDA_Project
165            @param project: a CEDA_Project instance
166            @return: a tuple containing the associated CEDA_Observation 
167        """
168        intSession = Moles3EPB._getSession(session)
169        return intSession.query(CEDA_Observation). \
170            join(CEDA_Observation, MO_Observation.inSupportOf).filter(CEDA_Project.id == project.id)
171
172    @classmethod
173    def extractProjectObservationCollections(self, project, session = None):
174        """
175            Searches for the Observation_Collections associated with a CEDA_Project
176            @param project: a CEDA_Project instance
177            @return: a tuple containing the associated CEDA_ObservationCollection 
178        """
179        intSession = Moles3EPB._getSession(session)
180        mo_obs = intSession.query(MO_Observation).join(CEDA_Project).filter(CEDA_Project.id == project.id).subquery()     
181        obsers = intSession.query(CEDA_Observation).join(mo_obs, CEDA_Observation.id == mo_obs.c.id).one()
182        #print "obsers: " + str(intSession.query(CEDA_Observation).join(mo_obs, CEDA_Observation.id == mo_obs.c.id).count())
183       
184        cos = intSession.query(CEDA_ObservationCollection).all()
185        co = intSession.query(MO_ObservationCollection).join(MO_ObservationCollection.member).filter(MO_ObservationCollection.member.contains(obsers))
186        print co
187        print co.all()
188       
189        observations = intSession.query(MO_ObservationCollection).join(CEDA_Observation). \
190            filter(obsers.any(CEDA_Observation.id==obsers.c.id))
191        print "observation:" + str(observations.count())
192        return observations
193
194    @classmethod
195    def addObservationToObservationCollection(self, observationCollection, observation, session = None, commit = False):
196        """
197            Adds an Observation instance to an ObservationCollection if still not part of the collection.
198            @param observationCollection: the collection to update
199            @param observation: the observation to add
200            @param session: the session to use for the operation
201            @param commit: if True commits at the end (defaul False)
202        """
203        intSession = Moles3EPB._getSession(session)
204        if not self.observationCollectionHasObservation(observationCollection.id, observation.id, intSession):
205            observationCollection.member.append(observation)
206            if commit:
207                intSession.commit()
208   
209    @classmethod
210    def addDataLineageToObservation(self, data_lineage, observation, session = None, commit = False):
211        """
212            Adds an data_lineage element to an Observation if still not assigned or not equal.
213            @param data_lineage: the quality string to persist
214            @param observation: the observation to update
215            @param session: the session to use for the operation
216            @param commit: if True commits at the end (defaul False)
217        """       
218        intSession = Moles3EPB._getSession(session)
219        if observation.dataLineage != data_lineage:
220            observation.dataLineage = data_lineage
221        if commit:
222            intSession.commit()               
223
224    @classmethod
225    def addDescriptionToObservation(self, description, observation, session = None, commit = False):
226        """
227            Adds an description element to an Observation if still not assigned or not equal.
228            @param description: the description string to persist
229            @param observation: the observation to update
230            @param session: the session to use for the operation
231            @param commit: if True commits at the end (defaul False)
232        """       
233        intSession = Moles3EPB._getSession(session)
234        if observation.description != description:
235            observation.description = description
236        if commit:
237            intSession.commit()
238
239    @classmethod
240    def addRelatedPartyInfoToObservation(self, responsibleParty, observation, session = None, commit = False):
241        """
242            Adds a relatedParty element to an Observation if still not assigned or not equal.
243            @param responsibleParty: the responsibleParty element to persist
244            @param observation: the observation to update
245            @param session: the session to use for the operation
246            @param commit: if True commits at the end (defaul False)
247        """         
248        intSession = Moles3EPB._getSession(session)
249        if not responsibleParty in observation.relatedParty:
250            observation.relatedParty.append(responsibleParty)                           
251            #moles3Append(observation, 'relatedParty', responsibleParty)
252        if commit:
253            intSession.commit()
254
255
256    @classmethod       
257    def getNewMolesSession(self):
258            return Moles3EPB._getSession()
259
260    @classmethod
261    def executeNative(self, sqlNative, session = None):
262        intSession = Moles3EPB._getSession(session)
263        return EPB.executeNative(sqlNative, intSession) 
264
265    @classmethod
266    def _getSession(self, session = None):
267        if Moles3EPB._molesDB is None:
268            raise NoDBManager("Moles3EPB")
269        return EPB._getSession(Moles3EPB._molesDB, session)
Note: See TracBrowser for help on using the repository browser.