Merge branch 'master' of https://code.grnet.gr/git/pithos
[pithos] / pithos / backends / lib_alchemy / xfeatures.py
1 # Copyright 2011 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.sql.expression import desc
39
40 from dbworker import DBWorker
41
42
43 class XFeatures(DBWorker):
44     """XFeatures are path properties that allow non-nested
45        inheritance patterns. Currently used for storing permissions.
46     """
47     
48     def __init__(self, **params):
49         DBWorker.__init__(self, **params)
50         metadata = MetaData()
51         columns=[]
52         columns.append(Column('feature_id', Integer, primary_key=True))
53         columns.append(Column('path', String(2048)))
54         self.xfeatures = Table('xfeatures', metadata, *columns)
55         # place an index on path
56         Index('idx_features_path', self.xfeatures.c.path)
57         
58         columns=[]
59         columns.append(Column('feature_id', Integer,
60                               ForeignKey('xfeatures.feature_id',
61                                          ondelete='CASCADE'),
62                               primary_key=True))
63         columns.append(Column('key', Integer, autoincrement=False,
64                               primary_key=True))
65         columns.append(Column('value', String(255), primary_key=True))
66         self.xfeaturevals = Table('xfeaturevals', metadata, *columns)
67         
68         metadata.create_all(self.engine)
69         metadata.bind = self.engine
70     
71     def xfeature_inherit(self, path):
72         """Return the (path, feature) inherited by the path, or None."""
73         
74         s = select([self.xfeatures.c.path, self.xfeatures.c.feature_id])
75         s = s.where(self.xfeatures.c.path <= path)
76         s = s.order_by(desc(self.xfeatures.c.path)).limit(1)
77         r = self.conn.execute(s)
78         row = r.fetchone()
79         r.close()
80         if row and path.startswith(row[0]):
81             return row
82         else:
83             return None
84     
85     def xfeature_list(self, path):
86         """Return the list of the (prefix, feature) pairs matching path.
87            A prefix matches path if either the prefix includes the path,
88            or the path includes the prefix.
89         """
90         
91         inherited = self.xfeature_inherit(path)
92         if inherited:
93             return [inherited]
94         
95         s = select([self.xfeatures.c.path, self.xfeatures.c.feature_id])
96         s = s.where(and_(self.xfeatures.c.path.like(path + '%'),
97                      self.xfeatures.c.path != path))
98         s = s.order_by(self.xfeatures.c.path)
99         r = self.conn.execute(s)
100         l = r.fetchall()
101         r.close()
102         return l
103     
104     def xfeature_create(self, path):
105         """Create and return a feature for path.
106            If the path already inherits a feature or
107            bestows to paths already inheriting a feature,
108            create no feature and return None.
109            If the path has a feature, return it.
110         """
111         
112         prefixes = self.xfeature_list(path)
113         pl = len(prefixes)
114         if (pl > 1) or (pl == 1 and prefixes[0][0] != path):
115             return None
116         if pl == 1 and prefixes[0][0] == path:
117             return prefixes[0][1]
118         s = self.xfeatures.insert()
119         r = self.conn.execute(s, path=path)
120         inserted_primary_key = r.inserted_primary_key[0]
121         r.close()
122         return inserted_primary_key
123     
124     def xfeature_destroy(self, path):
125         """Destroy a feature and all its key, value pairs."""
126         
127         s = self.xfeatures.delete().where(self.xfeatures.c.path == path)
128         r = self.conn.execute(s)
129         r.close()
130     
131     def feature_dict(self, feature):
132         """Return a dict mapping keys to list of values for feature."""
133         
134         s = select([self.xfeaturevals.c.key, self.xfeaturevals.c.value])
135         s = s.where(self.xfeaturevals.c.feature_id == feature)
136         r = self.conn.execute(s)
137         d = defaultdict(list)
138         for key, value in r.fetchall():
139             d[key].append(value)
140         r.close()
141         return d
142     
143     def feature_set(self, feature, key, value):
144         """Associate a key, value pair with a feature."""
145         
146         s = self.xfeaturevals.insert()
147         r = self.conn.execute(s, feature_id=feature, key=key, value=value)
148         r.close()
149     
150     def feature_setmany(self, feature, key, values):
151         """Associate the given key, and values with a feature."""
152         
153         s = self.xfeaturevals.insert()
154         values = [{'feature_id':feature, 'key':key, 'value':v} for v in values]
155         r = self.conn.execute(s, values)
156         r.close()
157     
158     def feature_unset(self, feature, key, value):
159         """Disassociate a key, value pair from a feature."""
160         
161         s = self.xfeaturevals.delete()
162         s = s.where(and_(self.xfeaturevals.c.feature_id == feature,
163                      self.xfeaturevals.c.key == key,
164                      self.xfeaturevals.c.value == value))
165         r = self.conn.execute(s)
166         r.close()
167     
168     def feature_unsetmany(self, feature, key, values):
169         """Disassociate the key for the values given, from a feature."""
170         
171         for v in values:
172             conditional = and_(self.xfeaturevals.c.feature_id == feature,
173                                self.xfeaturevals.c.key == key,
174                                self.xfeaturevals.c.value == v)
175             s = self.xfeaturevals.delete().where(conditional)
176             r = self.conn.execute(s)
177             r.close()
178         
179     def feature_get(self, feature, key):
180         """Return the list of values for a key of a feature."""
181         
182         s = select([self.xfeaturevals.c.value])
183         s = s.where(and_(self.xfeaturevals.c.feature_id == feature,
184                      self.xfeaturevals.c.key == key))
185         r = self.conn.execute(s)
186         l = [row[0] for row in r.fetchall()]
187         r.close()
188         return l
189     
190     def feature_clear(self, feature, key):
191         """Delete all key, value pairs for a key of a feature."""
192         
193         s = self.xfeaturevals.delete()
194         s = s.where(and_(self.xfeaturevals.c.feature_id == feature,
195                      self.xfeaturevals.c.key == key))
196         r = self.conn.execute(s)
197         r.close()