source: mauRepo/MolesManager/trunk/cedaMoles/MolesManager/db/partyIndexes.py @ 8514

Subversion URL: http://proj.badc.rl.ac.uk/svn/ndg/mauRepo/MolesManager/trunk/cedaMoles/MolesManager/db/partyIndexes.py@8514
Revision 8514, 6.8 KB checked in by mnagni, 8 years ago (diff)

Incomplete - # 22534: Add versiojn number to the gui page
 http://team.ceda.ac.uk/trac/ceda/ticket/22534
Correct party_indexes definition (from now on, ON DELETE = cascade)

Line 
1'''
2BSD Licence
3Copyright (c) 2012, Science & Technology Facilities Council (STFC)
4All rights reserved.
5
6Redistribution and use in source and binary forms, with or without modification,
7are permitted provided that the following conditions are met:
8
9    * Redistributions of source code must retain the above copyright notice,
10        this list of conditions and the following disclaimer.
11    * Redistributions in binary form must reproduce the above copyright notice,
12        this list of conditions and the following disclaimer in the documentation
13        and/or other materials provided with the distribution.
14    * Neither the name of the Science & Technology Facilities Council (STFC)
15        nor the names of its contributors may be used to endorse or promote
16        products derived from this software without specific prior written permission.
17
18THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
19AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
20THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
21PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS
22BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,
23OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
24SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
25HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
26OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
27OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
28
29Created on 3 Aug 2012
30
31@author: mnagni
32'''
33from cedaMoles.libs.epb import EPB
34from sqlalchemy import Table, Column, ForeignKey, Integer, String, event
35from sqlalchemy.orm import mapper
36from ea_model.moles3_4.utilities.mo_responsiblepartyinfo import MO_ResponsiblePartyInfo
37
38class PartyIndexes(object):
39    '''
40    Allows to assign on a MO_ResponsiblePartyInfo basis an index
41    to the the referred MO_Party instances.
42   
43     # The primary key refers to the MO_ResponsiblePartyInfo.id
44     # The sorted_party column shall contain a string formatted as
45         IDParty(1):partyOrder(1), IDParty(2):partyOrder(2), .....
46         
47       where
48         # IDParty(x) is a MO_Party.id in the mo_responsiblepartyinfo.party list
49         # partyOrder(x) is the assigned index
50    '''
51
52    def __init__(self):
53        self.id = None
54        self.party_order = None
55
56def associateMOParty_indexes(metadata):
57    '''
58    Creates the table used to store the index associated per ResponsiblePartyIngo
59    to each referenced party.
60   
61    **Parameters**
62         * metadata: an SQLAlchemy Metadata instance
63    '''
64    party_indexes_table = Table('party_indexes', metadata, \
65                       Column('id', Integer, ForeignKey('mo_responsiblepartyinfo.id', \
66                                                        ondelete="CASCADE"), \
67                              primary_key=True, unique=True),
68                       Column('party_orders', String))
69    mapper(PartyIndexes, party_indexes_table)
70    metadata.create_all()
71    event.listen(MO_ResponsiblePartyInfo, 'load', __associateIndexes)
72
73def addPartyIndexes(responsiblePartyInfo, session):
74    '''
75    Associates to a MO_ResponsiblePartyInfo entity a PartyIndexes entity
76   
77    **Parameters**
78        * responsiblePartyInfo: the MO_ResponsiblePartyInfo instance
79        * session: an SQLAlchemy session instance
80    '''
81    pi = createAssociateIndexes(responsiblePartyInfo)
82    session.add(pi)
83    #session.flush()
84
85def updatePartyIndexes(responsiblePartyInfo, session):
86    '''
87    Updates a PartyIndexes entity associated with a MO_ResponsiblePartyInfo entity
88   
89    **Parameters**
90        * responsiblePartyInfo: the MO_ResponsiblePartyInfo instance
91        * session: an SQLAlchemy session instance
92    '''
93    partyIndex = session.query(PartyIndexes).get(responsiblePartyInfo.id)
94    #uses this method just as utility
95    pi = createAssociateIndexes(responsiblePartyInfo)
96    partyIndex.party_orders = pi.party_orders
97    session.expunge(pi)
98    #session.flush()
99
100def deletePartyIndexes(responsiblePartyInfo, session):
101    '''
102    Deletes a PartyIndexes entity associated with a MO_ResponsiblePartyInfo entity
103   
104    **Parameters**
105        * responsiblePartyInfo: the MO_ResponsiblePartyInfo instance
106        * session: an SQLAlchemy session instance
107    '''
108    partyIndex = session.query(PartyIndexes).get(responsiblePartyInfo.id)
109    session.delete(partyIndex)
110    #session.flush()
111
112
113def __associateIndexes(target, content):
114    """
115    Associates to a responsiblePartyInfo instance an "party_order" attribute.
116    The method is associated when SQLAlchemy load a MO_ResponsiblePartyInfo instance
117
118    **Parameters**
119        * target: the MO_ResponsiblePartyInfo instance
120        * content: an SQLAlchemy content instance                 
121    """
122    partyIndex = EPB.search(PartyIndexes, target.id, content.session)
123    _associateIndexes(target, partyIndex)
124
125def _associateIndexes(responsiblePartyInfo, partyIndex):
126    """
127    Associates to a responsiblePartyInfo instance an "party_order" attribute.
128    This method is separated from the associateIndexes method purely for unittest purpose.
129   
130    **Parameters**
131        * responsiblePartyInfo: the MO_ResponsiblePartyInfo instance
132        * partyIndex: a string formatted like '1:1, 2:3, 3:2' where the pair #:# represents
133        the partyID:orderIndex       
134    """
135    if partyIndex is None or partyIndex.party_orders is None or len(partyIndex.party_orders) == 0:
136        return
137    pi = dict((x.split(':')[0], x.split(':')[1]) for x in partyIndex.party_orders.split(','))
138    for party in responsiblePartyInfo.party:
139        if pi.has_key(str(party.id)):
140            party.party_order = int(pi[str(party.id)]) 
141
142
143def createAssociateIndexes(responsiblePartyInfo):
144    """
145    Creates from MO_ResponsiblePartyInfo instance a PartyIndexes instance.
146    The PartyIndexes instance reads the MO_ResponsiblePartyInfo.party instances
147    and for each of them try to read their `party_order` attribute.
148    If `party_order` does not exists the methods assign automatically an incremental
149    index for each MO_Party
150   
151    **Parameters**
152        * responsiblePartyInfo: the MO_ResponsiblePartyInfo instance
153       
154    **Return**
155        * a PartyIndexes instance       
156    """
157    pi = PartyIndexes()
158    pi.id = getattr(responsiblePartyInfo, 'id', None)
159   
160    order = []
161    index = set([-1])
162    for party in responsiblePartyInfo.party:
163        pindex = max(index) + 1       
164        if hasattr(party, 'party_order'):
165            pindex = getattr(party, 'party_order')               
166        order.append('%s:%s,' % (party.id, pindex))
167        index.add(pindex)       
168    party_orders = ''.join(order)[:-1]
169    pi.party_orders = party_orders
170    return pi   
Note: See TracBrowser for help on using the repository browser.