-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcommentdb.py
339 lines (257 loc) · 9.41 KB
/
commentdb.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
from __future__ import annotations
import time
import json
import enum
import sqlite3
from typing import Optional, TextIO
import sys
REJECTED="REJECTED"
MAYBE="MAYBE"
class FilterMode(enum.Enum):
ALL = "All"
ALL_UNSTATUSED = "All un-statused"
MAYBE_ONLY = "MAYBE only"
REJECTED_ONLY = "REJECTED only"
class CommentDB:
def __init__(self, data):
# data is a list of dicts
self.data = data
# cursor is the current index into `data`
self.cursor = 0
# filter mode determines what data elements will be included/skipped when moving the cursor
self.filter_mode = FilterMode.ALL
@property
def comment_id(self) -> int:
return self.data[self.cursor]["comment_id"]
@property
def url(self) -> str:
return f"https://news.ycombinator.com/item?id={self.comment_id}"
@property
def comment_text(self) -> str:
return self.data[self.cursor]["body"]
@property
def status(self) -> Optional[str]:
return self.data[self.cursor].get("status", None)
@property
def modified_unixtime(self) -> Optional[int]:
return self.data[self.cursor].get("modified_unixtime", None)
@property
def notes(self) -> Optional[str]:
return self.data[self.cursor].get("notes", None)
@property
def as_json_record(self) -> str:
return json.dumps(self.data[self.cursor])
@staticmethod
def from_json_file(fd: TextIO) -> CommentDB:
data = [json.loads(x) for x in fd.readlines() if len(x) > 0]
return CommentDB(data)
# this is pretty dumb
def _passes_filter(self, element: dict) -> bool:
if self.filter_mode == FilterMode.ALL:
return True
elif self.filter_mode == FilterMode.ALL_UNSTATUSED:
return "status" not in element
elif self.filter_mode == FilterMode.MAYBE_ONLY:
return element.get("status", "") == MAYBE
elif self.filter_mode == FilterMode.REJECTED_ONLY:
return element.get("status", "") == REJECTED
#def next(self) -> bool:
# if self.cursor+1 > len(self.data):
# return False
#
# self.cursor += 1
# return True
def next(self) -> bool:
temp_cursor = self.cursor
while True:
temp_cursor += 1
if temp_cursor >= len(self.data):
# we scrolled past the end of the data without finding an element that passes the filter
return False
if self._passes_filter(self.data[temp_cursor]):
self.cursor = temp_cursor
return True
#def prev(self) -> bool:
# if self.cursor-1 < 0:
# return False
#
# self.cursor -= 1
# return True
def prev(self) -> bool:
temp_cursor = self.cursor
while True:
temp_cursor -= 1
if temp_cursor < 0:
# we scrolled past the start of the data without finding an element that passes the filter
return False
if self._passes_filter(self.data[temp_cursor]):
self.cursor = temp_cursor
return True
def first(self) -> bool:
self.cursor = 0
return True
def last(self) -> bool:
self.cursor = len(self.data)-1
return True
def reject(self, notes: str) -> None:
self.data[self.cursor]["status"] = REJECTED
if notes:
self.data[self.cursor]["notes"] = notes
self.data[self.cursor]["modified_unixtime"] = int(time.time())
def maybe(self, notes: str) -> None:
self.data[self.cursor]["status"] = MAYBE
if notes:
self.data[self.cursor]["notes"] = notes
self.data[self.cursor]["modified_unixtime"] = int(time.time())
###############################################################################
class SqliteCommentDB:
def __init__(self, dbconn):
dbconn.row_factory = SqliteCommentDB._dict_row
self.dbconn = dbconn
self.filter_mode = FilterMode.ALL
self.first()
@property
def comment_id(self) -> int:
return self.current_record["comment_id"]
@property
def url(self) -> str:
return f"https://news.ycombinator.com/item?id={self.comment_id}"
@property
def comment_text(self) -> str:
return self.current_record["body"]
@property
def status(self) -> Optional[str]:
return self.current_record.get("status", None)
@property
def modified_unixtime(self) -> Optional[int]:
return self.current_record.get("modified_unixtime", None)
@property
def notes(self) -> Optional[str]:
return self.current_record.get("notes", None)
@property
def as_json_record(self) -> str:
return json.dumps(self.current_record)
@staticmethod
def _dict_row(cursor, row): # pasted from the docs https://docs.python.org/3/library/sqlite3.html
d = {}
for idx, col in enumerate(cursor.description):
d[col[0]] = row[idx]
return d
@staticmethod
def _initialize_db(db_file_name: str) -> sqlite3.Connection:
dbconn = sqlite3.connect(db_file_name, check_same_thread=False)
dbconn.execute("""
create table comment
(
comment_id integer primary key not null
, body text not null
, status text
, notes text
, modified_unixtime integer
)
""".strip())
dbconn.commit()
return dbconn
@staticmethod
def import_json_file(fd: TextIO, db_file_name: str) -> SqliteCommentDB:
dbconn = SqliteCommentDB._initialize_db(db_file_name)
for line in fd.readlines():
if len(line) == 0:
continue
temp_record = json.loads(line)
dbconn.execute("insert into comment(comment_id, body) values(:comment_id, :body)", temp_record)
dbconn.commit()
return SqliteCommentDB(dbconn)
@staticmethod
def from_db_file(db_file_name: str) -> SqliteCommentDB:
dbconn = sqlite3.connect(db_file_name, check_same_thread=False)
return SqliteCommentDB(dbconn)
@property
def _filter_clause(self) -> str:
if self.filter_mode == FilterMode.ALL:
return "(1=1)"
elif self.filter_mode == FilterMode.ALL_UNSTATUSED:
return "(status is null)"
elif self.filter_mode == FilterMode.MAYBE_ONLY:
return f"(status = '{MAYBE}')"
elif self.filter_mode == FilterMode.REJECTED_ONLY:
return f"(status = '{REJECTED}')"
def next(self) -> bool:
query = f"""
select *
from comment
where comment_id > :current_id
and {self._filter_clause}
order by comment_id
limit 1
""".strip()
params = dict(current_id=self.comment_id)
for rec in self.dbconn.execute(query, params):
self.current_record = rec
return True
return False
def prev(self) -> bool:
query = f"""
select *
from comment
where comment_id < :current_id
and {self._filter_clause}
order by comment_id desc
limit 1
""".strip()
params = dict(current_id=self.comment_id)
for rec in self.dbconn.execute(query, params):
self.current_record = rec
return True
return False
def first(self) -> bool:
query = """
select *
from comment
order by comment_id
limit 1
""".strip()
for rec in self.dbconn.execute(query):
self.current_record = rec
return True
def last(self) -> bool:
query = """
select *
from comment
order by comment_id desc
limit 1
""".strip()
for rec in self.dbconn.execute(query):
self.current_record = rec
return True
def reject(self, notes: str) -> None:
query = """
update comment
set status = :status
, notes = :notes
, modified_unixtime = :modified_unixtime
where comment_id = :comment_id
""".strip()
params = {
"status": REJECTED,
"notes": notes,
"modified_unixtime": int(time.time()),
"comment_id": self.comment_id,
}
self.dbconn.execute(query, params)
self.dbconn.commit()
def maybe(self, notes: str) -> None:
query = """
update comment
set status = :status
, notes = :notes
, modified_unixtime = :modified_unixtime
where comment_id = :comment_id """.strip()
params = {
"status": MAYBE,
"notes": notes,
"modified_unixtime": int(time.time()),
"comment_id": self.comment_id,
}
self.dbconn.execute(query, params)
self.dbconn.commit()