Merge branch 'next'
[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
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, mysql_engine='InnoDB')
55         # place an index on path
56         Index('idx_features_path', self.xfeatures.c.path, unique=True)
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, primary_key=True,
64                               autoincrement=False))
65         columns.append(Column('value', String(256), primary_key=True))
66         self.xfeaturevals = Table('xfeaturevals', metadata, *columns, mysql_engine='InnoDB')
67         
68         metadata.create_all(self.engine)
69     
70 #     def xfeature_inherit(self, path):
71 #         """Return the (path, feature) inherited by the path, or None."""
72 #         
73 #         s = select([self.xfeatures.c.path, self.xfeatures.c.feature_id])
74 #         s = s.where(self.xfeatures.c.path <= path)
75 #         #s = s.where(self.xfeatures.c.path.like(self.escape_like(path) + '%', escape='\\')) # XXX: Implement reverse and escape like...
76 #         s = s.order_by(desc(self.xfeatures.c.path))
77 #         r = self.conn.execute(s)
78 #         l = r.fetchall()
79 #         r.close()
80 #         return l
81     
82     def xfeature_get(self, path):
83         """Return feature for path."""
84         
85         s = select([self.xfeatures.c.feature_id])
86         s = s.where(self.xfeatures.c.path == path)
87         s = s.order_by(self.xfeatures.c.path)
88         r = self.conn.execute(s)
89         row = r.fetchone()
90         r.close()
91         if row:
92             return row[0]
93         return None
94     
95     def xfeature_create(self, path):
96         """Create and return a feature for path.
97            If the path has a feature, return it.
98         """
99         
100         feature = self.xfeature_get(path)
101         if feature is not None:
102             return feature
103         s = self.xfeatures.insert()
104         r = self.conn.execute(s, path=path)
105         inserted_primary_key = r.inserted_primary_key[0]
106         r.close()
107         return inserted_primary_key
108     
109     def xfeature_destroy(self, path):
110         """Destroy a feature and all its key, value pairs."""
111         
112         s = self.xfeatures.delete().where(self.xfeatures.c.path == path)
113         r = self.conn.execute(s)
114         r.close()
115     
116     def xfeature_destroy_bulk(self, paths):
117         """Destroy features and all their key, value pairs."""
118         
119         s = self.xfeatures.delete().where(self.xfeatures.c.path.in_(paths))
120         r = self.conn.execute(s)
121         r.close()
122     
123     def feature_dict(self, feature):
124         """Return a dict mapping keys to list of values for feature."""
125         
126         s = select([self.xfeaturevals.c.key, self.xfeaturevals.c.value])
127         s = s.where(self.xfeaturevals.c.feature_id == feature)
128         r = self.conn.execute(s)
129         d = defaultdict(list)
130         for key, value in r.fetchall():
131             d[key].append(value)
132         r.close()
133         return d
134     
135     def feature_set(self, feature, key, value):
136         """Associate a key, value pair with a feature."""
137         
138         s = self.xfeaturevals.select()
139         s = s.where(self.xfeaturevals.c.feature_id == feature)
140         s = s.where(self.xfeaturevals.c.key == key)
141         s = s.where(self.xfeaturevals.c.value == value)
142         r = self.conn.execute(s)
143         xfeaturevals = r.fetchall()
144         r.close()
145         if len(xfeaturevals) == 0:
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         #TODO: more efficient way to do it
154         for v in values:
155             self.feature_set(feature, key, v)
156     
157     def feature_unset(self, feature, key, value):
158         """Disassociate a key, value pair from a feature."""
159         
160         s = self.xfeaturevals.delete()
161         s = s.where(and_(self.xfeaturevals.c.feature_id == feature,
162                      self.xfeaturevals.c.key == key,
163                      self.xfeaturevals.c.value == value))
164         r = self.conn.execute(s)
165         r.close()
166     
167     def feature_unsetmany(self, feature, key, values):
168         """Disassociate the key for the values given, from a feature."""
169         
170         for v in values:
171             conditional = and_(self.xfeaturevals.c.feature_id == feature,
172                                self.xfeaturevals.c.key == key,
173                                self.xfeaturevals.c.value == v)
174             s = self.xfeaturevals.delete().where(conditional)
175             r = self.conn.execute(s)
176             r.close()
177         
178     def feature_get(self, feature, key):
179         """Return the list of values for a key of a feature."""
180         
181         s = select([self.xfeaturevals.c.value])
182         s = s.where(and_(self.xfeaturevals.c.feature_id == feature,
183                      self.xfeaturevals.c.key == key))
184         r = self.conn.execute(s)
185         l = [row[0] for row in r.fetchall()]
186         r.close()
187         return l
188     
189     def feature_clear(self, feature, key):
190         """Delete all key, value pairs for a key of a feature."""
191         
192         s = self.xfeaturevals.delete()
193         s = s.where(and_(self.xfeaturevals.c.feature_id == feature,
194                      self.xfeaturevals.c.key == key))
195         r = self.conn.execute(s)
196         r.close()