dwtt/DataStore.py
2011-02-16 11:49:31 -05:00

113 lines
2.6 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 createProject(self, projectname):
c = self.conn.cursor()
projects = self.getProjects()
if projectname in projects.values():
return False
nextid = self.getNextId('projects')
c.execute('''
INSERT INTO projects (id, name)
VALUES (?, ?)
''', (nextid, projectname))
c.close()
self.conn.commit()
return True
def createTask(self, projectid, taskname):
c = self.conn.cursor()
tasks = self.getTasks(projectid)
if taskname in tasks.values():
return False
projects = self.getProjects()
if not projectid in projects:
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:
if row[0]:
nextid = row[0] + 1
c.close()
return nextid