-
Notifications
You must be signed in to change notification settings - Fork 0
/
currentcostdb.py
312 lines (267 loc) · 12.1 KB
/
currentcostdb.py
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
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
# -*- coding: utf-8 -*-
#
# CurrentCost GUI
#
# Copyright (C) 2008 Dale Lane
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
# The author of this code can be contacted at Dale.Lane@gmail.com
# Any contact about this application is warmly welcomed.
#
from pysqlite2 import dbapi2 as sqlite
import datetime, time
#
# We use a SQLite database to persist data - both historical CurrentCost data,
# and user preferences and settings.
#
# This class is used to provide the database.
#
#
# Dale Lane (http://dalelane.co.uk/blog)
class CurrentCostDB():
# connection to the database
connection = None
# what is the path to the database used to store CurrentCost data?
dbLocation = ""
# connect to the database
#
# create tables if not already found
#
def InitialiseDB(self, dbfilepath):
self.dbLocation = dbfilepath
self.connection = sqlite.connect(dbfilepath, detect_types=sqlite.PARSE_DECLTYPES|sqlite.PARSE_COLNAMES)
cursor = self.connection.cursor()
cursor.execute('SELECT name FROM sqlite_master WHERE type="table" AND NAME="settings" ORDER BY name')
if not cursor.fetchone():
cursor.execute('CREATE TABLE settings(settingkey TEXT unique, settingvalue TEXT)')
cursor.execute('SELECT name FROM sqlite_master WHERE type="table" AND NAME="hourdata" ORDER BY name')
if not cursor.fetchone():
cursor.execute('CREATE TABLE hourdata(ts timestamp unique, ccvalue REAL, hourofday INT, uploaded INT)')
cursor.execute('SELECT name FROM sqlite_master WHERE type="table" AND NAME="daydata" ORDER BY name')
if not cursor.fetchone():
cursor.execute('CREATE TABLE daydata(d date unique, ccvalue REAL, dayofweek INT, uploaded INT)')
cursor.execute('SELECT name FROM sqlite_master WHERE type="table" AND NAME="monthdata" ORDER BY name')
if not cursor.fetchone():
cursor.execute('CREATE TABLE monthdata(d date unique, ccvalue REAL, uploaded INT)')
cursor.execute('SELECT name FROM sqlite_master WHERE type="table" AND NAME="annotation" ORDER BY name')
if not cursor.fetchone():
cursor.execute('CREATE TABLE annotation(key INTEGER PRIMARY KEY AUTOINCREMENT, ts timestamp, timeoffset REAL, graphid INT, annotation TEXT, ccvalue REAL)')
self.connection.commit()
#
# disconnect from the database
#
# the connection is unusable after calling this
#
def CloseDB(self):
if self.connection != None:
self.connection.close()
def StoreAnnotation(self, timestamp, timeoffset, graphname, annotation, value):
graphid = None
if graphname == "hours":
graphid = 1
elif graphname == "days":
graphid = 2
elif graphname == "months":
graphid = 3
else:
return
cursor = self.connection.cursor()
cursor.execute('INSERT INTO annotation(ts, timeoffset, graphid, annotation, ccvalue) values(?, ?, ?, ?, ?)',
(timestamp, timeoffset, graphid, annotation, value))
newrowid = cursor.lastrowid
self.connection.commit()
return newrowid
def DeleteAnnotation(self, annotationid):
self.connection.execute('DELETE FROM annotation WHERE key="' + str(annotationid) + '"')
self.connection.commit()
# retrieve a collection of all persisted annotations
def RetrieveAnnotations(self, graphid):
return self.connection.execute('SELECT * FROM annotation WHERE graphid="' + str(graphid) + '"')
def RetrieveAnnotation(self, annotationid):
cursor = self.connection.cursor()
cursor.execute('SELECT * FROM annotation WHERE key="' + str(annotationid) + '"')
row = cursor.fetchone()
return row
# store a key-value pair in the database
def StoreSetting(self, key, value):
self.connection.execute('INSERT OR REPLACE INTO settings(settingkey, settingvalue) values(?, ?)',
(key, value))
self.connection.commit()
# retrieve the value from a key-value pair in the database
def RetrieveSetting(self, key):
cursor = self.connection.cursor()
cursor.execute('SELECT settingkey, settingvalue FROM settings WHERE settingkey="' + key + '"')
row = cursor.fetchone()
if row:
return row[1]
else:
return None
#
############################################################
# helper functions for storing data in the database
#
############################################################
#
def StoreHourData(self, timestamp, ccvalue):
if ccvalue > 0:
self.connection.execute('INSERT OR REPLACE INTO hourdata(ts, ccvalue, hourofday, uploaded) values(?, ?, ?, ?)',
(timestamp, ccvalue, timestamp.hour, 0))
self.connection.commit()
def StoreDayData(self, timestamp, ccvalue):
if ccvalue > 0:
self.connection.execute('INSERT OR REPLACE INTO daydata(d, ccvalue, dayofweek, uploaded) values(?, ?, ?, ?)',
(timestamp, ccvalue, timestamp.weekday(), 0))
self.connection.commit()
def StoreMonthData(self, timestamp, ccvalue):
if ccvalue > 0:
self.connection.execute('INSERT OR REPLACE INTO monthdata(d, ccvalue, uploaded) values(?, ?, ?)',
(timestamp, ccvalue, 0))
self.connection.commit()
#
############################################################
# helper functions for retrieving data from the database
#
############################################################
#
# COUNT THE NUMBER OF OBJECTS IN THE DATABASE
def CountMonthData(self):
cnt = 0
for row in self.connection.execute("SELECT * FROM monthdata"):
cnt += 1
return cnt
def CountDayData(self):
cnt = 0
for row in self.connection.execute("SELECT * FROM daydata"):
cnt += 1
return cnt
def CountHourData(self):
cnt = 0
for row in self.connection.execute("SELECT * FROM hourdata"):
cnt += 1
return cnt
##################
# MONTHS
# get the next recorded month's electricity usage that we've not already
# uploaded to the Google App Engine web service
def GetMonthDataToUpload(self):
monthdataitem = {}
cursor = self.connection.cursor()
cursor.execute('SELECT d, ccvalue FROM monthdata WHERE uploaded=0')
row = cursor.fetchone()
if row:
monthdataitem['timestamp'] = row[0]
monthdataitem['ccvalue'] = row[1]
return monthdataitem
else:
return None
# confirm that the provided data item has been uploaded successfully, so
# that it will not be uploaded again
def ConfirmMonthDataUploaded(self, monthdataitem):
self.connection.execute('INSERT OR REPLACE INTO monthdata(d, ccvalue, uploaded) values(?, ?, ?)',
(monthdataitem['timestamp'], monthdataitem['ccvalue'], 1))
self.connection.commit()
# convert the database's store of monthly electricity usage into a
# dictionary.
#
# this is a hang-over from an earlier version of the application which used
# pickle to store dictionaries as a way of persisting historical data
#
# the conversion to using pysqlite is not complete, so this is a helper
# function used by methods which depend on having a dictionary
#
# ideally, this function will no longer be required once the migration to
# pysqlite is complete.
#
def GetMonthDataCollection(self):
monthdatacollection = {}
for row in self.connection.execute("SELECT d, ccvalue FROM monthdata"):
monthdatacollection[row[0]] = row[1]
return monthdatacollection
##################
# DAYS
# get the next recorded day's electricity usage that we've not already
# uploaded to the Google App Engine web service
def GetDayDataToUpload(self):
daydataitem = {}
cursor = self.connection.cursor()
cursor.execute('SELECT d, ccvalue FROM daydata WHERE uploaded=0')
row = cursor.fetchone()
if row:
daydataitem['timestamp'] = row[0]
daydataitem['ccvalue'] = row[1]
return daydataitem
else:
return None
# confirm that the provided data item has been uploaded successfully, so
# that it will not be uploaded again
def ConfirmDayDataUploaded(self, daydataitem):
self.connection.execute('INSERT OR REPLACE INTO daydata(d, ccvalue, uploaded) values(?, ?, ?)',
(daydataitem['timestamp'], daydataitem['ccvalue'], 1))
self.connection.commit()
# convert the database's store of day electricity usage into a
# dictionary.
#
# this is a hang-over from an earlier version of the application which used
# pickle to store dictionaries as a way of persisting historical data
#
# the conversion to using pysqlite is not complete, so this is a helper
# function used by methods which depend on having a dictionary
#
# ideally, this function will no longer be required once the migration to
# pysqlite is complete.
#
def GetDayDataCollection(self):
daydatacollection = {}
for row in self.connection.execute("SELECT d, ccvalue FROM daydata"):
daydatacollection[row[0]] = row[1]
return daydatacollection
##################
# HOURS
# get the next recorded hours' electricity usage that we've not already
# uploaded to the Google App Engine web service
def GetHourDataToUpload(self):
hourdataitem = {}
cursor = self.connection.cursor()
cursor.execute('SELECT ts, ccvalue FROM hourdata WHERE uploaded=0')
row = cursor.fetchone()
if row:
hourdataitem['timestamp'] = row[0]
hourdataitem['ccvalue'] = row[1]
return hourdataitem
else:
return None
# confirm that the provided data item has been uploaded successfully, so
# that it will not be uploaded again
def ConfirmHourDataUploaded(self, hourdataitem):
self.connection.execute('INSERT OR REPLACE INTO hourdata(ts, ccvalue, uploaded) values(?, ?, ?)',
(hourdataitem['timestamp'], hourdataitem['ccvalue'], 1))
self.connection.commit()
# convert the database's store of hourly electricity usage into a
# dictionary.
#
# this is a hang-over from an earlier version of the application which used
# pickle to store dictionaries as a way of persisting historical data
#
# the conversion to using pysqlite is not complete, so this is a helper
# function used by methods which depend on having a dictionary
#
# ideally, this function will no longer be required once the migration to
# pysqlite is complete.
#
def GetHourDataCollection(self):
hourdatacollection = {}
for row in self.connection.execute("SELECT ts, ccvalue FROM hourdata"):
hourdatacollection[row[0]] = row[1]
return hourdatacollection