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
44 def create_tables(engine):
47 columns.append(Column('feature_id', Integer, primary_key=True))
48 columns.append(Column('path', String(2048)))
49 xfeatures = Table('xfeatures', metadata, *columns, mysql_engine='InnoDB')
50 # place an index on path
51 Index('idx_features_path', xfeatures.c.path, unique=True)
54 columns.append(Column('feature_id', Integer,
55 ForeignKey('xfeatures.feature_id',
58 columns.append(Column('key', Integer, primary_key=True,
60 columns.append(Column('value', String(256), primary_key=True))
62 'xfeaturevals', metadata, *columns, mysql_engine='InnoDB')
64 metadata.create_all(engine)
65 return metadata.sorted_tables
68 class XFeatures(DBWorker):
69 """XFeatures are path properties that allow non-nested
70 inheritance patterns. Currently used for storing permissions.
73 def __init__(self, **params):
74 DBWorker.__init__(self, **params)
76 metadata = MetaData(self.engine)
77 self.xfeatures = Table('xfeatures', metadata, autoload=True)
78 self.xfeaturevals = Table('xfeaturevals', metadata, autoload=True)
79 except NoSuchTableError:
80 tables = create_tables(self.engine)
81 map(lambda t: self.__setattr__(t.name, t), tables)
83 # def xfeature_inherit(self, path):
84 # """Return the (path, feature) inherited by the path, or None."""
86 # s = select([self.xfeatures.c.path, self.xfeatures.c.feature_id])
87 # s = s.where(self.xfeatures.c.path <= path)
88 # #s = s.where(self.xfeatures.c.path.like(self.escape_like(path) + '%', escape='\\')) # XXX: Implement reverse and escape like...
89 # s = s.order_by(desc(self.xfeatures.c.path))
90 # r = self.conn.execute(s)
95 def xfeature_get(self, path):
96 """Return feature for path."""
98 s = select([self.xfeatures.c.feature_id])
99 s = s.where(self.xfeatures.c.path == path)
100 s = s.order_by(self.xfeatures.c.path)
101 r = self.conn.execute(s)
108 def xfeature_create(self, path):
109 """Create and return a feature for path.
110 If the path has a feature, return it.
113 feature = self.xfeature_get(path)
114 if feature is not None:
116 s = self.xfeatures.insert()
117 r = self.conn.execute(s, path=path)
118 inserted_primary_key = r.inserted_primary_key[0]
120 return inserted_primary_key
122 def xfeature_destroy(self, path):
123 """Destroy a feature and all its key, value pairs."""
125 s = self.xfeatures.delete().where(self.xfeatures.c.path == path)
126 r = self.conn.execute(s)
129 def xfeature_destroy_bulk(self, paths):
130 """Destroy features and all their key, value pairs."""
132 s = self.xfeatures.delete().where(self.xfeatures.c.path.in_(paths))
133 r = self.conn.execute(s)
136 def feature_dict(self, feature):
137 """Return a dict mapping keys to list of values for feature."""
139 s = select([self.xfeaturevals.c.key, self.xfeaturevals.c.value])
140 s = s.where(self.xfeaturevals.c.feature_id == feature)
141 r = self.conn.execute(s)
142 d = defaultdict(list)
143 for key, value in r.fetchall():
148 def feature_set(self, feature, key, value):
149 """Associate a key, value pair with a feature."""
151 s = self.xfeaturevals.select()
152 s = s.where(self.xfeaturevals.c.feature_id == feature)
153 s = s.where(self.xfeaturevals.c.key == key)
154 s = s.where(self.xfeaturevals.c.value == value)
155 r = self.conn.execute(s)
156 xfeaturevals = r.fetchall()
158 if len(xfeaturevals) == 0:
159 s = self.xfeaturevals.insert()
160 r = self.conn.execute(s, feature_id=feature, key=key, value=value)
163 def feature_setmany(self, feature, key, values):
164 """Associate the given key, and values with a feature."""
166 #TODO: more efficient way to do it
168 self.feature_set(feature, key, v)
170 def feature_unset(self, feature, key, value):
171 """Disassociate a key, value pair from a feature."""
173 s = self.xfeaturevals.delete()
174 s = s.where(and_(self.xfeaturevals.c.feature_id == feature,
175 self.xfeaturevals.c.key == key,
176 self.xfeaturevals.c.value == value))
177 r = self.conn.execute(s)
180 def feature_unsetmany(self, feature, key, values):
181 """Disassociate the key for the values given, from a feature."""
184 conditional = and_(self.xfeaturevals.c.feature_id == feature,
185 self.xfeaturevals.c.key == key,
186 self.xfeaturevals.c.value == v)
187 s = self.xfeaturevals.delete().where(conditional)
188 r = self.conn.execute(s)
191 def feature_get(self, feature, key):
192 """Return the list of values for a key of a feature."""
194 s = select([self.xfeaturevals.c.value])
195 s = s.where(and_(self.xfeaturevals.c.feature_id == feature,
196 self.xfeaturevals.c.key == key))
197 r = self.conn.execute(s)
198 l = [row[0] for row in r.fetchall()]
202 def feature_clear(self, feature, key):
203 """Delete all key, value pairs for a key of a feature."""
205 s = self.xfeaturevals.delete()
206 s = s.where(and_(self.xfeaturevals.c.feature_id == feature,
207 self.xfeaturevals.c.key == key))
208 r = self.conn.execute(s)