3 # Copyright (C) 2013 Simo Sorce <simo@redhat.com>
5 # see file 'COPYING' for use and warranty information
7 # This program is free software; you can redistribute it and/or modify
8 # it under the terms of the GNU General Public License as published by
9 # the Free Software Foundation, either version 3 of the License, or
10 # (at your option) any later version.
12 # This program is distributed in the hope that it will be useful,
13 # but WITHOUT ANY WARRANTY; without even the implied warranty of
14 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 # GNU General Public License for more details.
17 # You should have received a copy of the GNU General Public License
18 # along with this program. If not, see <http://www.gnu.org/licenses/>.
21 from ipsilon.util.log import Log
22 from sqlalchemy import create_engine
23 from sqlalchemy import MetaData, Table, Column, Text
24 from sqlalchemy.sql import select
30 OPTIONS_COLUMNS = ['name', 'option', 'value']
31 UNIQUE_DATA_COLUMNS = ['uuid', 'name', 'value']
36 def __init__(self, name):
38 if '://' not in engine_name:
39 engine_name = 'sqlite:///' + engine_name
40 self._dbengine = create_engine(engine_name)
41 self.is_readonly = False
47 return self._dbengine.connect()
51 def at(self, *args, **kwargs):
53 return f(self, *args, **kwargs)
59 def __init__(self, db_obj, table, columns, trans=True):
61 self._con = self._db.connection()
62 self._trans = self._con.begin() if trans else None
63 self._table = self._get_table(table, columns)
65 def _get_table(self, name, columns):
66 table = Table(name, MetaData(self._db.engine()))
68 table.append_column(Column(c, Text()))
71 def _where(self, kvfilter):
73 if kvfilter is not None:
75 w = self._table.columns[k] == kvfilter[k]
82 def _columns(self, columns=None):
84 if columns is not None:
87 cols.append(self._table.columns[c])
89 cols = self._table.columns
93 self._trans.rollback()
99 self._table.create(checkfirst=True)
102 self._table.drop(checkfirst=True)
105 def select(self, kvfilter=None, columns=None):
106 return self._con.execute(select(self._columns(columns),
107 self._where(kvfilter)))
110 def insert(self, values):
111 self._con.execute(self._table.insert(values))
114 def update(self, values, kvfilter):
115 self._con.execute(self._table.update(self._where(kvfilter), values))
118 def delete(self, kvfilter):
119 self._con.execute(self._table.delete(self._where(kvfilter)))
122 class FileStore(Log):
124 def __init__(self, name):
125 self._filename = name
126 self.is_readonly = True
127 self._timestamp = None
130 def get_config(self):
132 stat = os.stat(self._filename)
134 self.error("Unable to check config file %s: [%s]" % (
138 timestamp = stat.st_mtime
139 if self._config is None or timestamp > self._timestamp:
140 self._config = ConfigParser.RawConfigParser()
141 self._config.read(self._filename)
145 class FileQuery(Log):
147 def __init__(self, fstore, table, columns, trans=True):
148 self._fstore = fstore
149 self._config = fstore.get_config()
150 self._section = table
151 if len(columns) > 3 or columns[-1] != 'value':
152 raise ValueError('Unsupported configuration format')
153 self._columns = columns
162 raise NotImplementedError
165 raise NotImplementedError
167 def select(self, kvfilter=None, columns=None):
168 if self._section not in self._config.sections():
171 opts = self._config.options(self._section)
175 if self._columns[0] in kvfilter:
176 prefix = kvfilter[self._columns[0]]
177 prefix_ = prefix + ' '
180 if len(self._columns) == 3 and self._columns[1] in kvfilter:
181 name = kvfilter[self._columns[1]]
184 if self._columns[-1] in kvfilter:
185 value = kvfilter[self._columns[-1]]
189 if len(self._columns) == 3:
191 if prefix and not o.startswith(prefix_):
194 col1, col2 = o.split(' ', 1)
195 if name and col2 != name:
198 col3 = self._config.get(self._section, o)
199 if value and col3 != value:
202 r = [col1, col2, col3]
205 if prefix and o != prefix:
207 r = [o, self._config.get(self._section, o)]
212 s.append(r[self._columns.index(c)])
217 self.debug('SELECT(%s, %s, %s) -> %s' % (self._section,
223 def insert(self, values):
224 raise NotImplementedError
226 def update(self, values, kvfilter):
227 raise NotImplementedError
229 def delete(self, kvfilter):
230 raise NotImplementedError
234 def __init__(self, config_name):
235 if config_name not in cherrypy.config:
236 raise NameError('Unknown database %s' % config_name)
237 name = cherrypy.config[config_name]
238 if name.startswith('configfile://'):
239 _, filename = name.split('://')
240 self._db = FileStore(filename)
241 self._query = FileQuery
243 self._db = SqlStore(name)
244 self._query = SqlQuery
247 def is_readonly(self):
248 return self._db.is_readonly
250 def _row_to_dict_tree(self, data, row):
256 self._row_to_dict_tree(d2, row[1:])
260 if data[name] is list:
261 data[name].append(value)
264 data[name] = [v, value]
268 def _rows_to_dict_tree(self, rows):
271 self._row_to_dict_tree(data, r)
274 def _load_data(self, table, columns, kvfilter=None):
277 q = self._query(self._db, table, columns, trans=False)
278 rows = q.select(kvfilter)
279 except Exception, e: # pylint: disable=broad-except
280 self.error("Failed to load data for table %s: [%s]" % (table, e))
281 return self._rows_to_dict_tree(rows)
283 def load_config(self):
285 columns = ['name', 'value']
286 return self._load_data(table, columns)
288 def load_options(self, table, name=None):
291 kvfilter['name'] = name
292 options = self._load_data(table, OPTIONS_COLUMNS, kvfilter)
293 if name and name in options:
297 def save_options(self, table, name, options):
301 q = self._query(self._db, table, OPTIONS_COLUMNS)
302 rows = q.select({'name': name}, ['option', 'value'])
304 curvals[row[0]] = row[1]
308 q.update({'value': options[opt]},
309 {'name': name, 'option': opt})
311 q.insert((name, opt, options[opt]))
314 except Exception, e: # pylint: disable=broad-except
317 self.error("Failed to save options: [%s]" % e)
320 def delete_options(self, table, name, options=None):
321 kvfilter = {'name': name}
324 q = self._query(self._db, table, OPTIONS_COLUMNS)
329 kvfilter['option'] = opt
332 except Exception, e: # pylint: disable=broad-except
335 self.error("Failed to delete from %s: [%s]" % (table, e))
338 def new_unique_data(self, table, data):
339 newid = str(uuid.uuid4())
342 q = self._query(self._db, table, UNIQUE_DATA_COLUMNS)
344 q.insert((newid, name, data[name]))
346 except Exception, e: # pylint: disable=broad-except
349 self.error("Failed to store %s data: [%s]" % (table, e))
353 def get_unique_data(self, table, uuidval=None, name=None, value=None):
356 kvfilter['uuid'] = uuidval
358 kvfilter['name'] = name
360 kvfilter['value'] = value
361 return self._load_data(table, UNIQUE_DATA_COLUMNS, kvfilter)
363 def save_unique_data(self, table, data):
366 q = self._query(self._db, table, UNIQUE_DATA_COLUMNS)
369 rows = q.select({'uuid': uid}, ['name', 'value'])
376 q.update({'value': datum[name]},
377 {'uuid': uid, 'name': name})
379 q.insert((uid, name, datum[name]))
382 except Exception, e: # pylint: disable=broad-except
385 self.error("Failed to store data in %s: [%s]" % (table, e))
388 def del_unique_data(self, table, uuidval):
389 kvfilter = {'uuid': uuidval}
391 q = self._query(self._db, table, UNIQUE_DATA_COLUMNS, trans=False)
393 except Exception, e: # pylint: disable=broad-except
394 self.error("Failed to delete data from %s: [%s]" % (table, e))
396 def _reset_data(self, table):
398 q = self._query(self._db, table, UNIQUE_DATA_COLUMNS)
402 except Exception, e: # pylint: disable=broad-except
405 self.error("Failed to erase all data from %s: [%s]" % (table, e))
408 class AdminStore(Store):
411 super(AdminStore, self).__init__('admin.config.db')
413 def get_data(self, plugin, idval=None, name=None, value=None):
414 return self.get_unique_data(plugin+"_data", idval, name, value)
416 def save_data(self, plugin, data):
417 return self.save_unique_data(plugin+"_data", data)
419 def new_datum(self, plugin, datum):
420 table = plugin+"_data"
421 return self.new_unique_data(table, datum)
423 def del_datum(self, plugin, idval):
424 table = plugin+"_data"
425 return self.del_unique_data(table, idval)
427 def wipe_data(self, plugin):
428 table = plugin+"_data"
429 self._reset_data(table)
432 class UserStore(Store):
434 def __init__(self, path=None):
435 super(UserStore, self).__init__('user.prefs.db')
437 def save_user_preferences(self, user, options):
438 self.save_options('users', user, options)
440 def load_user_preferences(self, user):
441 return self.load_options('users', user)
443 def save_plugin_data(self, plugin, user, options):
444 self.save_options(plugin+"_data", user, options)
446 def load_plugin_data(self, plugin, user):
447 return self.load_options(plugin+"_data", user)
450 class TranStore(Store):
452 def __init__(self, path=None):
453 super(TranStore, self).__init__('transactions.db')