1 # Copyright 2011-2012 GRNET S.A. All rights reserved.
3 # Redistribution and use in source and binary forms, with or
4 # without modification, are permitted provided that the following
7 # 1. Redistributions of source code must retain the above
8 # copyright notice, this list of conditions and the following
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.
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.
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.
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 from sqlalchemy.exc import NoSuchTableError
41 from dbworker import DBWorker
43 def create_tables(engine):
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)
53 columns.append(Column('feature_id', Integer,
54 ForeignKey('xfeatures.feature_id',
57 columns.append(Column('key', Integer, primary_key=True,
59 columns.append(Column('value', String(256), primary_key=True))
60 xfeaturevals = Table('xfeaturevals', metadata, *columns, mysql_engine='InnoDB')
62 metadata.create_all(engine)
63 return metadata.sorted_tables
65 class XFeatures(DBWorker):
66 """XFeatures are path properties that allow non-nested
67 inheritance patterns. Currently used for storing permissions.
70 def __init__(self, **params):
71 DBWorker.__init__(self, **params)
73 metadata = MetaData(self.engine)
74 self.xfeatures = Table('xfeatures', metadata, autoload=True)
75 self.xfeaturevals = Table('xfeaturevals', metadata, autoload=True)
76 except NoSuchTableError:
77 tables = create_tables(self.engine)
78 map(lambda t: self.__setattr__(t.name, t), tables)
80 # def xfeature_inherit(self, path):
81 # """Return the (path, feature) inherited by the path, or None."""
83 # s = select([self.xfeatures.c.path, self.xfeatures.c.feature_id])
84 # s = s.where(self.xfeatures.c.path <= path)
85 # #s = s.where(self.xfeatures.c.path.like(self.escape_like(path) + '%', escape='\\')) # XXX: Implement reverse and escape like...
86 # s = s.order_by(desc(self.xfeatures.c.path))
87 # r = self.conn.execute(s)
92 def xfeature_get(self, path):
93 """Return feature for path."""
95 s = select([self.xfeatures.c.feature_id])
96 s = s.where(self.xfeatures.c.path == path)
97 s = s.order_by(self.xfeatures.c.path)
98 r = self.conn.execute(s)
105 def xfeature_create(self, path):
106 """Create and return a feature for path.
107 If the path has a feature, return it.
110 feature = self.xfeature_get(path)
111 if feature is not None:
113 s = self.xfeatures.insert()
114 r = self.conn.execute(s, path=path)
115 inserted_primary_key = r.inserted_primary_key[0]
117 return inserted_primary_key
119 def xfeature_destroy(self, path):
120 """Destroy a feature and all its key, value pairs."""
122 s = self.xfeatures.delete().where(self.xfeatures.c.path == path)
123 r = self.conn.execute(s)
126 def xfeature_destroy_bulk(self, paths):
127 """Destroy features and all their key, value pairs."""
129 s = self.xfeatures.delete().where(self.xfeatures.c.path.in_(paths))
130 r = self.conn.execute(s)
133 def feature_dict(self, feature):
134 """Return a dict mapping keys to list of values for feature."""
136 s = select([self.xfeaturevals.c.key, self.xfeaturevals.c.value])
137 s = s.where(self.xfeaturevals.c.feature_id == feature)
138 r = self.conn.execute(s)
139 d = defaultdict(list)
140 for key, value in r.fetchall():
145 def feature_set(self, feature, key, value):
146 """Associate a key, value pair with a feature."""
148 s = self.xfeaturevals.select()
149 s = s.where(self.xfeaturevals.c.feature_id == feature)
150 s = s.where(self.xfeaturevals.c.key == key)
151 s = s.where(self.xfeaturevals.c.value == value)
152 r = self.conn.execute(s)
153 xfeaturevals = r.fetchall()
155 if len(xfeaturevals) == 0:
156 s = self.xfeaturevals.insert()
157 r = self.conn.execute(s, feature_id=feature, key=key, value=value)
160 def feature_setmany(self, feature, key, values):
161 """Associate the given key, and values with a feature."""
163 #TODO: more efficient way to do it
165 self.feature_set(feature, key, v)
167 def feature_unset(self, feature, key, value):
168 """Disassociate a key, value pair from a feature."""
170 s = self.xfeaturevals.delete()
171 s = s.where(and_(self.xfeaturevals.c.feature_id == feature,
172 self.xfeaturevals.c.key == key,
173 self.xfeaturevals.c.value == value))
174 r = self.conn.execute(s)
177 def feature_unsetmany(self, feature, key, values):
178 """Disassociate the key for the values given, from a feature."""
181 conditional = and_(self.xfeaturevals.c.feature_id == feature,
182 self.xfeaturevals.c.key == key,
183 self.xfeaturevals.c.value == v)
184 s = self.xfeaturevals.delete().where(conditional)
185 r = self.conn.execute(s)
188 def feature_get(self, feature, key):
189 """Return the list of values for a key of a feature."""
191 s = select([self.xfeaturevals.c.value])
192 s = s.where(and_(self.xfeaturevals.c.feature_id == feature,
193 self.xfeaturevals.c.key == key))
194 r = self.conn.execute(s)
195 l = [row[0] for row in r.fetchall()]
199 def feature_clear(self, feature, key):
200 """Delete all key, value pairs for a key of a feature."""
202 s = self.xfeaturevals.delete()
203 s = s.where(and_(self.xfeaturevals.c.feature_id == feature,
204 self.xfeaturevals.c.key == key))
205 r = self.conn.execute(s)