dwtt/DataStore.py
2011-02-15 22:15:21 -05:00

95 lines
2.1 KiB
Python

import sqlite3
import os
from datetime import datetime
class DataStore:
def __init__(self, dbfile):
if not os.path.exists(dbfile):
self.createdb(dbfile)
self.conn = sqlite3.connect(dbfile)
def __del__(self):
self.conn.close()
def createdb(self, dbfile):
conn = sqlite3.connect(dbfile)
c = conn.cursor()
c.execute('''
CREATE TABLE projects (
id INTEGER PRIMARY KEY,
name TEXT
)''')
c.execute('''
CREATE TABLE tasks (
id INTEGER PRIMARY KEY,
projectid INTEGER,
name TEXT,
UNIQUE (projectid, name),
FOREIGN KEY (projectid) REFERENCES projects(id)
)''')
c.execute('''
CREATE TABLE hours (
date TEXT,
taskid INTEGER,
seconds INTEGER,
PRIMARY KEY (date, taskid),
FOREIGN KEY (taskid) REFERENCES tasks(id)
)''')
conn.commit()
c.close()
conn.close()
def getProjects(self):
c = self.conn.cursor()
c.execute('''
SELECT id, name
FROM projects
''')
projects = {}
for row in c:
projects[row[0]] = row[1]
c.close()
self.conn.commit()
return projects
def getTasks(self, projectid):
c = self.conn.cursor()
c.execute('''
SELECT id, name
FROM tasks
WHERE projectid = ?
''', (projectid,))
tasks = {}
for row in c:
tasks[row[0]] = row[1]
c.close()
self.conn.commit()
return tasks
def createTask(self, projectid, taskname):
c = self.conn.cursor()
tasks = self.getTasks(projectid)
if taskname in tasks.values():
return False
nextid = self.getNextId('tasks')
c.execute('''
INSERT INTO tasks (id, projectid, name)
VALUES (?, ?)
''', (nextid, projectid, taskname))
c.close()
self.conn.commit()
return True
def getNextId(self, table):
c = self.conn.cursor()
nextid = 1
c.execute('''
SELECT MAX(id)
FROM %s
''' % table)
for row in c:
nextid = row[0] + 1
c.close()
return nextid