Statistics
| Branch: | Tag: | Revision:

root / snf-pithos-backend / pithos / backends / lib / sqlalchemy / xfeatures.py @ b83df225

History | View | Annotate | Download (8.2 kB)

1
# Copyright 2011-2012 GRNET S.A. All rights reserved.
2
#
3
# Redistribution and use in source and binary forms, with or
4
# without modification, are permitted provided that the following
5
# conditions are met:
6
#
7
#   1. Redistributions of source code must retain the above
8
#      copyright notice, this list of conditions and the following
9
#      disclaimer.
10
#
11
#   2. Redistributions in binary form must reproduce the above
12
#      copyright notice, this list of conditions and the following
13
#      disclaimer in the documentation and/or other materials
14
#      provided with the distribution.
15
#
16
# THIS SOFTWARE IS PROVIDED BY GRNET S.A. ``AS IS'' AND ANY EXPRESS
17
# OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
18
# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
19
# PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL GRNET S.A OR
20
# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
21
# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
22
# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
23
# USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
24
# AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
25
# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
26
# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
27
# POSSIBILITY OF SUCH DAMAGE.
28
#
29
# The views and conclusions contained in the software and
30
# documentation are those of the authors and should not be
31
# interpreted as representing official policies, either expressed
32
# or implied, of GRNET S.A.
33

    
34
from collections import defaultdict
35
from sqlalchemy import Table, Column, String, Integer, MetaData, ForeignKey
36
from sqlalchemy.sql import select, and_
37
from sqlalchemy.schema import Index
38
from sqlalchemy.exc import NoSuchTableError
39

    
40
from dbworker import DBWorker
41

    
42

    
43
def create_tables(engine):
44
    metadata = MetaData()
45
    columns = []
46
    columns.append(Column('feature_id', Integer, primary_key=True))
47
    columns.append(Column('path', String(2048)))
48
    xfeatures = Table('xfeatures', metadata, *columns, mysql_engine='InnoDB')
49
    # place an index on path
50
    Index('idx_features_path', xfeatures.c.path, unique=True)
51

    
52
    columns = []
53
    columns.append(Column('feature_id', Integer,
54
                          ForeignKey('xfeatures.feature_id',
55
                                     ondelete='CASCADE'),
56
                          primary_key=True))
57
    columns.append(Column('key', Integer, primary_key=True,
58
                          autoincrement=False))
59
    columns.append(Column('value', String(256), primary_key=True))
60
    Table('xfeaturevals', metadata, *columns, mysql_engine='InnoDB')
61

    
62
    metadata.create_all(engine)
63
    return metadata.sorted_tables
64

    
65

    
66
class XFeatures(DBWorker):
67
    """XFeatures are path properties that allow non-nested
68
       inheritance patterns. Currently used for storing permissions.
69
    """
70

    
71
    def __init__(self, **params):
72
        DBWorker.__init__(self, **params)
73
        try:
74
            metadata = MetaData(self.engine)
75
            self.xfeatures = Table('xfeatures', metadata, autoload=True)
76
            self.xfeaturevals = Table('xfeaturevals', metadata, autoload=True)
77
        except NoSuchTableError:
78
            tables = create_tables(self.engine)
79
            map(lambda t: self.__setattr__(t.name, t), tables)
80

    
81
#     def xfeature_inherit(self, path):
82
#         """Return the (path, feature) inherited by the path, or None."""
83
#
84
#         s = select([self.xfeatures.c.path, self.xfeatures.c.feature_id])
85
#         s = s.where(self.xfeatures.c.path <= path)
86
#         s = s.where(self.xfeatures.c.path.like(
87
#           self.escape_like(path) + '%', escape='\\'))  # XXX: Escape like...
88
#         s = s.order_by(desc(self.xfeatures.c.path))
89
#         r = self.conn.execute(s)
90
#         l = r.fetchall()
91
#         r.close()
92
#         return l
93

    
94
    def xfeature_get(self, path):
95
        """Return feature for path."""
96

    
97
        s = select([self.xfeatures.c.feature_id])
98
        s = s.where(self.xfeatures.c.path == path)
99
        s = s.order_by(self.xfeatures.c.path)
100
        r = self.conn.execute(s)
101
        row = r.fetchone()
102
        r.close()
103
        if row:
104
            return row[0]
105
        return None
106

    
107
    def xfeature_get_bulk(self, paths):
108
        """Return features for paths."""
109
        paths = list(set(paths))
