This repository has been archived by the owner on Dec 1, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
database.py
349 lines (292 loc) · 9.35 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
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
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
import logging
import os
import sqlite3
from typing import TypedDict
import config
class QuestionModel(TypedDict):
qid: int # primary
uid: str
tid: int | None
type: str | None # anon, system, shoutout
text: str | None
author_id: str | None
author_name: str | None
visual_id: str | None
created_at: int
class AnswerModel(TypedDict):
qid: int # primary
uid: str
text: str | None
visual_id: str | None
like_count: int
created_at: int
class ChatModel(TypedDict):
id: int
uid: str
qid: int
text: str
author_id: str
author_name: str
created_at: int
class VisualModel(TypedDict):
id: str
type: str # gif, photo, video
directory: str # relative to visuals directory
class QueueModel(TypedDict):
id: str
type: str # gif, photo, video
directory: str # relative to visuals directory
url: str
class ThreadModel(TypedDict):
id: int # tid, usually 1st answer
uid: str
qid: int
external: bool # true if manually linked
class UserModel(TypedDict):
id: str
name: str
blob: str
class SchemaVersion(TypedDict):
version: int
class QuestionAnswerView(TypedDict):
tid: int
qid: int
answer: str
a_vid: str # answer_visualid
a_ts: int # a.created_at
author_id: str
author_name: str
q_vid: str # question_visualid
question: str
q_ts: str # q.created_at
like_count: int
class Database:
def __init__(self, db_file):
self.db = None
self.db_file = db_file
if not os.path.exists(self.db_file):
self.create_inital()
def create_inital(self):
path = "./sqlite/migrations/1_inital_setup.sql"
logging.info("creating initial database file")
with open(path, "r") as sql_file:
init_script = sql_file.read()
db = sqlite3.connect(self.db_file)
cursor = db.cursor()
cursor.executescript(init_script)
cursor.close()
db.commit()
db.close()
def _dict_factory(self, cursor, row):
fields = [column[0] for column in cursor.description]
return {key: value for key, value in zip(fields, row)}
def connect(self):
if self.db is not None:
self.close()
self.db = sqlite3.connect(self.db_file)
self.db.row_factory = self._dict_factory
def close(self):
if self.db is None:
return
self.db.commit()
self.db.close()
self.db = None
def ready(self) -> bool:
return self.db is not None
def insert(self, table: str, obj: dict):
if not self.ready():
raise Exception("database not ready")
placeholders = ",".join(["?"] * len(obj))
columns = ", ".join(obj.keys())
sql = "INSERT OR IGNORE INTO %s ( %s ) VALUES ( %s )" % (
table,
columns,
placeholders,
)
try:
cursor = self.db.cursor()
cursor.execute(sql, list(obj.values()))
self.db.commit()
except sqlite3.Error as e:
logging.error(f"sqlite3 exception: {e}")
def insertmany(self, table: str, keys, values: list[tuple]):
if not self.ready():
raise Exception("database not ready")
if len(values) == 0:
return
placeholders = ",".join(["?"] * len(keys))
columns = ", ".join(keys)
sql = "INSERT OR IGNORE INTO %s ( %s ) VALUES ( %s )" % (
table,
columns,
placeholders,
)
try:
cursor = self.db.cursor()
cursor.executemany(sql, values)
self.db.commit()
except sqlite3.Error as e:
logging.error(f"sqlite3 exception: {e}")
def update_user_blob(self, id: str, blob: str):
if not self.ready():
raise Exception("database not ready")
sql = "UPDATE users SET blob=? WHERE id=?"
try:
cursor = self.db.cursor()
cursor.execute(sql, (blob, id))
self.db.commit()
except sqlite3.Error as e:
logging.error(f"sqlite3 exception update_user_blob: {e}")
def upsert_answers(self, keys, values):
if not self.ready():
raise Exception("database not ready")
placeholders = ",".join(["?"] * len(keys))
columns = ", ".join(keys)
sql = (
"INSERT INTO answers ( %s ) VALUES ( %s ) ON CONFLICT(qid) DO UPDATE SET like_count=(?)"
% (
columns,
placeholders,
)
)
try:
cursor = self.db.cursor()
cursor.executemany(sql, values)
self.db.commit()
except sqlite3.Error as e:
logging.error(f"sqlite3 exception upsert_answers: {e}")
def add_user(self, user: UserModel):
table = "users"
user["id"] = user["id"].lower()
self.insert(table, user)
def add_answers(self, keys, values):
self.upsert_answers(keys, values)
def add_chat(self, chat: ChatModel):
table = "chats"
if chat["author_id"] is not None:
chat["author_id"] = chat["author_id"].lower()
chat["uid"] = chat["uid"].lower()
self.insert(table, chat)
def add_questions(self, keys, values: list[tuple[QuestionModel]]):
table = "questions"
self.insertmany(table, keys, values)
def add_threads(self, keys, values: list[tuple[ThreadModel]]):
table = "threads"
self.insertmany(table, keys, values)
def add_visual(self, visual: VisualModel):
table = "visuals"
self.insert(table, visual)
def add_download_queue(self, visual: QueueModel):
table = "download_queue"
self.insert(table, visual)
def fetch_all(self, sql: str, args):
if not self.ready():
raise Exception("database not ready")
try:
cursor = self.db.cursor()
cursor.execute(sql, args)
return cursor.fetchall()
except Exception as e:
logging.error(f"sqlite3 exception: {e}")
def _get_question_answer_view(self, uid) -> dict[int, QuestionAnswerView]:
sql = """
SELECT
q.tid,
a.qid,
a.text as answer,
a.visual_id as a_vid,
a.created_at as a_ts,
a.like_count,
q.author_id,
q.author_name,
q.visual_id as q_vid,
q.text as question,
q.created_at as q_ts
FROM
questions q,
answers a
WHERE
q.uid = a.uid AND
q.qid = a.qid AND
q.uid = ?
ORDER BY q.qid DESC;
"""
records = self.fetch_all(sql, (uid,))
return records
def get_question_answer_view(self, uid) -> dict[int, QuestionAnswerView]:
records = self._get_question_answer_view(uid)
map = {}
for record in records:
qid = record["qid"]
map[qid] = record
return map
def get_threads(self, uid) -> dict[int, list[int]]:
"""
returns dict[int, list[int]]
key: thread_id
value: list of questions in the thread
"""
sql = """
SELECT id, qid
FROM
threads
Where
uid = ?
ORDER BY id ASC;
"""
records = self.fetch_all(sql, (uid,))
result: dict[int, list[int]] = {}
for record in records:
if record["id"] not in result:
result[record["id"]] = []
result[record["id"]].append(record["qid"])
return result
def _get_chats(self, uid: str) -> list[ChatModel]:
sql = """
SELECT c.*
FROM
chats c
WHERE
c.uid=?
ORDER BY
c.created_at ASC;
"""
records = self.fetch_all(sql, (uid,))
return records
def get_chats(self, uid: str) -> dict[int, list[ChatModel]]:
records = self._get_chats(uid)
result: dict[int, list[ChatModel]] = {}
for record in records:
if record["qid"] not in result:
result[record["qid"]] = []
result[record["qid"]].append(record)
return result
def get_user(self, uid: str) -> UserModel:
sql = "Select * FROM users where id = ?"
records = self.fetch_all(sql, (uid.lower(),))
return records[0]
def get_answer_count(self, uid: str) -> int:
sql = "select count(*) as count from answers where uid = ?"
records = self.fetch_all(sql, (uid.lower(),))
return records[0]["count"]
def get_chat_count(self, uid: str) -> int:
sql = "select count(*) as count from chats where uid = ?"
records = self.fetch_all(sql, (uid.lower(),))
return records[0]["count"]
def get_oldest_answer_time_stamp(self, uid: str) -> int:
sql = "select MIN(created_at) as created_at from answers where uid = ?"
records = self.fetch_all(sql, (uid.lower(),))
return records[0]["created_at"]
def get_newest_answer_time_stamp(self, uid: str) -> int:
sql = "select MAX(created_at) as created_at from answers where uid = ?"
records = self.fetch_all(sql, (uid.lower(),))
return records[0]["created_at"]
def get_top_n_answers(self, uid: str, limit: int = 500) -> list[QuestionModel]:
sql = "select qid from answers where uid = ? order by created_at DESC limit ?"
records = self.fetch_all(sql, (uid.lower(), limit))
result = []
for r in records:
result.append(r["qid"])
return result
def __delete__(self):
self.close()