summaryrefslogtreecommitdiff
path: root/sql.py
blob: d78c84c597c00e63815534222e62790dbf0007b0 (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
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
import sqlite3


class db:
    # https://docs.python.org/3/library/sqlite3.html
    def __init__(self, dbfile):
        # final variable
        self.dbfile = dbfile
        try:
            open(dbfile)
        except FileNotFoundError:
            self.setup()

    def exec(self, cmd, param=None):
        """
        A function to execute a database command without having to
        create the cursor
        """
        con = sqlite3.connect(self.dbfile)
        cur = con.cursor()
        if param == None:
             cur.execute(cmd)
        else:
             cur.execute(cmd, param)
        con.commit()
        con.close()

    def setup(self):
        """
        Necessary when the database does not exist and the tables must be
        created for the first time, otherwise not needed to be run.
        """
        con = sqlite3.connect(self.dbfile)
        cur = con.cursor()
        cur.execute(
            """
        CREATE TABLE temperature (
            date        text not null, 
            time        integer not null, 
            temperature            real,
            target           real,
            PRIMARY KEY (date, time)
        );
                """
        )
        cur.execute(
            """
        CREATE TABLE weather (
            date        text not null,
            temperature real,
            wind        real,
            PRIMARY KEY (date),
            FOREIGN KEY (date) REFERENCES temperature(date)
        );
                """
        )
        cur.execute(
            """
        CREATE TABLE schedule (
            day        text not null, 
            time        integer not null, 
            temperature real,
            PRIMARY KEY (day, time)
        );
                """
        )
        cur.execute(
            """
        CREATE TABLE history (
            date        text not null,
            time        integer not null, 
            heating_on  integer,
            PRIMARY KEY (date, time),
            FOREIGN KEY (date) REFERENCES temperature(date),
            FOREIGN KEY (time) REFERENCES temperature(time)
        );
                """
        )
        con.commit()
        con.close()
        pass

    def export_csv(self):
        return 0