3 from datetime import datetime
5 dbdir = os.path.dirname(__file__)
6 dbdef = os.path.join(dbdir, "coffee_db.sql")
7 dbfile = os.path.join(dbdir, "coffee.db")
11 conn = sqlite3.connect(dbfile)
23 with open(dbdef, "r") as f:
24 c.executescript(f.read())
30 c.execute("insert or ignore into users (id) values (?)", (uid,))
34 def add_user_identifier(uid, iid, name):
35 # Check if this identifier is not currently associated with different account
39 # Try to remove old relation of identifier
40 # As 'delete or ignore' does not exist, workaround is used
41 res = c.execute("select * from identifiers where id = ? and active = 0", (iid, ))
43 # This is True when some rows were found before; delete old relation
45 print("Deleting uid:%s id:%s" % (uid, iid))
46 res = c.execute("delete from identifiers where id = ? and active = 0", (iid, ))
49 res = c.execute("insert into identifiers (userid, id, name) values (?, ?, ?)", (uid, iid, name, ))
54 def disable_user_identifier(uid, iid):
56 c.execute("update identifiers set active = 0 where userid = ? and id = ?", (uid, iid, ))
62 for name, in c.execute("select name from users where id = ?", (uid,)):
71 res = list(c.execute("""
72 select userid from identifiers where id = ? and active
76 return res[0][0] if len(res) > 0 else None
79 def name_user(uid, name):
81 c.execute("update users set name = ? where id = ?", (name, uid))
85 def rename_user_identifier(uid, iid, name):
87 c.execute("update identifiers set name = ? where userid = ? and id = ?", (name, uid, iid, ))
93 for row in c.execute("select * from users"):
98 def list_user_identifiers(uid):
100 res = list(c.execute("""
101 select * from identifiers where userid = ? and active
107 def add_coffee(uid, flavor, time=None):
110 c.execute("insert into coffees (id, flavor) values (?,?)", (uid, flavor))
112 c.execute("insert or ignore into coffees (id, flavor, time) values (?,?,?)", (uid, flavor, time))
116 def add_event(uid, event_name, time):
118 c.execute("""insert into events (user_id, event_type, time)
119 values (?, (SELECT id FROM event_types WHERE name = ?), ?)""",
120 (uid, event_name, time))
126 res = list(c.execute("select distinct name, ord from flavors"))
131 def coffee_flavors(uid=None, days=0, start=0):
132 """Returns flavor statistics for team/user during selected
133 period/since beginning.
135 days -- number of days for computation
136 start -- shift size from the current time
138 When 'days' is not given or 0 return statistics since the beginning.
140 e.g. (7, 7) returns statistics for 7 days, 7 days ago.
148 if days is not None and days != 0:
149 query += " where date(time) between date('now', 'localtime', '-" + str(days+start-1) + " days') and date('now', 'localtime', '-" + str(start) + " days')"
152 query += " and ids.userid = ? and ids.active"
153 variables.append(uid)
154 elif uid is not None:
155 query += " where ids.userid = ? and ids.active"
156 variables.append(uid)
158 res = list(c.execute("""
159 select f.name, count(c.flavor) from flavors f
160 left join (select * from coffees co left join identifiers ids on co.id=ids.id
162 on f.name=c.flavor group by f.name
170 def coffee_history(uid=None):
174 res = list(c.execute("""
175 select strftime('%s', ds.d),count(c.flavor),c.flavor from
176 (select num,date('now', 'localtime', -num || ' days') as d from days) ds
178 (select time,flavor from coffees) c
179 on d = date(c.time) group by d, c.flavor
182 res = list(c.execute(
184 select strftime('%s', ds.d),count(c.flavor),c.flavor from
185 (select num,date('now', 'localtime', -num || ' days') as d from days) ds
187 (select date(time, 'localtime') as time,flavor from coffees co left join identifiers ids on co.id = ids.id where ids.userid = ? and ids.active) c
188 on d = date(c.time) group by d, c.flavor
196 def drink_count(uid=None, start=None, stop=None):
197 """Return a list of tuples ('<drink type>', <count>).
199 >>> drink_count(stop=0)
200 [('coffee', 7066), ('Club-Mate', 497), ('tea', 1)]
208 clauses.append("ids.userid = ? and ids.active")
211 if start is not None:
212 clauses.append("date(time, 'localtime') >= date('now', 'localtime', '-%d days')" % int(start))
215 clauses.append("date(time, 'localtime') <= date('now', 'localtime', '-%d days')" % int(stop))
217 return list(c.execute("select fl.type, count(*) from coffees co "
218 "left join flavors fl on co.flavor = fl.name "
219 "left join identifiers ids on co.id = ids.id where "
220 + " and ".join(clauses) + " group by fl.type "
221 "order by fl.ord asc", args))
223 def sqlite_timestring_to_datetime(timestring):
224 if timestring[-1] == 'Z': # Convert Zulu time zone to datetime compatible format
225 timestring = timestring[0:-1] + '+00:00'
226 return datetime.fromisoformat(timestring)
229 """Return mapping with event names as keys and SQLite time string of
230 the last event as values.
234 for name, time in c.execute("""select name, MAX(time)
235 from events as e left join event_types as et on e.event_type = et.id
237 res[name] = sqlite_timestring_to_datetime(time)