summaryrefslogtreecommitdiffstats
path: root/storage/sqlite.py
blob: 5b210541a329ce91208359f18d652d16a09104f3 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
# -*- coding: utf-8 -*-

from storageBase import storageBase
from itemList import itemList
from item import item
from pysqlite2 import dbapi2 as sqliteBackend

class sqlite(storageBase):
    dbVersion = '0.1'

    def __init__(self):
        self.con = sqliteBackend.connect(self.getConfigDir() + '/data.sqlite')
        self.cur = self.con.cursor()

        # wenn todo tabelle noch nicht exsistiert, dann sollten wir sie anlegen
        cur = self.cur.execute("select name from sqlite_master where type='table';")
        tables = cur.fetchall()
        if ('todo',) not in tables or ('control',) not in tables:
            self.init_db()

        # überprüfung ob die db-version identisch ist
        version = self.cur.execute("select value from control where setting='db-version'").fetchone()
        if (sqlite.dbVersion,) != version:
            # TODO: update not init
            self.init_db()
            


    def init_db(self):
        print '(re)create todo table...'
        self.cur.execute('drop table if exists todo')
        self.cur.execute('''create table todo (
                id INTEGER PRIMARY KEY AUTOINCREMENT,
                title TEXT(255),
                createdAt INTEGER,
                priority INTEGER,
                desc BLOB
        )''')

        self.cur.execute('drop table if exists control')
        self.cur.execute('''create table control (
                id INTEGER PRIMARY KEY AUTOINCREMENT,
                setting TEXT,
                value TEXT
        )''')

        self.cur.execute("insert into control (setting, value) VALUES ('db-version', ?)", (sqlite.dbVersion,))
        self.con.commit()

    def __del__(self):
        self.con.close()
        
    def load(self):
        items = itemList(self)
        todos = self.cur.execute('select * from todo').fetchall()
        for todo in todos:
            items += item(row=todo)
            
        return items

    def notifyChange(self, sender):
        if sender.getId() >= 0:
            self.cur.execute('update todo set title=?, createdAt=?, priority=? where id=?',
                             (sender.getTitle(), sender.getCreatedAt(), sender.getPriority(), sender.getId()))
            self.con.commit()
        else:      
            self.cur.execute('insert into todo (title, createdAt, priority) VALUES (?, ?, ?)',
                             (sender.getTitle(), sender.getCreatedAt(), sender.getPriority()))
            self.con.commit()
            sender.setId(self.cur.execute('select last_insert_rowid()').fetchone()[0])