-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdbhandler.py
99 lines (79 loc) · 2.88 KB
/
dbhandler.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
import logging
import sqlite3
import os
import random
def exists(path):
return os.path.exists(path)
class DBHandler:
def __init__(self):
self.DB_NAME = "base.db"
self.conn = sqlite3.connect(self.DB_NAME)
try:
self.totalWordsCount = self.countTotalWords()
except sqlite3.OperationalError:
self.totalWordsCount = 0
self.POOL = "pool"
self.WORDS = "dict"
self.LEARNT = "passed"
if self.totalWordsCount == 0:
self.setupDatabase()
def dropTables(self):
stmt = """
DROP TABLE IF EXISTS pool;
DROP TABLE IF EXISTS passed;
DROP TABLE IF EXISTS dict;
"""
self.conn.executescript(stmt)
self.conn.commit()
def createTables(self):
stmt = """
CREATE TABLE IF NOT EXISTS pool (id INT, count INT);
CREATE TABLE IF NOT EXISTS passed (id INT);
CREATE TABLE IF NOT EXISTS dict (id INT, kanji TEXT, xref TEXT, furi TEXT, trans TEXT);
"""
self.conn.executescript(stmt)
self.conn.commit()
def setupDatabase(self):
self.dropTables()
self.createTables()
def countTotalWords(self):
stmt = "SELECT COUNT(*) FROM dict"
res = self.conn.execute(stmt).fetchone()
return res[0]
def getDictContents(self):
stmt = "SELECT * FROM dict"
res = self.conn.execute(stmt).fetchall()
return res
def addDictionaryRow(self, uniqueId, kanji, xref, furi, trans):
stmt = "INSERT INTO dict (id, kanji, xref, furi, trans) VALUES (?, ?, ?, ?, ?)"
self.conn.execute(stmt, (uniqueId, kanji, xref, furi, trans))
self.conn.commit()
def getPassedWordsId(self):
stmt = "SELECT * FROM passed"
return self.conn.execute(stmt).fetchall()
def chooseNRandomWords(self, count):
lst = []
passedWordsId = self.getPassedWordsId()
for i in range(count):
x = random.randint(1, self.totalWordsCount)
while not (x in passedWordsId or x in lst):
x = random.randint(1, self.totalWordsCount)
lst.append(x)
for x in lst:
self.addWordPoolRow(x)
def addWordPoolRow(self, uniqueId):
stmt = "INSERT INTO pool (id, count) VALUES (?, ?)"
self.conn.execute(stmt, (uniqueId, 0))
self.conn.commit()
def removeWordsFromPool(self, uniqueIdList):
stmt = "DELETE FROM pool WHERE id=?"
for uniqueId in uniqueIdList:
self.conn.execute(stmt, (uniqueId, ))
self.conn.commit()
def getWellKnownWordsFromPool(self, counter):
stmt = "SELECT id FROM pool WHERE count >= ?"
cur = self.conn.execute(stmt, (counter, ))
return cur.fetchall()
def removeWellKnownWords(self, counter):
lst = self.getWellKnownWords(counter)
self.removeWordsFromPool(lst)