|
| 1 | +import sqlite3 |
| 2 | + |
| 3 | + |
| 4 | +class UnknownConstantError(Exception): |
| 5 | + pass |
| 6 | + |
| 7 | + |
| 8 | +class ConstantDb(object): |
| 9 | + |
| 10 | + def __init__(self, file_name='const.db'): |
| 11 | + self._conn = sqlite3.connect(file_name) |
| 12 | + |
| 13 | + def close(self): |
| 14 | + self._conn.close() |
| 15 | + |
| 16 | + def init(self): |
| 17 | + constants = { |
| 18 | + 'g': (9.81, 'm/s**2'), |
| 19 | + 'pi': (3.14, None), |
| 20 | + 'mach': (0.00338, 'm/s'), |
| 21 | + } |
| 22 | + cursor = self._conn.cursor() |
| 23 | + cursor.execute('''CREATE TABLE constants ( |
| 24 | + name TEXT NOT NULL, |
| 25 | + value REAL NOT NULL, |
| 26 | + unit TEXT |
| 27 | + )''') |
| 28 | + for name, data in constants.items(): |
| 29 | + cursor.execute('''INSERT INTO constants |
| 30 | + (name, value, unit) VALUES (?, ?, ?)''', |
| 31 | + (name, data[0], data[1])) |
| 32 | + cursor.execute('''INSERT INTO constants |
| 33 | + (name, value, unit) VALUES (?, ?, ?)''', |
| 34 | + ('pi', 3.1415, None)) |
| 35 | + self._conn.commit() |
| 36 | + cursor.close() |
| 37 | + |
| 38 | + def get_value(self, name): |
| 39 | + cursor = self._conn.cursor() |
| 40 | + cursor.execute('''SELECT value FROM constants |
| 41 | + WHERE name = ?''', (name, )) |
| 42 | + rows = cursor.fetchall() |
| 43 | + cursor.close() |
| 44 | + if not rows: |
| 45 | + msg = "constant '{0}' is undefined".format(name) |
| 46 | + raise UnknownConstantError(msg) |
| 47 | + else: |
| 48 | + return rows[0][0] |
| 49 | + |
| 50 | + def get_names(self): |
| 51 | + cursor = self._conn.cursor() |
| 52 | + cursor.execute('''SELECT name FROM constants''') |
| 53 | + rows = cursor.fetchall() |
| 54 | + cursor.close() |
| 55 | + return [row[0] for row in rows] |
| 56 | + |
| 57 | + def get_nr_constants(self): |
| 58 | + return len(self.get_names()) |
0 commit comments