110
        s = select([self.xfeatures.c.feature_id, self.xfeatures.c.path])
111
        s = s.where(self.xfeatures.c.path.in_(paths))
112
        s = s.order_by(self.xfeatures.c.path)
113
        r = self.conn.execute(s)
114
        row = r.fetchall()
115
        r.close()
116
        if row:
117
            return row
118
        return None
119

    
120
    def xfeature_create(self, path):
121
        """Create and return a feature for path.
122
           If the path has a feature, return it.
123
        """
124

    
125
        feature = self.xfeature_get(path)
126
        if feature is not None:
127
            return feature
128
        s = self.xfeatures.insert()
129
        r = self.conn.execute(s, path=path)
130
        inserted_primary_key = r.inserted_primary_key[0]
131
        r.close()
132
        return inserted_primary_key
133

    
134
    def xfeature_destroy(self, path):
135
        """Destroy a feature and all its key, value pairs."""
136

    
137
        s = self.xfeatures.delete().where(self.xfeatures.c.path == path)
138
        r = self.conn.execute(s)
139
        r.close()
140

    
141
    def xfeature_destroy_bulk(self, paths):
142
        """Destroy features and all their key, value pairs."""
143

    
144
        if not paths:
145
            return
146
        s = self.xfeatures.delete().where(self.xfeatures.c.path.in_(paths))
147
        r = self.conn.execute(s)
148
        r.close()
149

    
150
    def feature_dict(self, feature):
151
        """Return a dict mapping keys to list of values for feature."""
152

    
153
        s = select([self.xfeaturevals.c.key, self.xfeaturevals.c.value])
154
        s = s.where(self.xfeaturevals.c.feature_id == feature)
155
        r = self.conn.execute(s)
156
        d = defaultdict(list)
157
        for key, value in r.fetchall():
158
            d[key].append(value)
159
        r.close()
160
        return d
161

    
162
    def feature_set(self, feature, key, value):
163
        """Associate a key, value pair with a feature."""
164

    
165
        s = self.xfeaturevals.select()
166
        s = s.where(self.xfeaturevals.c.feature_id == feature)
167
        s = s.where(self.xfeaturevals.c.key == key)
168
        s = s.where(self.xfeaturevals.c.value == value)
169
        r = self.conn.execute(s)
170
        xfeaturevals = r.fetchall()
171
        r.close()
172
        if len(xfeaturevals) == 0:
173
            s = self.xfeaturevals.insert()
174
            r = self.conn.execute(s, feature_id=feature, key=key, value=value)
175
            r.close()
176

    
177
    def feature_setmany(self, feature, key, values):
178
        """Associate the given key, and values with a feature."""
179

    
180
        #TODO: more efficient way to do it
181
        for v in values:
182
            self.feature_set(feature, key, v)
183

    
184
    def feature_unset(self, feature, key, value):
185
        """Disassociate a key, value pair from a feature."""
186

    
187
        s = self.xfeaturevals.delete()
188
        s = s.where(and_(self.xfeaturevals.c.feature_id == feature,
189
                         self.xfeaturevals.c.key == key,
190
                         self.xfeaturevals.c.value == value))
191
        r = self.conn.execute(s)
192
        r.close()
193

    
194
    def feature_unsetmany(self, feature, key, values):
195
        """Disassociate the key for the values given, from a feature."""
196

    
197
        for v in values:
198
            conditional = and_(self.xfeaturevals.c.feature_id == feature,
199
                               self.xfeaturevals.c.key == key,
200
                               self.xfeaturevals.c.value == v)
201
            s = self.xfeaturevals.delete().where(conditional)
202
            r = self.conn.execute(s)
203
            r.close()
204

    
205
    def feature_get(self, feature, key):
206
        """Return the list of values for a key of a feature."""
207

    
208
        s = select([self.xfeaturevals.c.value])
209
        s = s.where(and_(self.xfeaturevals.c.feature_id == feature,
210
                         self.xfeaturevals.c.key == key))
211
        r = self.conn.execute(s)
212
        l = [row[0] for row in r.fetchall()]
213
        r.close()
214
        return l
215

    
216
    def feature_clear(self, feature, key):
217
        """Delete all key, value pairs for a key of a feature."""
218

    
219
        s = self.xfeaturevals.delete()
220
        s = s.where(and_(self.xfeaturevals.c.feature_id == feature,
221
                         self.xfeaturevals.c.key == key))
222
        r = self.conn.execute(s)
223
        r.close()