1 # Copyright (C) 2013 Simo Sorce <simo@redhat.com>
3 # see file 'COPYING' for use and warranty information
5 # This program is free software; you can redistribute it and/or modify
6 # it under the terms of the GNU General Public License as published by
7 # the Free Software Foundation, either version 3 of the License, or
8 # (at your option) any later version.
10 # This program is distributed in the hope that it will be useful,
11 # but WITHOUT ANY WARRANTY; without even the implied warranty of
12 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 # GNU General Public License for more details.
15 # You should have received a copy of the GNU General Public License
16 # along with this program. If not, see <http://www.gnu.org/licenses/>.
19 from ipsilon.util.log import Log
20 from sqlalchemy import create_engine
21 from sqlalchemy import MetaData, Table, Column, Text
22 from sqlalchemy.sql import select
28 OPTIONS_COLUMNS = ['name', 'option', 'value']
29 UNIQUE_DATA_COLUMNS = ['uuid', 'name', 'value']
34 def __init__(self, name):
36 if '://' not in engine_name:
37 engine_name = 'sqlite:///' + engine_name
38 self._dbengine = create_engine(engine_name)
39 self.is_readonly = False
45 return self._dbengine.connect()
49 def at(self, *args, **kwargs):
51 return f(self, *args, **kwargs)
57 def __init__(self, db_obj, table, columns, trans=True):
59 self._con = self._db.connection()
60 self._trans = self._con.begin() if trans else None
61 self._table = self._get_table(table, columns)
63 def _get_table(self, name, columns):
64 table = Table(name, MetaData(self._db.engine()))
66 table.append_column(Column(c, Text()))
69 def _where(self, kvfilter):
71 if kvfilter is not None:
73 w = self._table.columns[k] == kvfilter[k]
80 def _columns(self, columns=None):
82 if columns is not None:
85 cols.append(self._table.columns[c])
87 cols = self._table.columns
91 self._trans.rollback()
97 self._table.create(checkfirst=True)
100 self._table.drop(checkfirst=True)
103 def select(self, kvfilter=None, columns=None):
104 return self._con.execute(select(self._columns(columns),
105 self._where(kvfilter)))
108 def insert(self, values):
109 self._con.execute(self._table.insert(values))
112 def update(self, values, kvfilter):
113 self._con.execute(self._table.update(self._where(kvfilter), values))
116 def delete(self, kvfilter):
117 self._con.execute(self._table.delete(self._where(kvfilter)))
120 class FileStore(Log):
122 def __init__(self, name):
123 self._filename = name
124 self.is_readonly = True
125 self._timestamp = None
128 def get_config(self):
130 stat = os.stat(self._filename)
132 self.error("Unable to check config file %s: [%s]" % (
136 timestamp = stat.st_mtime
137 if self._config is None or timestamp > self._timestamp:
138 self._config = ConfigParser.RawConfigParser()
139 self._config.optionxform = str
140 self._config.read(self._filename)
144 class FileQuery(Log):
146 def __init__(self, fstore, table, columns, trans=True):
147 self._fstore = fstore
148 self._config = fstore.get_config()
149 self._section = table
150 if len(columns) > 3 or columns[-1] != 'value':
151 raise ValueError('Unsupported configuration format')
152 self._columns = columns
161 raise NotImplementedError
164 raise NotImplementedError
166 def select(self, kvfilter=None, columns=None):
167 if self._section not in self._config.sections():
170 opts = self._config.options(self._section)
174 if self._columns[0] in kvfilter:
175 prefix = kvfilter[self._columns[0]]
176 prefix_ = prefix + ' '
179 if len(self._columns) == 3 and self._columns[1] in kvfilter:
180 name = kvfilter[self._columns[1]]
183 if self._columns[-1] in kvfilter:
184 value = kvfilter[self._columns[-1]]
188 if len(self._columns) == 3:
190 if prefix and not o.startswith(prefix_):
193 col1, col2 = o.split(' ', 1)
194 if name and col2 != name:
197 col3 = self._config.get(self._section, o)
198 if value and col3 != value:
201 r = [col1, col2, col3]
204 if prefix and o != prefix:
206 r = [o, self._config.get(self._section, o)]
211 s.append(r[self._columns.index(c)])
216 self.debug('SELECT(%s, %s, %s) -> %s' % (self._section,
222 def insert(self, values):
223 raise NotImplementedError
225 def update(self, values, kvfilter):
226 raise NotImplementedError
228 def delete(self, kvfilter):
229 raise NotImplementedError
233 def __init__(self, config_name=None, database_url=None):
234 if config_name is None and database_url is None:
235 raise ValueError('config_name or database_url must be provided')
237 if config_name not in cherrypy.config:
238 raise NameError('Unknown database %s' % config_name)
239 name = cherrypy.config[config_name]
242 if name.startswith('configfile://'):
243 _, filename = name.split('://')
244 self._db = FileStore(filename)
245 self._query = FileQuery
247 self._db = SqlStore(name)
248 self._query = SqlQuery
251 def is_readonly(self):
252 return self._db.is_readonly
254 def _row_to_dict_tree(self, data, row):
260 self._row_to_dict_tree(d2, row[1:])
264 if data[name] is list:
265 data[name].append(value)
268 data[name] = [v, value]
272 def _rows_to_dict_tree(self, rows):
275 self._row_to_dict_tree(data, r)
278 def _load_data(self, table, columns, kvfilter=None):
281 q = self._query(self._db, table, columns, trans=False)
282 rows = q.select(kvfilter)
283 except Exception, e: # pylint: disable=broad-except
284 self.error("Failed to load data for table %s: [%s]" % (table, e))
285 return self._rows_to_dict_tree(rows)
287 def load_config(self):
289 columns = ['name', 'value']
290 return self._load_data(table, columns)
292 def load_options(self, table, name=None):
295 kvfilter['name'] = name
296 options = self._load_data(table, OPTIONS_COLUMNS, kvfilter)
297 if name and name in options:
301 def save_options(self, table, name, options):
305 q = self._query(self._db, table, OPTIONS_COLUMNS)
306 rows = q.select({'name': name}, ['option', 'value'])
308 curvals[row[0]] = row[1]
312 q.update({'value': options[opt]},
313 {'name': name, 'option': opt})
315 q.insert((name, opt, options[opt]))
318 except Exception, e: # pylint: disable=broad-except
321 self.error("Failed to save options: [%s]" % e)
324 def delete_options(self, table, name, options=None):
325 kvfilter = {'name': name}
328 q = self._query(self._db, table, OPTIONS_COLUMNS)
333 kvfilter['option'] = opt
336 except Exception, e: # pylint: disable=broad-except
339 self.error("Failed to delete from %s: [%s]" % (table, e))
342 def new_unique_data(self, table, data):
343 newid = str(uuid.uuid4())
346 q = self._query(self._db, table, UNIQUE_DATA_COLUMNS)
348 q.insert((newid, name, data[name]))
350 except Exception, e: # pylint: disable=broad-except
353 self.error("Failed to store %s data: [%s]" % (table, e))
357 def get_unique_data(self, table, uuidval=None, name=None, value=None):
360 kvfilter['uuid'] = uuidval
362 kvfilter['name'] = name
364 kvfilter['value'] = value
365 return self._load_data(table, UNIQUE_DATA_COLUMNS, kvfilter)
367 def save_unique_data(self, table, data):
370 q = self._query(self._db, table, UNIQUE_DATA_COLUMNS)
373 rows = q.select({'uuid': uid}, ['name', 'value'])
380 q.update({'value': datum[name]},
381 {'uuid': uid, 'name': name})
383 q.insert((uid, name, datum[name]))
386 except Exception, e: # pylint: disable=broad-except
389 self.error("Failed to store data in %s: [%s]" % (table, e))
392 def del_unique_data(self, table, uuidval):
393 kvfilter = {'uuid': uuidval}
395 q = self._query(self._db, table, UNIQUE_DATA_COLUMNS, trans=False)
397 except Exception, e: # pylint: disable=broad-except
398 self.error("Failed to delete data from %s: [%s]" % (table, e))
400 def _reset_data(self, table):
402 q = self._query(self._db, table, UNIQUE_DATA_COLUMNS)
406 except Exception, e: # pylint: disable=broad-except
409 self.error("Failed to erase all data from %s: [%s]" % (table, e))
412 class AdminStore(Store):
415 super(AdminStore, self).__init__('admin.config.db')
417 def get_data(self, plugin, idval=None, name=None, value=None):
418 return self.get_unique_data(plugin+"_data", idval, name, value)
420 def save_data(self, plugin, data):
421 return self.save_unique_data(plugin+"_data", data)
423 def new_datum(self, plugin, datum):
424 table = plugin+"_data"
425 return self.new_unique_data(table, datum)
427 def del_datum(self, plugin, idval):
428 table = plugin+"_data"
429 return self.del_unique_data(table, idval)
431 def wipe_data(self, plugin):
432 table = plugin+"_data"
433 self._reset_data(table)
436 class UserStore(Store):
438 def __init__(self, path=None):
439 super(UserStore, self).__init__('user.prefs.db')
441 def save_user_preferences(self, user, options):
442 self.save_options('users', user, options)
444 def load_user_preferences(self, user):
445 return self.load_options('users', user)
447 def save_plugin_data(self, plugin, user, options):
448 self.save_options(plugin+"_data", user, options)
450 def load_plugin_data(self, plugin, user):
451 return self.load_options(plugin+"_data", user)
454 class TranStore(Store):
456 def __init__(self, path=None):
457 super(TranStore, self).__init__('transactions.db')