changeset 40:e4759cc8f5e7

Create database file if it does not exist.
author Sascha L. Teichmann <teichmann@intevation.de>
date Wed, 15 Dec 2010 11:37:46 +0100
parents d4ce02a33acd
children f44f808e7d47
files ChangeLog getan/backend.py
diffstat 2 files changed, 50 insertions(+), 0 deletions(-) [+]
line wrap: on
line diff
--- 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 <sascha.teichmann@intevation.de>
+
+	* getan/backend.py: Create database file if it does
+	  not exist.
+
 2010-12-15	Sascha L. Teichmann <sascha.teichmann@intevation.de>
 
 	Some minor fixes
--- 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.")
This site is hosted by Intevation GmbH (Datenschutzerklärung und Impressum | Privacy Policy and Imprint)