-
Notifications
You must be signed in to change notification settings - Fork 0
/
database.py
75 lines (58 loc) · 2.01 KB
/
database.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
"""
database.py
Request's word list from sqlite database
"""
from re import T
import sqlite3
import os
DATABASE_NAME = "./database.db"
def get_mp3s_from_wordlist(words):
"""requests mp3s from database and loads from file system
Args:
words (list): a list of words in a sentence
"""
tuple_of_words = [(word,) for word in words]
with Database(DATABASE_NAME) as db:
db.cursor.executemany("SELECT path FROM word_list WHERE word=?", tuple_of_words)
for word in words:
r = db.cursor.fetchone()
if r is None:
print(f"No sound found for word: {word}")
continue
# Sqlite3 database
# https://www.sqlite.org/lang.html
class Database:
"""
boiler plate sqlite3 context handler
"""
def __init__(self, db_file):
self.db_file = db_file
# run sql migrations
conn = sqlite3.connect(self.db_file)
self.migrate(conn)
conn.close()
def __enter__(self):
self.connection: sqlite3.Connection = sqlite3.connect(self.db_file)
self.connection.row_factory = sqlite3.Row
self.cursor: sqlite3.Cursor = self.connection.cursor()
return self
def __exit__(self, exc_type, exc_value, traceback):
self.connection.close()
def migrate(self, conn: sqlite3.Connection):
"""
run though sql migrations
"""
# get migration version
path_to_migrations = f"{os.path.dirname(__file__)}/migrations/"
version: int
try:
version = conn.execute("SELECT version FROM meta").fetchone()[0]
except sqlite3.OperationalError or sqlite3.OperationalError:
version = -1
schema_version = len(os.listdir(path_to_migrations)) - 1
while version < schema_version:
version += 1
with open(f"{path_to_migrations}v{version}.sql", "r") as f:
sql = f.read()
conn.executescript(sql)
conn.commit()