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.pool import QueuePool, SingletonThreadPool
23 from sqlalchemy.sql import select
30 OPTIONS_COLUMNS = ['name', 'option', 'value']
31 UNIQUE_DATA_COLUMNS = ['uuid', 'name', 'value']
38 def get_connection(cls, name):
39 if name not in cls.__instances.keys():
40 logging.debug('SqlStore new: %s', name)
41 cls.__instances[name] = SqlStore(name)
42 return cls.__instances[name]
44 def __init__(self, name):
45 self.debug('SqlStore init: %s' % name)
48 if '://' not in engine_name:
49 engine_name = 'sqlite:///' + engine_name
50 # This pool size is per configured database. The minimum needed,
51 # determined by binary search, is 23. We're using 25 so we have a bit
52 # more playroom, and then the overflow should make sure things don't
53 # break when we suddenly need more.
54 pool_args = {'poolclass': QueuePool,
57 if engine_name.startswith('sqlite://'):
58 # It's not possible to share connections for SQLite between
59 # threads, so let's use the SingletonThreadPool for them
60 pool_args = {'poolclass': SingletonThreadPool}
61 # pylint: disable=star-args
62 self._dbengine = create_engine(engine_name, **pool_args)
63 self.is_readonly = False
69 self.debug('SqlStore connect: %s' % self.name)
70 conn = self._dbengine.connect()
72 def cleanup_connection():
73 self.debug('SqlStore cleanup: %s' % self.name)
75 cherrypy.request.hooks.attach('on_end_request', cleanup_connection)
80 def at(self, *args, **kwargs):
82 return f(self, *args, **kwargs)
88 def __init__(self, db_obj, table, columns, trans=True):
90 self._con = self._db.connection()
91 self._trans = self._con.begin() if trans else None
92 self._table = self._get_table(table, columns)
94 def _get_table(self, name, columns):
95 table = Table(name, MetaData(self._db.engine()))
97 table.append_column(Column(c, Text()))
100 def _where(self, kvfilter):
102 if kvfilter is not None:
104 w = self._table.columns[k] == kvfilter[k]
111 def _columns(self, columns=None):
113 if columns is not None:
116 cols.append(self._table.columns[c])
118 cols = self._table.columns
122 self._trans.rollback()
128 self._table.create(checkfirst=True)
131 self._table.drop(checkfirst=True)
134 def select(self, kvfilter=None, columns=None):
135 return self._con.execute(select(self._columns(columns),
136 self._where(kvfilter)))
139 def insert(self, values):
140 self._con.execute(self._table.insert(values))
143 def update(self, values, kvfilter):
144 self._con.execute(self._table.update(self._where(kvfilter), values))
147 def delete(self, kvfilter):
148 self._con.execute(self._table.delete(self._where(kvfilter)))
151 class FileStore(Log):
153 def __init__(self, name):
154 self._filename = name
155 self.is_readonly = True
156 self._timestamp = None
159 def get_config(self):
161 stat = os.stat(self._filename)
163 self.error("Unable to check config file %s: [%s]" % (
167 timestamp = stat.st_mtime
168 if self._config is None or timestamp > self._timestamp:
169 self._config = ConfigParser.RawConfigParser()
170 self._config.optionxform = str
171 self._config.read(self._filename)
175 class FileQuery(Log):
177 def __init__(self, fstore, table, columns, trans=True):
178 self._fstore = fstore
179 self._config = fstore.get_config()
180 self._section = table
181 if len(columns) > 3 or columns[-1] != 'value':
182 raise ValueError('Unsupported configuration format')
183 self._columns = columns
192 raise NotImplementedError
195 raise NotImplementedError
197 def select(self, kvfilter=None, columns=None):
198 if self._section not in self._config.sections():
201 opts = self._config.options(self._section)
205 if self._columns[0] in kvfilter:
206 prefix = kvfilter[self._columns[0]]
207 prefix_ = prefix + ' '
210 if len(self._columns) == 3 and self._columns[1] in kvfilter:
211 name = kvfilter[self._columns[1]]
214 if self._columns[-1] in kvfilter:
215 value = kvfilter[self._columns[-1]]
219 if len(self._columns) == 3:
221 if prefix and not o.startswith(prefix_):
224 col1, col2 = o.split(' ', 1)
225 if name and col2 != name:
228 col3 = self._config.get(self._section, o)
229 if value and col3 != value:
232 r = [col1, col2, col3]
235 if prefix and o != prefix:
237 r = [o, self._config.get(self._section, o)]
242 s.append(r[self._columns.index(c)])
247 self.debug('SELECT(%s, %s, %s) -> %s' % (self._section,
253 def insert(self, values):
254 raise NotImplementedError
256 def update(self, values, kvfilter):
257 raise NotImplementedError
259 def delete(self, kvfilter):
260 raise NotImplementedError
264 def __init__(self, config_name=None, database_url=None):
265 if config_name is None and database_url is None:
266 raise ValueError('config_name or database_url must be provided')
268 if config_name not in cherrypy.config:
269 raise NameError('Unknown database %s' % config_name)
270 name = cherrypy.config[config_name]
273 if name.startswith('configfile://'):
274 _, filename = name.split('://')
275 self._db = FileStore(filename)
276 self._query = FileQuery
278 self._db = SqlStore.get_connection(name)
279 self._query = SqlQuery
282 def is_readonly(self):
283 return self._db.is_readonly
285 def _row_to_dict_tree(self, data, row):
291 self._row_to_dict_tree(d2, row[1:])
295 if data[name] is list:
296 data[name].append(value)
299 data[name] = [v, value]
303 def _rows_to_dict_tree(self, rows):
306 self._row_to_dict_tree(data, r)
309 def _load_data(self, table, columns, kvfilter=None):
312 q = self._query(self._db, table, columns, trans=False)
313 rows = q.select(kvfilter)
314 except Exception, e: # pylint: disable=broad-except
315 self.error("Failed to load data for table %s: [%s]" % (table, e))
316 return self._rows_to_dict_tree(rows)
318 def load_config(self):
320 columns = ['name', 'value']
321 return self._load_data(table, columns)
323 def load_options(self, table, name=None):
326 kvfilter['name'] = name
327 options = self._load_data(table, OPTIONS_COLUMNS, kvfilter)
328 if name and name in options:
332 def save_options(self, table, name, options):
336 q = self._query(self._db, table, OPTIONS_COLUMNS)
337 rows = q.select({'name': name}, ['option', 'value'])
339 curvals[row[0]] = row[1]
343 q.update({'value': options[opt]},
344 {'name': name, 'option': opt})
346 q.insert((name, opt, options[opt]))
349 except Exception, e: # pylint: disable=broad-except
352 self.error("Failed to save options: [%s]" % e)
355 def delete_options(self, table, name, options=None):
356 kvfilter = {'name': name}
359 q = self._query(self._db, table, OPTIONS_COLUMNS)
364 kvfilter['option'] = opt
367 except Exception, e: # pylint: disable=broad-except
370 self.error("Failed to delete from %s: [%s]" % (table, e))
373 def new_unique_data(self, table, data):
374 newid = str(uuid.uuid4())
377 q = self._query(self._db, table, UNIQUE_DATA_COLUMNS)
379 q.insert((newid, name, data[name]))
381 except Exception, e: # pylint: disable=broad-except
384 self.error("Failed to store %s data: [%s]" % (table, e))
388 def get_unique_data(self, table, uuidval=None, name=None, value=None):
391 kvfilter['uuid'] = uuidval
393 kvfilter['name'] = name
395 kvfilter['value'] = value
396 return self._load_data(table, UNIQUE_DATA_COLUMNS, kvfilter)
398 def save_unique_data(self, table, data):
401 q = self._query(self._db, table, UNIQUE_DATA_COLUMNS)
404 rows = q.select({'uuid': uid}, ['name', 'value'])
411 if datum[name] is None:
412 q.delete({'uuid': uid, 'name': name})
414 q.update({'value': datum[name]},
415 {'uuid': uid, 'name': name})
417 if datum[name] is not None:
418 q.insert((uid, name, datum[name]))
421 except Exception, e: # pylint: disable=broad-except
424 self.error("Failed to store data in %s: [%s]" % (table, e))
427 def del_unique_data(self, table, uuidval):
428 kvfilter = {'uuid': uuidval}
430 q = self._query(self._db, table, UNIQUE_DATA_COLUMNS, trans=False)
432 except Exception, e: # pylint: disable=broad-except
433 self.error("Failed to delete data from %s: [%s]" % (table, e))
435 def _reset_data(self, table):
438 q = self._query(self._db, table, UNIQUE_DATA_COLUMNS)
442 except Exception, e: # pylint: disable=broad-except
445 self.error("Failed to erase all data from %s: [%s]" % (table, e))
448 class AdminStore(Store):
451 super(AdminStore, self).__init__('admin.config.db')
453 def get_data(self, plugin, idval=None, name=None, value=None):
454 return self.get_unique_data(plugin+"_data", idval, name, value)
456 def save_data(self, plugin, data):
457 return self.save_unique_data(plugin+"_data", data)
459 def new_datum(self, plugin, datum):
460 table = plugin+"_data"
461 return self.new_unique_data(table, datum)
463 def del_datum(self, plugin, idval):
464 table = plugin+"_data"
465 return self.del_unique_data(table, idval)
467 def wipe_data(self, plugin):
468 table = plugin+"_data"
469 self._reset_data(table)
472 class UserStore(Store):
474 def __init__(self, path=None):
475 super(UserStore, self).__init__('user.prefs.db')
477 def save_user_preferences(self, user, options):
478 self.save_options('users', user, options)
480 def load_user_preferences(self, user):
481 return self.load_options('users', user)
483 def save_plugin_data(self, plugin, user, options):
484 self.save_options(plugin+"_data", user, options)
486 def load_plugin_data(self, plugin, user):
487 return self.load_options(plugin+"_data", user)
490 class TranStore(Store):
492 def __init__(self, path=None):
493 super(TranStore, self).__init__('transactions.db')