# HG changeset patch # User Sascha L. Teichmann # Date 1292409466 -3600 # Node ID e4759cc8f5e7cae74872b405752f44da96fe6769 # Parent d4ce02a33acdd285ac2e85821cfc5c581582a74d Create database file if it does not exist. diff -r d4ce02a33acd -r e4759cc8f5e7 ChangeLog --- a/ChangeLog Wed Dec 15 11:35:59 2010 +0100 +++ b/ChangeLog Wed Dec 15 11:37:46 2010 +0100 @@ -1,3 +1,8 @@ +2010-12-15 Sascha L. Teichmann + + * getan/backend.py: Create database file if it does + not exist. + 2010-12-15 Sascha L. Teichmann Some minor fixes diff -r d4ce02a33acd -r e4759cc8f5e7 getan/backend.py --- a/getan/backend.py Wed Dec 15 11:35:59 2010 +0100 +++ b/getan/backend.py Wed Dec 15 11:37:46 2010 +0100 @@ -9,6 +9,8 @@ # import logging +import os + try: import sqlite3 as db except ImportError: @@ -18,6 +20,28 @@ DEFAULT_DATABASE = "time.db" +CREATE_TABLES = [ +""" +CREATE TABLE projects ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + key VARCHAR(16), + description VARCHAR(256), + active BOOLEAN DEFAULT 1 +) +""", +""" +CREATE TABLE entries ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + project_id INTEGER REFERENCES projects(id), + start_time TIMESTAMP NOT NULL, + stop_time TIMESTAMP NOT NULL, + description VARCHAR(256), + + CHECK (strftime('%s', start_time) <= strftime('%s', stop_time)) +) +""" +] + LOAD_ACTIVE_PROJECTS = ''' SELECT id, key, description, total FROM projects LEFT JOIN @@ -60,12 +84,33 @@ def __init__(self, database = DEFAULT_DATABASE): self.database = database + self.ensure_exists() self.con = db.connect(database, detect_types=db.PARSE_DECLTYPES | db.PARSE_COLNAMES) self.con.text_factory = lambda x: unicode(x, "utf-8", "ignore") + def ensure_exists(self): + """ Creates the database file if it does not exist. """ + if os.path.isfile(self.database): return + + con, cur = None, None + try: + con = db.connect(self.database); + cur = con.cursor() + try: + for sql in CREATE_TABLES: + cur.execute(sql) + con.commit() + except: + con.rollback() + raise + finally: + if cur: cur.close() + if con: con.close() + + def load_projects(self): """ Loads active projects from database and returns them as array """ logger.debug("load active projects from database.")