diff getan/backend.py @ 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 f96a18c10836
children 062ce001abd1
line wrap: on
line diff
--- 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)