summaryrefslogtreecommitdiff
path: root/tropical/db.py
blob: 372f440c9e057a94c0c576ec3a8805adf8034c24 (plain)
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
import sqlite3, time, socket

def rowFactory(cursor, row):
    """
    Create dictionary for each sqlite row
    """
    d = {}
    for idx, col in enumerate(cursor.description):
        d[col[0]] = row[idx]
    return d

class CalDB:
    __DBVERSION__="1"
    
    def __init__(self, dbPath):
        self.path=dbPath
        self.con=sqlite3.connect(dbPath)
        self.con.row_factory = rowFactory
        self.cur=self.con.cursor()

        # Init database
        res=self.cur.execute('SELECT name FROM sqlite_master WHERE type="table" AND name="infos";')
        if res.fetchone() is None:
            self.initDB()

    def initDB(self):
        # Infos table
        self.cur.execute("CREATE TABLE infos(name UNIQUE, value TEXT)")
        self.cur.execute('INSERT INTO infos VALUES("dbversion", "'+CalDB.__DBVERSION__+'")')
        self.cur.execute('INSERT INTO infos VALUES("creation", "'+str(time.time())+'")')
        self.cur.execute('INSERT INTO infos VALUES("created_on", "'+socket.gethostname()+'")')
        # Calendars table
        self.cur.execute("CREATE TABLE calendars(id INTEGER PRIMARY KEY, name TEXT,  description TEXT, color TEXT, type INTEGER)")
        # Events table
        self.cur.execute("CREATE TABLE events(id INTEGER PRIMARY KEY, name TEXT, calendar INTEGER, description TEXT, start REAL, end REAL, repeat INTEGER, frequency INTEGER, location INTEGER, FOREIGN KEY(calendar) REFERENCES calendars(id))")
        self.con.commit()

    def keyExists(self, db, key):
        res=self.cur.execute("SELECT * FROM {} WHERE id={}".format(db,key))
        return not res.fetchone() is None
        
    def addEvent(self, event):
        """
        Event format: { name: str, calendar: int, desc: str, start: float, end: float, repeat: str, frequency: int }
        """
        pass

    def listEvents(self):
        res=self.cur.execute("SELECT * FROM events")
        return res.fetchall()