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
29 OPTIONS_COLUMNS = ['name', 'option', 'value']
30 UNIQUE_DATA_COLUMNS = ['uuid', 'name', 'value']
37 def get_connection(cls, name):
38 if name not in cls.__instances.keys():
39 print 'SqlStore new: %s' % name
40 cls.__instances[name] = SqlStore(name)
41 return cls.__instances[name]
43 def __init__(self, name):
44 self.debug('SqlStore init: %s' % name)
47 if '://' not in engine_name:
48 engine_name = 'sqlite:///' + engine_name
49 # This pool size is per configured database. The minimum needed,
50 # determined by binary search, is 23. We're using 25 so we have a bit
51 # more playroom, and then the overflow should make sure things don't
52 # break when we suddenly need more.
53 pool_args = {'poolclass': QueuePool,
56 if engine_name.startswith('sqlite://'):
57 # It's not possible to share connections for SQLite between
58 # threads, so let's use the SingletonThreadPool for them
59 pool_args = {'poolclass': SingletonThreadPool}
60 # pylint: disable=star-args
61 self._dbengine = create_engine(engine_name, **pool_args)
62 self.is_readonly = False
68 self.debug('SqlStore connect: %s' % self.name)
69 conn = self._dbengine.connect()
71 def cleanup_connection():
72 self.debug('SqlStore cleanup: %s' % self.name)
74 cherrypy.request.hooks.attach('on_end_request', cleanup_connection)
79 def at(self, *args, **kwargs):
81 return f(self, *args, **kwargs)
87 def __init__(self, db_obj, table, columns, trans=True):
89 self._con = self._db.connection()
90 self._trans = self._con.begin() if trans else None
91 self._table = self._get_table(table, columns)
93 def _get_table(self, name, columns):
94 table = Table(name, MetaData(self._db.engine()))
96 table.append_column(Column(c, Text()))
99 def _where(self, kvfilter):
101 if kvfilter is not None:
103 w = self._table.columns[k] == kvfilter[k]
110 def _columns(self, columns=None):
112 if columns is not None:
115 cols.append(self._table.columns[c])
117 cols = self._table.columns
121 self._trans.rollback()
127 self._table.create(checkfirst=True)
130 self._table.drop(checkfirst=True)
133 def select(self, kvfilter=None, columns=None):
134 return self._con.execute(select(self._columns(columns),
135 self._where(kvfilter)))
138 def insert(self, values):
139 self._con.execute(self._table.insert(values))
142 def update(self, values, kvfilter):
143 self._con.execute(self._table.update(self._where(kvfilter), values))
146 def delete(self, kvfilter):
147 self._con.execute(self._table.delete(self._where(kvfilter)))
150 class FileStore(Log):
152 def __init__(self, name):
153 self._filename = name
154 self.is_readonly = True
155 self._timestamp = None
158 def get_config(self):
160 stat = os.stat(self._filename)
162 self.error("Unable to check config file %s: [%s]" % (
166 timestamp = stat.st_mtime
167 if self._config is None or timestamp > self._timestamp:
168 self._config = ConfigParser.RawConfigParser()
169 self._config.optionxform = str
170 self._config.read(self._filename)
174 class FileQuery(Log):
176 def __init__(self, fstore, table, columns, trans=True):
177 self._fstore = fstore
178 self._config = fstore.get_config()
179 self._section = table
180 if len(columns) > 3 or columns[-1] != 'value':
181 raise ValueError('Unsupported configuration format')
182 self._columns = columns
191 raise NotImplementedError
194 raise NotImplementedError
196 def select(self, kvfilter=None, columns=None):
197 if self._section not in self._config.sections():
200 opts = self._config.options(self._section)
204 if self._columns[0] in kvfilter:
205 prefix = kvfilter[self._columns[0]]
206 prefix_ = prefix + ' '
209 if len(self._columns) == 3 and self._columns[1] in kvfilter:
210 name = kvfilter[self._columns[1]]
213 if self._columns[-1] in kvfilter:
214 value = kvfilter[self._columns[-1]]
218 if len(self._columns) == 3:
220 if prefix and not o.startswith(prefix_):
223 col1, col2 = o.split(' ', 1)
224 if name and col2 != name:
227 col3 = self._config.get(self._section, o)
228 if value and col3 != value:
231 r = [col1, col2, col3]
234 if prefix and o != prefix:
236 r = [o, self._config.get(self._section, o)]
241 s.append(r[self._columns.index(c)])
246 self.debug('SELECT(%s, %s, %s) -> %s' % (self._section,
252 def insert(self, values):
253 raise NotImplementedError
255 def update(self, values, kvfilter):
256 raise NotImplementedError
258 def delete(self, kvfilter):
259 raise NotImplementedError
263 def __init__(self, config_name=None, database_url=None):
264 if config_name is None and database_url is None:
265 raise ValueError('config_name or database_url must be provided')
267 if config_name not in cherrypy.config:
268 raise NameError('Unknown database %s' % config_name)
269 name = cherrypy.config[config_name]
272 if name.startswith('configfile://'):
273 _, filename = name.split('://')
274 self._db = FileStore(filename)
275 self._query = FileQuery
277 self._db = SqlStore.get_connection(name)
278 self._query = SqlQuery
281 def is_readonly(self):
282 return self._db.is_readonly
284 def _row_to_dict_tree(self, data, row):
290 self._row_to_dict_tree(d2, row[1:])
294 if data[name] is list:
295 data[name].append(value)
298 data[name] = [v, value]
302 def _rows_to_dict_tree(self, rows):
305 self._row_to_dict_tree(data, r)
308 def _load_data(self, table, columns, kvfilter=None):
311 q = self._query(self._db, table, columns, trans=False)
312 rows = q.select(kvfilter)
313 except Exception, e: # pylint: disable=broad-except
314 self.error("Failed to load data for table %s: [%s]" % (table, e))
315 return self._rows_to_dict_tree(rows)
317 def load_config(self):
319 columns = ['name', 'value']
320 return self._load_data(table, columns)
322 def load_options(self, table, name=None):
325 kvfilter['name'] = name
326 options = self._load_data(table, OPTIONS_COLUMNS, kvfilter)
327 if name and name in options:
331 def save_options(self, table, name, options):
335 q = self._query(self._db, table, OPTIONS_COLUMNS)
336 rows = q.select({'name': name}, ['option', 'value'])
338 curvals[row[0]] = row[1]
342 q.update({'value': options[opt]},
343 {'name': name, 'option': opt})
345 q.insert((name, opt, options[opt]))
348 except Exception, e: # pylint: disable=broad-except
351 self.error("Failed to save options: [%s]" % e)
354 def delete_options(self, table, name, options=None):
355 kvfilter = {'name': name}
358 q = self._query(self._db, table, OPTIONS_COLUMNS)
363 kvfilter['option'] = opt
366 except Exception, e: # pylint: disable=broad-except
369 self.error("Failed to delete from %s: [%s]" % (table, e))
372 def new_unique_data(self, table, data):
373 newid = str(uuid.uuid4())
376 q = self._query(self._db, table, UNIQUE_DATA_COLUMNS)
378 q.insert((newid, name, data[name]))
380 except Exception, e: # pylint: disable=broad-except
383 self.error("Failed to store %s data: [%s]" % (table, e))
387 def get_unique_data(self, table, uuidval=None, name=None, value=None):
390 kvfilter['uuid'] = uuidval
392 kvfilter['name'] = name
394 kvfilter['value'] = value
395 return self._load_data(table, UNIQUE_DATA_COLUMNS, kvfilter)
397 def save_unique_data(self, table, data):
400 q = self._query(self._db, table, UNIQUE_DATA_COLUMNS)
403 rows = q.select({'uuid': uid}, ['name', 'value'])
410 if datum[name] is None:
411 q.delete({'uuid': uid, 'name': name})
413 q.update({'value': datum[name]},
414 {'uuid': uid, 'name': name})
416 if datum[name] is not None:
417 q.insert((uid, name, datum[name]))
420 except Exception, e: # pylint: disable=broad-except
423 self.error("Failed to store data in %s: [%s]" % (table, e))
426 def del_unique_data(self, table, uuidval):
427 kvfilter = {'uuid': uuidval}
429 q = self._query(self._db, table, UNIQUE_DATA_COLUMNS, trans=False)
431 except Exception, e: # pylint: disable=broad-except
432 self.error("Failed to delete data from %s: [%s]" % (table, e))
434 def _reset_data(self, table):
437 q = self._query(self._db, table, UNIQUE_DATA_COLUMNS)
441 except Exception, e: # pylint: disable=broad-except
444 self.error("Failed to erase all data from %s: [%s]" % (table, e))
447 class AdminStore(Store):
450 super(AdminStore, self).__init__('admin.config.db')
452 def get_data(self, plugin, idval=None, name=None, value=None):
453 return self.get_unique_data(plugin+"_data", idval, name, value)
455 def save_data(self, plugin, data):
456 return self.save_unique_data(plugin+"_data", data)
458 def new_datum(self, plugin, datum):
459 table = plugin+"_data"
460 return self.new_unique_data(table, datum)
462 def del_datum(self, plugin, idval):
463 table = plugin+"_data"
464 return self.del_unique_data(table, idval)
466 def wipe_data(self, plugin):
467 table = plugin+"_data"
468 self._reset_data(table)
471 class UserStore(Store):
473 def __init__(self, path=None):
474 super(UserStore, self).__init__('user.prefs.db')
476 def save_user_preferences(self, user, options):
477 self.save_options('users', user, options)
479 def load_user_preferences(self, user):
480 return self.load_options('users', user)
482 def save_plugin_data(self, plugin, user, options):
483 self.save_options(plugin+"_data", user, options)
485 def load_plugin_data(self, plugin, user):
486 return self.load_options(plugin+"_data", user)
489 class TranStore(Store):
491 def __init__(self, path=None):
492 super(TranStore, self).__init__('transactions.db')