-
Notifications
You must be signed in to change notification settings - Fork 1
/
db.py
48 lines (40 loc) · 1.33 KB
/
db.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
#!/usr/bin/env python3
import sqlite3
def prepare_db(path):
con = sqlite3.connect(path)
c = con.cursor()
c.execute('''CREATE TABLE IF NOT EXISTS
infections (
id INTEGER PRIMARY KEY AUTOINCREMENT,
uuid BLOB NOT NULL UNIQUE ON CONFLICT IGNORE
)''')
c.execute('''CREATE UNIQUE INDEX IF NOT EXISTS uuid ON infections (uuid)''')
c.close()
return con
def _convert_to_uuid_bytes(uuid):
if type(uuid) == str:
return uuid.encode("UTF-8")
if type(uuid) == bytes:
return uuid
raise ValueError("Invalid uuid type")
def insert_into_db(con, uuids):
"""
:param uuids: 16-byte bytes objects
"""
# filter out all uuids with the improper length and convert them to tuples
uuids = ((_convert_to_uuid_bytes(uuid),) for uuid in uuids if len(uuid) == 16)
c = con.cursor()
c.executemany('''INSERT OR IGNORE INTO infections(uuid) VALUES (?)''', uuids)
con.commit()
#def query_all():
# c = con.cursor()
# c.execute('''SELECT uuid FROM infections''')
# return c
def query_subsequent(con, uuid):
c = con.cursor()
c.execute('''SELECT uuid FROM infections WHERE id > (SELECT IFNULL((SELECT id FROM infections WHERE uuid = ?), 0))''', (uuid,))
return (_convert_to_uuid_bytes(row[0]) for row in c)
#def get_id(uuid):
# c = con.cursor()
# c.execute('''SELECT IFNULL((SELECT id FROM infections WHERE uuid = ?), 0)''', (uuid,))
# return c.fetchone()[0]