Fix code formatting to conform to the PEP 8 style guide
[pithos] / snf-pithos-backend / pithos / backends / lib / sqlalchemy / xfeatures.py
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.sql.expression import desc
39 from sqlalchemy.exc import NoSuchTableError
40
41 from dbworker import DBWorker
42
43
44 def create_tables(engine):
45     metadata = MetaData()
46     columns = []
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)
52
53     columns = []
54     columns.append(Column('feature_id', Integer,
55                           ForeignKey('xfeatures.feature_id',
56                                      ondelete='CASCADE'),
57                           primary_key=True))
58     columns.append(Column('key', Integer, primary_key=True,
59                           autoincrement=False))
60     columns.append(Column('value', String(256), primary_key=True))
61     xfeaturevals = Table(
62         'xfeaturevals', metadata, *columns, mysql_engine='InnoDB')
63
64     metadata.create_all(engine)
65     return metadata.sorted_tables
66
67
68 class XFeatures(DBWorker):
69     """XFeatures are path properties that allow non-nested
70        inheritance patterns. Currently used for storing permissions.
71     """
72
73     def __init__(self, **params):
74         DBWorker.__init__(self, **params)
75         try:
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)
82
83 #     def xfeature_inherit(self, path):
84 #         """Return the (path, feature) inherited by the path, or None."""
85 #
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)
91 #         l = r.fetchall()
92 #         r.close()
93 #         return l
94
95     def xfeature_get(self, path):
96         """Return feature for path."""
97
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)
102         row = r.fetchone()
103         r.close()
104         if row:
105             return row[0]
106         return None
107
108     def xfeature_create(self, path):
109         """Create and return a feature for path.
110            If the path has a feature, return it.
111         """
112
113         feature = self.xfeature_get(path)
114         if feature is not None:
115             return feature
116         s = self.xfeatures.insert()
117         r = self.conn.execute(s, path=path)
118         inserted_primary_key = r.inserted_primary_key[0]
119         r.close()
120         return inserted_primary_key
121
122     def xfeature_destroy(self, path):
123         """Destroy a feature and all its key, value pairs."""
124
125         s = self.xfeatures.delete().where(self.xfeatures.c.path == path)
126         r = self.conn.execute(s)
127         r.close()
128
129     def xfeature_destroy_bulk(self, paths):
130         """Destroy features and all their key, value pairs."""
131
132         s = self.xfeatures.delete().where(self.xfeatures.c.path.in_(paths))
133         r = self.conn.execute(s)
134         r.close()
135
136     def feature_dict(self, feature):
137         """Return a dict mapping keys to list of values for feature."""
138
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():
144             d[key].append(value)
145         r.close()
146         return d
147
148     def feature_set(self, feature, key, value):
149         """Associate a key, value pair with a feature."""
150
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()
157         r.close()
158         if len(xfeaturevals) == 0:
159             s = self.xfeaturevals.insert()
160             r = self.conn.execute(s, feature_id=feature, key=key, value=value)
161             r.close()
162
163     def feature_setmany(self, feature, key, values):
164         """Associate the given key, and values with a feature."""
165
166         #TODO: more efficient way to do it
167         for v in values:
168             self.feature_set(feature, key, v)
169
170     def feature_unset(self, feature, key, value):
171         """Disassociate a key, value pair from a feature."""
172
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)
178         r.close()
179
180     def feature_unsetmany(self, feature, key, values):
181         """Disassociate the key for the values given, from a feature."""
182
183         for v in values:
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)
189             r.close()
190
191     def feature_get(self, feature, key):
192         """Return the list of values for a key of a feature."""
193
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()]
199         r.close()
200         return l
201
202     def feature_clear(self, feature, key):
203         """Delete all key, value pairs for a key of a feature."""
204
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)
209         r.close()